1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306 
307     if (Subtarget.is64Bit())
308       setOperationAction(ISD::ABS, MVT::i32, Custom);
309   }
310 
311   if (Subtarget.hasStdExtZbt()) {
312     setOperationAction(ISD::FSHL, XLenVT, Custom);
313     setOperationAction(ISD::FSHR, XLenVT, Custom);
314     setOperationAction(ISD::SELECT, XLenVT, Legal);
315 
316     if (Subtarget.is64Bit()) {
317       setOperationAction(ISD::FSHL, MVT::i32, Custom);
318       setOperationAction(ISD::FSHR, MVT::i32, Custom);
319     }
320   } else {
321     setOperationAction(ISD::SELECT, XLenVT, Custom);
322   }
323 
324   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
325       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
326       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
327       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
328       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
329       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
330       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
331 
332   static const ISD::CondCode FPCCToExpand[] = {
333       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
334       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
335       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
336 
337   static const ISD::NodeType FPOpToExpand[] = {
338       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
339       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
340 
341   if (Subtarget.hasStdExtZfh())
342     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
343 
344   if (Subtarget.hasStdExtZfh()) {
345     for (auto NT : FPLegalNodeTypes)
346       setOperationAction(NT, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
352     setOperationAction(ISD::SELECT, MVT::f16, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
354 
355     setOperationAction(ISD::FREM,       MVT::f16, Promote);
356     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
357     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
358     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
359     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
360     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
361     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
362     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
363     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
364     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
365     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
366     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
367     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
368     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
369     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
370     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
371     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
372     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
373 
374     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
375     // complete support for all operations in LegalizeDAG.
376 
377     // We need to custom promote this.
378     if (Subtarget.is64Bit())
379       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
380   }
381 
382   if (Subtarget.hasStdExtF()) {
383     for (auto NT : FPLegalNodeTypes)
384       setOperationAction(NT, MVT::f32, Legal);
385     for (auto CC : FPCCToExpand)
386       setCondCodeAction(CC, MVT::f32, Expand);
387     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
388     setOperationAction(ISD::SELECT, MVT::f32, Custom);
389     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
390     for (auto Op : FPOpToExpand)
391       setOperationAction(Op, MVT::f32, Expand);
392     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
393     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   }
395 
396   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
397     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtD()) {
400     for (auto NT : FPLegalNodeTypes)
401       setOperationAction(NT, MVT::f64, Legal);
402     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
404     for (auto CC : FPCCToExpand)
405       setCondCodeAction(CC, MVT::f64, Expand);
406     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Custom);
408     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
409     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f64, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.is64Bit()) {
418     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
419     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
421     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
422   }
423 
424   if (Subtarget.hasStdExtF()) {
425     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
426     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
427 
428     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
429     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
430     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
494         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SEXT,
495         ISD::VP_ZEXT,        ISD::VP_TRUNC};
496 
497     static const unsigned FloatingPointVPOps[] = {
498         ISD::VP_FADD,        ISD::VP_FSUB,
499         ISD::VP_FMUL,        ISD::VP_FDIV,
500         ISD::VP_FNEG,        ISD::VP_FMA,
501         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
502         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
503         ISD::VP_MERGE,       ISD::VP_SELECT,
504         ISD::VP_SITOFP,      ISD::VP_UITOFP,
505         ISD::VP_SETCC};
506 
507     if (!Subtarget.is64Bit()) {
508       // We must custom-lower certain vXi64 operations on RV32 due to the vector
509       // element type being illegal.
510       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
511       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
512 
513       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
515       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
516       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
517       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
518       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
519       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
520       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
521 
522       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
524       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
525       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
526       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
527       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
528       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
529       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
530     }
531 
532     for (MVT VT : BoolVecVTs) {
533       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
534 
535       // Mask VTs are custom-expanded into a series of standard nodes
536       setOperationAction(ISD::TRUNCATE, VT, Custom);
537       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
538       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
539       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
540 
541       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
543 
544       setOperationAction(ISD::SELECT, VT, Custom);
545       setOperationAction(ISD::SELECT_CC, VT, Expand);
546       setOperationAction(ISD::VSELECT, VT, Expand);
547       setOperationAction(ISD::VP_MERGE, VT, Expand);
548       setOperationAction(ISD::VP_SELECT, VT, Expand);
549 
550       setOperationAction(ISD::VP_AND, VT, Custom);
551       setOperationAction(ISD::VP_OR, VT, Custom);
552       setOperationAction(ISD::VP_XOR, VT, Custom);
553 
554       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
555       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
556       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
557 
558       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
559       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
560       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
561 
562       // RVV has native int->float & float->int conversions where the
563       // element type sizes are within one power-of-two of each other. Any
564       // wider distances between type sizes have to be lowered as sequences
565       // which progressively narrow the gap in stages.
566       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
567       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
568       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
569       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
570 
571       // Expand all extending loads to types larger than this, and truncating
572       // stores from types larger than this.
573       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
574         setTruncStoreAction(OtherVT, VT, Expand);
575         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
576         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
577         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
578       }
579 
580       setOperationAction(ISD::VP_FPTOSI, VT, Custom);
581       setOperationAction(ISD::VP_FPTOUI, VT, Custom);
582       setOperationAction(ISD::VP_TRUNC, VT, Custom);
583     }
584 
585     for (MVT VT : IntVecVTs) {
586       if (VT.getVectorElementType() == MVT::i64 &&
587           !Subtarget.hasVInstructionsI64())
588         continue;
589 
590       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
591       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
592 
593       // Vectors implement MULHS/MULHU.
594       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
595       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
596 
597       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
598       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
599         setOperationAction(ISD::MULHU, VT, Expand);
600         setOperationAction(ISD::MULHS, VT, Expand);
601       }
602 
603       setOperationAction(ISD::SMIN, VT, Legal);
604       setOperationAction(ISD::SMAX, VT, Legal);
605       setOperationAction(ISD::UMIN, VT, Legal);
606       setOperationAction(ISD::UMAX, VT, Legal);
607 
608       setOperationAction(ISD::ROTL, VT, Expand);
609       setOperationAction(ISD::ROTR, VT, Expand);
610 
611       setOperationAction(ISD::CTTZ, VT, Expand);
612       setOperationAction(ISD::CTLZ, VT, Expand);
613       setOperationAction(ISD::CTPOP, VT, Expand);
614 
615       setOperationAction(ISD::BSWAP, VT, Expand);
616 
617       // Custom-lower extensions and truncations from/to mask types.
618       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
619       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
620       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
621 
622       // RVV has native int->float & float->int conversions where the
623       // element type sizes are within one power-of-two of each other. Any
624       // wider distances between type sizes have to be lowered as sequences
625       // which progressively narrow the gap in stages.
626       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
627       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
628       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
629       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
630 
631       setOperationAction(ISD::SADDSAT, VT, Legal);
632       setOperationAction(ISD::UADDSAT, VT, Legal);
633       setOperationAction(ISD::SSUBSAT, VT, Legal);
634       setOperationAction(ISD::USUBSAT, VT, Legal);
635 
636       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
637       // nodes which truncate by one power of two at a time.
638       setOperationAction(ISD::TRUNCATE, VT, Custom);
639 
640       // Custom-lower insert/extract operations to simplify patterns.
641       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
642       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
643 
644       // Custom-lower reduction operations to set up the corresponding custom
645       // nodes' operands.
646       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
647       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
648       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
649       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
650       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
651       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
652       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
653       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
654 
655       for (unsigned VPOpc : IntegerVPOps)
656         setOperationAction(VPOpc, VT, Custom);
657 
658       setOperationAction(ISD::LOAD, VT, Custom);
659       setOperationAction(ISD::STORE, VT, Custom);
660 
661       setOperationAction(ISD::MLOAD, VT, Custom);
662       setOperationAction(ISD::MSTORE, VT, Custom);
663       setOperationAction(ISD::MGATHER, VT, Custom);
664       setOperationAction(ISD::MSCATTER, VT, Custom);
665 
666       setOperationAction(ISD::VP_LOAD, VT, Custom);
667       setOperationAction(ISD::VP_STORE, VT, Custom);
668       setOperationAction(ISD::VP_GATHER, VT, Custom);
669       setOperationAction(ISD::VP_SCATTER, VT, Custom);
670 
671       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
672       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
673       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
674 
675       setOperationAction(ISD::SELECT, VT, Custom);
676       setOperationAction(ISD::SELECT_CC, VT, Expand);
677 
678       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
679       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
680 
681       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
682         setTruncStoreAction(VT, OtherVT, Expand);
683         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
684         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
685         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
686       }
687 
688       // Splice
689       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
690 
691       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
692       // type that can represent the value exactly.
693       if (VT.getVectorElementType() != MVT::i64) {
694         MVT FloatEltVT =
695             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
696         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
697         if (isTypeLegal(FloatVT)) {
698           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
699           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
700         }
701       }
702     }
703 
704     // Expand various CCs to best match the RVV ISA, which natively supports UNE
705     // but no other unordered comparisons, and supports all ordered comparisons
706     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
707     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
708     // and we pattern-match those back to the "original", swapping operands once
709     // more. This way we catch both operations and both "vf" and "fv" forms with
710     // fewer patterns.
711     static const ISD::CondCode VFPCCToExpand[] = {
712         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
713         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
714         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
715     };
716 
717     // Sets common operation actions on RVV floating-point vector types.
718     const auto SetCommonVFPActions = [&](MVT VT) {
719       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
720       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
721       // sizes are within one power-of-two of each other. Therefore conversions
722       // between vXf16 and vXf64 must be lowered as sequences which convert via
723       // vXf32.
724       setOperationAction(ISD::FP_ROUND, VT, Custom);
725       setOperationAction(ISD::FP_EXTEND, VT, Custom);
726       // Custom-lower insert/extract operations to simplify patterns.
727       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
728       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
729       // Expand various condition codes (explained above).
730       for (auto CC : VFPCCToExpand)
731         setCondCodeAction(CC, VT, Expand);
732 
733       setOperationAction(ISD::FMINNUM, VT, Legal);
734       setOperationAction(ISD::FMAXNUM, VT, Legal);
735 
736       setOperationAction(ISD::FTRUNC, VT, Custom);
737       setOperationAction(ISD::FCEIL, VT, Custom);
738       setOperationAction(ISD::FFLOOR, VT, Custom);
739       setOperationAction(ISD::FROUND, VT, Custom);
740 
741       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
742       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
743       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
744       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
745 
746       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
747 
748       setOperationAction(ISD::LOAD, VT, Custom);
749       setOperationAction(ISD::STORE, VT, Custom);
750 
751       setOperationAction(ISD::MLOAD, VT, Custom);
752       setOperationAction(ISD::MSTORE, VT, Custom);
753       setOperationAction(ISD::MGATHER, VT, Custom);
754       setOperationAction(ISD::MSCATTER, VT, Custom);
755 
756       setOperationAction(ISD::VP_LOAD, VT, Custom);
757       setOperationAction(ISD::VP_STORE, VT, Custom);
758       setOperationAction(ISD::VP_GATHER, VT, Custom);
759       setOperationAction(ISD::VP_SCATTER, VT, Custom);
760 
761       setOperationAction(ISD::SELECT, VT, Custom);
762       setOperationAction(ISD::SELECT_CC, VT, Expand);
763 
764       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
765       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
766       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
767 
768       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
769       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
770 
771       for (unsigned VPOpc : FloatingPointVPOps)
772         setOperationAction(VPOpc, VT, Custom);
773     };
774 
775     // Sets common extload/truncstore actions on RVV floating-point vector
776     // types.
777     const auto SetCommonVFPExtLoadTruncStoreActions =
778         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
779           for (auto SmallVT : SmallerVTs) {
780             setTruncStoreAction(VT, SmallVT, Expand);
781             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
782           }
783         };
784 
785     if (Subtarget.hasVInstructionsF16())
786       for (MVT VT : F16VecVTs)
787         SetCommonVFPActions(VT);
788 
789     for (MVT VT : F32VecVTs) {
790       if (Subtarget.hasVInstructionsF32())
791         SetCommonVFPActions(VT);
792       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
793     }
794 
795     for (MVT VT : F64VecVTs) {
796       if (Subtarget.hasVInstructionsF64())
797         SetCommonVFPActions(VT);
798       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
799       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
800     }
801 
802     if (Subtarget.useRVVForFixedLengthVectors()) {
803       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
804         if (!useRVVForFixedLengthVectorVT(VT))
805           continue;
806 
807         // By default everything must be expanded.
808         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
809           setOperationAction(Op, VT, Expand);
810         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
811           setTruncStoreAction(VT, OtherVT, Expand);
812           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
813           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
814           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
815         }
816 
817         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
818         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
819         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
820 
821         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
822         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
823 
824         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
825         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
826 
827         setOperationAction(ISD::LOAD, VT, Custom);
828         setOperationAction(ISD::STORE, VT, Custom);
829 
830         setOperationAction(ISD::SETCC, VT, Custom);
831 
832         setOperationAction(ISD::SELECT, VT, Custom);
833 
834         setOperationAction(ISD::TRUNCATE, VT, Custom);
835 
836         setOperationAction(ISD::BITCAST, VT, Custom);
837 
838         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
839         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
840         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
841 
842         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
843         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
844         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
845 
846         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
847         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
848         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
849         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
850 
851         // Operations below are different for between masks and other vectors.
852         if (VT.getVectorElementType() == MVT::i1) {
853           setOperationAction(ISD::VP_AND, VT, Custom);
854           setOperationAction(ISD::VP_OR, VT, Custom);
855           setOperationAction(ISD::VP_XOR, VT, Custom);
856           setOperationAction(ISD::AND, VT, Custom);
857           setOperationAction(ISD::OR, VT, Custom);
858           setOperationAction(ISD::XOR, VT, Custom);
859 
860           setOperationAction(ISD::VP_FPTOSI, VT, Custom);
861           setOperationAction(ISD::VP_FPTOUI, VT, Custom);
862           setOperationAction(ISD::VP_SETCC, VT, Custom);
863           setOperationAction(ISD::VP_TRUNC, VT, Custom);
864           continue;
865         }
866 
867         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
868         // it before type legalization for i64 vectors on RV32. It will then be
869         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
870         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
871         // improvements first.
872         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
873           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
874           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
875         }
876 
877         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
878         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
879 
880         setOperationAction(ISD::MLOAD, VT, Custom);
881         setOperationAction(ISD::MSTORE, VT, Custom);
882         setOperationAction(ISD::MGATHER, VT, Custom);
883         setOperationAction(ISD::MSCATTER, VT, Custom);
884 
885         setOperationAction(ISD::VP_LOAD, VT, Custom);
886         setOperationAction(ISD::VP_STORE, VT, Custom);
887         setOperationAction(ISD::VP_GATHER, VT, Custom);
888         setOperationAction(ISD::VP_SCATTER, VT, Custom);
889 
890         setOperationAction(ISD::ADD, VT, Custom);
891         setOperationAction(ISD::MUL, VT, Custom);
892         setOperationAction(ISD::SUB, VT, Custom);
893         setOperationAction(ISD::AND, VT, Custom);
894         setOperationAction(ISD::OR, VT, Custom);
895         setOperationAction(ISD::XOR, VT, Custom);
896         setOperationAction(ISD::SDIV, VT, Custom);
897         setOperationAction(ISD::SREM, VT, Custom);
898         setOperationAction(ISD::UDIV, VT, Custom);
899         setOperationAction(ISD::UREM, VT, Custom);
900         setOperationAction(ISD::SHL, VT, Custom);
901         setOperationAction(ISD::SRA, VT, Custom);
902         setOperationAction(ISD::SRL, VT, Custom);
903 
904         setOperationAction(ISD::SMIN, VT, Custom);
905         setOperationAction(ISD::SMAX, VT, Custom);
906         setOperationAction(ISD::UMIN, VT, Custom);
907         setOperationAction(ISD::UMAX, VT, Custom);
908         setOperationAction(ISD::ABS,  VT, Custom);
909 
910         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
911         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
912           setOperationAction(ISD::MULHS, VT, Custom);
913           setOperationAction(ISD::MULHU, VT, Custom);
914         }
915 
916         setOperationAction(ISD::SADDSAT, VT, Custom);
917         setOperationAction(ISD::UADDSAT, VT, Custom);
918         setOperationAction(ISD::SSUBSAT, VT, Custom);
919         setOperationAction(ISD::USUBSAT, VT, Custom);
920 
921         setOperationAction(ISD::VSELECT, VT, Custom);
922         setOperationAction(ISD::SELECT_CC, VT, Expand);
923 
924         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
925         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
926         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
927 
928         // Custom-lower reduction operations to set up the corresponding custom
929         // nodes' operands.
930         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
933         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
934         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
935 
936         for (unsigned VPOpc : IntegerVPOps)
937           setOperationAction(VPOpc, VT, Custom);
938 
939         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
940         // type that can represent the value exactly.
941         if (VT.getVectorElementType() != MVT::i64) {
942           MVT FloatEltVT =
943               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
944           EVT FloatVT =
945               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
946           if (isTypeLegal(FloatVT)) {
947             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
948             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
949           }
950         }
951       }
952 
953       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
954         if (!useRVVForFixedLengthVectorVT(VT))
955           continue;
956 
957         // By default everything must be expanded.
958         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
959           setOperationAction(Op, VT, Expand);
960         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
961           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
962           setTruncStoreAction(VT, OtherVT, Expand);
963         }
964 
965         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
966         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
967         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
968 
969         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
970         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
971         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
972         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
973         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
974 
975         setOperationAction(ISD::LOAD, VT, Custom);
976         setOperationAction(ISD::STORE, VT, Custom);
977         setOperationAction(ISD::MLOAD, VT, Custom);
978         setOperationAction(ISD::MSTORE, VT, Custom);
979         setOperationAction(ISD::MGATHER, VT, Custom);
980         setOperationAction(ISD::MSCATTER, VT, Custom);
981 
982         setOperationAction(ISD::VP_LOAD, VT, Custom);
983         setOperationAction(ISD::VP_STORE, VT, Custom);
984         setOperationAction(ISD::VP_GATHER, VT, Custom);
985         setOperationAction(ISD::VP_SCATTER, VT, Custom);
986 
987         setOperationAction(ISD::FADD, VT, Custom);
988         setOperationAction(ISD::FSUB, VT, Custom);
989         setOperationAction(ISD::FMUL, VT, Custom);
990         setOperationAction(ISD::FDIV, VT, Custom);
991         setOperationAction(ISD::FNEG, VT, Custom);
992         setOperationAction(ISD::FABS, VT, Custom);
993         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
994         setOperationAction(ISD::FSQRT, VT, Custom);
995         setOperationAction(ISD::FMA, VT, Custom);
996         setOperationAction(ISD::FMINNUM, VT, Custom);
997         setOperationAction(ISD::FMAXNUM, VT, Custom);
998 
999         setOperationAction(ISD::FP_ROUND, VT, Custom);
1000         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1001 
1002         setOperationAction(ISD::FTRUNC, VT, Custom);
1003         setOperationAction(ISD::FCEIL, VT, Custom);
1004         setOperationAction(ISD::FFLOOR, VT, Custom);
1005         setOperationAction(ISD::FROUND, VT, Custom);
1006 
1007         for (auto CC : VFPCCToExpand)
1008           setCondCodeAction(CC, VT, Expand);
1009 
1010         setOperationAction(ISD::VSELECT, VT, Custom);
1011         setOperationAction(ISD::SELECT, VT, Custom);
1012         setOperationAction(ISD::SELECT_CC, VT, Expand);
1013 
1014         setOperationAction(ISD::BITCAST, VT, Custom);
1015 
1016         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1018         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1019         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1020 
1021         for (unsigned VPOpc : FloatingPointVPOps)
1022           setOperationAction(VPOpc, VT, Custom);
1023       }
1024 
1025       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1026       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1028       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1029       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1030       if (Subtarget.hasStdExtZfh())
1031         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1032       if (Subtarget.hasStdExtF())
1033         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1034       if (Subtarget.hasStdExtD())
1035         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1036     }
1037   }
1038 
1039   // Function alignments.
1040   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1041   setMinFunctionAlignment(FunctionAlignment);
1042   setPrefFunctionAlignment(FunctionAlignment);
1043 
1044   setMinimumJumpTableEntries(5);
1045 
1046   // Jumps are expensive, compared to logic
1047   setJumpIsExpensive();
1048 
1049   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
1050                        ISD::OR, ISD::XOR});
1051 
1052   if (Subtarget.hasStdExtZbp())
1053     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
1054   if (Subtarget.hasStdExtZbkb())
1055     setTargetDAGCombine(ISD::BITREVERSE);
1056   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1057     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1058   if (Subtarget.hasStdExtF())
1059     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1060                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
1061   if (Subtarget.hasVInstructions())
1062     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
1063                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1064                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
1065 
1066   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1067   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1068 }
1069 
1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1071                                             LLVMContext &Context,
1072                                             EVT VT) const {
1073   if (!VT.isVector())
1074     return getPointerTy(DL);
1075   if (Subtarget.hasVInstructions() &&
1076       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1077     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1078   return VT.changeVectorElementTypeToInteger();
1079 }
1080 
1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1082   return Subtarget.getXLenVT();
1083 }
1084 
1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1086                                              const CallInst &I,
1087                                              MachineFunction &MF,
1088                                              unsigned Intrinsic) const {
1089   auto &DL = I.getModule()->getDataLayout();
1090   switch (Intrinsic) {
1091   default:
1092     return false;
1093   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1101   case Intrinsic::riscv_masked_cmpxchg_i32:
1102     Info.opc = ISD::INTRINSIC_W_CHAIN;
1103     Info.memVT = MVT::i32;
1104     Info.ptrVal = I.getArgOperand(0);
1105     Info.offset = 0;
1106     Info.align = Align(4);
1107     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1108                  MachineMemOperand::MOVolatile;
1109     return true;
1110   case Intrinsic::riscv_masked_strided_load:
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.ptrVal = I.getArgOperand(1);
1113     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1114     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOLoad;
1117     return true;
1118   case Intrinsic::riscv_masked_strided_store:
1119     Info.opc = ISD::INTRINSIC_VOID;
1120     Info.ptrVal = I.getArgOperand(1);
1121     Info.memVT =
1122         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1123     Info.align = Align(
1124         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1125         8);
1126     Info.size = MemoryLocation::UnknownSize;
1127     Info.flags |= MachineMemOperand::MOStore;
1128     return true;
1129   case Intrinsic::riscv_seg2_load:
1130   case Intrinsic::riscv_seg3_load:
1131   case Intrinsic::riscv_seg4_load:
1132   case Intrinsic::riscv_seg5_load:
1133   case Intrinsic::riscv_seg6_load:
1134   case Intrinsic::riscv_seg7_load:
1135   case Intrinsic::riscv_seg8_load:
1136     Info.opc = ISD::INTRINSIC_W_CHAIN;
1137     Info.ptrVal = I.getArgOperand(0);
1138     Info.memVT =
1139         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1140     Info.align =
1141         Align(DL.getTypeSizeInBits(
1142                   I.getType()->getStructElementType(0)->getScalarType()) /
1143               8);
1144     Info.size = MemoryLocation::UnknownSize;
1145     Info.flags |= MachineMemOperand::MOLoad;
1146     return true;
1147   }
1148 }
1149 
1150 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1151                                                 const AddrMode &AM, Type *Ty,
1152                                                 unsigned AS,
1153                                                 Instruction *I) const {
1154   // No global is ever allowed as a base.
1155   if (AM.BaseGV)
1156     return false;
1157 
1158   // Require a 12-bit signed offset.
1159   if (!isInt<12>(AM.BaseOffs))
1160     return false;
1161 
1162   switch (AM.Scale) {
1163   case 0: // "r+i" or just "i", depending on HasBaseReg.
1164     break;
1165   case 1:
1166     if (!AM.HasBaseReg) // allow "r+i".
1167       break;
1168     return false; // disallow "r+r" or "r+r+i".
1169   default:
1170     return false;
1171   }
1172 
1173   return true;
1174 }
1175 
1176 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1177   return isInt<12>(Imm);
1178 }
1179 
1180 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1181   return isInt<12>(Imm);
1182 }
1183 
1184 // On RV32, 64-bit integers are split into their high and low parts and held
1185 // in two different registers, so the trunc is free since the low register can
1186 // just be used.
1187 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1188   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1189     return false;
1190   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1191   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1192   return (SrcBits == 64 && DestBits == 32);
1193 }
1194 
1195 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1196   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1197       !SrcVT.isInteger() || !DstVT.isInteger())
1198     return false;
1199   unsigned SrcBits = SrcVT.getSizeInBits();
1200   unsigned DestBits = DstVT.getSizeInBits();
1201   return (SrcBits == 64 && DestBits == 32);
1202 }
1203 
1204 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1205   // Zexts are free if they can be combined with a load.
1206   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1207   // poorly with type legalization of compares preferring sext.
1208   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1209     EVT MemVT = LD->getMemoryVT();
1210     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1211         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1212          LD->getExtensionType() == ISD::ZEXTLOAD))
1213       return true;
1214   }
1215 
1216   return TargetLowering::isZExtFree(Val, VT2);
1217 }
1218 
1219 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1220   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1221 }
1222 
1223 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1224   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1225 }
1226 
1227 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1228   return Subtarget.hasStdExtZbb();
1229 }
1230 
1231 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1232   return Subtarget.hasStdExtZbb();
1233 }
1234 
1235 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1236   EVT VT = Y.getValueType();
1237 
1238   // FIXME: Support vectors once we have tests.
1239   if (VT.isVector())
1240     return false;
1241 
1242   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1243           Subtarget.hasStdExtZbkb()) &&
1244          !isa<ConstantSDNode>(Y);
1245 }
1246 
1247 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1248   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1249   auto *C = dyn_cast<ConstantSDNode>(Y);
1250   return C && C->getAPIntValue().ule(10);
1251 }
1252 
1253 /// Check if sinking \p I's operands to I's basic block is profitable, because
1254 /// the operands can be folded into a target instruction, e.g.
1255 /// splats of scalars can fold into vector instructions.
1256 bool RISCVTargetLowering::shouldSinkOperands(
1257     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1258   using namespace llvm::PatternMatch;
1259 
1260   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1261     return false;
1262 
1263   auto IsSinker = [&](Instruction *I, int Operand) {
1264     switch (I->getOpcode()) {
1265     case Instruction::Add:
1266     case Instruction::Sub:
1267     case Instruction::Mul:
1268     case Instruction::And:
1269     case Instruction::Or:
1270     case Instruction::Xor:
1271     case Instruction::FAdd:
1272     case Instruction::FSub:
1273     case Instruction::FMul:
1274     case Instruction::FDiv:
1275     case Instruction::ICmp:
1276     case Instruction::FCmp:
1277       return true;
1278     case Instruction::Shl:
1279     case Instruction::LShr:
1280     case Instruction::AShr:
1281     case Instruction::UDiv:
1282     case Instruction::SDiv:
1283     case Instruction::URem:
1284     case Instruction::SRem:
1285       return Operand == 1;
1286     case Instruction::Call:
1287       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1288         switch (II->getIntrinsicID()) {
1289         case Intrinsic::fma:
1290         case Intrinsic::vp_fma:
1291           return Operand == 0 || Operand == 1;
1292         // FIXME: Our patterns can only match vx/vf instructions when the splat
1293         // it on the RHS, because TableGen doesn't recognize our VP operations
1294         // as commutative.
1295         case Intrinsic::vp_add:
1296         case Intrinsic::vp_mul:
1297         case Intrinsic::vp_and:
1298         case Intrinsic::vp_or:
1299         case Intrinsic::vp_xor:
1300         case Intrinsic::vp_fadd:
1301         case Intrinsic::vp_fmul:
1302         case Intrinsic::vp_shl:
1303         case Intrinsic::vp_lshr:
1304         case Intrinsic::vp_ashr:
1305         case Intrinsic::vp_udiv:
1306         case Intrinsic::vp_sdiv:
1307         case Intrinsic::vp_urem:
1308         case Intrinsic::vp_srem:
1309           return Operand == 1;
1310         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1311         // explicit patterns for both LHS and RHS (as 'vr' versions).
1312         case Intrinsic::vp_sub:
1313         case Intrinsic::vp_fsub:
1314         case Intrinsic::vp_fdiv:
1315           return Operand == 0 || Operand == 1;
1316         default:
1317           return false;
1318         }
1319       }
1320       return false;
1321     default:
1322       return false;
1323     }
1324   };
1325 
1326   for (auto OpIdx : enumerate(I->operands())) {
1327     if (!IsSinker(I, OpIdx.index()))
1328       continue;
1329 
1330     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1331     // Make sure we are not already sinking this operand
1332     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1333       continue;
1334 
1335     // We are looking for a splat that can be sunk.
1336     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1337                              m_Undef(), m_ZeroMask())))
1338       continue;
1339 
1340     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1341     // and vector registers
1342     for (Use &U : Op->uses()) {
1343       Instruction *Insn = cast<Instruction>(U.getUser());
1344       if (!IsSinker(Insn, U.getOperandNo()))
1345         return false;
1346     }
1347 
1348     Ops.push_back(&Op->getOperandUse(0));
1349     Ops.push_back(&OpIdx.value());
1350   }
1351   return true;
1352 }
1353 
1354 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1355                                        bool ForCodeSize) const {
1356   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1357   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1358     return false;
1359   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1360     return false;
1361   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1362     return false;
1363   return Imm.isZero();
1364 }
1365 
1366 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1367   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1368          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1369          (VT == MVT::f64 && Subtarget.hasStdExtD());
1370 }
1371 
1372 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1373                                                       CallingConv::ID CC,
1374                                                       EVT VT) const {
1375   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1376   // We might still end up using a GPR but that will be decided based on ABI.
1377   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1378   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1379     return MVT::f32;
1380 
1381   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1382 }
1383 
1384 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1385                                                            CallingConv::ID CC,
1386                                                            EVT VT) const {
1387   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1388   // We might still end up using a GPR but that will be decided based on ABI.
1389   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1390   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1391     return 1;
1392 
1393   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1394 }
1395 
1396 // Changes the condition code and swaps operands if necessary, so the SetCC
1397 // operation matches one of the comparisons supported directly by branches
1398 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1399 // with 1/-1.
1400 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1401                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1402   // Convert X > -1 to X >= 0.
1403   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1404     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1405     CC = ISD::SETGE;
1406     return;
1407   }
1408   // Convert X < 1 to 0 >= X.
1409   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1410     RHS = LHS;
1411     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1412     CC = ISD::SETGE;
1413     return;
1414   }
1415 
1416   switch (CC) {
1417   default:
1418     break;
1419   case ISD::SETGT:
1420   case ISD::SETLE:
1421   case ISD::SETUGT:
1422   case ISD::SETULE:
1423     CC = ISD::getSetCCSwappedOperands(CC);
1424     std::swap(LHS, RHS);
1425     break;
1426   }
1427 }
1428 
1429 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1430   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1431   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1432   if (VT.getVectorElementType() == MVT::i1)
1433     KnownSize *= 8;
1434 
1435   switch (KnownSize) {
1436   default:
1437     llvm_unreachable("Invalid LMUL.");
1438   case 8:
1439     return RISCVII::VLMUL::LMUL_F8;
1440   case 16:
1441     return RISCVII::VLMUL::LMUL_F4;
1442   case 32:
1443     return RISCVII::VLMUL::LMUL_F2;
1444   case 64:
1445     return RISCVII::VLMUL::LMUL_1;
1446   case 128:
1447     return RISCVII::VLMUL::LMUL_2;
1448   case 256:
1449     return RISCVII::VLMUL::LMUL_4;
1450   case 512:
1451     return RISCVII::VLMUL::LMUL_8;
1452   }
1453 }
1454 
1455 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1456   switch (LMul) {
1457   default:
1458     llvm_unreachable("Invalid LMUL.");
1459   case RISCVII::VLMUL::LMUL_F8:
1460   case RISCVII::VLMUL::LMUL_F4:
1461   case RISCVII::VLMUL::LMUL_F2:
1462   case RISCVII::VLMUL::LMUL_1:
1463     return RISCV::VRRegClassID;
1464   case RISCVII::VLMUL::LMUL_2:
1465     return RISCV::VRM2RegClassID;
1466   case RISCVII::VLMUL::LMUL_4:
1467     return RISCV::VRM4RegClassID;
1468   case RISCVII::VLMUL::LMUL_8:
1469     return RISCV::VRM8RegClassID;
1470   }
1471 }
1472 
1473 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1474   RISCVII::VLMUL LMUL = getLMUL(VT);
1475   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1476       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1477       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1478       LMUL == RISCVII::VLMUL::LMUL_1) {
1479     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1480                   "Unexpected subreg numbering");
1481     return RISCV::sub_vrm1_0 + Index;
1482   }
1483   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1484     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1485                   "Unexpected subreg numbering");
1486     return RISCV::sub_vrm2_0 + Index;
1487   }
1488   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1489     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1490                   "Unexpected subreg numbering");
1491     return RISCV::sub_vrm4_0 + Index;
1492   }
1493   llvm_unreachable("Invalid vector type.");
1494 }
1495 
1496 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1497   if (VT.getVectorElementType() == MVT::i1)
1498     return RISCV::VRRegClassID;
1499   return getRegClassIDForLMUL(getLMUL(VT));
1500 }
1501 
1502 // Attempt to decompose a subvector insert/extract between VecVT and
1503 // SubVecVT via subregister indices. Returns the subregister index that
1504 // can perform the subvector insert/extract with the given element index, as
1505 // well as the index corresponding to any leftover subvectors that must be
1506 // further inserted/extracted within the register class for SubVecVT.
1507 std::pair<unsigned, unsigned>
1508 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1509     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1510     const RISCVRegisterInfo *TRI) {
1511   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1512                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1513                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1514                 "Register classes not ordered");
1515   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1516   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1517   // Try to compose a subregister index that takes us from the incoming
1518   // LMUL>1 register class down to the outgoing one. At each step we half
1519   // the LMUL:
1520   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1521   // Note that this is not guaranteed to find a subregister index, such as
1522   // when we are extracting from one VR type to another.
1523   unsigned SubRegIdx = RISCV::NoSubRegister;
1524   for (const unsigned RCID :
1525        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1526     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1527       VecVT = VecVT.getHalfNumVectorElementsVT();
1528       bool IsHi =
1529           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1530       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1531                                             getSubregIndexByMVT(VecVT, IsHi));
1532       if (IsHi)
1533         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1534     }
1535   return {SubRegIdx, InsertExtractIdx};
1536 }
1537 
1538 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1539 // stores for those types.
1540 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1541   return !Subtarget.useRVVForFixedLengthVectors() ||
1542          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1543 }
1544 
1545 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1546   if (ScalarTy->isPointerTy())
1547     return true;
1548 
1549   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1550       ScalarTy->isIntegerTy(32))
1551     return true;
1552 
1553   if (ScalarTy->isIntegerTy(64))
1554     return Subtarget.hasVInstructionsI64();
1555 
1556   if (ScalarTy->isHalfTy())
1557     return Subtarget.hasVInstructionsF16();
1558   if (ScalarTy->isFloatTy())
1559     return Subtarget.hasVInstructionsF32();
1560   if (ScalarTy->isDoubleTy())
1561     return Subtarget.hasVInstructionsF64();
1562 
1563   return false;
1564 }
1565 
1566 static SDValue getVLOperand(SDValue Op) {
1567   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1568           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1569          "Unexpected opcode");
1570   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1571   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1572   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1573       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1574   if (!II)
1575     return SDValue();
1576   return Op.getOperand(II->VLOperand + 1 + HasChain);
1577 }
1578 
1579 static bool useRVVForFixedLengthVectorVT(MVT VT,
1580                                          const RISCVSubtarget &Subtarget) {
1581   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1582   if (!Subtarget.useRVVForFixedLengthVectors())
1583     return false;
1584 
1585   // We only support a set of vector types with a consistent maximum fixed size
1586   // across all supported vector element types to avoid legalization issues.
1587   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1588   // fixed-length vector type we support is 1024 bytes.
1589   if (VT.getFixedSizeInBits() > 1024 * 8)
1590     return false;
1591 
1592   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1593 
1594   MVT EltVT = VT.getVectorElementType();
1595 
1596   // Don't use RVV for vectors we cannot scalarize if required.
1597   switch (EltVT.SimpleTy) {
1598   // i1 is supported but has different rules.
1599   default:
1600     return false;
1601   case MVT::i1:
1602     // Masks can only use a single register.
1603     if (VT.getVectorNumElements() > MinVLen)
1604       return false;
1605     MinVLen /= 8;
1606     break;
1607   case MVT::i8:
1608   case MVT::i16:
1609   case MVT::i32:
1610     break;
1611   case MVT::i64:
1612     if (!Subtarget.hasVInstructionsI64())
1613       return false;
1614     break;
1615   case MVT::f16:
1616     if (!Subtarget.hasVInstructionsF16())
1617       return false;
1618     break;
1619   case MVT::f32:
1620     if (!Subtarget.hasVInstructionsF32())
1621       return false;
1622     break;
1623   case MVT::f64:
1624     if (!Subtarget.hasVInstructionsF64())
1625       return false;
1626     break;
1627   }
1628 
1629   // Reject elements larger than ELEN.
1630   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1631     return false;
1632 
1633   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1634   // Don't use RVV for types that don't fit.
1635   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1636     return false;
1637 
1638   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1639   // the base fixed length RVV support in place.
1640   if (!VT.isPow2VectorType())
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1647   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1648 }
1649 
1650 // Return the largest legal scalable vector type that matches VT's element type.
1651 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1652                                             const RISCVSubtarget &Subtarget) {
1653   // This may be called before legal types are setup.
1654   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1655           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1656          "Expected legal fixed length vector!");
1657 
1658   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1659   unsigned MaxELen = Subtarget.getELEN();
1660 
1661   MVT EltVT = VT.getVectorElementType();
1662   switch (EltVT.SimpleTy) {
1663   default:
1664     llvm_unreachable("unexpected element type for RVV container");
1665   case MVT::i1:
1666   case MVT::i8:
1667   case MVT::i16:
1668   case MVT::i32:
1669   case MVT::i64:
1670   case MVT::f16:
1671   case MVT::f32:
1672   case MVT::f64: {
1673     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1674     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1675     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1676     unsigned NumElts =
1677         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1678     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1679     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1680     return MVT::getScalableVectorVT(EltVT, NumElts);
1681   }
1682   }
1683 }
1684 
1685 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1686                                             const RISCVSubtarget &Subtarget) {
1687   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1688                                           Subtarget);
1689 }
1690 
1691 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1692   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1693 }
1694 
1695 // Grow V to consume an entire RVV register.
1696 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1697                                        const RISCVSubtarget &Subtarget) {
1698   assert(VT.isScalableVector() &&
1699          "Expected to convert into a scalable vector!");
1700   assert(V.getValueType().isFixedLengthVector() &&
1701          "Expected a fixed length vector operand!");
1702   SDLoc DL(V);
1703   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1704   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1705 }
1706 
1707 // Shrink V so it's just big enough to maintain a VT's worth of data.
1708 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1709                                          const RISCVSubtarget &Subtarget) {
1710   assert(VT.isFixedLengthVector() &&
1711          "Expected to convert into a fixed length vector!");
1712   assert(V.getValueType().isScalableVector() &&
1713          "Expected a scalable vector operand!");
1714   SDLoc DL(V);
1715   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1716   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1717 }
1718 
1719 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1720 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1721 // the vector type that it is contained in.
1722 static std::pair<SDValue, SDValue>
1723 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1724                 const RISCVSubtarget &Subtarget) {
1725   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1726   MVT XLenVT = Subtarget.getXLenVT();
1727   SDValue VL = VecVT.isFixedLengthVector()
1728                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1729                    : DAG.getRegister(RISCV::X0, XLenVT);
1730   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1731   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1732   return {Mask, VL};
1733 }
1734 
1735 // As above but assuming the given type is a scalable vector type.
1736 static std::pair<SDValue, SDValue>
1737 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1738                         const RISCVSubtarget &Subtarget) {
1739   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1740   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1741 }
1742 
1743 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1744 // of either is (currently) supported. This can get us into an infinite loop
1745 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1746 // as a ..., etc.
1747 // Until either (or both) of these can reliably lower any node, reporting that
1748 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1749 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1750 // which is not desirable.
1751 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1752     EVT VT, unsigned DefinedValues) const {
1753   return false;
1754 }
1755 
1756 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1757                                   const RISCVSubtarget &Subtarget) {
1758   // RISCV FP-to-int conversions saturate to the destination register size, but
1759   // don't produce 0 for nan. We can use a conversion instruction and fix the
1760   // nan case with a compare and a select.
1761   SDValue Src = Op.getOperand(0);
1762 
1763   EVT DstVT = Op.getValueType();
1764   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1765 
1766   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1767   unsigned Opc;
1768   if (SatVT == DstVT)
1769     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1770   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1771     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1772   else
1773     return SDValue();
1774   // FIXME: Support other SatVTs by clamping before or after the conversion.
1775 
1776   SDLoc DL(Op);
1777   SDValue FpToInt = DAG.getNode(
1778       Opc, DL, DstVT, Src,
1779       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1780 
1781   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1782   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1783 }
1784 
1785 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1786 // and back. Taking care to avoid converting values that are nan or already
1787 // correct.
1788 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1789 // have FRM dependencies modeled yet.
1790 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1791   MVT VT = Op.getSimpleValueType();
1792   assert(VT.isVector() && "Unexpected type");
1793 
1794   SDLoc DL(Op);
1795 
1796   // Freeze the source since we are increasing the number of uses.
1797   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1798 
1799   // Truncate to integer and convert back to FP.
1800   MVT IntVT = VT.changeVectorElementTypeToInteger();
1801   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1802   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1803 
1804   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1805 
1806   if (Op.getOpcode() == ISD::FCEIL) {
1807     // If the truncated value is the greater than or equal to the original
1808     // value, we've computed the ceil. Otherwise, we went the wrong way and
1809     // need to increase by 1.
1810     // FIXME: This should use a masked operation. Handle here or in isel?
1811     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1812                                  DAG.getConstantFP(1.0, DL, VT));
1813     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1814     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1815   } else if (Op.getOpcode() == ISD::FFLOOR) {
1816     // If the truncated value is the less than or equal to the original value,
1817     // we've computed the floor. Otherwise, we went the wrong way and need to
1818     // decrease by 1.
1819     // FIXME: This should use a masked operation. Handle here or in isel?
1820     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1821                                  DAG.getConstantFP(1.0, DL, VT));
1822     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1823     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1824   }
1825 
1826   // Restore the original sign so that -0.0 is preserved.
1827   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1828 
1829   // Determine the largest integer that can be represented exactly. This and
1830   // values larger than it don't have any fractional bits so don't need to
1831   // be converted.
1832   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1833   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1834   APFloat MaxVal = APFloat(FltSem);
1835   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1836                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1837   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1838 
1839   // If abs(Src) was larger than MaxVal or nan, keep it.
1840   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1841   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1842   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1843 }
1844 
1845 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1846 // This mode isn't supported in vector hardware on RISCV. But as long as we
1847 // aren't compiling with trapping math, we can emulate this with
1848 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1849 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1850 // dependencies modeled yet.
1851 // FIXME: Use masked operations to avoid final merge.
1852 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1853   MVT VT = Op.getSimpleValueType();
1854   assert(VT.isVector() && "Unexpected type");
1855 
1856   SDLoc DL(Op);
1857 
1858   // Freeze the source since we are increasing the number of uses.
1859   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1860 
1861   // We do the conversion on the absolute value and fix the sign at the end.
1862   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1863 
1864   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1865   bool Ignored;
1866   APFloat Point5Pred = APFloat(0.5f);
1867   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1868   Point5Pred.next(/*nextDown*/ true);
1869 
1870   // Add the adjustment.
1871   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1872                                DAG.getConstantFP(Point5Pred, DL, VT));
1873 
1874   // Truncate to integer and convert back to fp.
1875   MVT IntVT = VT.changeVectorElementTypeToInteger();
1876   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1877   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1878 
1879   // Restore the original sign.
1880   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1881 
1882   // Determine the largest integer that can be represented exactly. This and
1883   // values larger than it don't have any fractional bits so don't need to
1884   // be converted.
1885   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1886   APFloat MaxVal = APFloat(FltSem);
1887   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1888                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1889   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1890 
1891   // If abs(Src) was larger than MaxVal or nan, keep it.
1892   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1893   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1894   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1895 }
1896 
1897 struct VIDSequence {
1898   int64_t StepNumerator;
1899   unsigned StepDenominator;
1900   int64_t Addend;
1901 };
1902 
1903 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1904 // to the (non-zero) step S and start value X. This can be then lowered as the
1905 // RVV sequence (VID * S) + X, for example.
1906 // The step S is represented as an integer numerator divided by a positive
1907 // denominator. Note that the implementation currently only identifies
1908 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1909 // cannot detect 2/3, for example.
1910 // Note that this method will also match potentially unappealing index
1911 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1912 // determine whether this is worth generating code for.
1913 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1914   unsigned NumElts = Op.getNumOperands();
1915   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1916   if (!Op.getValueType().isInteger())
1917     return None;
1918 
1919   Optional<unsigned> SeqStepDenom;
1920   Optional<int64_t> SeqStepNum, SeqAddend;
1921   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1922   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1923   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1924     // Assume undef elements match the sequence; we just have to be careful
1925     // when interpolating across them.
1926     if (Op.getOperand(Idx).isUndef())
1927       continue;
1928     // The BUILD_VECTOR must be all constants.
1929     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1930       return None;
1931 
1932     uint64_t Val = Op.getConstantOperandVal(Idx) &
1933                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1934 
1935     if (PrevElt) {
1936       // Calculate the step since the last non-undef element, and ensure
1937       // it's consistent across the entire sequence.
1938       unsigned IdxDiff = Idx - PrevElt->second;
1939       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1940 
1941       // A zero-value value difference means that we're somewhere in the middle
1942       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1943       // step change before evaluating the sequence.
1944       if (ValDiff != 0) {
1945         int64_t Remainder = ValDiff % IdxDiff;
1946         // Normalize the step if it's greater than 1.
1947         if (Remainder != ValDiff) {
1948           // The difference must cleanly divide the element span.
1949           if (Remainder != 0)
1950             return None;
1951           ValDiff /= IdxDiff;
1952           IdxDiff = 1;
1953         }
1954 
1955         if (!SeqStepNum)
1956           SeqStepNum = ValDiff;
1957         else if (ValDiff != SeqStepNum)
1958           return None;
1959 
1960         if (!SeqStepDenom)
1961           SeqStepDenom = IdxDiff;
1962         else if (IdxDiff != *SeqStepDenom)
1963           return None;
1964       }
1965     }
1966 
1967     // Record and/or check any addend.
1968     if (SeqStepNum && SeqStepDenom) {
1969       uint64_t ExpectedVal =
1970           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1971       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1972       if (!SeqAddend)
1973         SeqAddend = Addend;
1974       else if (SeqAddend != Addend)
1975         return None;
1976     }
1977 
1978     // Record this non-undef element for later.
1979     if (!PrevElt || PrevElt->first != Val)
1980       PrevElt = std::make_pair(Val, Idx);
1981   }
1982   // We need to have logged both a step and an addend for this to count as
1983   // a legal index sequence.
1984   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1985     return None;
1986 
1987   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1988 }
1989 
1990 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1991 // and lower it as a VRGATHER_VX_VL from the source vector.
1992 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1993                                   SelectionDAG &DAG,
1994                                   const RISCVSubtarget &Subtarget) {
1995   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1996     return SDValue();
1997   SDValue Vec = SplatVal.getOperand(0);
1998   // Only perform this optimization on vectors of the same size for simplicity.
1999   if (Vec.getValueType() != VT)
2000     return SDValue();
2001   SDValue Idx = SplatVal.getOperand(1);
2002   // The index must be a legal type.
2003   if (Idx.getValueType() != Subtarget.getXLenVT())
2004     return SDValue();
2005 
2006   MVT ContainerVT = VT;
2007   if (VT.isFixedLengthVector()) {
2008     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2009     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2010   }
2011 
2012   SDValue Mask, VL;
2013   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2014 
2015   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2016                                Idx, Mask, VL);
2017 
2018   if (!VT.isFixedLengthVector())
2019     return Gather;
2020 
2021   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2022 }
2023 
2024 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2025                                  const RISCVSubtarget &Subtarget) {
2026   MVT VT = Op.getSimpleValueType();
2027   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2028 
2029   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2030 
2031   SDLoc DL(Op);
2032   SDValue Mask, VL;
2033   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2034 
2035   MVT XLenVT = Subtarget.getXLenVT();
2036   unsigned NumElts = Op.getNumOperands();
2037 
2038   if (VT.getVectorElementType() == MVT::i1) {
2039     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2040       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2041       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2042     }
2043 
2044     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2045       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2046       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2047     }
2048 
2049     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2050     // scalar integer chunks whose bit-width depends on the number of mask
2051     // bits and XLEN.
2052     // First, determine the most appropriate scalar integer type to use. This
2053     // is at most XLenVT, but may be shrunk to a smaller vector element type
2054     // according to the size of the final vector - use i8 chunks rather than
2055     // XLenVT if we're producing a v8i1. This results in more consistent
2056     // codegen across RV32 and RV64.
2057     unsigned NumViaIntegerBits =
2058         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2059     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2060     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2061       // If we have to use more than one INSERT_VECTOR_ELT then this
2062       // optimization is likely to increase code size; avoid peforming it in
2063       // such a case. We can use a load from a constant pool in this case.
2064       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2065         return SDValue();
2066       // Now we can create our integer vector type. Note that it may be larger
2067       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2068       MVT IntegerViaVecVT =
2069           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2070                            divideCeil(NumElts, NumViaIntegerBits));
2071 
2072       uint64_t Bits = 0;
2073       unsigned BitPos = 0, IntegerEltIdx = 0;
2074       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2075 
2076       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2077         // Once we accumulate enough bits to fill our scalar type, insert into
2078         // our vector and clear our accumulated data.
2079         if (I != 0 && I % NumViaIntegerBits == 0) {
2080           if (NumViaIntegerBits <= 32)
2081             Bits = SignExtend64(Bits, 32);
2082           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2083           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2084                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2085           Bits = 0;
2086           BitPos = 0;
2087           IntegerEltIdx++;
2088         }
2089         SDValue V = Op.getOperand(I);
2090         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2091         Bits |= ((uint64_t)BitValue << BitPos);
2092       }
2093 
2094       // Insert the (remaining) scalar value into position in our integer
2095       // vector type.
2096       if (NumViaIntegerBits <= 32)
2097         Bits = SignExtend64(Bits, 32);
2098       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2099       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2100                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2101 
2102       if (NumElts < NumViaIntegerBits) {
2103         // If we're producing a smaller vector than our minimum legal integer
2104         // type, bitcast to the equivalent (known-legal) mask type, and extract
2105         // our final mask.
2106         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2107         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2108         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2109                           DAG.getConstant(0, DL, XLenVT));
2110       } else {
2111         // Else we must have produced an integer type with the same size as the
2112         // mask type; bitcast for the final result.
2113         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2114         Vec = DAG.getBitcast(VT, Vec);
2115       }
2116 
2117       return Vec;
2118     }
2119 
2120     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2121     // vector type, we have a legal equivalently-sized i8 type, so we can use
2122     // that.
2123     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2124     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2125 
2126     SDValue WideVec;
2127     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2128       // For a splat, perform a scalar truncate before creating the wider
2129       // vector.
2130       assert(Splat.getValueType() == XLenVT &&
2131              "Unexpected type for i1 splat value");
2132       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2133                           DAG.getConstant(1, DL, XLenVT));
2134       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2135     } else {
2136       SmallVector<SDValue, 8> Ops(Op->op_values());
2137       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2138       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2139       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2140     }
2141 
2142     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2143   }
2144 
2145   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2146     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2147       return Gather;
2148     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2149                                         : RISCVISD::VMV_V_X_VL;
2150     Splat =
2151         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2152     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2153   }
2154 
2155   // Try and match index sequences, which we can lower to the vid instruction
2156   // with optional modifications. An all-undef vector is matched by
2157   // getSplatValue, above.
2158   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2159     int64_t StepNumerator = SimpleVID->StepNumerator;
2160     unsigned StepDenominator = SimpleVID->StepDenominator;
2161     int64_t Addend = SimpleVID->Addend;
2162 
2163     assert(StepNumerator != 0 && "Invalid step");
2164     bool Negate = false;
2165     int64_t SplatStepVal = StepNumerator;
2166     unsigned StepOpcode = ISD::MUL;
2167     if (StepNumerator != 1) {
2168       if (isPowerOf2_64(std::abs(StepNumerator))) {
2169         Negate = StepNumerator < 0;
2170         StepOpcode = ISD::SHL;
2171         SplatStepVal = Log2_64(std::abs(StepNumerator));
2172       }
2173     }
2174 
2175     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2176     // threshold since it's the immediate value many RVV instructions accept.
2177     // There is no vmul.vi instruction so ensure multiply constant can fit in
2178     // a single addi instruction.
2179     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2180          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2181         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2182       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2183       // Convert right out of the scalable type so we can use standard ISD
2184       // nodes for the rest of the computation. If we used scalable types with
2185       // these, we'd lose the fixed-length vector info and generate worse
2186       // vsetvli code.
2187       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2188       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2189           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2190         SDValue SplatStep = DAG.getSplatBuildVector(
2191             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2192         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2193       }
2194       if (StepDenominator != 1) {
2195         SDValue SplatStep = DAG.getSplatBuildVector(
2196             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2197         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2198       }
2199       if (Addend != 0 || Negate) {
2200         SDValue SplatAddend = DAG.getSplatBuildVector(
2201             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2202         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2203       }
2204       return VID;
2205     }
2206   }
2207 
2208   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2209   // when re-interpreted as a vector with a larger element type. For example,
2210   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2211   // could be instead splat as
2212   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2213   // TODO: This optimization could also work on non-constant splats, but it
2214   // would require bit-manipulation instructions to construct the splat value.
2215   SmallVector<SDValue> Sequence;
2216   unsigned EltBitSize = VT.getScalarSizeInBits();
2217   const auto *BV = cast<BuildVectorSDNode>(Op);
2218   if (VT.isInteger() && EltBitSize < 64 &&
2219       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2220       BV->getRepeatedSequence(Sequence) &&
2221       (Sequence.size() * EltBitSize) <= 64) {
2222     unsigned SeqLen = Sequence.size();
2223     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2224     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2225     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2226             ViaIntVT == MVT::i64) &&
2227            "Unexpected sequence type");
2228 
2229     unsigned EltIdx = 0;
2230     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2231     uint64_t SplatValue = 0;
2232     // Construct the amalgamated value which can be splatted as this larger
2233     // vector type.
2234     for (const auto &SeqV : Sequence) {
2235       if (!SeqV.isUndef())
2236         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2237                        << (EltIdx * EltBitSize));
2238       EltIdx++;
2239     }
2240 
2241     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2242     // achieve better constant materializion.
2243     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2244       SplatValue = SignExtend64(SplatValue, 32);
2245 
2246     // Since we can't introduce illegal i64 types at this stage, we can only
2247     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2248     // way we can use RVV instructions to splat.
2249     assert((ViaIntVT.bitsLE(XLenVT) ||
2250             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2251            "Unexpected bitcast sequence");
2252     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2253       SDValue ViaVL =
2254           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2255       MVT ViaContainerVT =
2256           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2257       SDValue Splat =
2258           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2259                       DAG.getUNDEF(ViaContainerVT),
2260                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2261       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2262       return DAG.getBitcast(VT, Splat);
2263     }
2264   }
2265 
2266   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2267   // which constitute a large proportion of the elements. In such cases we can
2268   // splat a vector with the dominant element and make up the shortfall with
2269   // INSERT_VECTOR_ELTs.
2270   // Note that this includes vectors of 2 elements by association. The
2271   // upper-most element is the "dominant" one, allowing us to use a splat to
2272   // "insert" the upper element, and an insert of the lower element at position
2273   // 0, which improves codegen.
2274   SDValue DominantValue;
2275   unsigned MostCommonCount = 0;
2276   DenseMap<SDValue, unsigned> ValueCounts;
2277   unsigned NumUndefElts =
2278       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2279 
2280   // Track the number of scalar loads we know we'd be inserting, estimated as
2281   // any non-zero floating-point constant. Other kinds of element are either
2282   // already in registers or are materialized on demand. The threshold at which
2283   // a vector load is more desirable than several scalar materializion and
2284   // vector-insertion instructions is not known.
2285   unsigned NumScalarLoads = 0;
2286 
2287   for (SDValue V : Op->op_values()) {
2288     if (V.isUndef())
2289       continue;
2290 
2291     ValueCounts.insert(std::make_pair(V, 0));
2292     unsigned &Count = ValueCounts[V];
2293 
2294     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2295       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2296 
2297     // Is this value dominant? In case of a tie, prefer the highest element as
2298     // it's cheaper to insert near the beginning of a vector than it is at the
2299     // end.
2300     if (++Count >= MostCommonCount) {
2301       DominantValue = V;
2302       MostCommonCount = Count;
2303     }
2304   }
2305 
2306   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2307   unsigned NumDefElts = NumElts - NumUndefElts;
2308   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2309 
2310   // Don't perform this optimization when optimizing for size, since
2311   // materializing elements and inserting them tends to cause code bloat.
2312   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2313       ((MostCommonCount > DominantValueCountThreshold) ||
2314        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2315     // Start by splatting the most common element.
2316     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2317 
2318     DenseSet<SDValue> Processed{DominantValue};
2319     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2320     for (const auto &OpIdx : enumerate(Op->ops())) {
2321       const SDValue &V = OpIdx.value();
2322       if (V.isUndef() || !Processed.insert(V).second)
2323         continue;
2324       if (ValueCounts[V] == 1) {
2325         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2326                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2327       } else {
2328         // Blend in all instances of this value using a VSELECT, using a
2329         // mask where each bit signals whether that element is the one
2330         // we're after.
2331         SmallVector<SDValue> Ops;
2332         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2333           return DAG.getConstant(V == V1, DL, XLenVT);
2334         });
2335         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2336                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2337                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2338       }
2339     }
2340 
2341     return Vec;
2342   }
2343 
2344   return SDValue();
2345 }
2346 
2347 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2348                                    SDValue Lo, SDValue Hi, SDValue VL,
2349                                    SelectionDAG &DAG) {
2350   if (!Passthru)
2351     Passthru = DAG.getUNDEF(VT);
2352   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2353     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2354     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2355     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2356     // node in order to try and match RVV vector/scalar instructions.
2357     if ((LoC >> 31) == HiC)
2358       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2359 
2360     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2361     // vmv.v.x whose EEW = 32 to lower it.
2362     auto *Const = dyn_cast<ConstantSDNode>(VL);
2363     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2364       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2365       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2366       // access the subtarget here now.
2367       auto InterVec = DAG.getNode(
2368           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2369                                   DAG.getRegister(RISCV::X0, MVT::i32));
2370       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2371     }
2372   }
2373 
2374   // Fall back to a stack store and stride x0 vector load.
2375   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2376                      Hi, VL);
2377 }
2378 
2379 // Called by type legalization to handle splat of i64 on RV32.
2380 // FIXME: We can optimize this when the type has sign or zero bits in one
2381 // of the halves.
2382 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2383                                    SDValue Scalar, SDValue VL,
2384                                    SelectionDAG &DAG) {
2385   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2386   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2387                            DAG.getConstant(0, DL, MVT::i32));
2388   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2389                            DAG.getConstant(1, DL, MVT::i32));
2390   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2391 }
2392 
2393 // This function lowers a splat of a scalar operand Splat with the vector
2394 // length VL. It ensures the final sequence is type legal, which is useful when
2395 // lowering a splat after type legalization.
2396 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2397                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2398                                 const RISCVSubtarget &Subtarget) {
2399   bool HasPassthru = Passthru && !Passthru.isUndef();
2400   if (!HasPassthru && !Passthru)
2401     Passthru = DAG.getUNDEF(VT);
2402   if (VT.isFloatingPoint()) {
2403     // If VL is 1, we could use vfmv.s.f.
2404     if (isOneConstant(VL))
2405       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2406     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2407   }
2408 
2409   MVT XLenVT = Subtarget.getXLenVT();
2410 
2411   // Simplest case is that the operand needs to be promoted to XLenVT.
2412   if (Scalar.getValueType().bitsLE(XLenVT)) {
2413     // If the operand is a constant, sign extend to increase our chances
2414     // of being able to use a .vi instruction. ANY_EXTEND would become a
2415     // a zero extend and the simm5 check in isel would fail.
2416     // FIXME: Should we ignore the upper bits in isel instead?
2417     unsigned ExtOpc =
2418         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2419     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2420     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2421     // If VL is 1 and the scalar value won't benefit from immediate, we could
2422     // use vmv.s.x.
2423     if (isOneConstant(VL) &&
2424         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2425       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2426     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2427   }
2428 
2429   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2430          "Unexpected scalar for splat lowering!");
2431 
2432   if (isOneConstant(VL) && isNullConstant(Scalar))
2433     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2434                        DAG.getConstant(0, DL, XLenVT), VL);
2435 
2436   // Otherwise use the more complicated splatting algorithm.
2437   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2438 }
2439 
2440 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2441                                 const RISCVSubtarget &Subtarget) {
2442   // We need to be able to widen elements to the next larger integer type.
2443   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2444     return false;
2445 
2446   int Size = Mask.size();
2447   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2448 
2449   int Srcs[] = {-1, -1};
2450   for (int i = 0; i != Size; ++i) {
2451     // Ignore undef elements.
2452     if (Mask[i] < 0)
2453       continue;
2454 
2455     // Is this an even or odd element.
2456     int Pol = i % 2;
2457 
2458     // Ensure we consistently use the same source for this element polarity.
2459     int Src = Mask[i] / Size;
2460     if (Srcs[Pol] < 0)
2461       Srcs[Pol] = Src;
2462     if (Srcs[Pol] != Src)
2463       return false;
2464 
2465     // Make sure the element within the source is appropriate for this element
2466     // in the destination.
2467     int Elt = Mask[i] % Size;
2468     if (Elt != i / 2)
2469       return false;
2470   }
2471 
2472   // We need to find a source for each polarity and they can't be the same.
2473   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2474     return false;
2475 
2476   // Swap the sources if the second source was in the even polarity.
2477   SwapSources = Srcs[0] > Srcs[1];
2478 
2479   return true;
2480 }
2481 
2482 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2483 /// and then extract the original number of elements from the rotated result.
2484 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2485 /// returned rotation amount is for a rotate right, where elements move from
2486 /// higher elements to lower elements. \p LoSrc indicates the first source
2487 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2488 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2489 /// 0 or 1 if a rotation is found.
2490 ///
2491 /// NOTE: We talk about rotate to the right which matches how bit shift and
2492 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2493 /// and the table below write vectors with the lowest elements on the left.
2494 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2495   int Size = Mask.size();
2496 
2497   // We need to detect various ways of spelling a rotation:
2498   //   [11, 12, 13, 14, 15,  0,  1,  2]
2499   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2500   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2501   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2502   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2503   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2504   int Rotation = 0;
2505   LoSrc = -1;
2506   HiSrc = -1;
2507   for (int i = 0; i != Size; ++i) {
2508     int M = Mask[i];
2509     if (M < 0)
2510       continue;
2511 
2512     // Determine where a rotate vector would have started.
2513     int StartIdx = i - (M % Size);
2514     // The identity rotation isn't interesting, stop.
2515     if (StartIdx == 0)
2516       return -1;
2517 
2518     // If we found the tail of a vector the rotation must be the missing
2519     // front. If we found the head of a vector, it must be how much of the
2520     // head.
2521     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2522 
2523     if (Rotation == 0)
2524       Rotation = CandidateRotation;
2525     else if (Rotation != CandidateRotation)
2526       // The rotations don't match, so we can't match this mask.
2527       return -1;
2528 
2529     // Compute which value this mask is pointing at.
2530     int MaskSrc = M < Size ? 0 : 1;
2531 
2532     // Compute which of the two target values this index should be assigned to.
2533     // This reflects whether the high elements are remaining or the low elemnts
2534     // are remaining.
2535     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2536 
2537     // Either set up this value if we've not encountered it before, or check
2538     // that it remains consistent.
2539     if (TargetSrc < 0)
2540       TargetSrc = MaskSrc;
2541     else if (TargetSrc != MaskSrc)
2542       // This may be a rotation, but it pulls from the inputs in some
2543       // unsupported interleaving.
2544       return -1;
2545   }
2546 
2547   // Check that we successfully analyzed the mask, and normalize the results.
2548   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2549   assert((LoSrc >= 0 || HiSrc >= 0) &&
2550          "Failed to find a rotated input vector!");
2551 
2552   return Rotation;
2553 }
2554 
2555 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2556                                    const RISCVSubtarget &Subtarget) {
2557   SDValue V1 = Op.getOperand(0);
2558   SDValue V2 = Op.getOperand(1);
2559   SDLoc DL(Op);
2560   MVT XLenVT = Subtarget.getXLenVT();
2561   MVT VT = Op.getSimpleValueType();
2562   unsigned NumElts = VT.getVectorNumElements();
2563   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2564 
2565   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2566 
2567   SDValue TrueMask, VL;
2568   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2569 
2570   if (SVN->isSplat()) {
2571     const int Lane = SVN->getSplatIndex();
2572     if (Lane >= 0) {
2573       MVT SVT = VT.getVectorElementType();
2574 
2575       // Turn splatted vector load into a strided load with an X0 stride.
2576       SDValue V = V1;
2577       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2578       // with undef.
2579       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2580       int Offset = Lane;
2581       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2582         int OpElements =
2583             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2584         V = V.getOperand(Offset / OpElements);
2585         Offset %= OpElements;
2586       }
2587 
2588       // We need to ensure the load isn't atomic or volatile.
2589       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2590         auto *Ld = cast<LoadSDNode>(V);
2591         Offset *= SVT.getStoreSize();
2592         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2593                                                    TypeSize::Fixed(Offset), DL);
2594 
2595         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2596         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2597           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2598           SDValue IntID =
2599               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2600           SDValue Ops[] = {Ld->getChain(),
2601                            IntID,
2602                            DAG.getUNDEF(ContainerVT),
2603                            NewAddr,
2604                            DAG.getRegister(RISCV::X0, XLenVT),
2605                            VL};
2606           SDValue NewLoad = DAG.getMemIntrinsicNode(
2607               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2608               DAG.getMachineFunction().getMachineMemOperand(
2609                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2610           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2611           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2612         }
2613 
2614         // Otherwise use a scalar load and splat. This will give the best
2615         // opportunity to fold a splat into the operation. ISel can turn it into
2616         // the x0 strided load if we aren't able to fold away the select.
2617         if (SVT.isFloatingPoint())
2618           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2619                           Ld->getPointerInfo().getWithOffset(Offset),
2620                           Ld->getOriginalAlign(),
2621                           Ld->getMemOperand()->getFlags());
2622         else
2623           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2624                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2625                              Ld->getOriginalAlign(),
2626                              Ld->getMemOperand()->getFlags());
2627         DAG.makeEquivalentMemoryOrdering(Ld, V);
2628 
2629         unsigned Opc =
2630             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2631         SDValue Splat =
2632             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2633         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2634       }
2635 
2636       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2637       assert(Lane < (int)NumElts && "Unexpected lane!");
2638       SDValue Gather =
2639           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2640                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2641       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2642     }
2643   }
2644 
2645   ArrayRef<int> Mask = SVN->getMask();
2646 
2647   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2648   // be undef which can be handled with a single SLIDEDOWN/UP.
2649   int LoSrc, HiSrc;
2650   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2651   if (Rotation > 0) {
2652     SDValue LoV, HiV;
2653     if (LoSrc >= 0) {
2654       LoV = LoSrc == 0 ? V1 : V2;
2655       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2656     }
2657     if (HiSrc >= 0) {
2658       HiV = HiSrc == 0 ? V1 : V2;
2659       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2660     }
2661 
2662     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2663     // to slide LoV up by (NumElts - Rotation).
2664     unsigned InvRotate = NumElts - Rotation;
2665 
2666     SDValue Res = DAG.getUNDEF(ContainerVT);
2667     if (HiV) {
2668       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2669       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2670       // causes multiple vsetvlis in some test cases such as lowering
2671       // reduce.mul
2672       SDValue DownVL = VL;
2673       if (LoV)
2674         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2675       Res =
2676           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2677                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2678     }
2679     if (LoV)
2680       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2681                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2682 
2683     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2684   }
2685 
2686   // Detect an interleave shuffle and lower to
2687   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2688   bool SwapSources;
2689   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2690     // Swap sources if needed.
2691     if (SwapSources)
2692       std::swap(V1, V2);
2693 
2694     // Extract the lower half of the vectors.
2695     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2696     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2697                      DAG.getConstant(0, DL, XLenVT));
2698     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2699                      DAG.getConstant(0, DL, XLenVT));
2700 
2701     // Double the element width and halve the number of elements in an int type.
2702     unsigned EltBits = VT.getScalarSizeInBits();
2703     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2704     MVT WideIntVT =
2705         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2706     // Convert this to a scalable vector. We need to base this on the
2707     // destination size to ensure there's always a type with a smaller LMUL.
2708     MVT WideIntContainerVT =
2709         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2710 
2711     // Convert sources to scalable vectors with the same element count as the
2712     // larger type.
2713     MVT HalfContainerVT = MVT::getVectorVT(
2714         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2715     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2716     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2717 
2718     // Cast sources to integer.
2719     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2720     MVT IntHalfVT =
2721         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2722     V1 = DAG.getBitcast(IntHalfVT, V1);
2723     V2 = DAG.getBitcast(IntHalfVT, V2);
2724 
2725     // Freeze V2 since we use it twice and we need to be sure that the add and
2726     // multiply see the same value.
2727     V2 = DAG.getFreeze(V2);
2728 
2729     // Recreate TrueMask using the widened type's element count.
2730     MVT MaskVT =
2731         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2732     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2733 
2734     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2735     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2736                               V2, TrueMask, VL);
2737     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2738     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2739                                      DAG.getUNDEF(IntHalfVT),
2740                                      DAG.getAllOnesConstant(DL, XLenVT));
2741     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2742                                    V2, Multiplier, TrueMask, VL);
2743     // Add the new copies to our previous addition giving us 2^eltbits copies of
2744     // V2. This is equivalent to shifting V2 left by eltbits. This should
2745     // combine with the vwmulu.vv above to form vwmaccu.vv.
2746     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2747                       TrueMask, VL);
2748     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2749     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2750     // vector VT.
2751     ContainerVT =
2752         MVT::getVectorVT(VT.getVectorElementType(),
2753                          WideIntContainerVT.getVectorElementCount() * 2);
2754     Add = DAG.getBitcast(ContainerVT, Add);
2755     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2756   }
2757 
2758   // Detect shuffles which can be re-expressed as vector selects; these are
2759   // shuffles in which each element in the destination is taken from an element
2760   // at the corresponding index in either source vectors.
2761   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2762     int MaskIndex = MaskIdx.value();
2763     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2764   });
2765 
2766   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2767 
2768   SmallVector<SDValue> MaskVals;
2769   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2770   // merged with a second vrgather.
2771   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2772 
2773   // By default we preserve the original operand order, and use a mask to
2774   // select LHS as true and RHS as false. However, since RVV vector selects may
2775   // feature splats but only on the LHS, we may choose to invert our mask and
2776   // instead select between RHS and LHS.
2777   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2778   bool InvertMask = IsSelect == SwapOps;
2779 
2780   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2781   // half.
2782   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2783 
2784   // Now construct the mask that will be used by the vselect or blended
2785   // vrgather operation. For vrgathers, construct the appropriate indices into
2786   // each vector.
2787   for (int MaskIndex : Mask) {
2788     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2789     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2790     if (!IsSelect) {
2791       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2792       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2793                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2794                                      : DAG.getUNDEF(XLenVT));
2795       GatherIndicesRHS.push_back(
2796           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2797                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2798       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2799         ++LHSIndexCounts[MaskIndex];
2800       if (!IsLHSOrUndefIndex)
2801         ++RHSIndexCounts[MaskIndex - NumElts];
2802     }
2803   }
2804 
2805   if (SwapOps) {
2806     std::swap(V1, V2);
2807     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2808   }
2809 
2810   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2811   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2812   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2813 
2814   if (IsSelect)
2815     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2816 
2817   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2818     // On such a large vector we're unable to use i8 as the index type.
2819     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2820     // may involve vector splitting if we're already at LMUL=8, or our
2821     // user-supplied maximum fixed-length LMUL.
2822     return SDValue();
2823   }
2824 
2825   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2826   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2827   MVT IndexVT = VT.changeTypeToInteger();
2828   // Since we can't introduce illegal index types at this stage, use i16 and
2829   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2830   // than XLenVT.
2831   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2832     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2833     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2834   }
2835 
2836   MVT IndexContainerVT =
2837       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2838 
2839   SDValue Gather;
2840   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2841   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2842   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2843     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2844                               Subtarget);
2845   } else {
2846     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2847     // If only one index is used, we can use a "splat" vrgather.
2848     // TODO: We can splat the most-common index and fix-up any stragglers, if
2849     // that's beneficial.
2850     if (LHSIndexCounts.size() == 1) {
2851       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2852       Gather =
2853           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2854                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2855     } else {
2856       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2857       LHSIndices =
2858           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2859 
2860       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2861                            TrueMask, VL);
2862     }
2863   }
2864 
2865   // If a second vector operand is used by this shuffle, blend it in with an
2866   // additional vrgather.
2867   if (!V2.isUndef()) {
2868     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2869     // If only one index is used, we can use a "splat" vrgather.
2870     // TODO: We can splat the most-common index and fix-up any stragglers, if
2871     // that's beneficial.
2872     if (RHSIndexCounts.size() == 1) {
2873       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2874       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2875                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2876     } else {
2877       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2878       RHSIndices =
2879           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2880       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2881                        VL);
2882     }
2883 
2884     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2885     SelectMask =
2886         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2887 
2888     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2889                          Gather, VL);
2890   }
2891 
2892   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2893 }
2894 
2895 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2896   // Support splats for any type. These should type legalize well.
2897   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2898     return true;
2899 
2900   // Only support legal VTs for other shuffles for now.
2901   if (!isTypeLegal(VT))
2902     return false;
2903 
2904   MVT SVT = VT.getSimpleVT();
2905 
2906   bool SwapSources;
2907   int LoSrc, HiSrc;
2908   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2909          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2910 }
2911 
2912 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2913                                      SDLoc DL, SelectionDAG &DAG,
2914                                      const RISCVSubtarget &Subtarget) {
2915   if (VT.isScalableVector())
2916     return DAG.getFPExtendOrRound(Op, DL, VT);
2917   assert(VT.isFixedLengthVector() &&
2918          "Unexpected value type for RVV FP extend/round lowering");
2919   SDValue Mask, VL;
2920   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2921   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2922                         ? RISCVISD::FP_EXTEND_VL
2923                         : RISCVISD::FP_ROUND_VL;
2924   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2925 }
2926 
2927 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2928 // the exponent.
2929 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2930   MVT VT = Op.getSimpleValueType();
2931   unsigned EltSize = VT.getScalarSizeInBits();
2932   SDValue Src = Op.getOperand(0);
2933   SDLoc DL(Op);
2934 
2935   // We need a FP type that can represent the value.
2936   // TODO: Use f16 for i8 when possible?
2937   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2938   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2939 
2940   // Legal types should have been checked in the RISCVTargetLowering
2941   // constructor.
2942   // TODO: Splitting may make sense in some cases.
2943   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2944          "Expected legal float type!");
2945 
2946   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2947   // The trailing zero count is equal to log2 of this single bit value.
2948   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2949     SDValue Neg =
2950         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2951     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2952   }
2953 
2954   // We have a legal FP type, convert to it.
2955   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2956   // Bitcast to integer and shift the exponent to the LSB.
2957   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2958   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2959   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2960   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2961                               DAG.getConstant(ShiftAmt, DL, IntVT));
2962   // Truncate back to original type to allow vnsrl.
2963   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2964   // The exponent contains log2 of the value in biased form.
2965   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2966 
2967   // For trailing zeros, we just need to subtract the bias.
2968   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2969     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2970                        DAG.getConstant(ExponentBias, DL, VT));
2971 
2972   // For leading zeros, we need to remove the bias and convert from log2 to
2973   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2974   unsigned Adjust = ExponentBias + (EltSize - 1);
2975   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2976 }
2977 
2978 // While RVV has alignment restrictions, we should always be able to load as a
2979 // legal equivalently-sized byte-typed vector instead. This method is
2980 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2981 // the load is already correctly-aligned, it returns SDValue().
2982 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2983                                                     SelectionDAG &DAG) const {
2984   auto *Load = cast<LoadSDNode>(Op);
2985   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2986 
2987   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2988                                      Load->getMemoryVT(),
2989                                      *Load->getMemOperand()))
2990     return SDValue();
2991 
2992   SDLoc DL(Op);
2993   MVT VT = Op.getSimpleValueType();
2994   unsigned EltSizeBits = VT.getScalarSizeInBits();
2995   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2996          "Unexpected unaligned RVV load type");
2997   MVT NewVT =
2998       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2999   assert(NewVT.isValid() &&
3000          "Expecting equally-sized RVV vector types to be legal");
3001   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3002                           Load->getPointerInfo(), Load->getOriginalAlign(),
3003                           Load->getMemOperand()->getFlags());
3004   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3005 }
3006 
3007 // While RVV has alignment restrictions, we should always be able to store as a
3008 // legal equivalently-sized byte-typed vector instead. This method is
3009 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3010 // returns SDValue() if the store is already correctly aligned.
3011 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3012                                                      SelectionDAG &DAG) const {
3013   auto *Store = cast<StoreSDNode>(Op);
3014   assert(Store && Store->getValue().getValueType().isVector() &&
3015          "Expected vector store");
3016 
3017   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3018                                      Store->getMemoryVT(),
3019                                      *Store->getMemOperand()))
3020     return SDValue();
3021 
3022   SDLoc DL(Op);
3023   SDValue StoredVal = Store->getValue();
3024   MVT VT = StoredVal.getSimpleValueType();
3025   unsigned EltSizeBits = VT.getScalarSizeInBits();
3026   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3027          "Unexpected unaligned RVV store type");
3028   MVT NewVT =
3029       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3030   assert(NewVT.isValid() &&
3031          "Expecting equally-sized RVV vector types to be legal");
3032   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3033   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3034                       Store->getPointerInfo(), Store->getOriginalAlign(),
3035                       Store->getMemOperand()->getFlags());
3036 }
3037 
3038 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3039                                             SelectionDAG &DAG) const {
3040   switch (Op.getOpcode()) {
3041   default:
3042     report_fatal_error("unimplemented operand");
3043   case ISD::GlobalAddress:
3044     return lowerGlobalAddress(Op, DAG);
3045   case ISD::BlockAddress:
3046     return lowerBlockAddress(Op, DAG);
3047   case ISD::ConstantPool:
3048     return lowerConstantPool(Op, DAG);
3049   case ISD::JumpTable:
3050     return lowerJumpTable(Op, DAG);
3051   case ISD::GlobalTLSAddress:
3052     return lowerGlobalTLSAddress(Op, DAG);
3053   case ISD::SELECT:
3054     return lowerSELECT(Op, DAG);
3055   case ISD::BRCOND:
3056     return lowerBRCOND(Op, DAG);
3057   case ISD::VASTART:
3058     return lowerVASTART(Op, DAG);
3059   case ISD::FRAMEADDR:
3060     return lowerFRAMEADDR(Op, DAG);
3061   case ISD::RETURNADDR:
3062     return lowerRETURNADDR(Op, DAG);
3063   case ISD::SHL_PARTS:
3064     return lowerShiftLeftParts(Op, DAG);
3065   case ISD::SRA_PARTS:
3066     return lowerShiftRightParts(Op, DAG, true);
3067   case ISD::SRL_PARTS:
3068     return lowerShiftRightParts(Op, DAG, false);
3069   case ISD::BITCAST: {
3070     SDLoc DL(Op);
3071     EVT VT = Op.getValueType();
3072     SDValue Op0 = Op.getOperand(0);
3073     EVT Op0VT = Op0.getValueType();
3074     MVT XLenVT = Subtarget.getXLenVT();
3075     if (VT.isFixedLengthVector()) {
3076       // We can handle fixed length vector bitcasts with a simple replacement
3077       // in isel.
3078       if (Op0VT.isFixedLengthVector())
3079         return Op;
3080       // When bitcasting from scalar to fixed-length vector, insert the scalar
3081       // into a one-element vector of the result type, and perform a vector
3082       // bitcast.
3083       if (!Op0VT.isVector()) {
3084         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3085         if (!isTypeLegal(BVT))
3086           return SDValue();
3087         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3088                                               DAG.getUNDEF(BVT), Op0,
3089                                               DAG.getConstant(0, DL, XLenVT)));
3090       }
3091       return SDValue();
3092     }
3093     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3094     // thus: bitcast the vector to a one-element vector type whose element type
3095     // is the same as the result type, and extract the first element.
3096     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3097       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3098       if (!isTypeLegal(BVT))
3099         return SDValue();
3100       SDValue BVec = DAG.getBitcast(BVT, Op0);
3101       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3102                          DAG.getConstant(0, DL, XLenVT));
3103     }
3104     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3105       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3106       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3107       return FPConv;
3108     }
3109     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3110         Subtarget.hasStdExtF()) {
3111       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3112       SDValue FPConv =
3113           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3114       return FPConv;
3115     }
3116     return SDValue();
3117   }
3118   case ISD::INTRINSIC_WO_CHAIN:
3119     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3120   case ISD::INTRINSIC_W_CHAIN:
3121     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3122   case ISD::INTRINSIC_VOID:
3123     return LowerINTRINSIC_VOID(Op, DAG);
3124   case ISD::BSWAP:
3125   case ISD::BITREVERSE: {
3126     MVT VT = Op.getSimpleValueType();
3127     SDLoc DL(Op);
3128     if (Subtarget.hasStdExtZbp()) {
3129       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3130       // Start with the maximum immediate value which is the bitwidth - 1.
3131       unsigned Imm = VT.getSizeInBits() - 1;
3132       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3133       if (Op.getOpcode() == ISD::BSWAP)
3134         Imm &= ~0x7U;
3135       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3136                          DAG.getConstant(Imm, DL, VT));
3137     }
3138     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3139     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3140     // Expand bitreverse to a bswap(rev8) followed by brev8.
3141     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3142     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3143     // as brev8 by an isel pattern.
3144     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3145                        DAG.getConstant(7, DL, VT));
3146   }
3147   case ISD::FSHL:
3148   case ISD::FSHR: {
3149     MVT VT = Op.getSimpleValueType();
3150     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3151     SDLoc DL(Op);
3152     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3153     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3154     // accidentally setting the extra bit.
3155     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3156     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3157                                 DAG.getConstant(ShAmtWidth, DL, VT));
3158     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3159     // instruction use different orders. fshl will return its first operand for
3160     // shift of zero, fshr will return its second operand. fsl and fsr both
3161     // return rs1 so the ISD nodes need to have different operand orders.
3162     // Shift amount is in rs2.
3163     SDValue Op0 = Op.getOperand(0);
3164     SDValue Op1 = Op.getOperand(1);
3165     unsigned Opc = RISCVISD::FSL;
3166     if (Op.getOpcode() == ISD::FSHR) {
3167       std::swap(Op0, Op1);
3168       Opc = RISCVISD::FSR;
3169     }
3170     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3171   }
3172   case ISD::TRUNCATE:
3173     // Only custom-lower vector truncates
3174     if (!Op.getSimpleValueType().isVector())
3175       return Op;
3176     return lowerVectorTruncLike(Op, DAG);
3177   case ISD::ANY_EXTEND:
3178   case ISD::ZERO_EXTEND:
3179     if (Op.getOperand(0).getValueType().isVector() &&
3180         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3181       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3182     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3183   case ISD::SIGN_EXTEND:
3184     if (Op.getOperand(0).getValueType().isVector() &&
3185         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3186       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3187     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3188   case ISD::SPLAT_VECTOR_PARTS:
3189     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3190   case ISD::INSERT_VECTOR_ELT:
3191     return lowerINSERT_VECTOR_ELT(Op, DAG);
3192   case ISD::EXTRACT_VECTOR_ELT:
3193     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3194   case ISD::VSCALE: {
3195     MVT VT = Op.getSimpleValueType();
3196     SDLoc DL(Op);
3197     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3198     // We define our scalable vector types for lmul=1 to use a 64 bit known
3199     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3200     // vscale as VLENB / 8.
3201     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3202     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3203       report_fatal_error("Support for VLEN==32 is incomplete.");
3204     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3205       // We assume VLENB is a multiple of 8. We manually choose the best shift
3206       // here because SimplifyDemandedBits isn't always able to simplify it.
3207       uint64_t Val = Op.getConstantOperandVal(0);
3208       if (isPowerOf2_64(Val)) {
3209         uint64_t Log2 = Log2_64(Val);
3210         if (Log2 < 3)
3211           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3212                              DAG.getConstant(3 - Log2, DL, VT));
3213         if (Log2 > 3)
3214           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3215                              DAG.getConstant(Log2 - 3, DL, VT));
3216         return VLENB;
3217       }
3218       // If the multiplier is a multiple of 8, scale it down to avoid needing
3219       // to shift the VLENB value.
3220       if ((Val % 8) == 0)
3221         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3222                            DAG.getConstant(Val / 8, DL, VT));
3223     }
3224 
3225     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3226                                  DAG.getConstant(3, DL, VT));
3227     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3228   }
3229   case ISD::FPOWI: {
3230     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3231     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3232     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3233         Op.getOperand(1).getValueType() == MVT::i32) {
3234       SDLoc DL(Op);
3235       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3236       SDValue Powi =
3237           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3238       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3239                          DAG.getIntPtrConstant(0, DL));
3240     }
3241     return SDValue();
3242   }
3243   case ISD::FP_EXTEND: {
3244     // RVV can only do fp_extend to types double the size as the source. We
3245     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3246     // via f32.
3247     SDLoc DL(Op);
3248     MVT VT = Op.getSimpleValueType();
3249     SDValue Src = Op.getOperand(0);
3250     MVT SrcVT = Src.getSimpleValueType();
3251 
3252     // Prepare any fixed-length vector operands.
3253     MVT ContainerVT = VT;
3254     if (SrcVT.isFixedLengthVector()) {
3255       ContainerVT = getContainerForFixedLengthVector(VT);
3256       MVT SrcContainerVT =
3257           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3258       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3259     }
3260 
3261     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3262         SrcVT.getVectorElementType() != MVT::f16) {
3263       // For scalable vectors, we only need to close the gap between
3264       // vXf16->vXf64.
3265       if (!VT.isFixedLengthVector())
3266         return Op;
3267       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3268       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3269       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3270     }
3271 
3272     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3273     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3274     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3275         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3276 
3277     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3278                                            DL, DAG, Subtarget);
3279     if (VT.isFixedLengthVector())
3280       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3281     return Extend;
3282   }
3283   case ISD::FP_ROUND: {
3284     // RVV can only do fp_round to types half the size as the source. We
3285     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3286     // conversion instruction.
3287     SDLoc DL(Op);
3288     MVT VT = Op.getSimpleValueType();
3289     SDValue Src = Op.getOperand(0);
3290     MVT SrcVT = Src.getSimpleValueType();
3291 
3292     // Prepare any fixed-length vector operands.
3293     MVT ContainerVT = VT;
3294     if (VT.isFixedLengthVector()) {
3295       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3296       ContainerVT =
3297           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3298       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3299     }
3300 
3301     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3302         SrcVT.getVectorElementType() != MVT::f64) {
3303       // For scalable vectors, we only need to close the gap between
3304       // vXf64<->vXf16.
3305       if (!VT.isFixedLengthVector())
3306         return Op;
3307       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3308       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3309       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3310     }
3311 
3312     SDValue Mask, VL;
3313     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3314 
3315     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3316     SDValue IntermediateRound =
3317         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3318     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3319                                           DL, DAG, Subtarget);
3320 
3321     if (VT.isFixedLengthVector())
3322       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3323     return Round;
3324   }
3325   case ISD::FP_TO_SINT:
3326   case ISD::FP_TO_UINT:
3327   case ISD::SINT_TO_FP:
3328   case ISD::UINT_TO_FP: {
3329     // RVV can only do fp<->int conversions to types half/double the size as
3330     // the source. We custom-lower any conversions that do two hops into
3331     // sequences.
3332     MVT VT = Op.getSimpleValueType();
3333     if (!VT.isVector())
3334       return Op;
3335     SDLoc DL(Op);
3336     SDValue Src = Op.getOperand(0);
3337     MVT EltVT = VT.getVectorElementType();
3338     MVT SrcVT = Src.getSimpleValueType();
3339     MVT SrcEltVT = SrcVT.getVectorElementType();
3340     unsigned EltSize = EltVT.getSizeInBits();
3341     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3342     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3343            "Unexpected vector element types");
3344 
3345     bool IsInt2FP = SrcEltVT.isInteger();
3346     // Widening conversions
3347     if (EltSize > (2 * SrcEltSize)) {
3348       if (IsInt2FP) {
3349         // Do a regular integer sign/zero extension then convert to float.
3350         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3351                                       VT.getVectorElementCount());
3352         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3353                                  ? ISD::ZERO_EXTEND
3354                                  : ISD::SIGN_EXTEND;
3355         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3356         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3357       }
3358       // FP2Int
3359       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3360       // Do one doubling fp_extend then complete the operation by converting
3361       // to int.
3362       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3363       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3364       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3365     }
3366 
3367     // Narrowing conversions
3368     if (SrcEltSize > (2 * EltSize)) {
3369       if (IsInt2FP) {
3370         // One narrowing int_to_fp, then an fp_round.
3371         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3372         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3373         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3374         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3375       }
3376       // FP2Int
3377       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3378       // representable by the integer, the result is poison.
3379       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3380                                     VT.getVectorElementCount());
3381       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3382       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3383     }
3384 
3385     // Scalable vectors can exit here. Patterns will handle equally-sized
3386     // conversions halving/doubling ones.
3387     if (!VT.isFixedLengthVector())
3388       return Op;
3389 
3390     // For fixed-length vectors we lower to a custom "VL" node.
3391     unsigned RVVOpc = 0;
3392     switch (Op.getOpcode()) {
3393     default:
3394       llvm_unreachable("Impossible opcode");
3395     case ISD::FP_TO_SINT:
3396       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3397       break;
3398     case ISD::FP_TO_UINT:
3399       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3400       break;
3401     case ISD::SINT_TO_FP:
3402       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3403       break;
3404     case ISD::UINT_TO_FP:
3405       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3406       break;
3407     }
3408 
3409     MVT ContainerVT, SrcContainerVT;
3410     // Derive the reference container type from the larger vector type.
3411     if (SrcEltSize > EltSize) {
3412       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3413       ContainerVT =
3414           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3415     } else {
3416       ContainerVT = getContainerForFixedLengthVector(VT);
3417       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3418     }
3419 
3420     SDValue Mask, VL;
3421     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3422 
3423     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3424     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3425     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3426   }
3427   case ISD::FP_TO_SINT_SAT:
3428   case ISD::FP_TO_UINT_SAT:
3429     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3430   case ISD::FTRUNC:
3431   case ISD::FCEIL:
3432   case ISD::FFLOOR:
3433     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3434   case ISD::FROUND:
3435     return lowerFROUND(Op, DAG);
3436   case ISD::VECREDUCE_ADD:
3437   case ISD::VECREDUCE_UMAX:
3438   case ISD::VECREDUCE_SMAX:
3439   case ISD::VECREDUCE_UMIN:
3440   case ISD::VECREDUCE_SMIN:
3441     return lowerVECREDUCE(Op, DAG);
3442   case ISD::VECREDUCE_AND:
3443   case ISD::VECREDUCE_OR:
3444   case ISD::VECREDUCE_XOR:
3445     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3446       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3447     return lowerVECREDUCE(Op, DAG);
3448   case ISD::VECREDUCE_FADD:
3449   case ISD::VECREDUCE_SEQ_FADD:
3450   case ISD::VECREDUCE_FMIN:
3451   case ISD::VECREDUCE_FMAX:
3452     return lowerFPVECREDUCE(Op, DAG);
3453   case ISD::VP_REDUCE_ADD:
3454   case ISD::VP_REDUCE_UMAX:
3455   case ISD::VP_REDUCE_SMAX:
3456   case ISD::VP_REDUCE_UMIN:
3457   case ISD::VP_REDUCE_SMIN:
3458   case ISD::VP_REDUCE_FADD:
3459   case ISD::VP_REDUCE_SEQ_FADD:
3460   case ISD::VP_REDUCE_FMIN:
3461   case ISD::VP_REDUCE_FMAX:
3462     return lowerVPREDUCE(Op, DAG);
3463   case ISD::VP_REDUCE_AND:
3464   case ISD::VP_REDUCE_OR:
3465   case ISD::VP_REDUCE_XOR:
3466     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3467       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3468     return lowerVPREDUCE(Op, DAG);
3469   case ISD::INSERT_SUBVECTOR:
3470     return lowerINSERT_SUBVECTOR(Op, DAG);
3471   case ISD::EXTRACT_SUBVECTOR:
3472     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3473   case ISD::STEP_VECTOR:
3474     return lowerSTEP_VECTOR(Op, DAG);
3475   case ISD::VECTOR_REVERSE:
3476     return lowerVECTOR_REVERSE(Op, DAG);
3477   case ISD::VECTOR_SPLICE:
3478     return lowerVECTOR_SPLICE(Op, DAG);
3479   case ISD::BUILD_VECTOR:
3480     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3481   case ISD::SPLAT_VECTOR:
3482     if (Op.getValueType().getVectorElementType() == MVT::i1)
3483       return lowerVectorMaskSplat(Op, DAG);
3484     return SDValue();
3485   case ISD::VECTOR_SHUFFLE:
3486     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3487   case ISD::CONCAT_VECTORS: {
3488     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3489     // better than going through the stack, as the default expansion does.
3490     SDLoc DL(Op);
3491     MVT VT = Op.getSimpleValueType();
3492     unsigned NumOpElts =
3493         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3494     SDValue Vec = DAG.getUNDEF(VT);
3495     for (const auto &OpIdx : enumerate(Op->ops())) {
3496       SDValue SubVec = OpIdx.value();
3497       // Don't insert undef subvectors.
3498       if (SubVec.isUndef())
3499         continue;
3500       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3501                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3502     }
3503     return Vec;
3504   }
3505   case ISD::LOAD:
3506     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3507       return V;
3508     if (Op.getValueType().isFixedLengthVector())
3509       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3510     return Op;
3511   case ISD::STORE:
3512     if (auto V = expandUnalignedRVVStore(Op, DAG))
3513       return V;
3514     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3515       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3516     return Op;
3517   case ISD::MLOAD:
3518   case ISD::VP_LOAD:
3519     return lowerMaskedLoad(Op, DAG);
3520   case ISD::MSTORE:
3521   case ISD::VP_STORE:
3522     return lowerMaskedStore(Op, DAG);
3523   case ISD::SETCC:
3524     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3525   case ISD::ADD:
3526     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3527   case ISD::SUB:
3528     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3529   case ISD::MUL:
3530     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3531   case ISD::MULHS:
3532     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3533   case ISD::MULHU:
3534     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3535   case ISD::AND:
3536     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3537                                               RISCVISD::AND_VL);
3538   case ISD::OR:
3539     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3540                                               RISCVISD::OR_VL);
3541   case ISD::XOR:
3542     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3543                                               RISCVISD::XOR_VL);
3544   case ISD::SDIV:
3545     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3546   case ISD::SREM:
3547     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3548   case ISD::UDIV:
3549     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3550   case ISD::UREM:
3551     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3552   case ISD::SHL:
3553   case ISD::SRA:
3554   case ISD::SRL:
3555     if (Op.getSimpleValueType().isFixedLengthVector())
3556       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3557     // This can be called for an i32 shift amount that needs to be promoted.
3558     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3559            "Unexpected custom legalisation");
3560     return SDValue();
3561   case ISD::SADDSAT:
3562     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3563   case ISD::UADDSAT:
3564     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3565   case ISD::SSUBSAT:
3566     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3567   case ISD::USUBSAT:
3568     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3569   case ISD::FADD:
3570     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3571   case ISD::FSUB:
3572     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3573   case ISD::FMUL:
3574     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3575   case ISD::FDIV:
3576     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3577   case ISD::FNEG:
3578     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3579   case ISD::FABS:
3580     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3581   case ISD::FSQRT:
3582     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3583   case ISD::FMA:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3585   case ISD::SMIN:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3587   case ISD::SMAX:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3589   case ISD::UMIN:
3590     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3591   case ISD::UMAX:
3592     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3593   case ISD::FMINNUM:
3594     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3595   case ISD::FMAXNUM:
3596     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3597   case ISD::ABS:
3598     return lowerABS(Op, DAG);
3599   case ISD::CTLZ_ZERO_UNDEF:
3600   case ISD::CTTZ_ZERO_UNDEF:
3601     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3602   case ISD::VSELECT:
3603     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3604   case ISD::FCOPYSIGN:
3605     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3606   case ISD::MGATHER:
3607   case ISD::VP_GATHER:
3608     return lowerMaskedGather(Op, DAG);
3609   case ISD::MSCATTER:
3610   case ISD::VP_SCATTER:
3611     return lowerMaskedScatter(Op, DAG);
3612   case ISD::FLT_ROUNDS_:
3613     return lowerGET_ROUNDING(Op, DAG);
3614   case ISD::SET_ROUNDING:
3615     return lowerSET_ROUNDING(Op, DAG);
3616   case ISD::VP_SELECT:
3617     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3618   case ISD::VP_MERGE:
3619     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3620   case ISD::VP_ADD:
3621     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3622   case ISD::VP_SUB:
3623     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3624   case ISD::VP_MUL:
3625     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3626   case ISD::VP_SDIV:
3627     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3628   case ISD::VP_UDIV:
3629     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3630   case ISD::VP_SREM:
3631     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3632   case ISD::VP_UREM:
3633     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3634   case ISD::VP_AND:
3635     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3636   case ISD::VP_OR:
3637     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3638   case ISD::VP_XOR:
3639     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3640   case ISD::VP_ASHR:
3641     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3642   case ISD::VP_LSHR:
3643     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3644   case ISD::VP_SHL:
3645     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3646   case ISD::VP_FADD:
3647     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3648   case ISD::VP_FSUB:
3649     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3650   case ISD::VP_FMUL:
3651     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3652   case ISD::VP_FDIV:
3653     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3654   case ISD::VP_FNEG:
3655     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3656   case ISD::VP_FMA:
3657     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3658   case ISD::VP_SEXT:
3659   case ISD::VP_ZEXT:
3660     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3661       return lowerVPExtMaskOp(Op, DAG);
3662     return lowerVPOp(Op, DAG,
3663                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3664                                                     : RISCVISD::VZEXT_VL);
3665   case ISD::VP_TRUNC:
3666     return lowerVectorTruncLike(Op, DAG);
3667   case ISD::VP_FPTOSI:
3668     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3669   case ISD::VP_FPTOUI:
3670     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3671   case ISD::VP_SITOFP:
3672     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3673   case ISD::VP_UITOFP:
3674     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3675   case ISD::VP_SETCC:
3676     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3677   }
3678 }
3679 
3680 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3681                              SelectionDAG &DAG, unsigned Flags) {
3682   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3683 }
3684 
3685 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3686                              SelectionDAG &DAG, unsigned Flags) {
3687   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3688                                    Flags);
3689 }
3690 
3691 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3692                              SelectionDAG &DAG, unsigned Flags) {
3693   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3694                                    N->getOffset(), Flags);
3695 }
3696 
3697 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3698                              SelectionDAG &DAG, unsigned Flags) {
3699   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3700 }
3701 
3702 template <class NodeTy>
3703 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3704                                      bool IsLocal) const {
3705   SDLoc DL(N);
3706   EVT Ty = getPointerTy(DAG.getDataLayout());
3707 
3708   if (isPositionIndependent()) {
3709     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3710     if (IsLocal)
3711       // Use PC-relative addressing to access the symbol. This generates the
3712       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3713       // %pcrel_lo(auipc)).
3714       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3715 
3716     // Use PC-relative addressing to access the GOT for this symbol, then load
3717     // the address from the GOT. This generates the pattern (PseudoLA sym),
3718     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3719     SDValue Load =
3720         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3721     MachineFunction &MF = DAG.getMachineFunction();
3722     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3723         MachinePointerInfo::getGOT(MF),
3724         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3725             MachineMemOperand::MOInvariant,
3726         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3727     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3728     return Load;
3729   }
3730 
3731   switch (getTargetMachine().getCodeModel()) {
3732   default:
3733     report_fatal_error("Unsupported code model for lowering");
3734   case CodeModel::Small: {
3735     // Generate a sequence for accessing addresses within the first 2 GiB of
3736     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3737     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3738     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3739     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3740     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3741   }
3742   case CodeModel::Medium: {
3743     // Generate a sequence for accessing addresses within any 2GiB range within
3744     // the address space. This generates the pattern (PseudoLLA sym), which
3745     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3746     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3747     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3748   }
3749   }
3750 }
3751 
3752 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3753     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3754 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3755     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3756 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3757     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3758 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3759     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
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     MachineFunction &MF = DAG.getMachineFunction();
3821     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3822         MachinePointerInfo::getGOT(MF),
3823         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3824             MachineMemOperand::MOInvariant,
3825         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3826     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3827 
3828     // Add the thread pointer.
3829     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3830     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3831   }
3832 
3833   // Generate a sequence for accessing the address relative to the thread
3834   // pointer, with the appropriate adjustment for the thread pointer offset.
3835   // This generates the pattern
3836   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3837   SDValue AddrHi =
3838       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3839   SDValue AddrAdd =
3840       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3841   SDValue AddrLo =
3842       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3843 
3844   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3845   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3846   SDValue MNAdd = SDValue(
3847       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3848       0);
3849   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3850 }
3851 
3852 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3853                                                SelectionDAG &DAG) const {
3854   SDLoc DL(N);
3855   EVT Ty = getPointerTy(DAG.getDataLayout());
3856   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3857   const GlobalValue *GV = N->getGlobal();
3858 
3859   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3860   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3861   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3862   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3863   SDValue Load =
3864       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3865 
3866   // Prepare argument list to generate call.
3867   ArgListTy Args;
3868   ArgListEntry Entry;
3869   Entry.Node = Load;
3870   Entry.Ty = CallTy;
3871   Args.push_back(Entry);
3872 
3873   // Setup call to __tls_get_addr.
3874   TargetLowering::CallLoweringInfo CLI(DAG);
3875   CLI.setDebugLoc(DL)
3876       .setChain(DAG.getEntryNode())
3877       .setLibCallee(CallingConv::C, CallTy,
3878                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3879                     std::move(Args));
3880 
3881   return LowerCallTo(CLI).first;
3882 }
3883 
3884 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3885                                                    SelectionDAG &DAG) const {
3886   SDLoc DL(Op);
3887   EVT Ty = Op.getValueType();
3888   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3889   int64_t Offset = N->getOffset();
3890   MVT XLenVT = Subtarget.getXLenVT();
3891 
3892   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3893 
3894   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3895       CallingConv::GHC)
3896     report_fatal_error("In GHC calling convention TLS is not supported");
3897 
3898   SDValue Addr;
3899   switch (Model) {
3900   case TLSModel::LocalExec:
3901     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3902     break;
3903   case TLSModel::InitialExec:
3904     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3905     break;
3906   case TLSModel::LocalDynamic:
3907   case TLSModel::GeneralDynamic:
3908     Addr = getDynamicTLSAddr(N, DAG);
3909     break;
3910   }
3911 
3912   // In order to maximise the opportunity for common subexpression elimination,
3913   // emit a separate ADD node for the global address offset instead of folding
3914   // it in the global address node. Later peephole optimisations may choose to
3915   // fold it back in when profitable.
3916   if (Offset != 0)
3917     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3918                        DAG.getConstant(Offset, DL, XLenVT));
3919   return Addr;
3920 }
3921 
3922 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3923   SDValue CondV = Op.getOperand(0);
3924   SDValue TrueV = Op.getOperand(1);
3925   SDValue FalseV = Op.getOperand(2);
3926   SDLoc DL(Op);
3927   MVT VT = Op.getSimpleValueType();
3928   MVT XLenVT = Subtarget.getXLenVT();
3929 
3930   // Lower vector SELECTs to VSELECTs by splatting the condition.
3931   if (VT.isVector()) {
3932     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3933     SDValue CondSplat = VT.isScalableVector()
3934                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3935                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3936     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3937   }
3938 
3939   // If the result type is XLenVT and CondV is the output of a SETCC node
3940   // which also operated on XLenVT inputs, then merge the SETCC node into the
3941   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3942   // compare+branch instructions. i.e.:
3943   // (select (setcc lhs, rhs, cc), truev, falsev)
3944   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3945   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3946       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3947     SDValue LHS = CondV.getOperand(0);
3948     SDValue RHS = CondV.getOperand(1);
3949     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3950     ISD::CondCode CCVal = CC->get();
3951 
3952     // Special case for a select of 2 constants that have a diffence of 1.
3953     // Normally this is done by DAGCombine, but if the select is introduced by
3954     // type legalization or op legalization, we miss it. Restricting to SETLT
3955     // case for now because that is what signed saturating add/sub need.
3956     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3957     // but we would probably want to swap the true/false values if the condition
3958     // is SETGE/SETLE to avoid an XORI.
3959     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3960         CCVal == ISD::SETLT) {
3961       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3962       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3963       if (TrueVal - 1 == FalseVal)
3964         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3965       if (TrueVal + 1 == FalseVal)
3966         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3967     }
3968 
3969     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3970 
3971     SDValue TargetCC = DAG.getCondCode(CCVal);
3972     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3973     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3974   }
3975 
3976   // Otherwise:
3977   // (select condv, truev, falsev)
3978   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3979   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3980   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3981 
3982   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3983 
3984   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3985 }
3986 
3987 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3988   SDValue CondV = Op.getOperand(1);
3989   SDLoc DL(Op);
3990   MVT XLenVT = Subtarget.getXLenVT();
3991 
3992   if (CondV.getOpcode() == ISD::SETCC &&
3993       CondV.getOperand(0).getValueType() == XLenVT) {
3994     SDValue LHS = CondV.getOperand(0);
3995     SDValue RHS = CondV.getOperand(1);
3996     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3997 
3998     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3999 
4000     SDValue TargetCC = DAG.getCondCode(CCVal);
4001     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4002                        LHS, RHS, TargetCC, Op.getOperand(2));
4003   }
4004 
4005   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4006                      CondV, DAG.getConstant(0, DL, XLenVT),
4007                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4008 }
4009 
4010 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4011   MachineFunction &MF = DAG.getMachineFunction();
4012   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4013 
4014   SDLoc DL(Op);
4015   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4016                                  getPointerTy(MF.getDataLayout()));
4017 
4018   // vastart just stores the address of the VarArgsFrameIndex slot into the
4019   // memory location argument.
4020   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4021   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4022                       MachinePointerInfo(SV));
4023 }
4024 
4025 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4026                                             SelectionDAG &DAG) const {
4027   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4028   MachineFunction &MF = DAG.getMachineFunction();
4029   MachineFrameInfo &MFI = MF.getFrameInfo();
4030   MFI.setFrameAddressIsTaken(true);
4031   Register FrameReg = RI.getFrameRegister(MF);
4032   int XLenInBytes = Subtarget.getXLen() / 8;
4033 
4034   EVT VT = Op.getValueType();
4035   SDLoc DL(Op);
4036   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4037   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4038   while (Depth--) {
4039     int Offset = -(XLenInBytes * 2);
4040     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4041                               DAG.getIntPtrConstant(Offset, DL));
4042     FrameAddr =
4043         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4044   }
4045   return FrameAddr;
4046 }
4047 
4048 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4049                                              SelectionDAG &DAG) const {
4050   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4051   MachineFunction &MF = DAG.getMachineFunction();
4052   MachineFrameInfo &MFI = MF.getFrameInfo();
4053   MFI.setReturnAddressIsTaken(true);
4054   MVT XLenVT = Subtarget.getXLenVT();
4055   int XLenInBytes = Subtarget.getXLen() / 8;
4056 
4057   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4058     return SDValue();
4059 
4060   EVT VT = Op.getValueType();
4061   SDLoc DL(Op);
4062   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4063   if (Depth) {
4064     int Off = -XLenInBytes;
4065     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4066     SDValue Offset = DAG.getConstant(Off, DL, VT);
4067     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4068                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4069                        MachinePointerInfo());
4070   }
4071 
4072   // Return the value of the return address register, marking it an implicit
4073   // live-in.
4074   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4075   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4076 }
4077 
4078 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4079                                                  SelectionDAG &DAG) const {
4080   SDLoc DL(Op);
4081   SDValue Lo = Op.getOperand(0);
4082   SDValue Hi = Op.getOperand(1);
4083   SDValue Shamt = Op.getOperand(2);
4084   EVT VT = Lo.getValueType();
4085 
4086   // if Shamt-XLEN < 0: // Shamt < XLEN
4087   //   Lo = Lo << Shamt
4088   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4089   // else:
4090   //   Lo = 0
4091   //   Hi = Lo << (Shamt-XLEN)
4092 
4093   SDValue Zero = DAG.getConstant(0, DL, VT);
4094   SDValue One = DAG.getConstant(1, DL, VT);
4095   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4096   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4097   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4098   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4099 
4100   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4101   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4102   SDValue ShiftRightLo =
4103       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4104   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4105   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4106   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4107 
4108   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4109 
4110   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4111   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4112 
4113   SDValue Parts[2] = {Lo, Hi};
4114   return DAG.getMergeValues(Parts, DL);
4115 }
4116 
4117 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4118                                                   bool IsSRA) const {
4119   SDLoc DL(Op);
4120   SDValue Lo = Op.getOperand(0);
4121   SDValue Hi = Op.getOperand(1);
4122   SDValue Shamt = Op.getOperand(2);
4123   EVT VT = Lo.getValueType();
4124 
4125   // SRA expansion:
4126   //   if Shamt-XLEN < 0: // Shamt < XLEN
4127   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4128   //     Hi = Hi >>s Shamt
4129   //   else:
4130   //     Lo = Hi >>s (Shamt-XLEN);
4131   //     Hi = Hi >>s (XLEN-1)
4132   //
4133   // SRL expansion:
4134   //   if Shamt-XLEN < 0: // Shamt < XLEN
4135   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4136   //     Hi = Hi >>u Shamt
4137   //   else:
4138   //     Lo = Hi >>u (Shamt-XLEN);
4139   //     Hi = 0;
4140 
4141   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4142 
4143   SDValue Zero = DAG.getConstant(0, DL, VT);
4144   SDValue One = DAG.getConstant(1, DL, VT);
4145   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4146   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4147   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4148   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4149 
4150   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4151   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4152   SDValue ShiftLeftHi =
4153       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4154   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4155   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4156   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4157   SDValue HiFalse =
4158       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4159 
4160   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4161 
4162   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4163   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4164 
4165   SDValue Parts[2] = {Lo, Hi};
4166   return DAG.getMergeValues(Parts, DL);
4167 }
4168 
4169 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4170 // legal equivalently-sized i8 type, so we can use that as a go-between.
4171 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4172                                                   SelectionDAG &DAG) const {
4173   SDLoc DL(Op);
4174   MVT VT = Op.getSimpleValueType();
4175   SDValue SplatVal = Op.getOperand(0);
4176   // All-zeros or all-ones splats are handled specially.
4177   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4178     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4179     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4180   }
4181   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4182     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4183     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4184   }
4185   MVT XLenVT = Subtarget.getXLenVT();
4186   assert(SplatVal.getValueType() == XLenVT &&
4187          "Unexpected type for i1 splat value");
4188   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4189   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4190                          DAG.getConstant(1, DL, XLenVT));
4191   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4192   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4193   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4194 }
4195 
4196 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4197 // illegal (currently only vXi64 RV32).
4198 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4199 // them to VMV_V_X_VL.
4200 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4201                                                      SelectionDAG &DAG) const {
4202   SDLoc DL(Op);
4203   MVT VecVT = Op.getSimpleValueType();
4204   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4205          "Unexpected SPLAT_VECTOR_PARTS lowering");
4206 
4207   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4208   SDValue Lo = Op.getOperand(0);
4209   SDValue Hi = Op.getOperand(1);
4210 
4211   if (VecVT.isFixedLengthVector()) {
4212     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4213     SDLoc DL(Op);
4214     SDValue Mask, VL;
4215     std::tie(Mask, VL) =
4216         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4217 
4218     SDValue Res =
4219         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4220     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4221   }
4222 
4223   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4224     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4225     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4226     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4227     // node in order to try and match RVV vector/scalar instructions.
4228     if ((LoC >> 31) == HiC)
4229       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4230                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4231   }
4232 
4233   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4234   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4235       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4236       Hi.getConstantOperandVal(1) == 31)
4237     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4238                        DAG.getRegister(RISCV::X0, MVT::i32));
4239 
4240   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4241   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4242                      DAG.getUNDEF(VecVT), Lo, Hi,
4243                      DAG.getRegister(RISCV::X0, MVT::i32));
4244 }
4245 
4246 // Custom-lower extensions from mask vectors by using a vselect either with 1
4247 // for zero/any-extension or -1 for sign-extension:
4248 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4249 // Note that any-extension is lowered identically to zero-extension.
4250 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4251                                                 int64_t ExtTrueVal) const {
4252   SDLoc DL(Op);
4253   MVT VecVT = Op.getSimpleValueType();
4254   SDValue Src = Op.getOperand(0);
4255   // Only custom-lower extensions from mask types
4256   assert(Src.getValueType().isVector() &&
4257          Src.getValueType().getVectorElementType() == MVT::i1);
4258 
4259   if (VecVT.isScalableVector()) {
4260     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4261     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4262     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4263   }
4264 
4265   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4266   MVT I1ContainerVT =
4267       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4268 
4269   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4270 
4271   SDValue Mask, VL;
4272   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4273 
4274   MVT XLenVT = Subtarget.getXLenVT();
4275   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4276   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4277 
4278   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4279                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4280   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4281                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4282   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4283                                SplatTrueVal, SplatZero, VL);
4284 
4285   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4286 }
4287 
4288 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4289     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4290   MVT ExtVT = Op.getSimpleValueType();
4291   // Only custom-lower extensions from fixed-length vector types.
4292   if (!ExtVT.isFixedLengthVector())
4293     return Op;
4294   MVT VT = Op.getOperand(0).getSimpleValueType();
4295   // Grab the canonical container type for the extended type. Infer the smaller
4296   // type from that to ensure the same number of vector elements, as we know
4297   // the LMUL will be sufficient to hold the smaller type.
4298   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4299   // Get the extended container type manually to ensure the same number of
4300   // vector elements between source and dest.
4301   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4302                                      ContainerExtVT.getVectorElementCount());
4303 
4304   SDValue Op1 =
4305       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4306 
4307   SDLoc DL(Op);
4308   SDValue Mask, VL;
4309   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4310 
4311   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4312 
4313   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4314 }
4315 
4316 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4317 // setcc operation:
4318 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4319 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4320                                                       SelectionDAG &DAG) const {
4321   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4322   SDLoc DL(Op);
4323   EVT MaskVT = Op.getValueType();
4324   // Only expect to custom-lower truncations to mask types
4325   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4326          "Unexpected type for vector mask lowering");
4327   SDValue Src = Op.getOperand(0);
4328   MVT VecVT = Src.getSimpleValueType();
4329   SDValue Mask, VL;
4330   if (IsVPTrunc) {
4331     Mask = Op.getOperand(1);
4332     VL = Op.getOperand(2);
4333   }
4334   // If this is a fixed vector, we need to convert it to a scalable vector.
4335   MVT ContainerVT = VecVT;
4336 
4337   if (VecVT.isFixedLengthVector()) {
4338     ContainerVT = getContainerForFixedLengthVector(VecVT);
4339     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4340     if (IsVPTrunc) {
4341       MVT MaskContainerVT =
4342           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4343       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4344     }
4345   }
4346 
4347   if (!IsVPTrunc) {
4348     std::tie(Mask, VL) =
4349         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4350   }
4351 
4352   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4353   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4354 
4355   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4356                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4357   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4358                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4359 
4360   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4361   SDValue Trunc =
4362       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4363   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4364                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4365   if (MaskVT.isFixedLengthVector())
4366     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4367   return Trunc;
4368 }
4369 
4370 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4371                                                   SelectionDAG &DAG) const {
4372   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4373   SDLoc DL(Op);
4374 
4375   MVT VT = Op.getSimpleValueType();
4376   // Only custom-lower vector truncates
4377   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4378 
4379   // Truncates to mask types are handled differently
4380   if (VT.getVectorElementType() == MVT::i1)
4381     return lowerVectorMaskTruncLike(Op, DAG);
4382 
4383   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4384   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4385   // truncate by one power of two at a time.
4386   MVT DstEltVT = VT.getVectorElementType();
4387 
4388   SDValue Src = Op.getOperand(0);
4389   MVT SrcVT = Src.getSimpleValueType();
4390   MVT SrcEltVT = SrcVT.getVectorElementType();
4391 
4392   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4393          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4394          "Unexpected vector truncate lowering");
4395 
4396   MVT ContainerVT = SrcVT;
4397   SDValue Mask, VL;
4398   if (IsVPTrunc) {
4399     Mask = Op.getOperand(1);
4400     VL = Op.getOperand(2);
4401   }
4402   if (SrcVT.isFixedLengthVector()) {
4403     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4404     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4405     if (IsVPTrunc) {
4406       MVT MaskVT =
4407           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4408       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4409     }
4410   }
4411 
4412   SDValue Result = Src;
4413   if (!IsVPTrunc) {
4414     std::tie(Mask, VL) =
4415         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4416   }
4417 
4418   LLVMContext &Context = *DAG.getContext();
4419   const ElementCount Count = ContainerVT.getVectorElementCount();
4420   do {
4421     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4422     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4423     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4424                          Mask, VL);
4425   } while (SrcEltVT != DstEltVT);
4426 
4427   if (SrcVT.isFixedLengthVector())
4428     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4429 
4430   return Result;
4431 }
4432 
4433 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4434 // first position of a vector, and that vector is slid up to the insert index.
4435 // By limiting the active vector length to index+1 and merging with the
4436 // original vector (with an undisturbed tail policy for elements >= VL), we
4437 // achieve the desired result of leaving all elements untouched except the one
4438 // at VL-1, which is replaced with the desired value.
4439 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4440                                                     SelectionDAG &DAG) const {
4441   SDLoc DL(Op);
4442   MVT VecVT = Op.getSimpleValueType();
4443   SDValue Vec = Op.getOperand(0);
4444   SDValue Val = Op.getOperand(1);
4445   SDValue Idx = Op.getOperand(2);
4446 
4447   if (VecVT.getVectorElementType() == MVT::i1) {
4448     // FIXME: For now we just promote to an i8 vector and insert into that,
4449     // but this is probably not optimal.
4450     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4451     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4452     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4453     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4454   }
4455 
4456   MVT ContainerVT = VecVT;
4457   // If the operand is a fixed-length vector, convert to a scalable one.
4458   if (VecVT.isFixedLengthVector()) {
4459     ContainerVT = getContainerForFixedLengthVector(VecVT);
4460     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4461   }
4462 
4463   MVT XLenVT = Subtarget.getXLenVT();
4464 
4465   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4466   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4467   // Even i64-element vectors on RV32 can be lowered without scalar
4468   // legalization if the most-significant 32 bits of the value are not affected
4469   // by the sign-extension of the lower 32 bits.
4470   // TODO: We could also catch sign extensions of a 32-bit value.
4471   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4472     const auto *CVal = cast<ConstantSDNode>(Val);
4473     if (isInt<32>(CVal->getSExtValue())) {
4474       IsLegalInsert = true;
4475       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4476     }
4477   }
4478 
4479   SDValue Mask, VL;
4480   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4481 
4482   SDValue ValInVec;
4483 
4484   if (IsLegalInsert) {
4485     unsigned Opc =
4486         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4487     if (isNullConstant(Idx)) {
4488       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4489       if (!VecVT.isFixedLengthVector())
4490         return Vec;
4491       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4492     }
4493     ValInVec =
4494         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4495   } else {
4496     // On RV32, i64-element vectors must be specially handled to place the
4497     // value at element 0, by using two vslide1up instructions in sequence on
4498     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4499     // this.
4500     SDValue One = DAG.getConstant(1, DL, XLenVT);
4501     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4502     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4503     MVT I32ContainerVT =
4504         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4505     SDValue I32Mask =
4506         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4507     // Limit the active VL to two.
4508     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4509     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4510     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4511     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4512                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4513     // First slide in the hi value, then the lo in underneath it.
4514     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4515                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4516                            I32Mask, InsertI64VL);
4517     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4518                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4519                            I32Mask, InsertI64VL);
4520     // Bitcast back to the right container type.
4521     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4522   }
4523 
4524   // Now that the value is in a vector, slide it into position.
4525   SDValue InsertVL =
4526       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4527   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4528                                 ValInVec, Idx, Mask, InsertVL);
4529   if (!VecVT.isFixedLengthVector())
4530     return Slideup;
4531   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4532 }
4533 
4534 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4535 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4536 // types this is done using VMV_X_S to allow us to glean information about the
4537 // sign bits of the result.
4538 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4539                                                      SelectionDAG &DAG) const {
4540   SDLoc DL(Op);
4541   SDValue Idx = Op.getOperand(1);
4542   SDValue Vec = Op.getOperand(0);
4543   EVT EltVT = Op.getValueType();
4544   MVT VecVT = Vec.getSimpleValueType();
4545   MVT XLenVT = Subtarget.getXLenVT();
4546 
4547   if (VecVT.getVectorElementType() == MVT::i1) {
4548     if (VecVT.isFixedLengthVector()) {
4549       unsigned NumElts = VecVT.getVectorNumElements();
4550       if (NumElts >= 8) {
4551         MVT WideEltVT;
4552         unsigned WidenVecLen;
4553         SDValue ExtractElementIdx;
4554         SDValue ExtractBitIdx;
4555         unsigned MaxEEW = Subtarget.getELEN();
4556         MVT LargestEltVT = MVT::getIntegerVT(
4557             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4558         if (NumElts <= LargestEltVT.getSizeInBits()) {
4559           assert(isPowerOf2_32(NumElts) &&
4560                  "the number of elements should be power of 2");
4561           WideEltVT = MVT::getIntegerVT(NumElts);
4562           WidenVecLen = 1;
4563           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4564           ExtractBitIdx = Idx;
4565         } else {
4566           WideEltVT = LargestEltVT;
4567           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4568           // extract element index = index / element width
4569           ExtractElementIdx = DAG.getNode(
4570               ISD::SRL, DL, XLenVT, Idx,
4571               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4572           // mask bit index = index % element width
4573           ExtractBitIdx = DAG.getNode(
4574               ISD::AND, DL, XLenVT, Idx,
4575               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4576         }
4577         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4578         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4579         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4580                                          Vec, ExtractElementIdx);
4581         // Extract the bit from GPR.
4582         SDValue ShiftRight =
4583             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4584         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4585                            DAG.getConstant(1, DL, XLenVT));
4586       }
4587     }
4588     // Otherwise, promote to an i8 vector and extract from that.
4589     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4590     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4591     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4592   }
4593 
4594   // If this is a fixed vector, we need to convert it to a scalable vector.
4595   MVT ContainerVT = VecVT;
4596   if (VecVT.isFixedLengthVector()) {
4597     ContainerVT = getContainerForFixedLengthVector(VecVT);
4598     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4599   }
4600 
4601   // If the index is 0, the vector is already in the right position.
4602   if (!isNullConstant(Idx)) {
4603     // Use a VL of 1 to avoid processing more elements than we need.
4604     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4605     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4606     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4607     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4608                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4609   }
4610 
4611   if (!EltVT.isInteger()) {
4612     // Floating-point extracts are handled in TableGen.
4613     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4614                        DAG.getConstant(0, DL, XLenVT));
4615   }
4616 
4617   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4618   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4619 }
4620 
4621 // Some RVV intrinsics may claim that they want an integer operand to be
4622 // promoted or expanded.
4623 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4624                                            const RISCVSubtarget &Subtarget) {
4625   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4626           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4627          "Unexpected opcode");
4628 
4629   if (!Subtarget.hasVInstructions())
4630     return SDValue();
4631 
4632   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4633   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4634   SDLoc DL(Op);
4635 
4636   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4637       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4638   if (!II || !II->hasScalarOperand())
4639     return SDValue();
4640 
4641   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4642   assert(SplatOp < Op.getNumOperands());
4643 
4644   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4645   SDValue &ScalarOp = Operands[SplatOp];
4646   MVT OpVT = ScalarOp.getSimpleValueType();
4647   MVT XLenVT = Subtarget.getXLenVT();
4648 
4649   // If this isn't a scalar, or its type is XLenVT we're done.
4650   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4651     return SDValue();
4652 
4653   // Simplest case is that the operand needs to be promoted to XLenVT.
4654   if (OpVT.bitsLT(XLenVT)) {
4655     // If the operand is a constant, sign extend to increase our chances
4656     // of being able to use a .vi instruction. ANY_EXTEND would become a
4657     // a zero extend and the simm5 check in isel would fail.
4658     // FIXME: Should we ignore the upper bits in isel instead?
4659     unsigned ExtOpc =
4660         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4661     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4662     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4663   }
4664 
4665   // Use the previous operand to get the vXi64 VT. The result might be a mask
4666   // VT for compares. Using the previous operand assumes that the previous
4667   // operand will never have a smaller element size than a scalar operand and
4668   // that a widening operation never uses SEW=64.
4669   // NOTE: If this fails the below assert, we can probably just find the
4670   // element count from any operand or result and use it to construct the VT.
4671   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4672   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4673 
4674   // The more complex case is when the scalar is larger than XLenVT.
4675   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4676          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4677 
4678   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4679   // instruction to sign-extend since SEW>XLEN.
4680   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4681     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4682     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4683   }
4684 
4685   switch (IntNo) {
4686   case Intrinsic::riscv_vslide1up:
4687   case Intrinsic::riscv_vslide1down:
4688   case Intrinsic::riscv_vslide1up_mask:
4689   case Intrinsic::riscv_vslide1down_mask: {
4690     // We need to special case these when the scalar is larger than XLen.
4691     unsigned NumOps = Op.getNumOperands();
4692     bool IsMasked = NumOps == 7;
4693 
4694     // Convert the vector source to the equivalent nxvXi32 vector.
4695     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4696     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4697 
4698     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4699                                    DAG.getConstant(0, DL, XLenVT));
4700     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4701                                    DAG.getConstant(1, DL, XLenVT));
4702 
4703     // Double the VL since we halved SEW.
4704     SDValue AVL = getVLOperand(Op);
4705     SDValue I32VL;
4706 
4707     // Optimize for constant AVL
4708     if (isa<ConstantSDNode>(AVL)) {
4709       unsigned EltSize = VT.getScalarSizeInBits();
4710       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4711 
4712       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4713       unsigned MaxVLMAX =
4714           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4715 
4716       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4717       unsigned MinVLMAX =
4718           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4719 
4720       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4721       if (AVLInt <= MinVLMAX) {
4722         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4723       } else if (AVLInt >= 2 * MaxVLMAX) {
4724         // Just set vl to VLMAX in this situation
4725         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4726         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4727         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4728         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4729         SDValue SETVLMAX = DAG.getTargetConstant(
4730             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4731         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4732                             LMUL);
4733       } else {
4734         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4735         // is related to the hardware implementation.
4736         // So let the following code handle
4737       }
4738     }
4739     if (!I32VL) {
4740       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4741       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4742       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4743       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4744       SDValue SETVL =
4745           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4746       // Using vsetvli instruction to get actually used length which related to
4747       // the hardware implementation
4748       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4749                                SEW, LMUL);
4750       I32VL =
4751           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4752     }
4753 
4754     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4755     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4756 
4757     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4758     // instructions.
4759     SDValue Passthru;
4760     if (IsMasked)
4761       Passthru = DAG.getUNDEF(I32VT);
4762     else
4763       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4764 
4765     if (IntNo == Intrinsic::riscv_vslide1up ||
4766         IntNo == Intrinsic::riscv_vslide1up_mask) {
4767       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4768                         ScalarHi, I32Mask, I32VL);
4769       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4770                         ScalarLo, I32Mask, I32VL);
4771     } else {
4772       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4773                         ScalarLo, I32Mask, I32VL);
4774       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4775                         ScalarHi, I32Mask, I32VL);
4776     }
4777 
4778     // Convert back to nxvXi64.
4779     Vec = DAG.getBitcast(VT, Vec);
4780 
4781     if (!IsMasked)
4782       return Vec;
4783     // Apply mask after the operation.
4784     SDValue Mask = Operands[NumOps - 3];
4785     SDValue MaskedOff = Operands[1];
4786     // Assume Policy operand is the last operand.
4787     uint64_t Policy =
4788         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4789     // We don't need to select maskedoff if it's undef.
4790     if (MaskedOff.isUndef())
4791       return Vec;
4792     // TAMU
4793     if (Policy == RISCVII::TAIL_AGNOSTIC)
4794       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4795                          AVL);
4796     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4797     // It's fine because vmerge does not care mask policy.
4798     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4799                        AVL);
4800   }
4801   }
4802 
4803   // We need to convert the scalar to a splat vector.
4804   SDValue VL = getVLOperand(Op);
4805   assert(VL.getValueType() == XLenVT);
4806   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4807   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4808 }
4809 
4810 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4811                                                      SelectionDAG &DAG) const {
4812   unsigned IntNo = Op.getConstantOperandVal(0);
4813   SDLoc DL(Op);
4814   MVT XLenVT = Subtarget.getXLenVT();
4815 
4816   switch (IntNo) {
4817   default:
4818     break; // Don't custom lower most intrinsics.
4819   case Intrinsic::thread_pointer: {
4820     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4821     return DAG.getRegister(RISCV::X4, PtrVT);
4822   }
4823   case Intrinsic::riscv_orc_b:
4824   case Intrinsic::riscv_brev8: {
4825     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4826     unsigned Opc =
4827         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4828     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4829                        DAG.getConstant(7, DL, XLenVT));
4830   }
4831   case Intrinsic::riscv_grev:
4832   case Intrinsic::riscv_gorc: {
4833     unsigned Opc =
4834         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4835     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4836   }
4837   case Intrinsic::riscv_zip:
4838   case Intrinsic::riscv_unzip: {
4839     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4840     // For i32 the immediate is 15. For i64 the immediate is 31.
4841     unsigned Opc =
4842         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4843     unsigned BitWidth = Op.getValueSizeInBits();
4844     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4845     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4846                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4847   }
4848   case Intrinsic::riscv_shfl:
4849   case Intrinsic::riscv_unshfl: {
4850     unsigned Opc =
4851         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4852     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4853   }
4854   case Intrinsic::riscv_bcompress:
4855   case Intrinsic::riscv_bdecompress: {
4856     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4857                                                        : RISCVISD::BDECOMPRESS;
4858     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4859   }
4860   case Intrinsic::riscv_bfp:
4861     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4862                        Op.getOperand(2));
4863   case Intrinsic::riscv_fsl:
4864     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4865                        Op.getOperand(2), Op.getOperand(3));
4866   case Intrinsic::riscv_fsr:
4867     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4868                        Op.getOperand(2), Op.getOperand(3));
4869   case Intrinsic::riscv_vmv_x_s:
4870     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4871     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4872                        Op.getOperand(1));
4873   case Intrinsic::riscv_vmv_v_x:
4874     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4875                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4876                             Subtarget);
4877   case Intrinsic::riscv_vfmv_v_f:
4878     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4879                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4880   case Intrinsic::riscv_vmv_s_x: {
4881     SDValue Scalar = Op.getOperand(2);
4882 
4883     if (Scalar.getValueType().bitsLE(XLenVT)) {
4884       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4885       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4886                          Op.getOperand(1), Scalar, Op.getOperand(3));
4887     }
4888 
4889     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4890 
4891     // This is an i64 value that lives in two scalar registers. We have to
4892     // insert this in a convoluted way. First we build vXi64 splat containing
4893     // the two values that we assemble using some bit math. Next we'll use
4894     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4895     // to merge element 0 from our splat into the source vector.
4896     // FIXME: This is probably not the best way to do this, but it is
4897     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4898     // point.
4899     //   sw lo, (a0)
4900     //   sw hi, 4(a0)
4901     //   vlse vX, (a0)
4902     //
4903     //   vid.v      vVid
4904     //   vmseq.vx   mMask, vVid, 0
4905     //   vmerge.vvm vDest, vSrc, vVal, mMask
4906     MVT VT = Op.getSimpleValueType();
4907     SDValue Vec = Op.getOperand(1);
4908     SDValue VL = getVLOperand(Op);
4909 
4910     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4911     if (Op.getOperand(1).isUndef())
4912       return SplattedVal;
4913     SDValue SplattedIdx =
4914         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4915                     DAG.getConstant(0, DL, MVT::i32), VL);
4916 
4917     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4918     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4919     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4920     SDValue SelectCond =
4921         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4922                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4923     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4924                        Vec, VL);
4925   }
4926   }
4927 
4928   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4929 }
4930 
4931 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4932                                                     SelectionDAG &DAG) const {
4933   unsigned IntNo = Op.getConstantOperandVal(1);
4934   switch (IntNo) {
4935   default:
4936     break;
4937   case Intrinsic::riscv_masked_strided_load: {
4938     SDLoc DL(Op);
4939     MVT XLenVT = Subtarget.getXLenVT();
4940 
4941     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4942     // the selection of the masked intrinsics doesn't do this for us.
4943     SDValue Mask = Op.getOperand(5);
4944     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4945 
4946     MVT VT = Op->getSimpleValueType(0);
4947     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4948 
4949     SDValue PassThru = Op.getOperand(2);
4950     if (!IsUnmasked) {
4951       MVT MaskVT =
4952           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4953       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4954       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4955     }
4956 
4957     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4958 
4959     SDValue IntID = DAG.getTargetConstant(
4960         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4961         XLenVT);
4962 
4963     auto *Load = cast<MemIntrinsicSDNode>(Op);
4964     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4965     if (IsUnmasked)
4966       Ops.push_back(DAG.getUNDEF(ContainerVT));
4967     else
4968       Ops.push_back(PassThru);
4969     Ops.push_back(Op.getOperand(3)); // Ptr
4970     Ops.push_back(Op.getOperand(4)); // Stride
4971     if (!IsUnmasked)
4972       Ops.push_back(Mask);
4973     Ops.push_back(VL);
4974     if (!IsUnmasked) {
4975       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4976       Ops.push_back(Policy);
4977     }
4978 
4979     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4980     SDValue Result =
4981         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4982                                 Load->getMemoryVT(), Load->getMemOperand());
4983     SDValue Chain = Result.getValue(1);
4984     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4985     return DAG.getMergeValues({Result, Chain}, DL);
4986   }
4987   case Intrinsic::riscv_seg2_load:
4988   case Intrinsic::riscv_seg3_load:
4989   case Intrinsic::riscv_seg4_load:
4990   case Intrinsic::riscv_seg5_load:
4991   case Intrinsic::riscv_seg6_load:
4992   case Intrinsic::riscv_seg7_load:
4993   case Intrinsic::riscv_seg8_load: {
4994     SDLoc DL(Op);
4995     static const Intrinsic::ID VlsegInts[7] = {
4996         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4997         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4998         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4999         Intrinsic::riscv_vlseg8};
5000     unsigned NF = Op->getNumValues() - 1;
5001     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
5002     MVT XLenVT = Subtarget.getXLenVT();
5003     MVT VT = Op->getSimpleValueType(0);
5004     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5005 
5006     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5007     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
5008     auto *Load = cast<MemIntrinsicSDNode>(Op);
5009     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
5010     ContainerVTs.push_back(MVT::Other);
5011     SDVTList VTs = DAG.getVTList(ContainerVTs);
5012     SDValue Result =
5013         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
5014                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
5015                                 Load->getMemoryVT(), Load->getMemOperand());
5016     SmallVector<SDValue, 9> Results;
5017     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
5018       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
5019                                                   DAG, Subtarget));
5020     Results.push_back(Result.getValue(NF));
5021     return DAG.getMergeValues(Results, DL);
5022   }
5023   }
5024 
5025   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
5026 }
5027 
5028 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5029                                                  SelectionDAG &DAG) const {
5030   unsigned IntNo = Op.getConstantOperandVal(1);
5031   switch (IntNo) {
5032   default:
5033     break;
5034   case Intrinsic::riscv_masked_strided_store: {
5035     SDLoc DL(Op);
5036     MVT XLenVT = Subtarget.getXLenVT();
5037 
5038     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5039     // the selection of the masked intrinsics doesn't do this for us.
5040     SDValue Mask = Op.getOperand(5);
5041     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5042 
5043     SDValue Val = Op.getOperand(2);
5044     MVT VT = Val.getSimpleValueType();
5045     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5046 
5047     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5048     if (!IsUnmasked) {
5049       MVT MaskVT =
5050           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5051       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5052     }
5053 
5054     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5055 
5056     SDValue IntID = DAG.getTargetConstant(
5057         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5058         XLenVT);
5059 
5060     auto *Store = cast<MemIntrinsicSDNode>(Op);
5061     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5062     Ops.push_back(Val);
5063     Ops.push_back(Op.getOperand(3)); // Ptr
5064     Ops.push_back(Op.getOperand(4)); // Stride
5065     if (!IsUnmasked)
5066       Ops.push_back(Mask);
5067     Ops.push_back(VL);
5068 
5069     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5070                                    Ops, Store->getMemoryVT(),
5071                                    Store->getMemOperand());
5072   }
5073   }
5074 
5075   return SDValue();
5076 }
5077 
5078 static MVT getLMUL1VT(MVT VT) {
5079   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5080          "Unexpected vector MVT");
5081   return MVT::getScalableVectorVT(
5082       VT.getVectorElementType(),
5083       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5084 }
5085 
5086 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5087   switch (ISDOpcode) {
5088   default:
5089     llvm_unreachable("Unhandled reduction");
5090   case ISD::VECREDUCE_ADD:
5091     return RISCVISD::VECREDUCE_ADD_VL;
5092   case ISD::VECREDUCE_UMAX:
5093     return RISCVISD::VECREDUCE_UMAX_VL;
5094   case ISD::VECREDUCE_SMAX:
5095     return RISCVISD::VECREDUCE_SMAX_VL;
5096   case ISD::VECREDUCE_UMIN:
5097     return RISCVISD::VECREDUCE_UMIN_VL;
5098   case ISD::VECREDUCE_SMIN:
5099     return RISCVISD::VECREDUCE_SMIN_VL;
5100   case ISD::VECREDUCE_AND:
5101     return RISCVISD::VECREDUCE_AND_VL;
5102   case ISD::VECREDUCE_OR:
5103     return RISCVISD::VECREDUCE_OR_VL;
5104   case ISD::VECREDUCE_XOR:
5105     return RISCVISD::VECREDUCE_XOR_VL;
5106   }
5107 }
5108 
5109 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5110                                                          SelectionDAG &DAG,
5111                                                          bool IsVP) const {
5112   SDLoc DL(Op);
5113   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5114   MVT VecVT = Vec.getSimpleValueType();
5115   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5116           Op.getOpcode() == ISD::VECREDUCE_OR ||
5117           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5118           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5119           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5120           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5121          "Unexpected reduction lowering");
5122 
5123   MVT XLenVT = Subtarget.getXLenVT();
5124   assert(Op.getValueType() == XLenVT &&
5125          "Expected reduction output to be legalized to XLenVT");
5126 
5127   MVT ContainerVT = VecVT;
5128   if (VecVT.isFixedLengthVector()) {
5129     ContainerVT = getContainerForFixedLengthVector(VecVT);
5130     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5131   }
5132 
5133   SDValue Mask, VL;
5134   if (IsVP) {
5135     Mask = Op.getOperand(2);
5136     VL = Op.getOperand(3);
5137   } else {
5138     std::tie(Mask, VL) =
5139         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5140   }
5141 
5142   unsigned BaseOpc;
5143   ISD::CondCode CC;
5144   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5145 
5146   switch (Op.getOpcode()) {
5147   default:
5148     llvm_unreachable("Unhandled reduction");
5149   case ISD::VECREDUCE_AND:
5150   case ISD::VP_REDUCE_AND: {
5151     // vcpop ~x == 0
5152     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5153     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5154     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5155     CC = ISD::SETEQ;
5156     BaseOpc = ISD::AND;
5157     break;
5158   }
5159   case ISD::VECREDUCE_OR:
5160   case ISD::VP_REDUCE_OR:
5161     // vcpop x != 0
5162     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5163     CC = ISD::SETNE;
5164     BaseOpc = ISD::OR;
5165     break;
5166   case ISD::VECREDUCE_XOR:
5167   case ISD::VP_REDUCE_XOR: {
5168     // ((vcpop x) & 1) != 0
5169     SDValue One = DAG.getConstant(1, DL, XLenVT);
5170     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5171     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5172     CC = ISD::SETNE;
5173     BaseOpc = ISD::XOR;
5174     break;
5175   }
5176   }
5177 
5178   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5179 
5180   if (!IsVP)
5181     return SetCC;
5182 
5183   // Now include the start value in the operation.
5184   // Note that we must return the start value when no elements are operated
5185   // upon. The vcpop instructions we've emitted in each case above will return
5186   // 0 for an inactive vector, and so we've already received the neutral value:
5187   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5188   // can simply include the start value.
5189   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5190 }
5191 
5192 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5193                                             SelectionDAG &DAG) const {
5194   SDLoc DL(Op);
5195   SDValue Vec = Op.getOperand(0);
5196   EVT VecEVT = Vec.getValueType();
5197 
5198   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5199 
5200   // Due to ordering in legalize types we may have a vector type that needs to
5201   // be split. Do that manually so we can get down to a legal type.
5202   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5203          TargetLowering::TypeSplitVector) {
5204     SDValue Lo, Hi;
5205     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5206     VecEVT = Lo.getValueType();
5207     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5208   }
5209 
5210   // TODO: The type may need to be widened rather than split. Or widened before
5211   // it can be split.
5212   if (!isTypeLegal(VecEVT))
5213     return SDValue();
5214 
5215   MVT VecVT = VecEVT.getSimpleVT();
5216   MVT VecEltVT = VecVT.getVectorElementType();
5217   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5218 
5219   MVT ContainerVT = VecVT;
5220   if (VecVT.isFixedLengthVector()) {
5221     ContainerVT = getContainerForFixedLengthVector(VecVT);
5222     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5223   }
5224 
5225   MVT M1VT = getLMUL1VT(ContainerVT);
5226   MVT XLenVT = Subtarget.getXLenVT();
5227 
5228   SDValue Mask, VL;
5229   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5230 
5231   SDValue NeutralElem =
5232       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5233   SDValue IdentitySplat =
5234       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5235                        M1VT, DL, DAG, Subtarget);
5236   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5237                                   IdentitySplat, Mask, VL);
5238   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5239                              DAG.getConstant(0, DL, XLenVT));
5240   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5241 }
5242 
5243 // Given a reduction op, this function returns the matching reduction opcode,
5244 // the vector SDValue and the scalar SDValue required to lower this to a
5245 // RISCVISD node.
5246 static std::tuple<unsigned, SDValue, SDValue>
5247 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5248   SDLoc DL(Op);
5249   auto Flags = Op->getFlags();
5250   unsigned Opcode = Op.getOpcode();
5251   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5252   switch (Opcode) {
5253   default:
5254     llvm_unreachable("Unhandled reduction");
5255   case ISD::VECREDUCE_FADD: {
5256     // Use positive zero if we can. It is cheaper to materialize.
5257     SDValue Zero =
5258         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5259     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5260   }
5261   case ISD::VECREDUCE_SEQ_FADD:
5262     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5263                            Op.getOperand(0));
5264   case ISD::VECREDUCE_FMIN:
5265     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5266                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5267   case ISD::VECREDUCE_FMAX:
5268     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5269                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5270   }
5271 }
5272 
5273 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5274                                               SelectionDAG &DAG) const {
5275   SDLoc DL(Op);
5276   MVT VecEltVT = Op.getSimpleValueType();
5277 
5278   unsigned RVVOpcode;
5279   SDValue VectorVal, ScalarVal;
5280   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5281       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5282   MVT VecVT = VectorVal.getSimpleValueType();
5283 
5284   MVT ContainerVT = VecVT;
5285   if (VecVT.isFixedLengthVector()) {
5286     ContainerVT = getContainerForFixedLengthVector(VecVT);
5287     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5288   }
5289 
5290   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5291   MVT XLenVT = Subtarget.getXLenVT();
5292 
5293   SDValue Mask, VL;
5294   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5295 
5296   SDValue ScalarSplat =
5297       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5298                        M1VT, DL, DAG, Subtarget);
5299   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5300                                   VectorVal, ScalarSplat, Mask, VL);
5301   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5302                      DAG.getConstant(0, DL, XLenVT));
5303 }
5304 
5305 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5306   switch (ISDOpcode) {
5307   default:
5308     llvm_unreachable("Unhandled reduction");
5309   case ISD::VP_REDUCE_ADD:
5310     return RISCVISD::VECREDUCE_ADD_VL;
5311   case ISD::VP_REDUCE_UMAX:
5312     return RISCVISD::VECREDUCE_UMAX_VL;
5313   case ISD::VP_REDUCE_SMAX:
5314     return RISCVISD::VECREDUCE_SMAX_VL;
5315   case ISD::VP_REDUCE_UMIN:
5316     return RISCVISD::VECREDUCE_UMIN_VL;
5317   case ISD::VP_REDUCE_SMIN:
5318     return RISCVISD::VECREDUCE_SMIN_VL;
5319   case ISD::VP_REDUCE_AND:
5320     return RISCVISD::VECREDUCE_AND_VL;
5321   case ISD::VP_REDUCE_OR:
5322     return RISCVISD::VECREDUCE_OR_VL;
5323   case ISD::VP_REDUCE_XOR:
5324     return RISCVISD::VECREDUCE_XOR_VL;
5325   case ISD::VP_REDUCE_FADD:
5326     return RISCVISD::VECREDUCE_FADD_VL;
5327   case ISD::VP_REDUCE_SEQ_FADD:
5328     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5329   case ISD::VP_REDUCE_FMAX:
5330     return RISCVISD::VECREDUCE_FMAX_VL;
5331   case ISD::VP_REDUCE_FMIN:
5332     return RISCVISD::VECREDUCE_FMIN_VL;
5333   }
5334 }
5335 
5336 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5337                                            SelectionDAG &DAG) const {
5338   SDLoc DL(Op);
5339   SDValue Vec = Op.getOperand(1);
5340   EVT VecEVT = Vec.getValueType();
5341 
5342   // TODO: The type may need to be widened rather than split. Or widened before
5343   // it can be split.
5344   if (!isTypeLegal(VecEVT))
5345     return SDValue();
5346 
5347   MVT VecVT = VecEVT.getSimpleVT();
5348   MVT VecEltVT = VecVT.getVectorElementType();
5349   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5350 
5351   MVT ContainerVT = VecVT;
5352   if (VecVT.isFixedLengthVector()) {
5353     ContainerVT = getContainerForFixedLengthVector(VecVT);
5354     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5355   }
5356 
5357   SDValue VL = Op.getOperand(3);
5358   SDValue Mask = Op.getOperand(2);
5359 
5360   MVT M1VT = getLMUL1VT(ContainerVT);
5361   MVT XLenVT = Subtarget.getXLenVT();
5362   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5363 
5364   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5365                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5366                                         DL, DAG, Subtarget);
5367   SDValue Reduction =
5368       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5369   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5370                              DAG.getConstant(0, DL, XLenVT));
5371   if (!VecVT.isInteger())
5372     return Elt0;
5373   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5374 }
5375 
5376 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5377                                                    SelectionDAG &DAG) const {
5378   SDValue Vec = Op.getOperand(0);
5379   SDValue SubVec = Op.getOperand(1);
5380   MVT VecVT = Vec.getSimpleValueType();
5381   MVT SubVecVT = SubVec.getSimpleValueType();
5382 
5383   SDLoc DL(Op);
5384   MVT XLenVT = Subtarget.getXLenVT();
5385   unsigned OrigIdx = Op.getConstantOperandVal(2);
5386   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5387 
5388   // We don't have the ability to slide mask vectors up indexed by their i1
5389   // elements; the smallest we can do is i8. Often we are able to bitcast to
5390   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5391   // into a scalable one, we might not necessarily have enough scalable
5392   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5393   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5394       (OrigIdx != 0 || !Vec.isUndef())) {
5395     if (VecVT.getVectorMinNumElements() >= 8 &&
5396         SubVecVT.getVectorMinNumElements() >= 8) {
5397       assert(OrigIdx % 8 == 0 && "Invalid index");
5398       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5399              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5400              "Unexpected mask vector lowering");
5401       OrigIdx /= 8;
5402       SubVecVT =
5403           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5404                            SubVecVT.isScalableVector());
5405       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5406                                VecVT.isScalableVector());
5407       Vec = DAG.getBitcast(VecVT, Vec);
5408       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5409     } else {
5410       // We can't slide this mask vector up indexed by its i1 elements.
5411       // This poses a problem when we wish to insert a scalable vector which
5412       // can't be re-expressed as a larger type. Just choose the slow path and
5413       // extend to a larger type, then truncate back down.
5414       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5415       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5416       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5417       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5418       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5419                         Op.getOperand(2));
5420       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5421       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5422     }
5423   }
5424 
5425   // If the subvector vector is a fixed-length type, we cannot use subregister
5426   // manipulation to simplify the codegen; we don't know which register of a
5427   // LMUL group contains the specific subvector as we only know the minimum
5428   // register size. Therefore we must slide the vector group up the full
5429   // amount.
5430   if (SubVecVT.isFixedLengthVector()) {
5431     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5432       return Op;
5433     MVT ContainerVT = VecVT;
5434     if (VecVT.isFixedLengthVector()) {
5435       ContainerVT = getContainerForFixedLengthVector(VecVT);
5436       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5437     }
5438     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5439                          DAG.getUNDEF(ContainerVT), SubVec,
5440                          DAG.getConstant(0, DL, XLenVT));
5441     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5442       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5443       return DAG.getBitcast(Op.getValueType(), SubVec);
5444     }
5445     SDValue Mask =
5446         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5447     // Set the vector length to only the number of elements we care about. Note
5448     // that for slideup this includes the offset.
5449     SDValue VL =
5450         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5451     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5452     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5453                                   SubVec, SlideupAmt, Mask, VL);
5454     if (VecVT.isFixedLengthVector())
5455       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5456     return DAG.getBitcast(Op.getValueType(), Slideup);
5457   }
5458 
5459   unsigned SubRegIdx, RemIdx;
5460   std::tie(SubRegIdx, RemIdx) =
5461       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5462           VecVT, SubVecVT, OrigIdx, TRI);
5463 
5464   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5465   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5466                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5467                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5468 
5469   // 1. If the Idx has been completely eliminated and this subvector's size is
5470   // a vector register or a multiple thereof, or the surrounding elements are
5471   // undef, then this is a subvector insert which naturally aligns to a vector
5472   // register. These can easily be handled using subregister manipulation.
5473   // 2. If the subvector is smaller than a vector register, then the insertion
5474   // must preserve the undisturbed elements of the register. We do this by
5475   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5476   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5477   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5478   // LMUL=1 type back into the larger vector (resolving to another subregister
5479   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5480   // to avoid allocating a large register group to hold our subvector.
5481   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5482     return Op;
5483 
5484   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5485   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5486   // (in our case undisturbed). This means we can set up a subvector insertion
5487   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5488   // size of the subvector.
5489   MVT InterSubVT = VecVT;
5490   SDValue AlignedExtract = Vec;
5491   unsigned AlignedIdx = OrigIdx - RemIdx;
5492   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5493     InterSubVT = getLMUL1VT(VecVT);
5494     // Extract a subvector equal to the nearest full vector register type. This
5495     // should resolve to a EXTRACT_SUBREG instruction.
5496     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5497                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5498   }
5499 
5500   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5501   // For scalable vectors this must be further multiplied by vscale.
5502   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5503 
5504   SDValue Mask, VL;
5505   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5506 
5507   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5508   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5509   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5510   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5511 
5512   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5513                        DAG.getUNDEF(InterSubVT), SubVec,
5514                        DAG.getConstant(0, DL, XLenVT));
5515 
5516   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5517                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5518 
5519   // If required, insert this subvector back into the correct vector register.
5520   // This should resolve to an INSERT_SUBREG instruction.
5521   if (VecVT.bitsGT(InterSubVT))
5522     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5523                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5524 
5525   // We might have bitcast from a mask type: cast back to the original type if
5526   // required.
5527   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5528 }
5529 
5530 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5531                                                     SelectionDAG &DAG) const {
5532   SDValue Vec = Op.getOperand(0);
5533   MVT SubVecVT = Op.getSimpleValueType();
5534   MVT VecVT = Vec.getSimpleValueType();
5535 
5536   SDLoc DL(Op);
5537   MVT XLenVT = Subtarget.getXLenVT();
5538   unsigned OrigIdx = Op.getConstantOperandVal(1);
5539   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5540 
5541   // We don't have the ability to slide mask vectors down indexed by their i1
5542   // elements; the smallest we can do is i8. Often we are able to bitcast to
5543   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5544   // from a scalable one, we might not necessarily have enough scalable
5545   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5546   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5547     if (VecVT.getVectorMinNumElements() >= 8 &&
5548         SubVecVT.getVectorMinNumElements() >= 8) {
5549       assert(OrigIdx % 8 == 0 && "Invalid index");
5550       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5551              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5552              "Unexpected mask vector lowering");
5553       OrigIdx /= 8;
5554       SubVecVT =
5555           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5556                            SubVecVT.isScalableVector());
5557       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5558                                VecVT.isScalableVector());
5559       Vec = DAG.getBitcast(VecVT, Vec);
5560     } else {
5561       // We can't slide this mask vector down, indexed by its i1 elements.
5562       // This poses a problem when we wish to extract a scalable vector which
5563       // can't be re-expressed as a larger type. Just choose the slow path and
5564       // extend to a larger type, then truncate back down.
5565       // TODO: We could probably improve this when extracting certain fixed
5566       // from fixed, where we can extract as i8 and shift the correct element
5567       // right to reach the desired subvector?
5568       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5569       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5570       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5571       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5572                         Op.getOperand(1));
5573       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5574       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5575     }
5576   }
5577 
5578   // If the subvector vector is a fixed-length type, we cannot use subregister
5579   // manipulation to simplify the codegen; we don't know which register of a
5580   // LMUL group contains the specific subvector as we only know the minimum
5581   // register size. Therefore we must slide the vector group down the full
5582   // amount.
5583   if (SubVecVT.isFixedLengthVector()) {
5584     // With an index of 0 this is a cast-like subvector, which can be performed
5585     // with subregister operations.
5586     if (OrigIdx == 0)
5587       return Op;
5588     MVT ContainerVT = VecVT;
5589     if (VecVT.isFixedLengthVector()) {
5590       ContainerVT = getContainerForFixedLengthVector(VecVT);
5591       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5592     }
5593     SDValue Mask =
5594         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5595     // Set the vector length to only the number of elements we care about. This
5596     // avoids sliding down elements we're going to discard straight away.
5597     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5598     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5599     SDValue Slidedown =
5600         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5601                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5602     // Now we can use a cast-like subvector extract to get the result.
5603     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5604                             DAG.getConstant(0, DL, XLenVT));
5605     return DAG.getBitcast(Op.getValueType(), Slidedown);
5606   }
5607 
5608   unsigned SubRegIdx, RemIdx;
5609   std::tie(SubRegIdx, RemIdx) =
5610       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5611           VecVT, SubVecVT, OrigIdx, TRI);
5612 
5613   // If the Idx has been completely eliminated then this is a subvector extract
5614   // which naturally aligns to a vector register. These can easily be handled
5615   // using subregister manipulation.
5616   if (RemIdx == 0)
5617     return Op;
5618 
5619   // Else we must shift our vector register directly to extract the subvector.
5620   // Do this using VSLIDEDOWN.
5621 
5622   // If the vector type is an LMUL-group type, extract a subvector equal to the
5623   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5624   // instruction.
5625   MVT InterSubVT = VecVT;
5626   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5627     InterSubVT = getLMUL1VT(VecVT);
5628     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5629                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5630   }
5631 
5632   // Slide this vector register down by the desired number of elements in order
5633   // to place the desired subvector starting at element 0.
5634   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5635   // For scalable vectors this must be further multiplied by vscale.
5636   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5637 
5638   SDValue Mask, VL;
5639   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5640   SDValue Slidedown =
5641       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5642                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5643 
5644   // Now the vector is in the right position, extract our final subvector. This
5645   // should resolve to a COPY.
5646   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5647                           DAG.getConstant(0, DL, XLenVT));
5648 
5649   // We might have bitcast from a mask type: cast back to the original type if
5650   // required.
5651   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5652 }
5653 
5654 // Lower step_vector to the vid instruction. Any non-identity step value must
5655 // be accounted for my manual expansion.
5656 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5657                                               SelectionDAG &DAG) const {
5658   SDLoc DL(Op);
5659   MVT VT = Op.getSimpleValueType();
5660   MVT XLenVT = Subtarget.getXLenVT();
5661   SDValue Mask, VL;
5662   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5663   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5664   uint64_t StepValImm = Op.getConstantOperandVal(0);
5665   if (StepValImm != 1) {
5666     if (isPowerOf2_64(StepValImm)) {
5667       SDValue StepVal =
5668           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5669                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5670       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5671     } else {
5672       SDValue StepVal = lowerScalarSplat(
5673           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5674           VL, VT, DL, DAG, Subtarget);
5675       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5676     }
5677   }
5678   return StepVec;
5679 }
5680 
5681 // Implement vector_reverse using vrgather.vv with indices determined by
5682 // subtracting the id of each element from (VLMAX-1). This will convert
5683 // the indices like so:
5684 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5685 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5686 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5687                                                  SelectionDAG &DAG) const {
5688   SDLoc DL(Op);
5689   MVT VecVT = Op.getSimpleValueType();
5690   unsigned EltSize = VecVT.getScalarSizeInBits();
5691   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5692 
5693   unsigned MaxVLMAX = 0;
5694   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5695   if (VectorBitsMax != 0)
5696     MaxVLMAX =
5697         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5698 
5699   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5700   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5701 
5702   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5703   // to use vrgatherei16.vv.
5704   // TODO: It's also possible to use vrgatherei16.vv for other types to
5705   // decrease register width for the index calculation.
5706   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5707     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5708     // Reverse each half, then reassemble them in reverse order.
5709     // NOTE: It's also possible that after splitting that VLMAX no longer
5710     // requires vrgatherei16.vv.
5711     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5712       SDValue Lo, Hi;
5713       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5714       EVT LoVT, HiVT;
5715       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5716       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5717       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5718       // Reassemble the low and high pieces reversed.
5719       // FIXME: This is a CONCAT_VECTORS.
5720       SDValue Res =
5721           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5722                       DAG.getIntPtrConstant(0, DL));
5723       return DAG.getNode(
5724           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5725           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5726     }
5727 
5728     // Just promote the int type to i16 which will double the LMUL.
5729     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5730     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5731   }
5732 
5733   MVT XLenVT = Subtarget.getXLenVT();
5734   SDValue Mask, VL;
5735   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5736 
5737   // Calculate VLMAX-1 for the desired SEW.
5738   unsigned MinElts = VecVT.getVectorMinNumElements();
5739   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5740                               DAG.getConstant(MinElts, DL, XLenVT));
5741   SDValue VLMinus1 =
5742       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5743 
5744   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5745   bool IsRV32E64 =
5746       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5747   SDValue SplatVL;
5748   if (!IsRV32E64)
5749     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5750   else
5751     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5752                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5753 
5754   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5755   SDValue Indices =
5756       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5757 
5758   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5759 }
5760 
5761 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5762                                                 SelectionDAG &DAG) const {
5763   SDLoc DL(Op);
5764   SDValue V1 = Op.getOperand(0);
5765   SDValue V2 = Op.getOperand(1);
5766   MVT XLenVT = Subtarget.getXLenVT();
5767   MVT VecVT = Op.getSimpleValueType();
5768 
5769   unsigned MinElts = VecVT.getVectorMinNumElements();
5770   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5771                               DAG.getConstant(MinElts, DL, XLenVT));
5772 
5773   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5774   SDValue DownOffset, UpOffset;
5775   if (ImmValue >= 0) {
5776     // The operand is a TargetConstant, we need to rebuild it as a regular
5777     // constant.
5778     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5779     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5780   } else {
5781     // The operand is a TargetConstant, we need to rebuild it as a regular
5782     // constant rather than negating the original operand.
5783     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5784     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5785   }
5786 
5787   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5788   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5789 
5790   SDValue SlideDown =
5791       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5792                   DownOffset, TrueMask, UpOffset);
5793   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5794                      TrueMask,
5795                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5796 }
5797 
5798 SDValue
5799 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5800                                                      SelectionDAG &DAG) const {
5801   SDLoc DL(Op);
5802   auto *Load = cast<LoadSDNode>(Op);
5803 
5804   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5805                                         Load->getMemoryVT(),
5806                                         *Load->getMemOperand()) &&
5807          "Expecting a correctly-aligned load");
5808 
5809   MVT VT = Op.getSimpleValueType();
5810   MVT XLenVT = Subtarget.getXLenVT();
5811   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5812 
5813   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5814 
5815   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5816   SDValue IntID = DAG.getTargetConstant(
5817       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5818   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5819   if (!IsMaskOp)
5820     Ops.push_back(DAG.getUNDEF(ContainerVT));
5821   Ops.push_back(Load->getBasePtr());
5822   Ops.push_back(VL);
5823   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5824   SDValue NewLoad =
5825       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5826                               Load->getMemoryVT(), Load->getMemOperand());
5827 
5828   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5829   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5830 }
5831 
5832 SDValue
5833 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5834                                                       SelectionDAG &DAG) const {
5835   SDLoc DL(Op);
5836   auto *Store = cast<StoreSDNode>(Op);
5837 
5838   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5839                                         Store->getMemoryVT(),
5840                                         *Store->getMemOperand()) &&
5841          "Expecting a correctly-aligned store");
5842 
5843   SDValue StoreVal = Store->getValue();
5844   MVT VT = StoreVal.getSimpleValueType();
5845   MVT XLenVT = Subtarget.getXLenVT();
5846 
5847   // If the size less than a byte, we need to pad with zeros to make a byte.
5848   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5849     VT = MVT::v8i1;
5850     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5851                            DAG.getConstant(0, DL, VT), StoreVal,
5852                            DAG.getIntPtrConstant(0, DL));
5853   }
5854 
5855   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5856 
5857   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5858 
5859   SDValue NewValue =
5860       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5861 
5862   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5863   SDValue IntID = DAG.getTargetConstant(
5864       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5865   return DAG.getMemIntrinsicNode(
5866       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5867       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5868       Store->getMemoryVT(), Store->getMemOperand());
5869 }
5870 
5871 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5872                                              SelectionDAG &DAG) const {
5873   SDLoc DL(Op);
5874   MVT VT = Op.getSimpleValueType();
5875 
5876   const auto *MemSD = cast<MemSDNode>(Op);
5877   EVT MemVT = MemSD->getMemoryVT();
5878   MachineMemOperand *MMO = MemSD->getMemOperand();
5879   SDValue Chain = MemSD->getChain();
5880   SDValue BasePtr = MemSD->getBasePtr();
5881 
5882   SDValue Mask, PassThru, VL;
5883   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5884     Mask = VPLoad->getMask();
5885     PassThru = DAG.getUNDEF(VT);
5886     VL = VPLoad->getVectorLength();
5887   } else {
5888     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5889     Mask = MLoad->getMask();
5890     PassThru = MLoad->getPassThru();
5891   }
5892 
5893   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5894 
5895   MVT XLenVT = Subtarget.getXLenVT();
5896 
5897   MVT ContainerVT = VT;
5898   if (VT.isFixedLengthVector()) {
5899     ContainerVT = getContainerForFixedLengthVector(VT);
5900     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5901     if (!IsUnmasked) {
5902       MVT MaskVT =
5903           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5904       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5905     }
5906   }
5907 
5908   if (!VL)
5909     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5910 
5911   unsigned IntID =
5912       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5913   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5914   if (IsUnmasked)
5915     Ops.push_back(DAG.getUNDEF(ContainerVT));
5916   else
5917     Ops.push_back(PassThru);
5918   Ops.push_back(BasePtr);
5919   if (!IsUnmasked)
5920     Ops.push_back(Mask);
5921   Ops.push_back(VL);
5922   if (!IsUnmasked)
5923     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5924 
5925   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5926 
5927   SDValue Result =
5928       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5929   Chain = Result.getValue(1);
5930 
5931   if (VT.isFixedLengthVector())
5932     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5933 
5934   return DAG.getMergeValues({Result, Chain}, DL);
5935 }
5936 
5937 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5938                                               SelectionDAG &DAG) const {
5939   SDLoc DL(Op);
5940 
5941   const auto *MemSD = cast<MemSDNode>(Op);
5942   EVT MemVT = MemSD->getMemoryVT();
5943   MachineMemOperand *MMO = MemSD->getMemOperand();
5944   SDValue Chain = MemSD->getChain();
5945   SDValue BasePtr = MemSD->getBasePtr();
5946   SDValue Val, Mask, VL;
5947 
5948   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5949     Val = VPStore->getValue();
5950     Mask = VPStore->getMask();
5951     VL = VPStore->getVectorLength();
5952   } else {
5953     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5954     Val = MStore->getValue();
5955     Mask = MStore->getMask();
5956   }
5957 
5958   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5959 
5960   MVT VT = Val.getSimpleValueType();
5961   MVT XLenVT = Subtarget.getXLenVT();
5962 
5963   MVT ContainerVT = VT;
5964   if (VT.isFixedLengthVector()) {
5965     ContainerVT = getContainerForFixedLengthVector(VT);
5966 
5967     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5968     if (!IsUnmasked) {
5969       MVT MaskVT =
5970           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5971       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5972     }
5973   }
5974 
5975   if (!VL)
5976     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5977 
5978   unsigned IntID =
5979       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5980   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5981   Ops.push_back(Val);
5982   Ops.push_back(BasePtr);
5983   if (!IsUnmasked)
5984     Ops.push_back(Mask);
5985   Ops.push_back(VL);
5986 
5987   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5988                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5989 }
5990 
5991 SDValue
5992 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5993                                                       SelectionDAG &DAG) const {
5994   MVT InVT = Op.getOperand(0).getSimpleValueType();
5995   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5996 
5997   MVT VT = Op.getSimpleValueType();
5998 
5999   SDValue Op1 =
6000       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
6001   SDValue Op2 =
6002       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6003 
6004   SDLoc DL(Op);
6005   SDValue VL =
6006       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
6007 
6008   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6009   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6010 
6011   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
6012                             Op.getOperand(2), Mask, VL);
6013 
6014   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
6015 }
6016 
6017 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
6018     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
6019   MVT VT = Op.getSimpleValueType();
6020 
6021   if (VT.getVectorElementType() == MVT::i1)
6022     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
6023 
6024   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
6025 }
6026 
6027 SDValue
6028 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
6029                                                       SelectionDAG &DAG) const {
6030   unsigned Opc;
6031   switch (Op.getOpcode()) {
6032   default: llvm_unreachable("Unexpected opcode!");
6033   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6034   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6035   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6036   }
6037 
6038   return lowerToScalableOp(Op, DAG, Opc);
6039 }
6040 
6041 // Lower vector ABS to smax(X, sub(0, X)).
6042 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6043   SDLoc DL(Op);
6044   MVT VT = Op.getSimpleValueType();
6045   SDValue X = Op.getOperand(0);
6046 
6047   assert(VT.isFixedLengthVector() && "Unexpected type");
6048 
6049   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6050   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6051 
6052   SDValue Mask, VL;
6053   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6054 
6055   SDValue SplatZero = DAG.getNode(
6056       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6057       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6058   SDValue NegX =
6059       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6060   SDValue Max =
6061       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6062 
6063   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6064 }
6065 
6066 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6067     SDValue Op, SelectionDAG &DAG) const {
6068   SDLoc DL(Op);
6069   MVT VT = Op.getSimpleValueType();
6070   SDValue Mag = Op.getOperand(0);
6071   SDValue Sign = Op.getOperand(1);
6072   assert(Mag.getValueType() == Sign.getValueType() &&
6073          "Can only handle COPYSIGN with matching types.");
6074 
6075   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6076   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6077   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6078 
6079   SDValue Mask, VL;
6080   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6081 
6082   SDValue CopySign =
6083       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6084 
6085   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6086 }
6087 
6088 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6089     SDValue Op, SelectionDAG &DAG) const {
6090   MVT VT = Op.getSimpleValueType();
6091   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6092 
6093   MVT I1ContainerVT =
6094       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6095 
6096   SDValue CC =
6097       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6098   SDValue Op1 =
6099       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6100   SDValue Op2 =
6101       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6102 
6103   SDLoc DL(Op);
6104   SDValue Mask, VL;
6105   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6106 
6107   SDValue Select =
6108       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6109 
6110   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6111 }
6112 
6113 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6114                                                unsigned NewOpc,
6115                                                bool HasMask) const {
6116   MVT VT = Op.getSimpleValueType();
6117   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6118 
6119   // Create list of operands by converting existing ones to scalable types.
6120   SmallVector<SDValue, 6> Ops;
6121   for (const SDValue &V : Op->op_values()) {
6122     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6123 
6124     // Pass through non-vector operands.
6125     if (!V.getValueType().isVector()) {
6126       Ops.push_back(V);
6127       continue;
6128     }
6129 
6130     // "cast" fixed length vector to a scalable vector.
6131     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6132            "Only fixed length vectors are supported!");
6133     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6134   }
6135 
6136   SDLoc DL(Op);
6137   SDValue Mask, VL;
6138   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6139   if (HasMask)
6140     Ops.push_back(Mask);
6141   Ops.push_back(VL);
6142 
6143   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6144   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6145 }
6146 
6147 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6148 // * Operands of each node are assumed to be in the same order.
6149 // * The EVL operand is promoted from i32 to i64 on RV64.
6150 // * Fixed-length vectors are converted to their scalable-vector container
6151 //   types.
6152 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6153                                        unsigned RISCVISDOpc) const {
6154   SDLoc DL(Op);
6155   MVT VT = Op.getSimpleValueType();
6156   SmallVector<SDValue, 4> Ops;
6157 
6158   for (const auto &OpIdx : enumerate(Op->ops())) {
6159     SDValue V = OpIdx.value();
6160     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6161     // Pass through operands which aren't fixed-length vectors.
6162     if (!V.getValueType().isFixedLengthVector()) {
6163       Ops.push_back(V);
6164       continue;
6165     }
6166     // "cast" fixed length vector to a scalable vector.
6167     MVT OpVT = V.getSimpleValueType();
6168     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6169     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6170            "Only fixed length vectors are supported!");
6171     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6172   }
6173 
6174   if (!VT.isFixedLengthVector())
6175     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6176 
6177   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6178 
6179   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6180 
6181   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6182 }
6183 
6184 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6185                                               SelectionDAG &DAG) const {
6186   SDLoc DL(Op);
6187   MVT VT = Op.getSimpleValueType();
6188 
6189   SDValue Src = Op.getOperand(0);
6190   // NOTE: Mask is dropped.
6191   SDValue VL = Op.getOperand(2);
6192 
6193   MVT ContainerVT = VT;
6194   if (VT.isFixedLengthVector()) {
6195     ContainerVT = getContainerForFixedLengthVector(VT);
6196     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6197     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6198   }
6199 
6200   MVT XLenVT = Subtarget.getXLenVT();
6201   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6202   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6203                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6204 
6205   SDValue SplatValue =
6206       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6207   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6208                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6209 
6210   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6211                                Splat, ZeroSplat, VL);
6212   if (!VT.isFixedLengthVector())
6213     return Result;
6214   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6215 }
6216 
6217 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6218 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6219                                                 unsigned RISCVISDOpc) const {
6220   SDLoc DL(Op);
6221 
6222   SDValue Src = Op.getOperand(0);
6223   SDValue Mask = Op.getOperand(1);
6224   SDValue VL = Op.getOperand(2);
6225 
6226   MVT DstVT = Op.getSimpleValueType();
6227   MVT SrcVT = Src.getSimpleValueType();
6228   if (DstVT.isFixedLengthVector()) {
6229     DstVT = getContainerForFixedLengthVector(DstVT);
6230     SrcVT = getContainerForFixedLengthVector(SrcVT);
6231     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6232     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6233     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6234   }
6235 
6236   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6237                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6238                                 ? RISCVISD::VSEXT_VL
6239                                 : RISCVISD::VZEXT_VL;
6240 
6241   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6242   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6243 
6244   SDValue Result;
6245   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6246     if (SrcVT.isInteger()) {
6247       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6248 
6249       // Do we need to do any pre-widening before converting?
6250       if (SrcEltSize == 1) {
6251         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6252         MVT XLenVT = Subtarget.getXLenVT();
6253         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6254         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6255                                         DAG.getUNDEF(IntVT), Zero, VL);
6256         SDValue One = DAG.getConstant(
6257             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6258         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6259                                        DAG.getUNDEF(IntVT), One, VL);
6260         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6261                           ZeroSplat, VL);
6262       } else if (DstEltSize > (2 * SrcEltSize)) {
6263         // Widen before converting.
6264         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6265                                      DstVT.getVectorElementCount());
6266         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6267       }
6268 
6269       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6270     } else {
6271       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6272              "Wrong input/output vector types");
6273 
6274       // Convert f16 to f32 then convert f32 to i64.
6275       if (DstEltSize > (2 * SrcEltSize)) {
6276         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6277         MVT InterimFVT =
6278             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6279         Src =
6280             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6281       }
6282 
6283       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6284     }
6285   } else { // Narrowing + Conversion
6286     if (SrcVT.isInteger()) {
6287       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6288       // First do a narrowing convert to an FP type half the size, then round
6289       // the FP type to a small FP type if needed.
6290 
6291       MVT InterimFVT = DstVT;
6292       if (SrcEltSize > (2 * DstEltSize)) {
6293         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6294         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6295         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6296       }
6297 
6298       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6299 
6300       if (InterimFVT != DstVT) {
6301         Src = Result;
6302         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6303       }
6304     } else {
6305       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6306              "Wrong input/output vector types");
6307       // First do a narrowing conversion to an integer half the size, then
6308       // truncate if needed.
6309 
6310       if (DstEltSize == 1) {
6311         // First convert to the same size integer, then convert to mask using
6312         // setcc.
6313         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6314         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6315                                           DstVT.getVectorElementCount());
6316         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6317 
6318         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6319         // otherwise the conversion was undefined.
6320         MVT XLenVT = Subtarget.getXLenVT();
6321         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6322         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6323                                 DAG.getUNDEF(InterimIVT), SplatZero);
6324         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6325                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6326       } else {
6327         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6328                                           DstVT.getVectorElementCount());
6329 
6330         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6331 
6332         while (InterimIVT != DstVT) {
6333           SrcEltSize /= 2;
6334           Src = Result;
6335           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6336                                         DstVT.getVectorElementCount());
6337           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6338                                Src, Mask, VL);
6339         }
6340       }
6341     }
6342   }
6343 
6344   MVT VT = Op.getSimpleValueType();
6345   if (!VT.isFixedLengthVector())
6346     return Result;
6347   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6348 }
6349 
6350 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6351                                             unsigned MaskOpc,
6352                                             unsigned VecOpc) const {
6353   MVT VT = Op.getSimpleValueType();
6354   if (VT.getVectorElementType() != MVT::i1)
6355     return lowerVPOp(Op, DAG, VecOpc);
6356 
6357   // It is safe to drop mask parameter as masked-off elements are undef.
6358   SDValue Op1 = Op->getOperand(0);
6359   SDValue Op2 = Op->getOperand(1);
6360   SDValue VL = Op->getOperand(3);
6361 
6362   MVT ContainerVT = VT;
6363   const bool IsFixed = VT.isFixedLengthVector();
6364   if (IsFixed) {
6365     ContainerVT = getContainerForFixedLengthVector(VT);
6366     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6367     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6368   }
6369 
6370   SDLoc DL(Op);
6371   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6372   if (!IsFixed)
6373     return Val;
6374   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6375 }
6376 
6377 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6378 // matched to a RVV indexed load. The RVV indexed load instructions only
6379 // support the "unsigned unscaled" addressing mode; indices are implicitly
6380 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6381 // signed or scaled indexing is extended to the XLEN value type and scaled
6382 // accordingly.
6383 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6384                                                SelectionDAG &DAG) const {
6385   SDLoc DL(Op);
6386   MVT VT = Op.getSimpleValueType();
6387 
6388   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6389   EVT MemVT = MemSD->getMemoryVT();
6390   MachineMemOperand *MMO = MemSD->getMemOperand();
6391   SDValue Chain = MemSD->getChain();
6392   SDValue BasePtr = MemSD->getBasePtr();
6393 
6394   ISD::LoadExtType LoadExtType;
6395   SDValue Index, Mask, PassThru, VL;
6396 
6397   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6398     Index = VPGN->getIndex();
6399     Mask = VPGN->getMask();
6400     PassThru = DAG.getUNDEF(VT);
6401     VL = VPGN->getVectorLength();
6402     // VP doesn't support extending loads.
6403     LoadExtType = ISD::NON_EXTLOAD;
6404   } else {
6405     // Else it must be a MGATHER.
6406     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6407     Index = MGN->getIndex();
6408     Mask = MGN->getMask();
6409     PassThru = MGN->getPassThru();
6410     LoadExtType = MGN->getExtensionType();
6411   }
6412 
6413   MVT IndexVT = Index.getSimpleValueType();
6414   MVT XLenVT = Subtarget.getXLenVT();
6415 
6416   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6417          "Unexpected VTs!");
6418   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6419   // Targets have to explicitly opt-in for extending vector loads.
6420   assert(LoadExtType == ISD::NON_EXTLOAD &&
6421          "Unexpected extending MGATHER/VP_GATHER");
6422   (void)LoadExtType;
6423 
6424   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6425   // the selection of the masked intrinsics doesn't do this for us.
6426   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6427 
6428   MVT ContainerVT = VT;
6429   if (VT.isFixedLengthVector()) {
6430     // We need to use the larger of the result and index type to determine the
6431     // scalable type to use so we don't increase LMUL for any operand/result.
6432     if (VT.bitsGE(IndexVT)) {
6433       ContainerVT = getContainerForFixedLengthVector(VT);
6434       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6435                                  ContainerVT.getVectorElementCount());
6436     } else {
6437       IndexVT = getContainerForFixedLengthVector(IndexVT);
6438       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6439                                      IndexVT.getVectorElementCount());
6440     }
6441 
6442     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6443 
6444     if (!IsUnmasked) {
6445       MVT MaskVT =
6446           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6447       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6448       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6449     }
6450   }
6451 
6452   if (!VL)
6453     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6454 
6455   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6456     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6457     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6458                                    VL);
6459     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6460                         TrueMask, VL);
6461   }
6462 
6463   unsigned IntID =
6464       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6465   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6466   if (IsUnmasked)
6467     Ops.push_back(DAG.getUNDEF(ContainerVT));
6468   else
6469     Ops.push_back(PassThru);
6470   Ops.push_back(BasePtr);
6471   Ops.push_back(Index);
6472   if (!IsUnmasked)
6473     Ops.push_back(Mask);
6474   Ops.push_back(VL);
6475   if (!IsUnmasked)
6476     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6477 
6478   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6479   SDValue Result =
6480       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6481   Chain = Result.getValue(1);
6482 
6483   if (VT.isFixedLengthVector())
6484     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6485 
6486   return DAG.getMergeValues({Result, Chain}, DL);
6487 }
6488 
6489 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6490 // matched to a RVV indexed store. The RVV indexed store instructions only
6491 // support the "unsigned unscaled" addressing mode; indices are implicitly
6492 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6493 // signed or scaled indexing is extended to the XLEN value type and scaled
6494 // accordingly.
6495 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6496                                                 SelectionDAG &DAG) const {
6497   SDLoc DL(Op);
6498   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6499   EVT MemVT = MemSD->getMemoryVT();
6500   MachineMemOperand *MMO = MemSD->getMemOperand();
6501   SDValue Chain = MemSD->getChain();
6502   SDValue BasePtr = MemSD->getBasePtr();
6503 
6504   bool IsTruncatingStore = false;
6505   SDValue Index, Mask, Val, VL;
6506 
6507   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6508     Index = VPSN->getIndex();
6509     Mask = VPSN->getMask();
6510     Val = VPSN->getValue();
6511     VL = VPSN->getVectorLength();
6512     // VP doesn't support truncating stores.
6513     IsTruncatingStore = false;
6514   } else {
6515     // Else it must be a MSCATTER.
6516     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6517     Index = MSN->getIndex();
6518     Mask = MSN->getMask();
6519     Val = MSN->getValue();
6520     IsTruncatingStore = MSN->isTruncatingStore();
6521   }
6522 
6523   MVT VT = Val.getSimpleValueType();
6524   MVT IndexVT = Index.getSimpleValueType();
6525   MVT XLenVT = Subtarget.getXLenVT();
6526 
6527   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6528          "Unexpected VTs!");
6529   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6530   // Targets have to explicitly opt-in for extending vector loads and
6531   // truncating vector stores.
6532   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6533   (void)IsTruncatingStore;
6534 
6535   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6536   // the selection of the masked intrinsics doesn't do this for us.
6537   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6538 
6539   MVT ContainerVT = VT;
6540   if (VT.isFixedLengthVector()) {
6541     // We need to use the larger of the value and index type to determine the
6542     // scalable type to use so we don't increase LMUL for any operand/result.
6543     if (VT.bitsGE(IndexVT)) {
6544       ContainerVT = getContainerForFixedLengthVector(VT);
6545       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6546                                  ContainerVT.getVectorElementCount());
6547     } else {
6548       IndexVT = getContainerForFixedLengthVector(IndexVT);
6549       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6550                                      IndexVT.getVectorElementCount());
6551     }
6552 
6553     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6554     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6555 
6556     if (!IsUnmasked) {
6557       MVT MaskVT =
6558           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6559       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6560     }
6561   }
6562 
6563   if (!VL)
6564     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6565 
6566   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6567     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6568     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6569                                    VL);
6570     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6571                         TrueMask, VL);
6572   }
6573 
6574   unsigned IntID =
6575       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6576   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6577   Ops.push_back(Val);
6578   Ops.push_back(BasePtr);
6579   Ops.push_back(Index);
6580   if (!IsUnmasked)
6581     Ops.push_back(Mask);
6582   Ops.push_back(VL);
6583 
6584   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6585                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6586 }
6587 
6588 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6589                                                SelectionDAG &DAG) const {
6590   const MVT XLenVT = Subtarget.getXLenVT();
6591   SDLoc DL(Op);
6592   SDValue Chain = Op->getOperand(0);
6593   SDValue SysRegNo = DAG.getTargetConstant(
6594       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6595   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6596   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6597 
6598   // Encoding used for rounding mode in RISCV differs from that used in
6599   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6600   // table, which consists of a sequence of 4-bit fields, each representing
6601   // corresponding FLT_ROUNDS mode.
6602   static const int Table =
6603       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6604       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6605       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6606       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6607       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6608 
6609   SDValue Shift =
6610       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6611   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6612                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6613   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6614                                DAG.getConstant(7, DL, XLenVT));
6615 
6616   return DAG.getMergeValues({Masked, Chain}, DL);
6617 }
6618 
6619 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6620                                                SelectionDAG &DAG) const {
6621   const MVT XLenVT = Subtarget.getXLenVT();
6622   SDLoc DL(Op);
6623   SDValue Chain = Op->getOperand(0);
6624   SDValue RMValue = Op->getOperand(1);
6625   SDValue SysRegNo = DAG.getTargetConstant(
6626       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6627 
6628   // Encoding used for rounding mode in RISCV differs from that used in
6629   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6630   // a table, which consists of a sequence of 4-bit fields, each representing
6631   // corresponding RISCV mode.
6632   static const unsigned Table =
6633       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6634       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6635       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6636       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6637       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6638 
6639   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6640                               DAG.getConstant(2, DL, XLenVT));
6641   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6642                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6643   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6644                         DAG.getConstant(0x7, DL, XLenVT));
6645   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6646                      RMValue);
6647 }
6648 
6649 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6650   switch (IntNo) {
6651   default:
6652     llvm_unreachable("Unexpected Intrinsic");
6653   case Intrinsic::riscv_bcompress:
6654     return RISCVISD::BCOMPRESSW;
6655   case Intrinsic::riscv_bdecompress:
6656     return RISCVISD::BDECOMPRESSW;
6657   case Intrinsic::riscv_bfp:
6658     return RISCVISD::BFPW;
6659   case Intrinsic::riscv_fsl:
6660     return RISCVISD::FSLW;
6661   case Intrinsic::riscv_fsr:
6662     return RISCVISD::FSRW;
6663   }
6664 }
6665 
6666 // Converts the given intrinsic to a i64 operation with any extension.
6667 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6668                                          unsigned IntNo) {
6669   SDLoc DL(N);
6670   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6671   // Deal with the Instruction Operands
6672   SmallVector<SDValue, 3> NewOps;
6673   for (SDValue Op : drop_begin(N->ops()))
6674     // Promote the operand to i64 type
6675     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6676   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6677   // ReplaceNodeResults requires we maintain the same type for the return value.
6678   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6679 }
6680 
6681 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6682 // form of the given Opcode.
6683 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6684   switch (Opcode) {
6685   default:
6686     llvm_unreachable("Unexpected opcode");
6687   case ISD::SHL:
6688     return RISCVISD::SLLW;
6689   case ISD::SRA:
6690     return RISCVISD::SRAW;
6691   case ISD::SRL:
6692     return RISCVISD::SRLW;
6693   case ISD::SDIV:
6694     return RISCVISD::DIVW;
6695   case ISD::UDIV:
6696     return RISCVISD::DIVUW;
6697   case ISD::UREM:
6698     return RISCVISD::REMUW;
6699   case ISD::ROTL:
6700     return RISCVISD::ROLW;
6701   case ISD::ROTR:
6702     return RISCVISD::RORW;
6703   }
6704 }
6705 
6706 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6707 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6708 // otherwise be promoted to i64, making it difficult to select the
6709 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6710 // type i8/i16/i32 is lost.
6711 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6712                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6713   SDLoc DL(N);
6714   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6715   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6716   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6717   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6718   // ReplaceNodeResults requires we maintain the same type for the return value.
6719   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6720 }
6721 
6722 // Converts the given 32-bit operation to a i64 operation with signed extension
6723 // semantic to reduce the signed extension instructions.
6724 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6725   SDLoc DL(N);
6726   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6727   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6728   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6729   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6730                                DAG.getValueType(MVT::i32));
6731   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6732 }
6733 
6734 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6735                                              SmallVectorImpl<SDValue> &Results,
6736                                              SelectionDAG &DAG) const {
6737   SDLoc DL(N);
6738   switch (N->getOpcode()) {
6739   default:
6740     llvm_unreachable("Don't know how to custom type legalize this operation!");
6741   case ISD::STRICT_FP_TO_SINT:
6742   case ISD::STRICT_FP_TO_UINT:
6743   case ISD::FP_TO_SINT:
6744   case ISD::FP_TO_UINT: {
6745     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6746            "Unexpected custom legalisation");
6747     bool IsStrict = N->isStrictFPOpcode();
6748     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6749                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6750     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6751     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6752         TargetLowering::TypeSoftenFloat) {
6753       if (!isTypeLegal(Op0.getValueType()))
6754         return;
6755       if (IsStrict) {
6756         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6757                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6758         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6759         SDValue Res = DAG.getNode(
6760             Opc, DL, VTs, N->getOperand(0), Op0,
6761             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6762         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6763         Results.push_back(Res.getValue(1));
6764         return;
6765       }
6766       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6767       SDValue Res =
6768           DAG.getNode(Opc, DL, MVT::i64, Op0,
6769                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6770       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6771       return;
6772     }
6773     // If the FP type needs to be softened, emit a library call using the 'si'
6774     // version. If we left it to default legalization we'd end up with 'di'. If
6775     // the FP type doesn't need to be softened just let generic type
6776     // legalization promote the result type.
6777     RTLIB::Libcall LC;
6778     if (IsSigned)
6779       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6780     else
6781       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6782     MakeLibCallOptions CallOptions;
6783     EVT OpVT = Op0.getValueType();
6784     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6785     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6786     SDValue Result;
6787     std::tie(Result, Chain) =
6788         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6789     Results.push_back(Result);
6790     if (IsStrict)
6791       Results.push_back(Chain);
6792     break;
6793   }
6794   case ISD::READCYCLECOUNTER: {
6795     assert(!Subtarget.is64Bit() &&
6796            "READCYCLECOUNTER only has custom type legalization on riscv32");
6797 
6798     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6799     SDValue RCW =
6800         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6801 
6802     Results.push_back(
6803         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6804     Results.push_back(RCW.getValue(2));
6805     break;
6806   }
6807   case ISD::MUL: {
6808     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6809     unsigned XLen = Subtarget.getXLen();
6810     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6811     if (Size > XLen) {
6812       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6813       SDValue LHS = N->getOperand(0);
6814       SDValue RHS = N->getOperand(1);
6815       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6816 
6817       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6818       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6819       // We need exactly one side to be unsigned.
6820       if (LHSIsU == RHSIsU)
6821         return;
6822 
6823       auto MakeMULPair = [&](SDValue S, SDValue U) {
6824         MVT XLenVT = Subtarget.getXLenVT();
6825         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6826         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6827         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6828         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6829         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6830       };
6831 
6832       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6833       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6834 
6835       // The other operand should be signed, but still prefer MULH when
6836       // possible.
6837       if (RHSIsU && LHSIsS && !RHSIsS)
6838         Results.push_back(MakeMULPair(LHS, RHS));
6839       else if (LHSIsU && RHSIsS && !LHSIsS)
6840         Results.push_back(MakeMULPair(RHS, LHS));
6841 
6842       return;
6843     }
6844     LLVM_FALLTHROUGH;
6845   }
6846   case ISD::ADD:
6847   case ISD::SUB:
6848     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6849            "Unexpected custom legalisation");
6850     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6851     break;
6852   case ISD::SHL:
6853   case ISD::SRA:
6854   case ISD::SRL:
6855     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6856            "Unexpected custom legalisation");
6857     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6858       Results.push_back(customLegalizeToWOp(N, DAG));
6859       break;
6860     }
6861 
6862     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6863     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6864     // shift amount.
6865     if (N->getOpcode() == ISD::SHL) {
6866       SDLoc DL(N);
6867       SDValue NewOp0 =
6868           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6869       SDValue NewOp1 =
6870           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6871       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6872       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6873                                    DAG.getValueType(MVT::i32));
6874       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6875     }
6876 
6877     break;
6878   case ISD::ROTL:
6879   case ISD::ROTR:
6880     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6881            "Unexpected custom legalisation");
6882     Results.push_back(customLegalizeToWOp(N, DAG));
6883     break;
6884   case ISD::CTTZ:
6885   case ISD::CTTZ_ZERO_UNDEF:
6886   case ISD::CTLZ:
6887   case ISD::CTLZ_ZERO_UNDEF: {
6888     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6889            "Unexpected custom legalisation");
6890 
6891     SDValue NewOp0 =
6892         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6893     bool IsCTZ =
6894         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6895     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6896     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6897     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6898     return;
6899   }
6900   case ISD::SDIV:
6901   case ISD::UDIV:
6902   case ISD::UREM: {
6903     MVT VT = N->getSimpleValueType(0);
6904     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6905            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6906            "Unexpected custom legalisation");
6907     // Don't promote division/remainder by constant since we should expand those
6908     // to multiply by magic constant.
6909     // FIXME: What if the expansion is disabled for minsize.
6910     if (N->getOperand(1).getOpcode() == ISD::Constant)
6911       return;
6912 
6913     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6914     // the upper 32 bits. For other types we need to sign or zero extend
6915     // based on the opcode.
6916     unsigned ExtOpc = ISD::ANY_EXTEND;
6917     if (VT != MVT::i32)
6918       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6919                                            : ISD::ZERO_EXTEND;
6920 
6921     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6922     break;
6923   }
6924   case ISD::UADDO:
6925   case ISD::USUBO: {
6926     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6927            "Unexpected custom legalisation");
6928     bool IsAdd = N->getOpcode() == ISD::UADDO;
6929     // Create an ADDW or SUBW.
6930     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6931     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6932     SDValue Res =
6933         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6934     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6935                       DAG.getValueType(MVT::i32));
6936 
6937     SDValue Overflow;
6938     if (IsAdd && isOneConstant(RHS)) {
6939       // Special case uaddo X, 1 overflowed if the addition result is 0.
6940       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6941       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6942                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6943     } else {
6944       // Sign extend the LHS and perform an unsigned compare with the ADDW
6945       // result. Since the inputs are sign extended from i32, this is equivalent
6946       // to comparing the lower 32 bits.
6947       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6948       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6949                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6950     }
6951 
6952     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6953     Results.push_back(Overflow);
6954     return;
6955   }
6956   case ISD::UADDSAT:
6957   case ISD::USUBSAT: {
6958     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6959            "Unexpected custom legalisation");
6960     if (Subtarget.hasStdExtZbb()) {
6961       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6962       // sign extend allows overflow of the lower 32 bits to be detected on
6963       // the promoted size.
6964       SDValue LHS =
6965           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6966       SDValue RHS =
6967           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6968       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6969       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6970       return;
6971     }
6972 
6973     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6974     // promotion for UADDO/USUBO.
6975     Results.push_back(expandAddSubSat(N, DAG));
6976     return;
6977   }
6978   case ISD::ABS: {
6979     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6980            "Unexpected custom legalisation");
6981           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6982 
6983     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6984 
6985     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6986 
6987     // Freeze the source so we can increase it's use count.
6988     Src = DAG.getFreeze(Src);
6989 
6990     // Copy sign bit to all bits using the sraiw pattern.
6991     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6992                                    DAG.getValueType(MVT::i32));
6993     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6994                            DAG.getConstant(31, DL, MVT::i64));
6995 
6996     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6997     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6998 
6999     // NOTE: The result is only required to be anyextended, but sext is
7000     // consistent with type legalization of sub.
7001     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7002                          DAG.getValueType(MVT::i32));
7003     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7004     return;
7005   }
7006   case ISD::BITCAST: {
7007     EVT VT = N->getValueType(0);
7008     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7009     SDValue Op0 = N->getOperand(0);
7010     EVT Op0VT = Op0.getValueType();
7011     MVT XLenVT = Subtarget.getXLenVT();
7012     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7013       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7014       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7015     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7016                Subtarget.hasStdExtF()) {
7017       SDValue FPConv =
7018           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7019       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7020     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7021                isTypeLegal(Op0VT)) {
7022       // Custom-legalize bitcasts from fixed-length vector types to illegal
7023       // scalar types in order to improve codegen. Bitcast the vector to a
7024       // one-element vector type whose element type is the same as the result
7025       // type, and extract the first element.
7026       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7027       if (isTypeLegal(BVT)) {
7028         SDValue BVec = DAG.getBitcast(BVT, Op0);
7029         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7030                                       DAG.getConstant(0, DL, XLenVT)));
7031       }
7032     }
7033     break;
7034   }
7035   case RISCVISD::GREV:
7036   case RISCVISD::GORC:
7037   case RISCVISD::SHFL: {
7038     MVT VT = N->getSimpleValueType(0);
7039     MVT XLenVT = Subtarget.getXLenVT();
7040     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7041            "Unexpected custom legalisation");
7042     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7043     assert((Subtarget.hasStdExtZbp() ||
7044             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7045              N->getConstantOperandVal(1) == 7)) &&
7046            "Unexpected extension");
7047     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7048     SDValue NewOp1 =
7049         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7050     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7051     // ReplaceNodeResults requires we maintain the same type for the return
7052     // value.
7053     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7054     break;
7055   }
7056   case ISD::BSWAP:
7057   case ISD::BITREVERSE: {
7058     MVT VT = N->getSimpleValueType(0);
7059     MVT XLenVT = Subtarget.getXLenVT();
7060     assert((VT == MVT::i8 || VT == MVT::i16 ||
7061             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7062            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7063     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7064     unsigned Imm = VT.getSizeInBits() - 1;
7065     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7066     if (N->getOpcode() == ISD::BSWAP)
7067       Imm &= ~0x7U;
7068     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7069                                 DAG.getConstant(Imm, DL, XLenVT));
7070     // ReplaceNodeResults requires we maintain the same type for the return
7071     // value.
7072     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7073     break;
7074   }
7075   case ISD::FSHL:
7076   case ISD::FSHR: {
7077     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7078            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7079     SDValue NewOp0 =
7080         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7081     SDValue NewOp1 =
7082         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7083     SDValue NewShAmt =
7084         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7085     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7086     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7087     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7088                            DAG.getConstant(0x1f, DL, MVT::i64));
7089     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7090     // instruction use different orders. fshl will return its first operand for
7091     // shift of zero, fshr will return its second operand. fsl and fsr both
7092     // return rs1 so the ISD nodes need to have different operand orders.
7093     // Shift amount is in rs2.
7094     unsigned Opc = RISCVISD::FSLW;
7095     if (N->getOpcode() == ISD::FSHR) {
7096       std::swap(NewOp0, NewOp1);
7097       Opc = RISCVISD::FSRW;
7098     }
7099     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7100     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7101     break;
7102   }
7103   case ISD::EXTRACT_VECTOR_ELT: {
7104     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7105     // type is illegal (currently only vXi64 RV32).
7106     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7107     // transferred to the destination register. We issue two of these from the
7108     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7109     // first element.
7110     SDValue Vec = N->getOperand(0);
7111     SDValue Idx = N->getOperand(1);
7112 
7113     // The vector type hasn't been legalized yet so we can't issue target
7114     // specific nodes if it needs legalization.
7115     // FIXME: We would manually legalize if it's important.
7116     if (!isTypeLegal(Vec.getValueType()))
7117       return;
7118 
7119     MVT VecVT = Vec.getSimpleValueType();
7120 
7121     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7122            VecVT.getVectorElementType() == MVT::i64 &&
7123            "Unexpected EXTRACT_VECTOR_ELT legalization");
7124 
7125     // If this is a fixed vector, we need to convert it to a scalable vector.
7126     MVT ContainerVT = VecVT;
7127     if (VecVT.isFixedLengthVector()) {
7128       ContainerVT = getContainerForFixedLengthVector(VecVT);
7129       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7130     }
7131 
7132     MVT XLenVT = Subtarget.getXLenVT();
7133 
7134     // Use a VL of 1 to avoid processing more elements than we need.
7135     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7136     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7137     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7138 
7139     // Unless the index is known to be 0, we must slide the vector down to get
7140     // the desired element into index 0.
7141     if (!isNullConstant(Idx)) {
7142       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7143                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7144     }
7145 
7146     // Extract the lower XLEN bits of the correct vector element.
7147     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7148 
7149     // To extract the upper XLEN bits of the vector element, shift the first
7150     // element right by 32 bits and re-extract the lower XLEN bits.
7151     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7152                                      DAG.getUNDEF(ContainerVT),
7153                                      DAG.getConstant(32, DL, XLenVT), VL);
7154     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7155                                  ThirtyTwoV, Mask, VL);
7156 
7157     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7158 
7159     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7160     break;
7161   }
7162   case ISD::INTRINSIC_WO_CHAIN: {
7163     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7164     switch (IntNo) {
7165     default:
7166       llvm_unreachable(
7167           "Don't know how to custom type legalize this intrinsic!");
7168     case Intrinsic::riscv_grev:
7169     case Intrinsic::riscv_gorc: {
7170       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7171              "Unexpected custom legalisation");
7172       SDValue NewOp1 =
7173           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7174       SDValue NewOp2 =
7175           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7176       unsigned Opc =
7177           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7178       // If the control is a constant, promote the node by clearing any extra
7179       // bits bits in the control. isel will form greviw/gorciw if the result is
7180       // sign extended.
7181       if (isa<ConstantSDNode>(NewOp2)) {
7182         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7183                              DAG.getConstant(0x1f, DL, MVT::i64));
7184         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7185       }
7186       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7187       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7188       break;
7189     }
7190     case Intrinsic::riscv_bcompress:
7191     case Intrinsic::riscv_bdecompress:
7192     case Intrinsic::riscv_bfp:
7193     case Intrinsic::riscv_fsl:
7194     case Intrinsic::riscv_fsr: {
7195       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7196              "Unexpected custom legalisation");
7197       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7198       break;
7199     }
7200     case Intrinsic::riscv_orc_b: {
7201       // Lower to the GORCI encoding for orc.b with the operand extended.
7202       SDValue NewOp =
7203           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7204       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7205                                 DAG.getConstant(7, DL, MVT::i64));
7206       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7207       return;
7208     }
7209     case Intrinsic::riscv_shfl:
7210     case Intrinsic::riscv_unshfl: {
7211       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7212              "Unexpected custom legalisation");
7213       SDValue NewOp1 =
7214           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7215       SDValue NewOp2 =
7216           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7217       unsigned Opc =
7218           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7219       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7220       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7221       // will be shuffled the same way as the lower 32 bit half, but the two
7222       // halves won't cross.
7223       if (isa<ConstantSDNode>(NewOp2)) {
7224         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7225                              DAG.getConstant(0xf, DL, MVT::i64));
7226         Opc =
7227             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7228       }
7229       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7230       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7231       break;
7232     }
7233     case Intrinsic::riscv_vmv_x_s: {
7234       EVT VT = N->getValueType(0);
7235       MVT XLenVT = Subtarget.getXLenVT();
7236       if (VT.bitsLT(XLenVT)) {
7237         // Simple case just extract using vmv.x.s and truncate.
7238         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7239                                       Subtarget.getXLenVT(), N->getOperand(1));
7240         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7241         return;
7242       }
7243 
7244       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7245              "Unexpected custom legalization");
7246 
7247       // We need to do the move in two steps.
7248       SDValue Vec = N->getOperand(1);
7249       MVT VecVT = Vec.getSimpleValueType();
7250 
7251       // First extract the lower XLEN bits of the element.
7252       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7253 
7254       // To extract the upper XLEN bits of the vector element, shift the first
7255       // element right by 32 bits and re-extract the lower XLEN bits.
7256       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7257       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7258       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7259       SDValue ThirtyTwoV =
7260           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7261                       DAG.getConstant(32, DL, XLenVT), VL);
7262       SDValue LShr32 =
7263           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7264       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7265 
7266       Results.push_back(
7267           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7268       break;
7269     }
7270     }
7271     break;
7272   }
7273   case ISD::VECREDUCE_ADD:
7274   case ISD::VECREDUCE_AND:
7275   case ISD::VECREDUCE_OR:
7276   case ISD::VECREDUCE_XOR:
7277   case ISD::VECREDUCE_SMAX:
7278   case ISD::VECREDUCE_UMAX:
7279   case ISD::VECREDUCE_SMIN:
7280   case ISD::VECREDUCE_UMIN:
7281     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7282       Results.push_back(V);
7283     break;
7284   case ISD::VP_REDUCE_ADD:
7285   case ISD::VP_REDUCE_AND:
7286   case ISD::VP_REDUCE_OR:
7287   case ISD::VP_REDUCE_XOR:
7288   case ISD::VP_REDUCE_SMAX:
7289   case ISD::VP_REDUCE_UMAX:
7290   case ISD::VP_REDUCE_SMIN:
7291   case ISD::VP_REDUCE_UMIN:
7292     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7293       Results.push_back(V);
7294     break;
7295   case ISD::FLT_ROUNDS_: {
7296     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7297     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7298     Results.push_back(Res.getValue(0));
7299     Results.push_back(Res.getValue(1));
7300     break;
7301   }
7302   }
7303 }
7304 
7305 // A structure to hold one of the bit-manipulation patterns below. Together, a
7306 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7307 //   (or (and (shl x, 1), 0xAAAAAAAA),
7308 //       (and (srl x, 1), 0x55555555))
7309 struct RISCVBitmanipPat {
7310   SDValue Op;
7311   unsigned ShAmt;
7312   bool IsSHL;
7313 
7314   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7315     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7316   }
7317 };
7318 
7319 // Matches patterns of the form
7320 //   (and (shl x, C2), (C1 << C2))
7321 //   (and (srl x, C2), C1)
7322 //   (shl (and x, C1), C2)
7323 //   (srl (and x, (C1 << C2)), C2)
7324 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7325 // The expected masks for each shift amount are specified in BitmanipMasks where
7326 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7327 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7328 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7329 // XLen is 64.
7330 static Optional<RISCVBitmanipPat>
7331 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7332   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7333          "Unexpected number of masks");
7334   Optional<uint64_t> Mask;
7335   // Optionally consume a mask around the shift operation.
7336   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7337     Mask = Op.getConstantOperandVal(1);
7338     Op = Op.getOperand(0);
7339   }
7340   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7341     return None;
7342   bool IsSHL = Op.getOpcode() == ISD::SHL;
7343 
7344   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7345     return None;
7346   uint64_t ShAmt = Op.getConstantOperandVal(1);
7347 
7348   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7349   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7350     return None;
7351   // If we don't have enough masks for 64 bit, then we must be trying to
7352   // match SHFL so we're only allowed to shift 1/4 of the width.
7353   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7354     return None;
7355 
7356   SDValue Src = Op.getOperand(0);
7357 
7358   // The expected mask is shifted left when the AND is found around SHL
7359   // patterns.
7360   //   ((x >> 1) & 0x55555555)
7361   //   ((x << 1) & 0xAAAAAAAA)
7362   bool SHLExpMask = IsSHL;
7363 
7364   if (!Mask) {
7365     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7366     // the mask is all ones: consume that now.
7367     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7368       Mask = Src.getConstantOperandVal(1);
7369       Src = Src.getOperand(0);
7370       // The expected mask is now in fact shifted left for SRL, so reverse the
7371       // decision.
7372       //   ((x & 0xAAAAAAAA) >> 1)
7373       //   ((x & 0x55555555) << 1)
7374       SHLExpMask = !SHLExpMask;
7375     } else {
7376       // Use a default shifted mask of all-ones if there's no AND, truncated
7377       // down to the expected width. This simplifies the logic later on.
7378       Mask = maskTrailingOnes<uint64_t>(Width);
7379       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7380     }
7381   }
7382 
7383   unsigned MaskIdx = Log2_32(ShAmt);
7384   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7385 
7386   if (SHLExpMask)
7387     ExpMask <<= ShAmt;
7388 
7389   if (Mask != ExpMask)
7390     return None;
7391 
7392   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7393 }
7394 
7395 // Matches any of the following bit-manipulation patterns:
7396 //   (and (shl x, 1), (0x55555555 << 1))
7397 //   (and (srl x, 1), 0x55555555)
7398 //   (shl (and x, 0x55555555), 1)
7399 //   (srl (and x, (0x55555555 << 1)), 1)
7400 // where the shift amount and mask may vary thus:
7401 //   [1]  = 0x55555555 / 0xAAAAAAAA
7402 //   [2]  = 0x33333333 / 0xCCCCCCCC
7403 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7404 //   [8]  = 0x00FF00FF / 0xFF00FF00
7405 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7406 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7407 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7408   // These are the unshifted masks which we use to match bit-manipulation
7409   // patterns. They may be shifted left in certain circumstances.
7410   static const uint64_t BitmanipMasks[] = {
7411       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7412       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7413 
7414   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7415 }
7416 
7417 // Match the following pattern as a GREVI(W) operation
7418 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7419 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7420                                const RISCVSubtarget &Subtarget) {
7421   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7422   EVT VT = Op.getValueType();
7423 
7424   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7425     auto LHS = matchGREVIPat(Op.getOperand(0));
7426     auto RHS = matchGREVIPat(Op.getOperand(1));
7427     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7428       SDLoc DL(Op);
7429       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7430                          DAG.getConstant(LHS->ShAmt, DL, VT));
7431     }
7432   }
7433   return SDValue();
7434 }
7435 
7436 // Matches any the following pattern as a GORCI(W) operation
7437 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7438 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7439 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7440 // Note that with the variant of 3.,
7441 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7442 // the inner pattern will first be matched as GREVI and then the outer
7443 // pattern will be matched to GORC via the first rule above.
7444 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7445 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7446                                const RISCVSubtarget &Subtarget) {
7447   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7448   EVT VT = Op.getValueType();
7449 
7450   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7451     SDLoc DL(Op);
7452     SDValue Op0 = Op.getOperand(0);
7453     SDValue Op1 = Op.getOperand(1);
7454 
7455     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7456       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7457           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7458           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7459         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7460       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7461       if ((Reverse.getOpcode() == ISD::ROTL ||
7462            Reverse.getOpcode() == ISD::ROTR) &&
7463           Reverse.getOperand(0) == X &&
7464           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7465         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7466         if (RotAmt == (VT.getSizeInBits() / 2))
7467           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7468                              DAG.getConstant(RotAmt, DL, VT));
7469       }
7470       return SDValue();
7471     };
7472 
7473     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7474     if (SDValue V = MatchOROfReverse(Op0, Op1))
7475       return V;
7476     if (SDValue V = MatchOROfReverse(Op1, Op0))
7477       return V;
7478 
7479     // OR is commutable so canonicalize its OR operand to the left
7480     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7481       std::swap(Op0, Op1);
7482     if (Op0.getOpcode() != ISD::OR)
7483       return SDValue();
7484     SDValue OrOp0 = Op0.getOperand(0);
7485     SDValue OrOp1 = Op0.getOperand(1);
7486     auto LHS = matchGREVIPat(OrOp0);
7487     // OR is commutable so swap the operands and try again: x might have been
7488     // on the left
7489     if (!LHS) {
7490       std::swap(OrOp0, OrOp1);
7491       LHS = matchGREVIPat(OrOp0);
7492     }
7493     auto RHS = matchGREVIPat(Op1);
7494     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7495       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7496                          DAG.getConstant(LHS->ShAmt, DL, VT));
7497     }
7498   }
7499   return SDValue();
7500 }
7501 
7502 // Matches any of the following bit-manipulation patterns:
7503 //   (and (shl x, 1), (0x22222222 << 1))
7504 //   (and (srl x, 1), 0x22222222)
7505 //   (shl (and x, 0x22222222), 1)
7506 //   (srl (and x, (0x22222222 << 1)), 1)
7507 // where the shift amount and mask may vary thus:
7508 //   [1]  = 0x22222222 / 0x44444444
7509 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7510 //   [4]  = 0x00F000F0 / 0x0F000F00
7511 //   [8]  = 0x0000FF00 / 0x00FF0000
7512 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7513 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7514   // These are the unshifted masks which we use to match bit-manipulation
7515   // patterns. They may be shifted left in certain circumstances.
7516   static const uint64_t BitmanipMasks[] = {
7517       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7518       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7519 
7520   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7521 }
7522 
7523 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7524 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7525                                const RISCVSubtarget &Subtarget) {
7526   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7527   EVT VT = Op.getValueType();
7528 
7529   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7530     return SDValue();
7531 
7532   SDValue Op0 = Op.getOperand(0);
7533   SDValue Op1 = Op.getOperand(1);
7534 
7535   // Or is commutable so canonicalize the second OR to the LHS.
7536   if (Op0.getOpcode() != ISD::OR)
7537     std::swap(Op0, Op1);
7538   if (Op0.getOpcode() != ISD::OR)
7539     return SDValue();
7540 
7541   // We found an inner OR, so our operands are the operands of the inner OR
7542   // and the other operand of the outer OR.
7543   SDValue A = Op0.getOperand(0);
7544   SDValue B = Op0.getOperand(1);
7545   SDValue C = Op1;
7546 
7547   auto Match1 = matchSHFLPat(A);
7548   auto Match2 = matchSHFLPat(B);
7549 
7550   // If neither matched, we failed.
7551   if (!Match1 && !Match2)
7552     return SDValue();
7553 
7554   // We had at least one match. if one failed, try the remaining C operand.
7555   if (!Match1) {
7556     std::swap(A, C);
7557     Match1 = matchSHFLPat(A);
7558     if (!Match1)
7559       return SDValue();
7560   } else if (!Match2) {
7561     std::swap(B, C);
7562     Match2 = matchSHFLPat(B);
7563     if (!Match2)
7564       return SDValue();
7565   }
7566   assert(Match1 && Match2);
7567 
7568   // Make sure our matches pair up.
7569   if (!Match1->formsPairWith(*Match2))
7570     return SDValue();
7571 
7572   // All the remains is to make sure C is an AND with the same input, that masks
7573   // out the bits that are being shuffled.
7574   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7575       C.getOperand(0) != Match1->Op)
7576     return SDValue();
7577 
7578   uint64_t Mask = C.getConstantOperandVal(1);
7579 
7580   static const uint64_t BitmanipMasks[] = {
7581       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7582       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7583   };
7584 
7585   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7586   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7587   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7588 
7589   if (Mask != ExpMask)
7590     return SDValue();
7591 
7592   SDLoc DL(Op);
7593   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7594                      DAG.getConstant(Match1->ShAmt, DL, VT));
7595 }
7596 
7597 // Optimize (add (shl x, c0), (shl y, c1)) ->
7598 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7599 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7600                                   const RISCVSubtarget &Subtarget) {
7601   // Perform this optimization only in the zba extension.
7602   if (!Subtarget.hasStdExtZba())
7603     return SDValue();
7604 
7605   // Skip for vector types and larger types.
7606   EVT VT = N->getValueType(0);
7607   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7608     return SDValue();
7609 
7610   // The two operand nodes must be SHL and have no other use.
7611   SDValue N0 = N->getOperand(0);
7612   SDValue N1 = N->getOperand(1);
7613   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7614       !N0->hasOneUse() || !N1->hasOneUse())
7615     return SDValue();
7616 
7617   // Check c0 and c1.
7618   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7619   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7620   if (!N0C || !N1C)
7621     return SDValue();
7622   int64_t C0 = N0C->getSExtValue();
7623   int64_t C1 = N1C->getSExtValue();
7624   if (C0 <= 0 || C1 <= 0)
7625     return SDValue();
7626 
7627   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7628   int64_t Bits = std::min(C0, C1);
7629   int64_t Diff = std::abs(C0 - C1);
7630   if (Diff != 1 && Diff != 2 && Diff != 3)
7631     return SDValue();
7632 
7633   // Build nodes.
7634   SDLoc DL(N);
7635   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7636   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7637   SDValue NA0 =
7638       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7639   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7640   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7641 }
7642 
7643 // Combine
7644 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7645 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7646 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7647 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7648 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7649 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7650 // The grev patterns represents BSWAP.
7651 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7652 // off the grev.
7653 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7654                                           const RISCVSubtarget &Subtarget) {
7655   bool IsWInstruction =
7656       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7657   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7658           IsWInstruction) &&
7659          "Unexpected opcode!");
7660   SDValue Src = N->getOperand(0);
7661   EVT VT = N->getValueType(0);
7662   SDLoc DL(N);
7663 
7664   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7665     return SDValue();
7666 
7667   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7668       !isa<ConstantSDNode>(Src.getOperand(1)))
7669     return SDValue();
7670 
7671   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7672   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7673 
7674   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7675   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7676   unsigned ShAmt1 = N->getConstantOperandVal(1);
7677   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7678   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7679     return SDValue();
7680 
7681   Src = Src.getOperand(0);
7682 
7683   // Toggle bit the MSB of the shift.
7684   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7685   if (CombinedShAmt == 0)
7686     return Src;
7687 
7688   SDValue Res = DAG.getNode(
7689       RISCVISD::GREV, DL, VT, Src,
7690       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7691   if (!IsWInstruction)
7692     return Res;
7693 
7694   // Sign extend the result to match the behavior of the rotate. This will be
7695   // selected to GREVIW in isel.
7696   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7697                      DAG.getValueType(MVT::i32));
7698 }
7699 
7700 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7701 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7702 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7703 // not undo itself, but they are redundant.
7704 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7705   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7706   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7707   SDValue Src = N->getOperand(0);
7708 
7709   if (Src.getOpcode() != N->getOpcode())
7710     return SDValue();
7711 
7712   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7713       !isa<ConstantSDNode>(Src.getOperand(1)))
7714     return SDValue();
7715 
7716   unsigned ShAmt1 = N->getConstantOperandVal(1);
7717   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7718   Src = Src.getOperand(0);
7719 
7720   unsigned CombinedShAmt;
7721   if (IsGORC)
7722     CombinedShAmt = ShAmt1 | ShAmt2;
7723   else
7724     CombinedShAmt = ShAmt1 ^ ShAmt2;
7725 
7726   if (CombinedShAmt == 0)
7727     return Src;
7728 
7729   SDLoc DL(N);
7730   return DAG.getNode(
7731       N->getOpcode(), DL, N->getValueType(0), Src,
7732       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7733 }
7734 
7735 // Combine a constant select operand into its use:
7736 //
7737 // (and (select cond, -1, c), x)
7738 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7739 // (or  (select cond, 0, c), x)
7740 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7741 // (xor (select cond, 0, c), x)
7742 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7743 // (add (select cond, 0, c), x)
7744 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7745 // (sub x, (select cond, 0, c))
7746 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7747 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7748                                    SelectionDAG &DAG, bool AllOnes) {
7749   EVT VT = N->getValueType(0);
7750 
7751   // Skip vectors.
7752   if (VT.isVector())
7753     return SDValue();
7754 
7755   if ((Slct.getOpcode() != ISD::SELECT &&
7756        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7757       !Slct.hasOneUse())
7758     return SDValue();
7759 
7760   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7761     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7762   };
7763 
7764   bool SwapSelectOps;
7765   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7766   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7767   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7768   SDValue NonConstantVal;
7769   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7770     SwapSelectOps = false;
7771     NonConstantVal = FalseVal;
7772   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7773     SwapSelectOps = true;
7774     NonConstantVal = TrueVal;
7775   } else
7776     return SDValue();
7777 
7778   // Slct is now know to be the desired identity constant when CC is true.
7779   TrueVal = OtherOp;
7780   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7781   // Unless SwapSelectOps says the condition should be false.
7782   if (SwapSelectOps)
7783     std::swap(TrueVal, FalseVal);
7784 
7785   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7786     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7787                        {Slct.getOperand(0), Slct.getOperand(1),
7788                         Slct.getOperand(2), TrueVal, FalseVal});
7789 
7790   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7791                      {Slct.getOperand(0), TrueVal, FalseVal});
7792 }
7793 
7794 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7795 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7796                                               bool AllOnes) {
7797   SDValue N0 = N->getOperand(0);
7798   SDValue N1 = N->getOperand(1);
7799   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7800     return Result;
7801   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7802     return Result;
7803   return SDValue();
7804 }
7805 
7806 // Transform (add (mul x, c0), c1) ->
7807 //           (add (mul (add x, c1/c0), c0), c1%c0).
7808 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7809 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7810 // to an infinite loop in DAGCombine if transformed.
7811 // Or transform (add (mul x, c0), c1) ->
7812 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7813 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7814 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7815 // lead to an infinite loop in DAGCombine if transformed.
7816 // Or transform (add (mul x, c0), c1) ->
7817 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7818 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7819 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7820 // lead to an infinite loop in DAGCombine if transformed.
7821 // Or transform (add (mul x, c0), c1) ->
7822 //              (mul (add x, c1/c0), c0).
7823 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7824 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7825                                      const RISCVSubtarget &Subtarget) {
7826   // Skip for vector types and larger types.
7827   EVT VT = N->getValueType(0);
7828   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7829     return SDValue();
7830   // The first operand node must be a MUL and has no other use.
7831   SDValue N0 = N->getOperand(0);
7832   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7833     return SDValue();
7834   // Check if c0 and c1 match above conditions.
7835   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7836   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7837   if (!N0C || !N1C)
7838     return SDValue();
7839   // If N0C has multiple uses it's possible one of the cases in
7840   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7841   // in an infinite loop.
7842   if (!N0C->hasOneUse())
7843     return SDValue();
7844   int64_t C0 = N0C->getSExtValue();
7845   int64_t C1 = N1C->getSExtValue();
7846   int64_t CA, CB;
7847   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7848     return SDValue();
7849   // Search for proper CA (non-zero) and CB that both are simm12.
7850   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7851       !isInt<12>(C0 * (C1 / C0))) {
7852     CA = C1 / C0;
7853     CB = C1 % C0;
7854   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7855              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7856     CA = C1 / C0 + 1;
7857     CB = C1 % C0 - C0;
7858   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7859              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7860     CA = C1 / C0 - 1;
7861     CB = C1 % C0 + C0;
7862   } else
7863     return SDValue();
7864   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7865   SDLoc DL(N);
7866   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7867                              DAG.getConstant(CA, DL, VT));
7868   SDValue New1 =
7869       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7870   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7871 }
7872 
7873 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7874                                  const RISCVSubtarget &Subtarget) {
7875   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7876     return V;
7877   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7878     return V;
7879   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7880   //      (select lhs, rhs, cc, x, (add x, y))
7881   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7882 }
7883 
7884 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7885   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7886   //      (select lhs, rhs, cc, x, (sub x, y))
7887   SDValue N0 = N->getOperand(0);
7888   SDValue N1 = N->getOperand(1);
7889   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7890 }
7891 
7892 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7893   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7894   //      (select lhs, rhs, cc, x, (and x, y))
7895   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7896 }
7897 
7898 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7899                                 const RISCVSubtarget &Subtarget) {
7900   if (Subtarget.hasStdExtZbp()) {
7901     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7902       return GREV;
7903     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7904       return GORC;
7905     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7906       return SHFL;
7907   }
7908 
7909   // fold (or (select cond, 0, y), x) ->
7910   //      (select cond, x, (or x, y))
7911   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7912 }
7913 
7914 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7915   // fold (xor (select cond, 0, y), x) ->
7916   //      (select cond, x, (xor x, y))
7917   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7918 }
7919 
7920 static SDValue
7921 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7922                                 const RISCVSubtarget &Subtarget) {
7923   SDValue Src = N->getOperand(0);
7924   EVT VT = N->getValueType(0);
7925 
7926   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7927   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7928       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7929     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7930                        Src.getOperand(0));
7931 
7932   // Fold (i64 (sext_inreg (abs X), i32)) ->
7933   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7934   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7935   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7936   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7937   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7938   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7939   // may get combined into an earlier operation so we need to use
7940   // ComputeNumSignBits.
7941   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7942   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7943   // we can't assume that X has 33 sign bits. We must check.
7944   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7945       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7946       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7947       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7948     SDLoc DL(N);
7949     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7950     SDValue Neg =
7951         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7952     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7953                       DAG.getValueType(MVT::i32));
7954     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7955   }
7956 
7957   return SDValue();
7958 }
7959 
7960 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7961 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7962 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7963                                              bool Commute = false) {
7964   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7965           N->getOpcode() == RISCVISD::SUB_VL) &&
7966          "Unexpected opcode");
7967   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7968   SDValue Op0 = N->getOperand(0);
7969   SDValue Op1 = N->getOperand(1);
7970   if (Commute)
7971     std::swap(Op0, Op1);
7972 
7973   MVT VT = N->getSimpleValueType(0);
7974 
7975   // Determine the narrow size for a widening add/sub.
7976   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7977   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7978                                   VT.getVectorElementCount());
7979 
7980   SDValue Mask = N->getOperand(2);
7981   SDValue VL = N->getOperand(3);
7982 
7983   SDLoc DL(N);
7984 
7985   // If the RHS is a sext or zext, we can form a widening op.
7986   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7987        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7988       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7989     unsigned ExtOpc = Op1.getOpcode();
7990     Op1 = Op1.getOperand(0);
7991     // Re-introduce narrower extends if needed.
7992     if (Op1.getValueType() != NarrowVT)
7993       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7994 
7995     unsigned WOpc;
7996     if (ExtOpc == RISCVISD::VSEXT_VL)
7997       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7998     else
7999       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8000 
8001     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8002   }
8003 
8004   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8005   // sext/zext?
8006 
8007   return SDValue();
8008 }
8009 
8010 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8011 // vwsub(u).vv/vx.
8012 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8013   SDValue Op0 = N->getOperand(0);
8014   SDValue Op1 = N->getOperand(1);
8015   SDValue Mask = N->getOperand(2);
8016   SDValue VL = N->getOperand(3);
8017 
8018   MVT VT = N->getSimpleValueType(0);
8019   MVT NarrowVT = Op1.getSimpleValueType();
8020   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8021 
8022   unsigned VOpc;
8023   switch (N->getOpcode()) {
8024   default: llvm_unreachable("Unexpected opcode");
8025   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8026   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8027   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8028   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8029   }
8030 
8031   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8032                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8033 
8034   SDLoc DL(N);
8035 
8036   // If the LHS is a sext or zext, we can narrow this op to the same size as
8037   // the RHS.
8038   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8039        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8040       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8041     unsigned ExtOpc = Op0.getOpcode();
8042     Op0 = Op0.getOperand(0);
8043     // Re-introduce narrower extends if needed.
8044     if (Op0.getValueType() != NarrowVT)
8045       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8046     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8047   }
8048 
8049   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8050                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8051 
8052   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8053   // to commute and use a vwadd(u).vx instead.
8054   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8055       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8056     Op0 = Op0.getOperand(1);
8057 
8058     // See if have enough sign bits or zero bits in the scalar to use a
8059     // widening add/sub by splatting to smaller element size.
8060     unsigned EltBits = VT.getScalarSizeInBits();
8061     unsigned ScalarBits = Op0.getValueSizeInBits();
8062     // Make sure we're getting all element bits from the scalar register.
8063     // FIXME: Support implicit sign extension of vmv.v.x?
8064     if (ScalarBits < EltBits)
8065       return SDValue();
8066 
8067     if (IsSigned) {
8068       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8069         return SDValue();
8070     } else {
8071       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8072       if (!DAG.MaskedValueIsZero(Op0, Mask))
8073         return SDValue();
8074     }
8075 
8076     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8077                       DAG.getUNDEF(NarrowVT), Op0, VL);
8078     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8079   }
8080 
8081   return SDValue();
8082 }
8083 
8084 // Try to form VWMUL, VWMULU or VWMULSU.
8085 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8086 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8087                                        bool Commute) {
8088   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8089   SDValue Op0 = N->getOperand(0);
8090   SDValue Op1 = N->getOperand(1);
8091   if (Commute)
8092     std::swap(Op0, Op1);
8093 
8094   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8095   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8096   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8097   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8098     return SDValue();
8099 
8100   SDValue Mask = N->getOperand(2);
8101   SDValue VL = N->getOperand(3);
8102 
8103   // Make sure the mask and VL match.
8104   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8105     return SDValue();
8106 
8107   MVT VT = N->getSimpleValueType(0);
8108 
8109   // Determine the narrow size for a widening multiply.
8110   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8111   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8112                                   VT.getVectorElementCount());
8113 
8114   SDLoc DL(N);
8115 
8116   // See if the other operand is the same opcode.
8117   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8118     if (!Op1.hasOneUse())
8119       return SDValue();
8120 
8121     // Make sure the mask and VL match.
8122     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8123       return SDValue();
8124 
8125     Op1 = Op1.getOperand(0);
8126   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8127     // The operand is a splat of a scalar.
8128 
8129     // The pasthru must be undef for tail agnostic
8130     if (!Op1.getOperand(0).isUndef())
8131       return SDValue();
8132     // The VL must be the same.
8133     if (Op1.getOperand(2) != VL)
8134       return SDValue();
8135 
8136     // Get the scalar value.
8137     Op1 = Op1.getOperand(1);
8138 
8139     // See if have enough sign bits or zero bits in the scalar to use a
8140     // widening multiply by splatting to smaller element size.
8141     unsigned EltBits = VT.getScalarSizeInBits();
8142     unsigned ScalarBits = Op1.getValueSizeInBits();
8143     // Make sure we're getting all element bits from the scalar register.
8144     // FIXME: Support implicit sign extension of vmv.v.x?
8145     if (ScalarBits < EltBits)
8146       return SDValue();
8147 
8148     // If the LHS is a sign extend, try to use vwmul.
8149     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8150       // Can use vwmul.
8151     } else {
8152       // Otherwise try to use vwmulu or vwmulsu.
8153       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8154       if (DAG.MaskedValueIsZero(Op1, Mask))
8155         IsVWMULSU = IsSignExt;
8156       else
8157         return SDValue();
8158     }
8159 
8160     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8161                       DAG.getUNDEF(NarrowVT), Op1, VL);
8162   } else
8163     return SDValue();
8164 
8165   Op0 = Op0.getOperand(0);
8166 
8167   // Re-introduce narrower extends if needed.
8168   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8169   if (Op0.getValueType() != NarrowVT)
8170     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8171   // vwmulsu requires second operand to be zero extended.
8172   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8173   if (Op1.getValueType() != NarrowVT)
8174     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8175 
8176   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8177   if (!IsVWMULSU)
8178     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8179   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8180 }
8181 
8182 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8183   switch (Op.getOpcode()) {
8184   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8185   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8186   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8187   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8188   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8189   }
8190 
8191   return RISCVFPRndMode::Invalid;
8192 }
8193 
8194 // Fold
8195 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8196 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8197 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8198 //   (fp_to_int (fceil X))      -> fcvt X, rup
8199 //   (fp_to_int (fround X))     -> fcvt X, rmm
8200 static SDValue performFP_TO_INTCombine(SDNode *N,
8201                                        TargetLowering::DAGCombinerInfo &DCI,
8202                                        const RISCVSubtarget &Subtarget) {
8203   SelectionDAG &DAG = DCI.DAG;
8204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8205   MVT XLenVT = Subtarget.getXLenVT();
8206 
8207   // Only handle XLen or i32 types. Other types narrower than XLen will
8208   // eventually be legalized to XLenVT.
8209   EVT VT = N->getValueType(0);
8210   if (VT != MVT::i32 && VT != XLenVT)
8211     return SDValue();
8212 
8213   SDValue Src = N->getOperand(0);
8214 
8215   // Ensure the FP type is also legal.
8216   if (!TLI.isTypeLegal(Src.getValueType()))
8217     return SDValue();
8218 
8219   // Don't do this for f16 with Zfhmin and not Zfh.
8220   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8221     return SDValue();
8222 
8223   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8224   if (FRM == RISCVFPRndMode::Invalid)
8225     return SDValue();
8226 
8227   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8228 
8229   unsigned Opc;
8230   if (VT == XLenVT)
8231     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8232   else
8233     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8234 
8235   SDLoc DL(N);
8236   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8237                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8238   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8239 }
8240 
8241 // Fold
8242 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8243 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8244 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8245 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8246 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8247 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8248                                        TargetLowering::DAGCombinerInfo &DCI,
8249                                        const RISCVSubtarget &Subtarget) {
8250   SelectionDAG &DAG = DCI.DAG;
8251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8252   MVT XLenVT = Subtarget.getXLenVT();
8253 
8254   // Only handle XLen types. Other types narrower than XLen will eventually be
8255   // legalized to XLenVT.
8256   EVT DstVT = N->getValueType(0);
8257   if (DstVT != XLenVT)
8258     return SDValue();
8259 
8260   SDValue Src = N->getOperand(0);
8261 
8262   // Ensure the FP type is also legal.
8263   if (!TLI.isTypeLegal(Src.getValueType()))
8264     return SDValue();
8265 
8266   // Don't do this for f16 with Zfhmin and not Zfh.
8267   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8268     return SDValue();
8269 
8270   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8271 
8272   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8273   if (FRM == RISCVFPRndMode::Invalid)
8274     return SDValue();
8275 
8276   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8277 
8278   unsigned Opc;
8279   if (SatVT == DstVT)
8280     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8281   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8282     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8283   else
8284     return SDValue();
8285   // FIXME: Support other SatVTs by clamping before or after the conversion.
8286 
8287   Src = Src.getOperand(0);
8288 
8289   SDLoc DL(N);
8290   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8291                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8292 
8293   // RISCV FP-to-int conversions saturate to the destination register size, but
8294   // don't produce 0 for nan.
8295   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8296   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8297 }
8298 
8299 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8300 // smaller than XLenVT.
8301 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8302                                         const RISCVSubtarget &Subtarget) {
8303   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8304 
8305   SDValue Src = N->getOperand(0);
8306   if (Src.getOpcode() != ISD::BSWAP)
8307     return SDValue();
8308 
8309   EVT VT = N->getValueType(0);
8310   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8311       !isPowerOf2_32(VT.getSizeInBits()))
8312     return SDValue();
8313 
8314   SDLoc DL(N);
8315   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8316                      DAG.getConstant(7, DL, VT));
8317 }
8318 
8319 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8320                                                DAGCombinerInfo &DCI) const {
8321   SelectionDAG &DAG = DCI.DAG;
8322 
8323   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8324   // bits are demanded. N will be added to the Worklist if it was not deleted.
8325   // Caller should return SDValue(N, 0) if this returns true.
8326   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8327     SDValue Op = N->getOperand(OpNo);
8328     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8329     if (!SimplifyDemandedBits(Op, Mask, DCI))
8330       return false;
8331 
8332     if (N->getOpcode() != ISD::DELETED_NODE)
8333       DCI.AddToWorklist(N);
8334     return true;
8335   };
8336 
8337   switch (N->getOpcode()) {
8338   default:
8339     break;
8340   case RISCVISD::SplitF64: {
8341     SDValue Op0 = N->getOperand(0);
8342     // If the input to SplitF64 is just BuildPairF64 then the operation is
8343     // redundant. Instead, use BuildPairF64's operands directly.
8344     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8345       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8346 
8347     if (Op0->isUndef()) {
8348       SDValue Lo = DAG.getUNDEF(MVT::i32);
8349       SDValue Hi = DAG.getUNDEF(MVT::i32);
8350       return DCI.CombineTo(N, Lo, Hi);
8351     }
8352 
8353     SDLoc DL(N);
8354 
8355     // It's cheaper to materialise two 32-bit integers than to load a double
8356     // from the constant pool and transfer it to integer registers through the
8357     // stack.
8358     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8359       APInt V = C->getValueAPF().bitcastToAPInt();
8360       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8361       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8362       return DCI.CombineTo(N, Lo, Hi);
8363     }
8364 
8365     // This is a target-specific version of a DAGCombine performed in
8366     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8367     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8368     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8369     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8370         !Op0.getNode()->hasOneUse())
8371       break;
8372     SDValue NewSplitF64 =
8373         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8374                     Op0.getOperand(0));
8375     SDValue Lo = NewSplitF64.getValue(0);
8376     SDValue Hi = NewSplitF64.getValue(1);
8377     APInt SignBit = APInt::getSignMask(32);
8378     if (Op0.getOpcode() == ISD::FNEG) {
8379       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8380                                   DAG.getConstant(SignBit, DL, MVT::i32));
8381       return DCI.CombineTo(N, Lo, NewHi);
8382     }
8383     assert(Op0.getOpcode() == ISD::FABS);
8384     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8385                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8386     return DCI.CombineTo(N, Lo, NewHi);
8387   }
8388   case RISCVISD::SLLW:
8389   case RISCVISD::SRAW:
8390   case RISCVISD::SRLW: {
8391     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8392     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8393         SimplifyDemandedLowBitsHelper(1, 5))
8394       return SDValue(N, 0);
8395 
8396     break;
8397   }
8398   case ISD::ROTR:
8399   case ISD::ROTL:
8400   case RISCVISD::RORW:
8401   case RISCVISD::ROLW: {
8402     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8403       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8404       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8405           SimplifyDemandedLowBitsHelper(1, 5))
8406         return SDValue(N, 0);
8407     }
8408 
8409     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8410   }
8411   case RISCVISD::CLZW:
8412   case RISCVISD::CTZW: {
8413     // Only the lower 32 bits of the first operand are read
8414     if (SimplifyDemandedLowBitsHelper(0, 32))
8415       return SDValue(N, 0);
8416     break;
8417   }
8418   case RISCVISD::GREV:
8419   case RISCVISD::GORC: {
8420     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8421     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8422     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8423     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8424       return SDValue(N, 0);
8425 
8426     return combineGREVI_GORCI(N, DAG);
8427   }
8428   case RISCVISD::GREVW:
8429   case RISCVISD::GORCW: {
8430     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8431     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8432         SimplifyDemandedLowBitsHelper(1, 5))
8433       return SDValue(N, 0);
8434 
8435     break;
8436   }
8437   case RISCVISD::SHFL:
8438   case RISCVISD::UNSHFL: {
8439     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8440     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8441     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8442     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8443       return SDValue(N, 0);
8444 
8445     break;
8446   }
8447   case RISCVISD::SHFLW:
8448   case RISCVISD::UNSHFLW: {
8449     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8450     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8451         SimplifyDemandedLowBitsHelper(1, 4))
8452       return SDValue(N, 0);
8453 
8454     break;
8455   }
8456   case RISCVISD::BCOMPRESSW:
8457   case RISCVISD::BDECOMPRESSW: {
8458     // Only the lower 32 bits of LHS and RHS are read.
8459     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8460         SimplifyDemandedLowBitsHelper(1, 32))
8461       return SDValue(N, 0);
8462 
8463     break;
8464   }
8465   case RISCVISD::FSR:
8466   case RISCVISD::FSL:
8467   case RISCVISD::FSRW:
8468   case RISCVISD::FSLW: {
8469     bool IsWInstruction =
8470         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8471     unsigned BitWidth =
8472         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8473     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8474     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8475     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8476       return SDValue(N, 0);
8477 
8478     break;
8479   }
8480   case RISCVISD::FMV_X_ANYEXTH:
8481   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8482     SDLoc DL(N);
8483     SDValue Op0 = N->getOperand(0);
8484     MVT VT = N->getSimpleValueType(0);
8485     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8486     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8487     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8488     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8489          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8490         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8491          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8492       assert(Op0.getOperand(0).getValueType() == VT &&
8493              "Unexpected value type!");
8494       return Op0.getOperand(0);
8495     }
8496 
8497     // This is a target-specific version of a DAGCombine performed in
8498     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8499     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8500     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8501     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8502         !Op0.getNode()->hasOneUse())
8503       break;
8504     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8505     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8506     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8507     if (Op0.getOpcode() == ISD::FNEG)
8508       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8509                          DAG.getConstant(SignBit, DL, VT));
8510 
8511     assert(Op0.getOpcode() == ISD::FABS);
8512     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8513                        DAG.getConstant(~SignBit, DL, VT));
8514   }
8515   case ISD::ADD:
8516     return performADDCombine(N, DAG, Subtarget);
8517   case ISD::SUB:
8518     return performSUBCombine(N, DAG);
8519   case ISD::AND:
8520     return performANDCombine(N, DAG);
8521   case ISD::OR:
8522     return performORCombine(N, DAG, Subtarget);
8523   case ISD::XOR:
8524     return performXORCombine(N, DAG);
8525   case ISD::SIGN_EXTEND_INREG:
8526     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8527   case ISD::ZERO_EXTEND:
8528     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8529     // type legalization. This is safe because fp_to_uint produces poison if
8530     // it overflows.
8531     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8532       SDValue Src = N->getOperand(0);
8533       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8534           isTypeLegal(Src.getOperand(0).getValueType()))
8535         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8536                            Src.getOperand(0));
8537       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8538           isTypeLegal(Src.getOperand(1).getValueType())) {
8539         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8540         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8541                                   Src.getOperand(0), Src.getOperand(1));
8542         DCI.CombineTo(N, Res);
8543         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8544         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8545         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8546       }
8547     }
8548     return SDValue();
8549   case RISCVISD::SELECT_CC: {
8550     // Transform
8551     SDValue LHS = N->getOperand(0);
8552     SDValue RHS = N->getOperand(1);
8553     SDValue TrueV = N->getOperand(3);
8554     SDValue FalseV = N->getOperand(4);
8555 
8556     // If the True and False values are the same, we don't need a select_cc.
8557     if (TrueV == FalseV)
8558       return TrueV;
8559 
8560     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8561     if (!ISD::isIntEqualitySetCC(CCVal))
8562       break;
8563 
8564     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8565     //      (select_cc X, Y, lt, trueV, falseV)
8566     // Sometimes the setcc is introduced after select_cc has been formed.
8567     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8568         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8569       // If we're looking for eq 0 instead of ne 0, we need to invert the
8570       // condition.
8571       bool Invert = CCVal == ISD::SETEQ;
8572       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8573       if (Invert)
8574         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8575 
8576       SDLoc DL(N);
8577       RHS = LHS.getOperand(1);
8578       LHS = LHS.getOperand(0);
8579       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8580 
8581       SDValue TargetCC = DAG.getCondCode(CCVal);
8582       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8583                          {LHS, RHS, TargetCC, TrueV, FalseV});
8584     }
8585 
8586     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8587     //      (select_cc X, Y, eq/ne, trueV, falseV)
8588     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8589       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8590                          {LHS.getOperand(0), LHS.getOperand(1),
8591                           N->getOperand(2), TrueV, FalseV});
8592     // (select_cc X, 1, setne, trueV, falseV) ->
8593     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8594     // This can occur when legalizing some floating point comparisons.
8595     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8596     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8597       SDLoc DL(N);
8598       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8599       SDValue TargetCC = DAG.getCondCode(CCVal);
8600       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8601       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8602                          {LHS, RHS, TargetCC, TrueV, FalseV});
8603     }
8604 
8605     break;
8606   }
8607   case RISCVISD::BR_CC: {
8608     SDValue LHS = N->getOperand(1);
8609     SDValue RHS = N->getOperand(2);
8610     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8611     if (!ISD::isIntEqualitySetCC(CCVal))
8612       break;
8613 
8614     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8615     //      (br_cc X, Y, lt, dest)
8616     // Sometimes the setcc is introduced after br_cc has been formed.
8617     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8618         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8619       // If we're looking for eq 0 instead of ne 0, we need to invert the
8620       // condition.
8621       bool Invert = CCVal == ISD::SETEQ;
8622       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8623       if (Invert)
8624         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8625 
8626       SDLoc DL(N);
8627       RHS = LHS.getOperand(1);
8628       LHS = LHS.getOperand(0);
8629       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8630 
8631       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8632                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8633                          N->getOperand(4));
8634     }
8635 
8636     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8637     //      (br_cc X, Y, eq/ne, trueV, falseV)
8638     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8639       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8640                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8641                          N->getOperand(3), N->getOperand(4));
8642 
8643     // (br_cc X, 1, setne, br_cc) ->
8644     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8645     // This can occur when legalizing some floating point comparisons.
8646     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8647     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8648       SDLoc DL(N);
8649       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8650       SDValue TargetCC = DAG.getCondCode(CCVal);
8651       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8652       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8653                          N->getOperand(0), LHS, RHS, TargetCC,
8654                          N->getOperand(4));
8655     }
8656     break;
8657   }
8658   case ISD::BITREVERSE:
8659     return performBITREVERSECombine(N, DAG, Subtarget);
8660   case ISD::FP_TO_SINT:
8661   case ISD::FP_TO_UINT:
8662     return performFP_TO_INTCombine(N, DCI, Subtarget);
8663   case ISD::FP_TO_SINT_SAT:
8664   case ISD::FP_TO_UINT_SAT:
8665     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8666   case ISD::FCOPYSIGN: {
8667     EVT VT = N->getValueType(0);
8668     if (!VT.isVector())
8669       break;
8670     // There is a form of VFSGNJ which injects the negated sign of its second
8671     // operand. Try and bubble any FNEG up after the extend/round to produce
8672     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8673     // TRUNC=1.
8674     SDValue In2 = N->getOperand(1);
8675     // Avoid cases where the extend/round has multiple uses, as duplicating
8676     // those is typically more expensive than removing a fneg.
8677     if (!In2.hasOneUse())
8678       break;
8679     if (In2.getOpcode() != ISD::FP_EXTEND &&
8680         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8681       break;
8682     In2 = In2.getOperand(0);
8683     if (In2.getOpcode() != ISD::FNEG)
8684       break;
8685     SDLoc DL(N);
8686     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8687     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8688                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8689   }
8690   case ISD::MGATHER:
8691   case ISD::MSCATTER:
8692   case ISD::VP_GATHER:
8693   case ISD::VP_SCATTER: {
8694     if (!DCI.isBeforeLegalize())
8695       break;
8696     SDValue Index, ScaleOp;
8697     bool IsIndexScaled = false;
8698     bool IsIndexSigned = false;
8699     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8700       Index = VPGSN->getIndex();
8701       ScaleOp = VPGSN->getScale();
8702       IsIndexScaled = VPGSN->isIndexScaled();
8703       IsIndexSigned = VPGSN->isIndexSigned();
8704     } else {
8705       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8706       Index = MGSN->getIndex();
8707       ScaleOp = MGSN->getScale();
8708       IsIndexScaled = MGSN->isIndexScaled();
8709       IsIndexSigned = MGSN->isIndexSigned();
8710     }
8711     EVT IndexVT = Index.getValueType();
8712     MVT XLenVT = Subtarget.getXLenVT();
8713     // RISCV indexed loads only support the "unsigned unscaled" addressing
8714     // mode, so anything else must be manually legalized.
8715     bool NeedsIdxLegalization =
8716         IsIndexScaled ||
8717         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8718     if (!NeedsIdxLegalization)
8719       break;
8720 
8721     SDLoc DL(N);
8722 
8723     // Any index legalization should first promote to XLenVT, so we don't lose
8724     // bits when scaling. This may create an illegal index type so we let
8725     // LLVM's legalization take care of the splitting.
8726     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8727     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8728       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8729       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8730                           DL, IndexVT, Index);
8731     }
8732 
8733     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8734     if (IsIndexScaled && Scale != 1) {
8735       // Manually scale the indices by the element size.
8736       // TODO: Sanitize the scale operand here?
8737       // TODO: For VP nodes, should we use VP_SHL here?
8738       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8739       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8740       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8741     }
8742 
8743     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8744     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8745       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8746                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8747                               VPGN->getScale(), VPGN->getMask(),
8748                               VPGN->getVectorLength()},
8749                              VPGN->getMemOperand(), NewIndexTy);
8750     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8751       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8752                               {VPSN->getChain(), VPSN->getValue(),
8753                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8754                                VPSN->getMask(), VPSN->getVectorLength()},
8755                               VPSN->getMemOperand(), NewIndexTy);
8756     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8757       return DAG.getMaskedGather(
8758           N->getVTList(), MGN->getMemoryVT(), DL,
8759           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8760            MGN->getBasePtr(), Index, MGN->getScale()},
8761           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8762     const auto *MSN = cast<MaskedScatterSDNode>(N);
8763     return DAG.getMaskedScatter(
8764         N->getVTList(), MSN->getMemoryVT(), DL,
8765         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8766          Index, MSN->getScale()},
8767         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8768   }
8769   case RISCVISD::SRA_VL:
8770   case RISCVISD::SRL_VL:
8771   case RISCVISD::SHL_VL: {
8772     SDValue ShAmt = N->getOperand(1);
8773     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8774       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8775       SDLoc DL(N);
8776       SDValue VL = N->getOperand(3);
8777       EVT VT = N->getValueType(0);
8778       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8779                           ShAmt.getOperand(1), VL);
8780       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8781                          N->getOperand(2), N->getOperand(3));
8782     }
8783     break;
8784   }
8785   case ISD::SRA:
8786   case ISD::SRL:
8787   case ISD::SHL: {
8788     SDValue ShAmt = N->getOperand(1);
8789     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8790       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8791       SDLoc DL(N);
8792       EVT VT = N->getValueType(0);
8793       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8794                           ShAmt.getOperand(1),
8795                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8796       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8797     }
8798     break;
8799   }
8800   case RISCVISD::ADD_VL:
8801     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8802       return V;
8803     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8804   case RISCVISD::SUB_VL:
8805     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8806   case RISCVISD::VWADD_W_VL:
8807   case RISCVISD::VWADDU_W_VL:
8808   case RISCVISD::VWSUB_W_VL:
8809   case RISCVISD::VWSUBU_W_VL:
8810     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8811   case RISCVISD::MUL_VL:
8812     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8813       return V;
8814     // Mul is commutative.
8815     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8816   case ISD::STORE: {
8817     auto *Store = cast<StoreSDNode>(N);
8818     SDValue Val = Store->getValue();
8819     // Combine store of vmv.x.s to vse with VL of 1.
8820     // FIXME: Support FP.
8821     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8822       SDValue Src = Val.getOperand(0);
8823       EVT VecVT = Src.getValueType();
8824       EVT MemVT = Store->getMemoryVT();
8825       // The memory VT and the element type must match.
8826       if (VecVT.getVectorElementType() == MemVT) {
8827         SDLoc DL(N);
8828         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8829         return DAG.getStoreVP(
8830             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8831             DAG.getConstant(1, DL, MaskVT),
8832             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8833             Store->getMemOperand(), Store->getAddressingMode(),
8834             Store->isTruncatingStore(), /*IsCompress*/ false);
8835       }
8836     }
8837 
8838     break;
8839   }
8840   case ISD::SPLAT_VECTOR: {
8841     EVT VT = N->getValueType(0);
8842     // Only perform this combine on legal MVT types.
8843     if (!isTypeLegal(VT))
8844       break;
8845     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8846                                          DAG, Subtarget))
8847       return Gather;
8848     break;
8849   }
8850   case RISCVISD::VMV_V_X_VL: {
8851     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8852     // scalar input.
8853     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8854     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8855     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8856       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8857         return SDValue(N, 0);
8858 
8859     break;
8860   }
8861   case ISD::INTRINSIC_WO_CHAIN: {
8862     unsigned IntNo = N->getConstantOperandVal(0);
8863     switch (IntNo) {
8864       // By default we do not combine any intrinsic.
8865     default:
8866       return SDValue();
8867     case Intrinsic::riscv_vcpop:
8868     case Intrinsic::riscv_vcpop_mask:
8869     case Intrinsic::riscv_vfirst:
8870     case Intrinsic::riscv_vfirst_mask: {
8871       SDValue VL = N->getOperand(2);
8872       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8873           IntNo == Intrinsic::riscv_vfirst_mask)
8874         VL = N->getOperand(3);
8875       if (!isNullConstant(VL))
8876         return SDValue();
8877       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8878       SDLoc DL(N);
8879       EVT VT = N->getValueType(0);
8880       if (IntNo == Intrinsic::riscv_vfirst ||
8881           IntNo == Intrinsic::riscv_vfirst_mask)
8882         return DAG.getConstant(-1, DL, VT);
8883       return DAG.getConstant(0, DL, VT);
8884     }
8885     }
8886   }
8887   }
8888 
8889   return SDValue();
8890 }
8891 
8892 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8893     const SDNode *N, CombineLevel Level) const {
8894   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8895   // materialised in fewer instructions than `(OP _, c1)`:
8896   //
8897   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8898   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8899   SDValue N0 = N->getOperand(0);
8900   EVT Ty = N0.getValueType();
8901   if (Ty.isScalarInteger() &&
8902       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8903     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8904     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8905     if (C1 && C2) {
8906       const APInt &C1Int = C1->getAPIntValue();
8907       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8908 
8909       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8910       // and the combine should happen, to potentially allow further combines
8911       // later.
8912       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8913           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8914         return true;
8915 
8916       // We can materialise `c1` in an add immediate, so it's "free", and the
8917       // combine should be prevented.
8918       if (C1Int.getMinSignedBits() <= 64 &&
8919           isLegalAddImmediate(C1Int.getSExtValue()))
8920         return false;
8921 
8922       // Neither constant will fit into an immediate, so find materialisation
8923       // costs.
8924       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8925                                               Subtarget.getFeatureBits(),
8926                                               /*CompressionCost*/true);
8927       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8928           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8929           /*CompressionCost*/true);
8930 
8931       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8932       // combine should be prevented.
8933       if (C1Cost < ShiftedC1Cost)
8934         return false;
8935     }
8936   }
8937   return true;
8938 }
8939 
8940 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8941     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8942     TargetLoweringOpt &TLO) const {
8943   // Delay this optimization as late as possible.
8944   if (!TLO.LegalOps)
8945     return false;
8946 
8947   EVT VT = Op.getValueType();
8948   if (VT.isVector())
8949     return false;
8950 
8951   // Only handle AND for now.
8952   if (Op.getOpcode() != ISD::AND)
8953     return false;
8954 
8955   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8956   if (!C)
8957     return false;
8958 
8959   const APInt &Mask = C->getAPIntValue();
8960 
8961   // Clear all non-demanded bits initially.
8962   APInt ShrunkMask = Mask & DemandedBits;
8963 
8964   // Try to make a smaller immediate by setting undemanded bits.
8965 
8966   APInt ExpandedMask = Mask | ~DemandedBits;
8967 
8968   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8969     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8970   };
8971   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8972     if (NewMask == Mask)
8973       return true;
8974     SDLoc DL(Op);
8975     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8976     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8977     return TLO.CombineTo(Op, NewOp);
8978   };
8979 
8980   // If the shrunk mask fits in sign extended 12 bits, let the target
8981   // independent code apply it.
8982   if (ShrunkMask.isSignedIntN(12))
8983     return false;
8984 
8985   // Preserve (and X, 0xffff) when zext.h is supported.
8986   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8987     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8988     if (IsLegalMask(NewMask))
8989       return UseMask(NewMask);
8990   }
8991 
8992   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8993   if (VT == MVT::i64) {
8994     APInt NewMask = APInt(64, 0xffffffff);
8995     if (IsLegalMask(NewMask))
8996       return UseMask(NewMask);
8997   }
8998 
8999   // For the remaining optimizations, we need to be able to make a negative
9000   // number through a combination of mask and undemanded bits.
9001   if (!ExpandedMask.isNegative())
9002     return false;
9003 
9004   // What is the fewest number of bits we need to represent the negative number.
9005   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9006 
9007   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9008   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9009   APInt NewMask = ShrunkMask;
9010   if (MinSignedBits <= 12)
9011     NewMask.setBitsFrom(11);
9012   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9013     NewMask.setBitsFrom(31);
9014   else
9015     return false;
9016 
9017   // Check that our new mask is a subset of the demanded mask.
9018   assert(IsLegalMask(NewMask));
9019   return UseMask(NewMask);
9020 }
9021 
9022 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9023   static const uint64_t GREVMasks[] = {
9024       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9025       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9026 
9027   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9028     unsigned Shift = 1 << Stage;
9029     if (ShAmt & Shift) {
9030       uint64_t Mask = GREVMasks[Stage];
9031       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9032       if (IsGORC)
9033         Res |= x;
9034       x = Res;
9035     }
9036   }
9037 
9038   return x;
9039 }
9040 
9041 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9042                                                         KnownBits &Known,
9043                                                         const APInt &DemandedElts,
9044                                                         const SelectionDAG &DAG,
9045                                                         unsigned Depth) const {
9046   unsigned BitWidth = Known.getBitWidth();
9047   unsigned Opc = Op.getOpcode();
9048   assert((Opc >= ISD::BUILTIN_OP_END ||
9049           Opc == ISD::INTRINSIC_WO_CHAIN ||
9050           Opc == ISD::INTRINSIC_W_CHAIN ||
9051           Opc == ISD::INTRINSIC_VOID) &&
9052          "Should use MaskedValueIsZero if you don't know whether Op"
9053          " is a target node!");
9054 
9055   Known.resetAll();
9056   switch (Opc) {
9057   default: break;
9058   case RISCVISD::SELECT_CC: {
9059     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9060     // If we don't know any bits, early out.
9061     if (Known.isUnknown())
9062       break;
9063     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9064 
9065     // Only known if known in both the LHS and RHS.
9066     Known = KnownBits::commonBits(Known, Known2);
9067     break;
9068   }
9069   case RISCVISD::REMUW: {
9070     KnownBits Known2;
9071     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9072     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9073     // We only care about the lower 32 bits.
9074     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9075     // Restore the original width by sign extending.
9076     Known = Known.sext(BitWidth);
9077     break;
9078   }
9079   case RISCVISD::DIVUW: {
9080     KnownBits Known2;
9081     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9082     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9083     // We only care about the lower 32 bits.
9084     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9085     // Restore the original width by sign extending.
9086     Known = Known.sext(BitWidth);
9087     break;
9088   }
9089   case RISCVISD::CTZW: {
9090     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9091     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9092     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9093     Known.Zero.setBitsFrom(LowBits);
9094     break;
9095   }
9096   case RISCVISD::CLZW: {
9097     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9098     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9099     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9100     Known.Zero.setBitsFrom(LowBits);
9101     break;
9102   }
9103   case RISCVISD::GREV:
9104   case RISCVISD::GORC: {
9105     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9106       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9107       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9108       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9109       // To compute zeros, we need to invert the value and invert it back after.
9110       Known.Zero =
9111           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9112       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9113     }
9114     break;
9115   }
9116   case RISCVISD::READ_VLENB: {
9117     // If we know the minimum VLen from Zvl extensions, we can use that to
9118     // determine the trailing zeros of VLENB.
9119     // FIXME: Limit to 128 bit vectors until we have more testing.
9120     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9121     if (MinVLenB > 0)
9122       Known.Zero.setLowBits(Log2_32(MinVLenB));
9123     // We assume VLENB is no more than 65536 / 8 bytes.
9124     Known.Zero.setBitsFrom(14);
9125     break;
9126   }
9127   case ISD::INTRINSIC_W_CHAIN:
9128   case ISD::INTRINSIC_WO_CHAIN: {
9129     unsigned IntNo =
9130         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9131     switch (IntNo) {
9132     default:
9133       // We can't do anything for most intrinsics.
9134       break;
9135     case Intrinsic::riscv_vsetvli:
9136     case Intrinsic::riscv_vsetvlimax:
9137     case Intrinsic::riscv_vsetvli_opt:
9138     case Intrinsic::riscv_vsetvlimax_opt:
9139       // Assume that VL output is positive and would fit in an int32_t.
9140       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9141       if (BitWidth >= 32)
9142         Known.Zero.setBitsFrom(31);
9143       break;
9144     }
9145     break;
9146   }
9147   }
9148 }
9149 
9150 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9151     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9152     unsigned Depth) const {
9153   switch (Op.getOpcode()) {
9154   default:
9155     break;
9156   case RISCVISD::SELECT_CC: {
9157     unsigned Tmp =
9158         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9159     if (Tmp == 1) return 1;  // Early out.
9160     unsigned Tmp2 =
9161         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9162     return std::min(Tmp, Tmp2);
9163   }
9164   case RISCVISD::SLLW:
9165   case RISCVISD::SRAW:
9166   case RISCVISD::SRLW:
9167   case RISCVISD::DIVW:
9168   case RISCVISD::DIVUW:
9169   case RISCVISD::REMUW:
9170   case RISCVISD::ROLW:
9171   case RISCVISD::RORW:
9172   case RISCVISD::GREVW:
9173   case RISCVISD::GORCW:
9174   case RISCVISD::FSLW:
9175   case RISCVISD::FSRW:
9176   case RISCVISD::SHFLW:
9177   case RISCVISD::UNSHFLW:
9178   case RISCVISD::BCOMPRESSW:
9179   case RISCVISD::BDECOMPRESSW:
9180   case RISCVISD::BFPW:
9181   case RISCVISD::FCVT_W_RV64:
9182   case RISCVISD::FCVT_WU_RV64:
9183   case RISCVISD::STRICT_FCVT_W_RV64:
9184   case RISCVISD::STRICT_FCVT_WU_RV64:
9185     // TODO: As the result is sign-extended, this is conservatively correct. A
9186     // more precise answer could be calculated for SRAW depending on known
9187     // bits in the shift amount.
9188     return 33;
9189   case RISCVISD::SHFL:
9190   case RISCVISD::UNSHFL: {
9191     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9192     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9193     // will stay within the upper 32 bits. If there were more than 32 sign bits
9194     // before there will be at least 33 sign bits after.
9195     if (Op.getValueType() == MVT::i64 &&
9196         isa<ConstantSDNode>(Op.getOperand(1)) &&
9197         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9198       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9199       if (Tmp > 32)
9200         return 33;
9201     }
9202     break;
9203   }
9204   case RISCVISD::VMV_X_S: {
9205     // The number of sign bits of the scalar result is computed by obtaining the
9206     // element type of the input vector operand, subtracting its width from the
9207     // XLEN, and then adding one (sign bit within the element type). If the
9208     // element type is wider than XLen, the least-significant XLEN bits are
9209     // taken.
9210     unsigned XLen = Subtarget.getXLen();
9211     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9212     if (EltBits <= XLen)
9213       return XLen - EltBits + 1;
9214     break;
9215   }
9216   }
9217 
9218   return 1;
9219 }
9220 
9221 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9222                                                   MachineBasicBlock *BB) {
9223   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9224 
9225   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9226   // Should the count have wrapped while it was being read, we need to try
9227   // again.
9228   // ...
9229   // read:
9230   // rdcycleh x3 # load high word of cycle
9231   // rdcycle  x2 # load low word of cycle
9232   // rdcycleh x4 # load high word of cycle
9233   // bne x3, x4, read # check if high word reads match, otherwise try again
9234   // ...
9235 
9236   MachineFunction &MF = *BB->getParent();
9237   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9238   MachineFunction::iterator It = ++BB->getIterator();
9239 
9240   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9241   MF.insert(It, LoopMBB);
9242 
9243   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9244   MF.insert(It, DoneMBB);
9245 
9246   // Transfer the remainder of BB and its successor edges to DoneMBB.
9247   DoneMBB->splice(DoneMBB->begin(), BB,
9248                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9249   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9250 
9251   BB->addSuccessor(LoopMBB);
9252 
9253   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9254   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9255   Register LoReg = MI.getOperand(0).getReg();
9256   Register HiReg = MI.getOperand(1).getReg();
9257   DebugLoc DL = MI.getDebugLoc();
9258 
9259   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9260   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9261       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9262       .addReg(RISCV::X0);
9263   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9264       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9265       .addReg(RISCV::X0);
9266   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9267       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9268       .addReg(RISCV::X0);
9269 
9270   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9271       .addReg(HiReg)
9272       .addReg(ReadAgainReg)
9273       .addMBB(LoopMBB);
9274 
9275   LoopMBB->addSuccessor(LoopMBB);
9276   LoopMBB->addSuccessor(DoneMBB);
9277 
9278   MI.eraseFromParent();
9279 
9280   return DoneMBB;
9281 }
9282 
9283 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9284                                              MachineBasicBlock *BB) {
9285   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9286 
9287   MachineFunction &MF = *BB->getParent();
9288   DebugLoc DL = MI.getDebugLoc();
9289   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9290   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9291   Register LoReg = MI.getOperand(0).getReg();
9292   Register HiReg = MI.getOperand(1).getReg();
9293   Register SrcReg = MI.getOperand(2).getReg();
9294   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9295   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9296 
9297   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9298                           RI);
9299   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9300   MachineMemOperand *MMOLo =
9301       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9302   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9303       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9304   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9305       .addFrameIndex(FI)
9306       .addImm(0)
9307       .addMemOperand(MMOLo);
9308   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9309       .addFrameIndex(FI)
9310       .addImm(4)
9311       .addMemOperand(MMOHi);
9312   MI.eraseFromParent(); // The pseudo instruction is gone now.
9313   return BB;
9314 }
9315 
9316 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9317                                                  MachineBasicBlock *BB) {
9318   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9319          "Unexpected instruction");
9320 
9321   MachineFunction &MF = *BB->getParent();
9322   DebugLoc DL = MI.getDebugLoc();
9323   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9324   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9325   Register DstReg = MI.getOperand(0).getReg();
9326   Register LoReg = MI.getOperand(1).getReg();
9327   Register HiReg = MI.getOperand(2).getReg();
9328   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9329   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9330 
9331   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9332   MachineMemOperand *MMOLo =
9333       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9334   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9335       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9336   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9337       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9338       .addFrameIndex(FI)
9339       .addImm(0)
9340       .addMemOperand(MMOLo);
9341   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9342       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9343       .addFrameIndex(FI)
9344       .addImm(4)
9345       .addMemOperand(MMOHi);
9346   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9347   MI.eraseFromParent(); // The pseudo instruction is gone now.
9348   return BB;
9349 }
9350 
9351 static bool isSelectPseudo(MachineInstr &MI) {
9352   switch (MI.getOpcode()) {
9353   default:
9354     return false;
9355   case RISCV::Select_GPR_Using_CC_GPR:
9356   case RISCV::Select_FPR16_Using_CC_GPR:
9357   case RISCV::Select_FPR32_Using_CC_GPR:
9358   case RISCV::Select_FPR64_Using_CC_GPR:
9359     return true;
9360   }
9361 }
9362 
9363 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9364                                         unsigned RelOpcode, unsigned EqOpcode,
9365                                         const RISCVSubtarget &Subtarget) {
9366   DebugLoc DL = MI.getDebugLoc();
9367   Register DstReg = MI.getOperand(0).getReg();
9368   Register Src1Reg = MI.getOperand(1).getReg();
9369   Register Src2Reg = MI.getOperand(2).getReg();
9370   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9371   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9372   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9373 
9374   // Save the current FFLAGS.
9375   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9376 
9377   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9378                  .addReg(Src1Reg)
9379                  .addReg(Src2Reg);
9380   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9381     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9382 
9383   // Restore the FFLAGS.
9384   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9385       .addReg(SavedFFlags, RegState::Kill);
9386 
9387   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9388   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9389                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9390                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9391   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9392     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9393 
9394   // Erase the pseudoinstruction.
9395   MI.eraseFromParent();
9396   return BB;
9397 }
9398 
9399 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9400                                            MachineBasicBlock *BB,
9401                                            const RISCVSubtarget &Subtarget) {
9402   // To "insert" Select_* instructions, we actually have to insert the triangle
9403   // control-flow pattern.  The incoming instructions know the destination vreg
9404   // to set, the condition code register to branch on, the true/false values to
9405   // select between, and the condcode to use to select the appropriate branch.
9406   //
9407   // We produce the following control flow:
9408   //     HeadMBB
9409   //     |  \
9410   //     |  IfFalseMBB
9411   //     | /
9412   //    TailMBB
9413   //
9414   // When we find a sequence of selects we attempt to optimize their emission
9415   // by sharing the control flow. Currently we only handle cases where we have
9416   // multiple selects with the exact same condition (same LHS, RHS and CC).
9417   // The selects may be interleaved with other instructions if the other
9418   // instructions meet some requirements we deem safe:
9419   // - They are debug instructions. Otherwise,
9420   // - They do not have side-effects, do not access memory and their inputs do
9421   //   not depend on the results of the select pseudo-instructions.
9422   // The TrueV/FalseV operands of the selects cannot depend on the result of
9423   // previous selects in the sequence.
9424   // These conditions could be further relaxed. See the X86 target for a
9425   // related approach and more information.
9426   Register LHS = MI.getOperand(1).getReg();
9427   Register RHS = MI.getOperand(2).getReg();
9428   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9429 
9430   SmallVector<MachineInstr *, 4> SelectDebugValues;
9431   SmallSet<Register, 4> SelectDests;
9432   SelectDests.insert(MI.getOperand(0).getReg());
9433 
9434   MachineInstr *LastSelectPseudo = &MI;
9435 
9436   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9437        SequenceMBBI != E; ++SequenceMBBI) {
9438     if (SequenceMBBI->isDebugInstr())
9439       continue;
9440     else if (isSelectPseudo(*SequenceMBBI)) {
9441       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9442           SequenceMBBI->getOperand(2).getReg() != RHS ||
9443           SequenceMBBI->getOperand(3).getImm() != CC ||
9444           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9445           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9446         break;
9447       LastSelectPseudo = &*SequenceMBBI;
9448       SequenceMBBI->collectDebugValues(SelectDebugValues);
9449       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9450     } else {
9451       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9452           SequenceMBBI->mayLoadOrStore())
9453         break;
9454       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9455             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9456           }))
9457         break;
9458     }
9459   }
9460 
9461   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9462   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9463   DebugLoc DL = MI.getDebugLoc();
9464   MachineFunction::iterator I = ++BB->getIterator();
9465 
9466   MachineBasicBlock *HeadMBB = BB;
9467   MachineFunction *F = BB->getParent();
9468   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9469   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9470 
9471   F->insert(I, IfFalseMBB);
9472   F->insert(I, TailMBB);
9473 
9474   // Transfer debug instructions associated with the selects to TailMBB.
9475   for (MachineInstr *DebugInstr : SelectDebugValues) {
9476     TailMBB->push_back(DebugInstr->removeFromParent());
9477   }
9478 
9479   // Move all instructions after the sequence to TailMBB.
9480   TailMBB->splice(TailMBB->end(), HeadMBB,
9481                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9482   // Update machine-CFG edges by transferring all successors of the current
9483   // block to the new block which will contain the Phi nodes for the selects.
9484   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9485   // Set the successors for HeadMBB.
9486   HeadMBB->addSuccessor(IfFalseMBB);
9487   HeadMBB->addSuccessor(TailMBB);
9488 
9489   // Insert appropriate branch.
9490   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9491     .addReg(LHS)
9492     .addReg(RHS)
9493     .addMBB(TailMBB);
9494 
9495   // IfFalseMBB just falls through to TailMBB.
9496   IfFalseMBB->addSuccessor(TailMBB);
9497 
9498   // Create PHIs for all of the select pseudo-instructions.
9499   auto SelectMBBI = MI.getIterator();
9500   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9501   auto InsertionPoint = TailMBB->begin();
9502   while (SelectMBBI != SelectEnd) {
9503     auto Next = std::next(SelectMBBI);
9504     if (isSelectPseudo(*SelectMBBI)) {
9505       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9506       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9507               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9508           .addReg(SelectMBBI->getOperand(4).getReg())
9509           .addMBB(HeadMBB)
9510           .addReg(SelectMBBI->getOperand(5).getReg())
9511           .addMBB(IfFalseMBB);
9512       SelectMBBI->eraseFromParent();
9513     }
9514     SelectMBBI = Next;
9515   }
9516 
9517   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9518   return TailMBB;
9519 }
9520 
9521 MachineBasicBlock *
9522 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9523                                                  MachineBasicBlock *BB) const {
9524   switch (MI.getOpcode()) {
9525   default:
9526     llvm_unreachable("Unexpected instr type to insert");
9527   case RISCV::ReadCycleWide:
9528     assert(!Subtarget.is64Bit() &&
9529            "ReadCycleWrite is only to be used on riscv32");
9530     return emitReadCycleWidePseudo(MI, BB);
9531   case RISCV::Select_GPR_Using_CC_GPR:
9532   case RISCV::Select_FPR16_Using_CC_GPR:
9533   case RISCV::Select_FPR32_Using_CC_GPR:
9534   case RISCV::Select_FPR64_Using_CC_GPR:
9535     return emitSelectPseudo(MI, BB, Subtarget);
9536   case RISCV::BuildPairF64Pseudo:
9537     return emitBuildPairF64Pseudo(MI, BB);
9538   case RISCV::SplitF64Pseudo:
9539     return emitSplitF64Pseudo(MI, BB);
9540   case RISCV::PseudoQuietFLE_H:
9541     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9542   case RISCV::PseudoQuietFLT_H:
9543     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9544   case RISCV::PseudoQuietFLE_S:
9545     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9546   case RISCV::PseudoQuietFLT_S:
9547     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9548   case RISCV::PseudoQuietFLE_D:
9549     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9550   case RISCV::PseudoQuietFLT_D:
9551     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9552   }
9553 }
9554 
9555 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9556                                                         SDNode *Node) const {
9557   // Add FRM dependency to any instructions with dynamic rounding mode.
9558   unsigned Opc = MI.getOpcode();
9559   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9560   if (Idx < 0)
9561     return;
9562   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9563     return;
9564   // If the instruction already reads FRM, don't add another read.
9565   if (MI.readsRegister(RISCV::FRM))
9566     return;
9567   MI.addOperand(
9568       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9569 }
9570 
9571 // Calling Convention Implementation.
9572 // The expectations for frontend ABI lowering vary from target to target.
9573 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9574 // details, but this is a longer term goal. For now, we simply try to keep the
9575 // role of the frontend as simple and well-defined as possible. The rules can
9576 // be summarised as:
9577 // * Never split up large scalar arguments. We handle them here.
9578 // * If a hardfloat calling convention is being used, and the struct may be
9579 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9580 // available, then pass as two separate arguments. If either the GPRs or FPRs
9581 // are exhausted, then pass according to the rule below.
9582 // * If a struct could never be passed in registers or directly in a stack
9583 // slot (as it is larger than 2*XLEN and the floating point rules don't
9584 // apply), then pass it using a pointer with the byval attribute.
9585 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9586 // word-sized array or a 2*XLEN scalar (depending on alignment).
9587 // * The frontend can determine whether a struct is returned by reference or
9588 // not based on its size and fields. If it will be returned by reference, the
9589 // frontend must modify the prototype so a pointer with the sret annotation is
9590 // passed as the first argument. This is not necessary for large scalar
9591 // returns.
9592 // * Struct return values and varargs should be coerced to structs containing
9593 // register-size fields in the same situations they would be for fixed
9594 // arguments.
9595 
9596 static const MCPhysReg ArgGPRs[] = {
9597   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9598   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9599 };
9600 static const MCPhysReg ArgFPR16s[] = {
9601   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9602   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9603 };
9604 static const MCPhysReg ArgFPR32s[] = {
9605   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9606   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9607 };
9608 static const MCPhysReg ArgFPR64s[] = {
9609   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9610   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9611 };
9612 // This is an interim calling convention and it may be changed in the future.
9613 static const MCPhysReg ArgVRs[] = {
9614     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9615     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9616     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9617 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9618                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9619                                      RISCV::V20M2, RISCV::V22M2};
9620 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9621                                      RISCV::V20M4};
9622 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9623 
9624 // Pass a 2*XLEN argument that has been split into two XLEN values through
9625 // registers or the stack as necessary.
9626 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9627                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9628                                 MVT ValVT2, MVT LocVT2,
9629                                 ISD::ArgFlagsTy ArgFlags2) {
9630   unsigned XLenInBytes = XLen / 8;
9631   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9632     // At least one half can be passed via register.
9633     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9634                                      VA1.getLocVT(), CCValAssign::Full));
9635   } else {
9636     // Both halves must be passed on the stack, with proper alignment.
9637     Align StackAlign =
9638         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9639     State.addLoc(
9640         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9641                             State.AllocateStack(XLenInBytes, StackAlign),
9642                             VA1.getLocVT(), CCValAssign::Full));
9643     State.addLoc(CCValAssign::getMem(
9644         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9645         LocVT2, CCValAssign::Full));
9646     return false;
9647   }
9648 
9649   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9650     // The second half can also be passed via register.
9651     State.addLoc(
9652         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9653   } else {
9654     // The second half is passed via the stack, without additional alignment.
9655     State.addLoc(CCValAssign::getMem(
9656         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9657         LocVT2, CCValAssign::Full));
9658   }
9659 
9660   return false;
9661 }
9662 
9663 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9664                                Optional<unsigned> FirstMaskArgument,
9665                                CCState &State, const RISCVTargetLowering &TLI) {
9666   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9667   if (RC == &RISCV::VRRegClass) {
9668     // Assign the first mask argument to V0.
9669     // This is an interim calling convention and it may be changed in the
9670     // future.
9671     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9672       return State.AllocateReg(RISCV::V0);
9673     return State.AllocateReg(ArgVRs);
9674   }
9675   if (RC == &RISCV::VRM2RegClass)
9676     return State.AllocateReg(ArgVRM2s);
9677   if (RC == &RISCV::VRM4RegClass)
9678     return State.AllocateReg(ArgVRM4s);
9679   if (RC == &RISCV::VRM8RegClass)
9680     return State.AllocateReg(ArgVRM8s);
9681   llvm_unreachable("Unhandled register class for ValueType");
9682 }
9683 
9684 // Implements the RISC-V calling convention. Returns true upon failure.
9685 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9686                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9687                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9688                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9689                      Optional<unsigned> FirstMaskArgument) {
9690   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9691   assert(XLen == 32 || XLen == 64);
9692   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9693 
9694   // Any return value split in to more than two values can't be returned
9695   // directly. Vectors are returned via the available vector registers.
9696   if (!LocVT.isVector() && IsRet && ValNo > 1)
9697     return true;
9698 
9699   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9700   // variadic argument, or if no F16/F32 argument registers are available.
9701   bool UseGPRForF16_F32 = true;
9702   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9703   // variadic argument, or if no F64 argument registers are available.
9704   bool UseGPRForF64 = true;
9705 
9706   switch (ABI) {
9707   default:
9708     llvm_unreachable("Unexpected ABI");
9709   case RISCVABI::ABI_ILP32:
9710   case RISCVABI::ABI_LP64:
9711     break;
9712   case RISCVABI::ABI_ILP32F:
9713   case RISCVABI::ABI_LP64F:
9714     UseGPRForF16_F32 = !IsFixed;
9715     break;
9716   case RISCVABI::ABI_ILP32D:
9717   case RISCVABI::ABI_LP64D:
9718     UseGPRForF16_F32 = !IsFixed;
9719     UseGPRForF64 = !IsFixed;
9720     break;
9721   }
9722 
9723   // FPR16, FPR32, and FPR64 alias each other.
9724   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9725     UseGPRForF16_F32 = true;
9726     UseGPRForF64 = true;
9727   }
9728 
9729   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9730   // similar local variables rather than directly checking against the target
9731   // ABI.
9732 
9733   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9734     LocVT = XLenVT;
9735     LocInfo = CCValAssign::BCvt;
9736   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9737     LocVT = MVT::i64;
9738     LocInfo = CCValAssign::BCvt;
9739   }
9740 
9741   // If this is a variadic argument, the RISC-V calling convention requires
9742   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9743   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9744   // be used regardless of whether the original argument was split during
9745   // legalisation or not. The argument will not be passed by registers if the
9746   // original type is larger than 2*XLEN, so the register alignment rule does
9747   // not apply.
9748   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9749   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9750       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9751     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9752     // Skip 'odd' register if necessary.
9753     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9754       State.AllocateReg(ArgGPRs);
9755   }
9756 
9757   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9758   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9759       State.getPendingArgFlags();
9760 
9761   assert(PendingLocs.size() == PendingArgFlags.size() &&
9762          "PendingLocs and PendingArgFlags out of sync");
9763 
9764   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9765   // registers are exhausted.
9766   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9767     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9768            "Can't lower f64 if it is split");
9769     // Depending on available argument GPRS, f64 may be passed in a pair of
9770     // GPRs, split between a GPR and the stack, or passed completely on the
9771     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9772     // cases.
9773     Register Reg = State.AllocateReg(ArgGPRs);
9774     LocVT = MVT::i32;
9775     if (!Reg) {
9776       unsigned StackOffset = State.AllocateStack(8, Align(8));
9777       State.addLoc(
9778           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9779       return false;
9780     }
9781     if (!State.AllocateReg(ArgGPRs))
9782       State.AllocateStack(4, Align(4));
9783     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9784     return false;
9785   }
9786 
9787   // Fixed-length vectors are located in the corresponding scalable-vector
9788   // container types.
9789   if (ValVT.isFixedLengthVector())
9790     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9791 
9792   // Split arguments might be passed indirectly, so keep track of the pending
9793   // values. Split vectors are passed via a mix of registers and indirectly, so
9794   // treat them as we would any other argument.
9795   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9796     LocVT = XLenVT;
9797     LocInfo = CCValAssign::Indirect;
9798     PendingLocs.push_back(
9799         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9800     PendingArgFlags.push_back(ArgFlags);
9801     if (!ArgFlags.isSplitEnd()) {
9802       return false;
9803     }
9804   }
9805 
9806   // If the split argument only had two elements, it should be passed directly
9807   // in registers or on the stack.
9808   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9809       PendingLocs.size() <= 2) {
9810     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9811     // Apply the normal calling convention rules to the first half of the
9812     // split argument.
9813     CCValAssign VA = PendingLocs[0];
9814     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9815     PendingLocs.clear();
9816     PendingArgFlags.clear();
9817     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9818                                ArgFlags);
9819   }
9820 
9821   // Allocate to a register if possible, or else a stack slot.
9822   Register Reg;
9823   unsigned StoreSizeBytes = XLen / 8;
9824   Align StackAlign = Align(XLen / 8);
9825 
9826   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9827     Reg = State.AllocateReg(ArgFPR16s);
9828   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9829     Reg = State.AllocateReg(ArgFPR32s);
9830   else if (ValVT == MVT::f64 && !UseGPRForF64)
9831     Reg = State.AllocateReg(ArgFPR64s);
9832   else if (ValVT.isVector()) {
9833     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9834     if (!Reg) {
9835       // For return values, the vector must be passed fully via registers or
9836       // via the stack.
9837       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9838       // but we're using all of them.
9839       if (IsRet)
9840         return true;
9841       // Try using a GPR to pass the address
9842       if ((Reg = State.AllocateReg(ArgGPRs))) {
9843         LocVT = XLenVT;
9844         LocInfo = CCValAssign::Indirect;
9845       } else if (ValVT.isScalableVector()) {
9846         LocVT = XLenVT;
9847         LocInfo = CCValAssign::Indirect;
9848       } else {
9849         // Pass fixed-length vectors on the stack.
9850         LocVT = ValVT;
9851         StoreSizeBytes = ValVT.getStoreSize();
9852         // Align vectors to their element sizes, being careful for vXi1
9853         // vectors.
9854         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9855       }
9856     }
9857   } else {
9858     Reg = State.AllocateReg(ArgGPRs);
9859   }
9860 
9861   unsigned StackOffset =
9862       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9863 
9864   // If we reach this point and PendingLocs is non-empty, we must be at the
9865   // end of a split argument that must be passed indirectly.
9866   if (!PendingLocs.empty()) {
9867     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9868     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9869 
9870     for (auto &It : PendingLocs) {
9871       if (Reg)
9872         It.convertToReg(Reg);
9873       else
9874         It.convertToMem(StackOffset);
9875       State.addLoc(It);
9876     }
9877     PendingLocs.clear();
9878     PendingArgFlags.clear();
9879     return false;
9880   }
9881 
9882   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9883           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9884          "Expected an XLenVT or vector types at this stage");
9885 
9886   if (Reg) {
9887     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9888     return false;
9889   }
9890 
9891   // When a floating-point value is passed on the stack, no bit-conversion is
9892   // needed.
9893   if (ValVT.isFloatingPoint()) {
9894     LocVT = ValVT;
9895     LocInfo = CCValAssign::Full;
9896   }
9897   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9898   return false;
9899 }
9900 
9901 template <typename ArgTy>
9902 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9903   for (const auto &ArgIdx : enumerate(Args)) {
9904     MVT ArgVT = ArgIdx.value().VT;
9905     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9906       return ArgIdx.index();
9907   }
9908   return None;
9909 }
9910 
9911 void RISCVTargetLowering::analyzeInputArgs(
9912     MachineFunction &MF, CCState &CCInfo,
9913     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9914     RISCVCCAssignFn Fn) const {
9915   unsigned NumArgs = Ins.size();
9916   FunctionType *FType = MF.getFunction().getFunctionType();
9917 
9918   Optional<unsigned> FirstMaskArgument;
9919   if (Subtarget.hasVInstructions())
9920     FirstMaskArgument = preAssignMask(Ins);
9921 
9922   for (unsigned i = 0; i != NumArgs; ++i) {
9923     MVT ArgVT = Ins[i].VT;
9924     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9925 
9926     Type *ArgTy = nullptr;
9927     if (IsRet)
9928       ArgTy = FType->getReturnType();
9929     else if (Ins[i].isOrigArg())
9930       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9931 
9932     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9933     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9934            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9935            FirstMaskArgument)) {
9936       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9937                         << EVT(ArgVT).getEVTString() << '\n');
9938       llvm_unreachable(nullptr);
9939     }
9940   }
9941 }
9942 
9943 void RISCVTargetLowering::analyzeOutputArgs(
9944     MachineFunction &MF, CCState &CCInfo,
9945     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9946     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9947   unsigned NumArgs = Outs.size();
9948 
9949   Optional<unsigned> FirstMaskArgument;
9950   if (Subtarget.hasVInstructions())
9951     FirstMaskArgument = preAssignMask(Outs);
9952 
9953   for (unsigned i = 0; i != NumArgs; i++) {
9954     MVT ArgVT = Outs[i].VT;
9955     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9956     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9957 
9958     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9959     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9960            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9961            FirstMaskArgument)) {
9962       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9963                         << EVT(ArgVT).getEVTString() << "\n");
9964       llvm_unreachable(nullptr);
9965     }
9966   }
9967 }
9968 
9969 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9970 // values.
9971 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9972                                    const CCValAssign &VA, const SDLoc &DL,
9973                                    const RISCVSubtarget &Subtarget) {
9974   switch (VA.getLocInfo()) {
9975   default:
9976     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9977   case CCValAssign::Full:
9978     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9979       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9980     break;
9981   case CCValAssign::BCvt:
9982     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9983       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9984     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9985       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9986     else
9987       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9988     break;
9989   }
9990   return Val;
9991 }
9992 
9993 // The caller is responsible for loading the full value if the argument is
9994 // passed with CCValAssign::Indirect.
9995 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9996                                 const CCValAssign &VA, const SDLoc &DL,
9997                                 const RISCVTargetLowering &TLI) {
9998   MachineFunction &MF = DAG.getMachineFunction();
9999   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10000   EVT LocVT = VA.getLocVT();
10001   SDValue Val;
10002   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10003   Register VReg = RegInfo.createVirtualRegister(RC);
10004   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10005   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10006 
10007   if (VA.getLocInfo() == CCValAssign::Indirect)
10008     return Val;
10009 
10010   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10011 }
10012 
10013 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10014                                    const CCValAssign &VA, const SDLoc &DL,
10015                                    const RISCVSubtarget &Subtarget) {
10016   EVT LocVT = VA.getLocVT();
10017 
10018   switch (VA.getLocInfo()) {
10019   default:
10020     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10021   case CCValAssign::Full:
10022     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10023       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10024     break;
10025   case CCValAssign::BCvt:
10026     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10027       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10028     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10029       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10030     else
10031       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10032     break;
10033   }
10034   return Val;
10035 }
10036 
10037 // The caller is responsible for loading the full value if the argument is
10038 // passed with CCValAssign::Indirect.
10039 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10040                                 const CCValAssign &VA, const SDLoc &DL) {
10041   MachineFunction &MF = DAG.getMachineFunction();
10042   MachineFrameInfo &MFI = MF.getFrameInfo();
10043   EVT LocVT = VA.getLocVT();
10044   EVT ValVT = VA.getValVT();
10045   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10046   if (ValVT.isScalableVector()) {
10047     // When the value is a scalable vector, we save the pointer which points to
10048     // the scalable vector value in the stack. The ValVT will be the pointer
10049     // type, instead of the scalable vector type.
10050     ValVT = LocVT;
10051   }
10052   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10053                                  /*IsImmutable=*/true);
10054   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10055   SDValue Val;
10056 
10057   ISD::LoadExtType ExtType;
10058   switch (VA.getLocInfo()) {
10059   default:
10060     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10061   case CCValAssign::Full:
10062   case CCValAssign::Indirect:
10063   case CCValAssign::BCvt:
10064     ExtType = ISD::NON_EXTLOAD;
10065     break;
10066   }
10067   Val = DAG.getExtLoad(
10068       ExtType, DL, LocVT, Chain, FIN,
10069       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10070   return Val;
10071 }
10072 
10073 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10074                                        const CCValAssign &VA, const SDLoc &DL) {
10075   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10076          "Unexpected VA");
10077   MachineFunction &MF = DAG.getMachineFunction();
10078   MachineFrameInfo &MFI = MF.getFrameInfo();
10079   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10080 
10081   if (VA.isMemLoc()) {
10082     // f64 is passed on the stack.
10083     int FI =
10084         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10085     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10086     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10087                        MachinePointerInfo::getFixedStack(MF, FI));
10088   }
10089 
10090   assert(VA.isRegLoc() && "Expected register VA assignment");
10091 
10092   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10093   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10094   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10095   SDValue Hi;
10096   if (VA.getLocReg() == RISCV::X17) {
10097     // Second half of f64 is passed on the stack.
10098     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10099     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10100     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10101                      MachinePointerInfo::getFixedStack(MF, FI));
10102   } else {
10103     // Second half of f64 is passed in another GPR.
10104     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10105     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10106     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10107   }
10108   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10109 }
10110 
10111 // FastCC has less than 1% performance improvement for some particular
10112 // benchmark. But theoretically, it may has benenfit for some cases.
10113 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10114                             unsigned ValNo, MVT ValVT, MVT LocVT,
10115                             CCValAssign::LocInfo LocInfo,
10116                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10117                             bool IsFixed, bool IsRet, Type *OrigTy,
10118                             const RISCVTargetLowering &TLI,
10119                             Optional<unsigned> FirstMaskArgument) {
10120 
10121   // X5 and X6 might be used for save-restore libcall.
10122   static const MCPhysReg GPRList[] = {
10123       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10124       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10125       RISCV::X29, RISCV::X30, RISCV::X31};
10126 
10127   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10128     if (unsigned Reg = State.AllocateReg(GPRList)) {
10129       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10130       return false;
10131     }
10132   }
10133 
10134   if (LocVT == MVT::f16) {
10135     static const MCPhysReg FPR16List[] = {
10136         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10137         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10138         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10139         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10140     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10141       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10142       return false;
10143     }
10144   }
10145 
10146   if (LocVT == MVT::f32) {
10147     static const MCPhysReg FPR32List[] = {
10148         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10149         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10150         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10151         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10152     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10153       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10154       return false;
10155     }
10156   }
10157 
10158   if (LocVT == MVT::f64) {
10159     static const MCPhysReg FPR64List[] = {
10160         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10161         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10162         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10163         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10164     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10165       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10166       return false;
10167     }
10168   }
10169 
10170   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10171     unsigned Offset4 = State.AllocateStack(4, Align(4));
10172     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10173     return false;
10174   }
10175 
10176   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10177     unsigned Offset5 = State.AllocateStack(8, Align(8));
10178     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10179     return false;
10180   }
10181 
10182   if (LocVT.isVector()) {
10183     if (unsigned Reg =
10184             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10185       // Fixed-length vectors are located in the corresponding scalable-vector
10186       // container types.
10187       if (ValVT.isFixedLengthVector())
10188         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10189       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10190     } else {
10191       // Try and pass the address via a "fast" GPR.
10192       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10193         LocInfo = CCValAssign::Indirect;
10194         LocVT = TLI.getSubtarget().getXLenVT();
10195         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10196       } else if (ValVT.isFixedLengthVector()) {
10197         auto StackAlign =
10198             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10199         unsigned StackOffset =
10200             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10201         State.addLoc(
10202             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10203       } else {
10204         // Can't pass scalable vectors on the stack.
10205         return true;
10206       }
10207     }
10208 
10209     return false;
10210   }
10211 
10212   return true; // CC didn't match.
10213 }
10214 
10215 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10216                          CCValAssign::LocInfo LocInfo,
10217                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10218 
10219   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10220     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10221     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10222     static const MCPhysReg GPRList[] = {
10223         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10224         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10225     if (unsigned Reg = State.AllocateReg(GPRList)) {
10226       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10227       return false;
10228     }
10229   }
10230 
10231   if (LocVT == MVT::f32) {
10232     // Pass in STG registers: F1, ..., F6
10233     //                        fs0 ... fs5
10234     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10235                                           RISCV::F18_F, RISCV::F19_F,
10236                                           RISCV::F20_F, RISCV::F21_F};
10237     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10238       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10239       return false;
10240     }
10241   }
10242 
10243   if (LocVT == MVT::f64) {
10244     // Pass in STG registers: D1, ..., D6
10245     //                        fs6 ... fs11
10246     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10247                                           RISCV::F24_D, RISCV::F25_D,
10248                                           RISCV::F26_D, RISCV::F27_D};
10249     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10250       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10251       return false;
10252     }
10253   }
10254 
10255   report_fatal_error("No registers left in GHC calling convention");
10256   return true;
10257 }
10258 
10259 // Transform physical registers into virtual registers.
10260 SDValue RISCVTargetLowering::LowerFormalArguments(
10261     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10262     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10263     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10264 
10265   MachineFunction &MF = DAG.getMachineFunction();
10266 
10267   switch (CallConv) {
10268   default:
10269     report_fatal_error("Unsupported calling convention");
10270   case CallingConv::C:
10271   case CallingConv::Fast:
10272     break;
10273   case CallingConv::GHC:
10274     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10275         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10276       report_fatal_error(
10277         "GHC calling convention requires the F and D instruction set extensions");
10278   }
10279 
10280   const Function &Func = MF.getFunction();
10281   if (Func.hasFnAttribute("interrupt")) {
10282     if (!Func.arg_empty())
10283       report_fatal_error(
10284         "Functions with the interrupt attribute cannot have arguments!");
10285 
10286     StringRef Kind =
10287       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10288 
10289     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10290       report_fatal_error(
10291         "Function interrupt attribute argument not supported!");
10292   }
10293 
10294   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10295   MVT XLenVT = Subtarget.getXLenVT();
10296   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10297   // Used with vargs to acumulate store chains.
10298   std::vector<SDValue> OutChains;
10299 
10300   // Assign locations to all of the incoming arguments.
10301   SmallVector<CCValAssign, 16> ArgLocs;
10302   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10303 
10304   if (CallConv == CallingConv::GHC)
10305     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10306   else
10307     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10308                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10309                                                    : CC_RISCV);
10310 
10311   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10312     CCValAssign &VA = ArgLocs[i];
10313     SDValue ArgValue;
10314     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10315     // case.
10316     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10317       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10318     else if (VA.isRegLoc())
10319       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10320     else
10321       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10322 
10323     if (VA.getLocInfo() == CCValAssign::Indirect) {
10324       // If the original argument was split and passed by reference (e.g. i128
10325       // on RV32), we need to load all parts of it here (using the same
10326       // address). Vectors may be partly split to registers and partly to the
10327       // stack, in which case the base address is partly offset and subsequent
10328       // stores are relative to that.
10329       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10330                                    MachinePointerInfo()));
10331       unsigned ArgIndex = Ins[i].OrigArgIndex;
10332       unsigned ArgPartOffset = Ins[i].PartOffset;
10333       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10334       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10335         CCValAssign &PartVA = ArgLocs[i + 1];
10336         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10337         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10338         if (PartVA.getValVT().isScalableVector())
10339           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10340         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10341         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10342                                      MachinePointerInfo()));
10343         ++i;
10344       }
10345       continue;
10346     }
10347     InVals.push_back(ArgValue);
10348   }
10349 
10350   if (IsVarArg) {
10351     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10352     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10353     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10354     MachineFrameInfo &MFI = MF.getFrameInfo();
10355     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10356     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10357 
10358     // Offset of the first variable argument from stack pointer, and size of
10359     // the vararg save area. For now, the varargs save area is either zero or
10360     // large enough to hold a0-a7.
10361     int VaArgOffset, VarArgsSaveSize;
10362 
10363     // If all registers are allocated, then all varargs must be passed on the
10364     // stack and we don't need to save any argregs.
10365     if (ArgRegs.size() == Idx) {
10366       VaArgOffset = CCInfo.getNextStackOffset();
10367       VarArgsSaveSize = 0;
10368     } else {
10369       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10370       VaArgOffset = -VarArgsSaveSize;
10371     }
10372 
10373     // Record the frame index of the first variable argument
10374     // which is a value necessary to VASTART.
10375     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10376     RVFI->setVarArgsFrameIndex(FI);
10377 
10378     // If saving an odd number of registers then create an extra stack slot to
10379     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10380     // offsets to even-numbered registered remain 2*XLEN-aligned.
10381     if (Idx % 2) {
10382       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10383       VarArgsSaveSize += XLenInBytes;
10384     }
10385 
10386     // Copy the integer registers that may have been used for passing varargs
10387     // to the vararg save area.
10388     for (unsigned I = Idx; I < ArgRegs.size();
10389          ++I, VaArgOffset += XLenInBytes) {
10390       const Register Reg = RegInfo.createVirtualRegister(RC);
10391       RegInfo.addLiveIn(ArgRegs[I], Reg);
10392       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10393       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10394       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10395       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10396                                    MachinePointerInfo::getFixedStack(MF, FI));
10397       cast<StoreSDNode>(Store.getNode())
10398           ->getMemOperand()
10399           ->setValue((Value *)nullptr);
10400       OutChains.push_back(Store);
10401     }
10402     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10403   }
10404 
10405   // All stores are grouped in one node to allow the matching between
10406   // the size of Ins and InVals. This only happens for vararg functions.
10407   if (!OutChains.empty()) {
10408     OutChains.push_back(Chain);
10409     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10410   }
10411 
10412   return Chain;
10413 }
10414 
10415 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10416 /// for tail call optimization.
10417 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10418 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10419     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10420     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10421 
10422   auto &Callee = CLI.Callee;
10423   auto CalleeCC = CLI.CallConv;
10424   auto &Outs = CLI.Outs;
10425   auto &Caller = MF.getFunction();
10426   auto CallerCC = Caller.getCallingConv();
10427 
10428   // Exception-handling functions need a special set of instructions to
10429   // indicate a return to the hardware. Tail-calling another function would
10430   // probably break this.
10431   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10432   // should be expanded as new function attributes are introduced.
10433   if (Caller.hasFnAttribute("interrupt"))
10434     return false;
10435 
10436   // Do not tail call opt if the stack is used to pass parameters.
10437   if (CCInfo.getNextStackOffset() != 0)
10438     return false;
10439 
10440   // Do not tail call opt if any parameters need to be passed indirectly.
10441   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10442   // passed indirectly. So the address of the value will be passed in a
10443   // register, or if not available, then the address is put on the stack. In
10444   // order to pass indirectly, space on the stack often needs to be allocated
10445   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10446   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10447   // are passed CCValAssign::Indirect.
10448   for (auto &VA : ArgLocs)
10449     if (VA.getLocInfo() == CCValAssign::Indirect)
10450       return false;
10451 
10452   // Do not tail call opt if either caller or callee uses struct return
10453   // semantics.
10454   auto IsCallerStructRet = Caller.hasStructRetAttr();
10455   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10456   if (IsCallerStructRet || IsCalleeStructRet)
10457     return false;
10458 
10459   // Externally-defined functions with weak linkage should not be
10460   // tail-called. The behaviour of branch instructions in this situation (as
10461   // used for tail calls) is implementation-defined, so we cannot rely on the
10462   // linker replacing the tail call with a return.
10463   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10464     const GlobalValue *GV = G->getGlobal();
10465     if (GV->hasExternalWeakLinkage())
10466       return false;
10467   }
10468 
10469   // The callee has to preserve all registers the caller needs to preserve.
10470   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10471   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10472   if (CalleeCC != CallerCC) {
10473     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10474     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10475       return false;
10476   }
10477 
10478   // Byval parameters hand the function a pointer directly into the stack area
10479   // we want to reuse during a tail call. Working around this *is* possible
10480   // but less efficient and uglier in LowerCall.
10481   for (auto &Arg : Outs)
10482     if (Arg.Flags.isByVal())
10483       return false;
10484 
10485   return true;
10486 }
10487 
10488 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10489   return DAG.getDataLayout().getPrefTypeAlign(
10490       VT.getTypeForEVT(*DAG.getContext()));
10491 }
10492 
10493 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10494 // and output parameter nodes.
10495 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10496                                        SmallVectorImpl<SDValue> &InVals) const {
10497   SelectionDAG &DAG = CLI.DAG;
10498   SDLoc &DL = CLI.DL;
10499   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10500   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10501   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10502   SDValue Chain = CLI.Chain;
10503   SDValue Callee = CLI.Callee;
10504   bool &IsTailCall = CLI.IsTailCall;
10505   CallingConv::ID CallConv = CLI.CallConv;
10506   bool IsVarArg = CLI.IsVarArg;
10507   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10508   MVT XLenVT = Subtarget.getXLenVT();
10509 
10510   MachineFunction &MF = DAG.getMachineFunction();
10511 
10512   // Analyze the operands of the call, assigning locations to each operand.
10513   SmallVector<CCValAssign, 16> ArgLocs;
10514   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10515 
10516   if (CallConv == CallingConv::GHC)
10517     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10518   else
10519     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10520                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10521                                                     : CC_RISCV);
10522 
10523   // Check if it's really possible to do a tail call.
10524   if (IsTailCall)
10525     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10526 
10527   if (IsTailCall)
10528     ++NumTailCalls;
10529   else if (CLI.CB && CLI.CB->isMustTailCall())
10530     report_fatal_error("failed to perform tail call elimination on a call "
10531                        "site marked musttail");
10532 
10533   // Get a count of how many bytes are to be pushed on the stack.
10534   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10535 
10536   // Create local copies for byval args
10537   SmallVector<SDValue, 8> ByValArgs;
10538   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10539     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10540     if (!Flags.isByVal())
10541       continue;
10542 
10543     SDValue Arg = OutVals[i];
10544     unsigned Size = Flags.getByValSize();
10545     Align Alignment = Flags.getNonZeroByValAlign();
10546 
10547     int FI =
10548         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10549     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10550     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10551 
10552     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10553                           /*IsVolatile=*/false,
10554                           /*AlwaysInline=*/false, IsTailCall,
10555                           MachinePointerInfo(), MachinePointerInfo());
10556     ByValArgs.push_back(FIPtr);
10557   }
10558 
10559   if (!IsTailCall)
10560     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10561 
10562   // Copy argument values to their designated locations.
10563   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10564   SmallVector<SDValue, 8> MemOpChains;
10565   SDValue StackPtr;
10566   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10567     CCValAssign &VA = ArgLocs[i];
10568     SDValue ArgValue = OutVals[i];
10569     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10570 
10571     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10572     bool IsF64OnRV32DSoftABI =
10573         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10574     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10575       SDValue SplitF64 = DAG.getNode(
10576           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10577       SDValue Lo = SplitF64.getValue(0);
10578       SDValue Hi = SplitF64.getValue(1);
10579 
10580       Register RegLo = VA.getLocReg();
10581       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10582 
10583       if (RegLo == RISCV::X17) {
10584         // Second half of f64 is passed on the stack.
10585         // Work out the address of the stack slot.
10586         if (!StackPtr.getNode())
10587           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10588         // Emit the store.
10589         MemOpChains.push_back(
10590             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10591       } else {
10592         // Second half of f64 is passed in another GPR.
10593         assert(RegLo < RISCV::X31 && "Invalid register pair");
10594         Register RegHigh = RegLo + 1;
10595         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10596       }
10597       continue;
10598     }
10599 
10600     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10601     // as any other MemLoc.
10602 
10603     // Promote the value if needed.
10604     // For now, only handle fully promoted and indirect arguments.
10605     if (VA.getLocInfo() == CCValAssign::Indirect) {
10606       // Store the argument in a stack slot and pass its address.
10607       Align StackAlign =
10608           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10609                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10610       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10611       // If the original argument was split (e.g. i128), we need
10612       // to store the required parts of it here (and pass just one address).
10613       // Vectors may be partly split to registers and partly to the stack, in
10614       // which case the base address is partly offset and subsequent stores are
10615       // relative to that.
10616       unsigned ArgIndex = Outs[i].OrigArgIndex;
10617       unsigned ArgPartOffset = Outs[i].PartOffset;
10618       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10619       // Calculate the total size to store. We don't have access to what we're
10620       // actually storing other than performing the loop and collecting the
10621       // info.
10622       SmallVector<std::pair<SDValue, SDValue>> Parts;
10623       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10624         SDValue PartValue = OutVals[i + 1];
10625         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10626         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10627         EVT PartVT = PartValue.getValueType();
10628         if (PartVT.isScalableVector())
10629           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10630         StoredSize += PartVT.getStoreSize();
10631         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10632         Parts.push_back(std::make_pair(PartValue, Offset));
10633         ++i;
10634       }
10635       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10636       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10637       MemOpChains.push_back(
10638           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10639                        MachinePointerInfo::getFixedStack(MF, FI)));
10640       for (const auto &Part : Parts) {
10641         SDValue PartValue = Part.first;
10642         SDValue PartOffset = Part.second;
10643         SDValue Address =
10644             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10645         MemOpChains.push_back(
10646             DAG.getStore(Chain, DL, PartValue, Address,
10647                          MachinePointerInfo::getFixedStack(MF, FI)));
10648       }
10649       ArgValue = SpillSlot;
10650     } else {
10651       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10652     }
10653 
10654     // Use local copy if it is a byval arg.
10655     if (Flags.isByVal())
10656       ArgValue = ByValArgs[j++];
10657 
10658     if (VA.isRegLoc()) {
10659       // Queue up the argument copies and emit them at the end.
10660       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10661     } else {
10662       assert(VA.isMemLoc() && "Argument not register or memory");
10663       assert(!IsTailCall && "Tail call not allowed if stack is used "
10664                             "for passing parameters");
10665 
10666       // Work out the address of the stack slot.
10667       if (!StackPtr.getNode())
10668         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10669       SDValue Address =
10670           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10671                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10672 
10673       // Emit the store.
10674       MemOpChains.push_back(
10675           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10676     }
10677   }
10678 
10679   // Join the stores, which are independent of one another.
10680   if (!MemOpChains.empty())
10681     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10682 
10683   SDValue Glue;
10684 
10685   // Build a sequence of copy-to-reg nodes, chained and glued together.
10686   for (auto &Reg : RegsToPass) {
10687     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10688     Glue = Chain.getValue(1);
10689   }
10690 
10691   // Validate that none of the argument registers have been marked as
10692   // reserved, if so report an error. Do the same for the return address if this
10693   // is not a tailcall.
10694   validateCCReservedRegs(RegsToPass, MF);
10695   if (!IsTailCall &&
10696       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10697     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10698         MF.getFunction(),
10699         "Return address register required, but has been reserved."});
10700 
10701   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10702   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10703   // split it and then direct call can be matched by PseudoCALL.
10704   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10705     const GlobalValue *GV = S->getGlobal();
10706 
10707     unsigned OpFlags = RISCVII::MO_CALL;
10708     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10709       OpFlags = RISCVII::MO_PLT;
10710 
10711     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10712   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10713     unsigned OpFlags = RISCVII::MO_CALL;
10714 
10715     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10716                                                  nullptr))
10717       OpFlags = RISCVII::MO_PLT;
10718 
10719     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10720   }
10721 
10722   // The first call operand is the chain and the second is the target address.
10723   SmallVector<SDValue, 8> Ops;
10724   Ops.push_back(Chain);
10725   Ops.push_back(Callee);
10726 
10727   // Add argument registers to the end of the list so that they are
10728   // known live into the call.
10729   for (auto &Reg : RegsToPass)
10730     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10731 
10732   if (!IsTailCall) {
10733     // Add a register mask operand representing the call-preserved registers.
10734     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10735     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10736     assert(Mask && "Missing call preserved mask for calling convention");
10737     Ops.push_back(DAG.getRegisterMask(Mask));
10738   }
10739 
10740   // Glue the call to the argument copies, if any.
10741   if (Glue.getNode())
10742     Ops.push_back(Glue);
10743 
10744   // Emit the call.
10745   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10746 
10747   if (IsTailCall) {
10748     MF.getFrameInfo().setHasTailCall();
10749     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10750   }
10751 
10752   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10753   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10754   Glue = Chain.getValue(1);
10755 
10756   // Mark the end of the call, which is glued to the call itself.
10757   Chain = DAG.getCALLSEQ_END(Chain,
10758                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10759                              DAG.getConstant(0, DL, PtrVT, true),
10760                              Glue, DL);
10761   Glue = Chain.getValue(1);
10762 
10763   // Assign locations to each value returned by this call.
10764   SmallVector<CCValAssign, 16> RVLocs;
10765   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10766   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10767 
10768   // Copy all of the result registers out of their specified physreg.
10769   for (auto &VA : RVLocs) {
10770     // Copy the value out
10771     SDValue RetValue =
10772         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10773     // Glue the RetValue to the end of the call sequence
10774     Chain = RetValue.getValue(1);
10775     Glue = RetValue.getValue(2);
10776 
10777     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10778       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10779       SDValue RetValue2 =
10780           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10781       Chain = RetValue2.getValue(1);
10782       Glue = RetValue2.getValue(2);
10783       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10784                              RetValue2);
10785     }
10786 
10787     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10788 
10789     InVals.push_back(RetValue);
10790   }
10791 
10792   return Chain;
10793 }
10794 
10795 bool RISCVTargetLowering::CanLowerReturn(
10796     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10797     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10798   SmallVector<CCValAssign, 16> RVLocs;
10799   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10800 
10801   Optional<unsigned> FirstMaskArgument;
10802   if (Subtarget.hasVInstructions())
10803     FirstMaskArgument = preAssignMask(Outs);
10804 
10805   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10806     MVT VT = Outs[i].VT;
10807     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10808     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10809     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10810                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10811                  *this, FirstMaskArgument))
10812       return false;
10813   }
10814   return true;
10815 }
10816 
10817 SDValue
10818 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10819                                  bool IsVarArg,
10820                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10821                                  const SmallVectorImpl<SDValue> &OutVals,
10822                                  const SDLoc &DL, SelectionDAG &DAG) const {
10823   const MachineFunction &MF = DAG.getMachineFunction();
10824   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10825 
10826   // Stores the assignment of the return value to a location.
10827   SmallVector<CCValAssign, 16> RVLocs;
10828 
10829   // Info about the registers and stack slot.
10830   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10831                  *DAG.getContext());
10832 
10833   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10834                     nullptr, CC_RISCV);
10835 
10836   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10837     report_fatal_error("GHC functions return void only");
10838 
10839   SDValue Glue;
10840   SmallVector<SDValue, 4> RetOps(1, Chain);
10841 
10842   // Copy the result values into the output registers.
10843   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10844     SDValue Val = OutVals[i];
10845     CCValAssign &VA = RVLocs[i];
10846     assert(VA.isRegLoc() && "Can only return in registers!");
10847 
10848     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10849       // Handle returning f64 on RV32D with a soft float ABI.
10850       assert(VA.isRegLoc() && "Expected return via registers");
10851       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10852                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10853       SDValue Lo = SplitF64.getValue(0);
10854       SDValue Hi = SplitF64.getValue(1);
10855       Register RegLo = VA.getLocReg();
10856       assert(RegLo < RISCV::X31 && "Invalid register pair");
10857       Register RegHi = RegLo + 1;
10858 
10859       if (STI.isRegisterReservedByUser(RegLo) ||
10860           STI.isRegisterReservedByUser(RegHi))
10861         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10862             MF.getFunction(),
10863             "Return value register required, but has been reserved."});
10864 
10865       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10866       Glue = Chain.getValue(1);
10867       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10868       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10869       Glue = Chain.getValue(1);
10870       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10871     } else {
10872       // Handle a 'normal' return.
10873       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10874       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10875 
10876       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10877         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10878             MF.getFunction(),
10879             "Return value register required, but has been reserved."});
10880 
10881       // Guarantee that all emitted copies are stuck together.
10882       Glue = Chain.getValue(1);
10883       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10884     }
10885   }
10886 
10887   RetOps[0] = Chain; // Update chain.
10888 
10889   // Add the glue node if we have it.
10890   if (Glue.getNode()) {
10891     RetOps.push_back(Glue);
10892   }
10893 
10894   unsigned RetOpc = RISCVISD::RET_FLAG;
10895   // Interrupt service routines use different return instructions.
10896   const Function &Func = DAG.getMachineFunction().getFunction();
10897   if (Func.hasFnAttribute("interrupt")) {
10898     if (!Func.getReturnType()->isVoidTy())
10899       report_fatal_error(
10900           "Functions with the interrupt attribute must have void return type!");
10901 
10902     MachineFunction &MF = DAG.getMachineFunction();
10903     StringRef Kind =
10904       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10905 
10906     if (Kind == "user")
10907       RetOpc = RISCVISD::URET_FLAG;
10908     else if (Kind == "supervisor")
10909       RetOpc = RISCVISD::SRET_FLAG;
10910     else
10911       RetOpc = RISCVISD::MRET_FLAG;
10912   }
10913 
10914   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10915 }
10916 
10917 void RISCVTargetLowering::validateCCReservedRegs(
10918     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10919     MachineFunction &MF) const {
10920   const Function &F = MF.getFunction();
10921   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10922 
10923   if (llvm::any_of(Regs, [&STI](auto Reg) {
10924         return STI.isRegisterReservedByUser(Reg.first);
10925       }))
10926     F.getContext().diagnose(DiagnosticInfoUnsupported{
10927         F, "Argument register required, but has been reserved."});
10928 }
10929 
10930 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10931   return CI->isTailCall();
10932 }
10933 
10934 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10935 #define NODE_NAME_CASE(NODE)                                                   \
10936   case RISCVISD::NODE:                                                         \
10937     return "RISCVISD::" #NODE;
10938   // clang-format off
10939   switch ((RISCVISD::NodeType)Opcode) {
10940   case RISCVISD::FIRST_NUMBER:
10941     break;
10942   NODE_NAME_CASE(RET_FLAG)
10943   NODE_NAME_CASE(URET_FLAG)
10944   NODE_NAME_CASE(SRET_FLAG)
10945   NODE_NAME_CASE(MRET_FLAG)
10946   NODE_NAME_CASE(CALL)
10947   NODE_NAME_CASE(SELECT_CC)
10948   NODE_NAME_CASE(BR_CC)
10949   NODE_NAME_CASE(BuildPairF64)
10950   NODE_NAME_CASE(SplitF64)
10951   NODE_NAME_CASE(TAIL)
10952   NODE_NAME_CASE(MULHSU)
10953   NODE_NAME_CASE(SLLW)
10954   NODE_NAME_CASE(SRAW)
10955   NODE_NAME_CASE(SRLW)
10956   NODE_NAME_CASE(DIVW)
10957   NODE_NAME_CASE(DIVUW)
10958   NODE_NAME_CASE(REMUW)
10959   NODE_NAME_CASE(ROLW)
10960   NODE_NAME_CASE(RORW)
10961   NODE_NAME_CASE(CLZW)
10962   NODE_NAME_CASE(CTZW)
10963   NODE_NAME_CASE(FSLW)
10964   NODE_NAME_CASE(FSRW)
10965   NODE_NAME_CASE(FSL)
10966   NODE_NAME_CASE(FSR)
10967   NODE_NAME_CASE(FMV_H_X)
10968   NODE_NAME_CASE(FMV_X_ANYEXTH)
10969   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10970   NODE_NAME_CASE(FMV_W_X_RV64)
10971   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10972   NODE_NAME_CASE(FCVT_X)
10973   NODE_NAME_CASE(FCVT_XU)
10974   NODE_NAME_CASE(FCVT_W_RV64)
10975   NODE_NAME_CASE(FCVT_WU_RV64)
10976   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10977   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10978   NODE_NAME_CASE(READ_CYCLE_WIDE)
10979   NODE_NAME_CASE(GREV)
10980   NODE_NAME_CASE(GREVW)
10981   NODE_NAME_CASE(GORC)
10982   NODE_NAME_CASE(GORCW)
10983   NODE_NAME_CASE(SHFL)
10984   NODE_NAME_CASE(SHFLW)
10985   NODE_NAME_CASE(UNSHFL)
10986   NODE_NAME_CASE(UNSHFLW)
10987   NODE_NAME_CASE(BFP)
10988   NODE_NAME_CASE(BFPW)
10989   NODE_NAME_CASE(BCOMPRESS)
10990   NODE_NAME_CASE(BCOMPRESSW)
10991   NODE_NAME_CASE(BDECOMPRESS)
10992   NODE_NAME_CASE(BDECOMPRESSW)
10993   NODE_NAME_CASE(VMV_V_X_VL)
10994   NODE_NAME_CASE(VFMV_V_F_VL)
10995   NODE_NAME_CASE(VMV_X_S)
10996   NODE_NAME_CASE(VMV_S_X_VL)
10997   NODE_NAME_CASE(VFMV_S_F_VL)
10998   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10999   NODE_NAME_CASE(READ_VLENB)
11000   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11001   NODE_NAME_CASE(VSLIDEUP_VL)
11002   NODE_NAME_CASE(VSLIDE1UP_VL)
11003   NODE_NAME_CASE(VSLIDEDOWN_VL)
11004   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11005   NODE_NAME_CASE(VID_VL)
11006   NODE_NAME_CASE(VFNCVT_ROD_VL)
11007   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11008   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11009   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11010   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11011   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11012   NODE_NAME_CASE(VECREDUCE_AND_VL)
11013   NODE_NAME_CASE(VECREDUCE_OR_VL)
11014   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11015   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11016   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11017   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11018   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11019   NODE_NAME_CASE(ADD_VL)
11020   NODE_NAME_CASE(AND_VL)
11021   NODE_NAME_CASE(MUL_VL)
11022   NODE_NAME_CASE(OR_VL)
11023   NODE_NAME_CASE(SDIV_VL)
11024   NODE_NAME_CASE(SHL_VL)
11025   NODE_NAME_CASE(SREM_VL)
11026   NODE_NAME_CASE(SRA_VL)
11027   NODE_NAME_CASE(SRL_VL)
11028   NODE_NAME_CASE(SUB_VL)
11029   NODE_NAME_CASE(UDIV_VL)
11030   NODE_NAME_CASE(UREM_VL)
11031   NODE_NAME_CASE(XOR_VL)
11032   NODE_NAME_CASE(SADDSAT_VL)
11033   NODE_NAME_CASE(UADDSAT_VL)
11034   NODE_NAME_CASE(SSUBSAT_VL)
11035   NODE_NAME_CASE(USUBSAT_VL)
11036   NODE_NAME_CASE(FADD_VL)
11037   NODE_NAME_CASE(FSUB_VL)
11038   NODE_NAME_CASE(FMUL_VL)
11039   NODE_NAME_CASE(FDIV_VL)
11040   NODE_NAME_CASE(FNEG_VL)
11041   NODE_NAME_CASE(FABS_VL)
11042   NODE_NAME_CASE(FSQRT_VL)
11043   NODE_NAME_CASE(FMA_VL)
11044   NODE_NAME_CASE(FCOPYSIGN_VL)
11045   NODE_NAME_CASE(SMIN_VL)
11046   NODE_NAME_CASE(SMAX_VL)
11047   NODE_NAME_CASE(UMIN_VL)
11048   NODE_NAME_CASE(UMAX_VL)
11049   NODE_NAME_CASE(FMINNUM_VL)
11050   NODE_NAME_CASE(FMAXNUM_VL)
11051   NODE_NAME_CASE(MULHS_VL)
11052   NODE_NAME_CASE(MULHU_VL)
11053   NODE_NAME_CASE(FP_TO_SINT_VL)
11054   NODE_NAME_CASE(FP_TO_UINT_VL)
11055   NODE_NAME_CASE(SINT_TO_FP_VL)
11056   NODE_NAME_CASE(UINT_TO_FP_VL)
11057   NODE_NAME_CASE(FP_EXTEND_VL)
11058   NODE_NAME_CASE(FP_ROUND_VL)
11059   NODE_NAME_CASE(VWMUL_VL)
11060   NODE_NAME_CASE(VWMULU_VL)
11061   NODE_NAME_CASE(VWMULSU_VL)
11062   NODE_NAME_CASE(VWADD_VL)
11063   NODE_NAME_CASE(VWADDU_VL)
11064   NODE_NAME_CASE(VWSUB_VL)
11065   NODE_NAME_CASE(VWSUBU_VL)
11066   NODE_NAME_CASE(VWADD_W_VL)
11067   NODE_NAME_CASE(VWADDU_W_VL)
11068   NODE_NAME_CASE(VWSUB_W_VL)
11069   NODE_NAME_CASE(VWSUBU_W_VL)
11070   NODE_NAME_CASE(SETCC_VL)
11071   NODE_NAME_CASE(VSELECT_VL)
11072   NODE_NAME_CASE(VP_MERGE_VL)
11073   NODE_NAME_CASE(VMAND_VL)
11074   NODE_NAME_CASE(VMOR_VL)
11075   NODE_NAME_CASE(VMXOR_VL)
11076   NODE_NAME_CASE(VMCLR_VL)
11077   NODE_NAME_CASE(VMSET_VL)
11078   NODE_NAME_CASE(VRGATHER_VX_VL)
11079   NODE_NAME_CASE(VRGATHER_VV_VL)
11080   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11081   NODE_NAME_CASE(VSEXT_VL)
11082   NODE_NAME_CASE(VZEXT_VL)
11083   NODE_NAME_CASE(VCPOP_VL)
11084   NODE_NAME_CASE(READ_CSR)
11085   NODE_NAME_CASE(WRITE_CSR)
11086   NODE_NAME_CASE(SWAP_CSR)
11087   }
11088   // clang-format on
11089   return nullptr;
11090 #undef NODE_NAME_CASE
11091 }
11092 
11093 /// getConstraintType - Given a constraint letter, return the type of
11094 /// constraint it is for this target.
11095 RISCVTargetLowering::ConstraintType
11096 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11097   if (Constraint.size() == 1) {
11098     switch (Constraint[0]) {
11099     default:
11100       break;
11101     case 'f':
11102       return C_RegisterClass;
11103     case 'I':
11104     case 'J':
11105     case 'K':
11106       return C_Immediate;
11107     case 'A':
11108       return C_Memory;
11109     case 'S': // A symbolic address
11110       return C_Other;
11111     }
11112   } else {
11113     if (Constraint == "vr" || Constraint == "vm")
11114       return C_RegisterClass;
11115   }
11116   return TargetLowering::getConstraintType(Constraint);
11117 }
11118 
11119 std::pair<unsigned, const TargetRegisterClass *>
11120 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11121                                                   StringRef Constraint,
11122                                                   MVT VT) const {
11123   // First, see if this is a constraint that directly corresponds to a
11124   // RISCV register class.
11125   if (Constraint.size() == 1) {
11126     switch (Constraint[0]) {
11127     case 'r':
11128       // TODO: Support fixed vectors up to XLen for P extension?
11129       if (VT.isVector())
11130         break;
11131       return std::make_pair(0U, &RISCV::GPRRegClass);
11132     case 'f':
11133       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11134         return std::make_pair(0U, &RISCV::FPR16RegClass);
11135       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11136         return std::make_pair(0U, &RISCV::FPR32RegClass);
11137       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11138         return std::make_pair(0U, &RISCV::FPR64RegClass);
11139       break;
11140     default:
11141       break;
11142     }
11143   } else if (Constraint == "vr") {
11144     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11145                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11146       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11147         return std::make_pair(0U, RC);
11148     }
11149   } else if (Constraint == "vm") {
11150     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11151       return std::make_pair(0U, &RISCV::VMV0RegClass);
11152   }
11153 
11154   // Clang will correctly decode the usage of register name aliases into their
11155   // official names. However, other frontends like `rustc` do not. This allows
11156   // users of these frontends to use the ABI names for registers in LLVM-style
11157   // register constraints.
11158   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11159                                .Case("{zero}", RISCV::X0)
11160                                .Case("{ra}", RISCV::X1)
11161                                .Case("{sp}", RISCV::X2)
11162                                .Case("{gp}", RISCV::X3)
11163                                .Case("{tp}", RISCV::X4)
11164                                .Case("{t0}", RISCV::X5)
11165                                .Case("{t1}", RISCV::X6)
11166                                .Case("{t2}", RISCV::X7)
11167                                .Cases("{s0}", "{fp}", RISCV::X8)
11168                                .Case("{s1}", RISCV::X9)
11169                                .Case("{a0}", RISCV::X10)
11170                                .Case("{a1}", RISCV::X11)
11171                                .Case("{a2}", RISCV::X12)
11172                                .Case("{a3}", RISCV::X13)
11173                                .Case("{a4}", RISCV::X14)
11174                                .Case("{a5}", RISCV::X15)
11175                                .Case("{a6}", RISCV::X16)
11176                                .Case("{a7}", RISCV::X17)
11177                                .Case("{s2}", RISCV::X18)
11178                                .Case("{s3}", RISCV::X19)
11179                                .Case("{s4}", RISCV::X20)
11180                                .Case("{s5}", RISCV::X21)
11181                                .Case("{s6}", RISCV::X22)
11182                                .Case("{s7}", RISCV::X23)
11183                                .Case("{s8}", RISCV::X24)
11184                                .Case("{s9}", RISCV::X25)
11185                                .Case("{s10}", RISCV::X26)
11186                                .Case("{s11}", RISCV::X27)
11187                                .Case("{t3}", RISCV::X28)
11188                                .Case("{t4}", RISCV::X29)
11189                                .Case("{t5}", RISCV::X30)
11190                                .Case("{t6}", RISCV::X31)
11191                                .Default(RISCV::NoRegister);
11192   if (XRegFromAlias != RISCV::NoRegister)
11193     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11194 
11195   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11196   // TableGen record rather than the AsmName to choose registers for InlineAsm
11197   // constraints, plus we want to match those names to the widest floating point
11198   // register type available, manually select floating point registers here.
11199   //
11200   // The second case is the ABI name of the register, so that frontends can also
11201   // use the ABI names in register constraint lists.
11202   if (Subtarget.hasStdExtF()) {
11203     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11204                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11205                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11206                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11207                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11208                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11209                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11210                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11211                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11212                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11213                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11214                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11215                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11216                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11217                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11218                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11219                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11220                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11221                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11222                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11223                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11224                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11225                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11226                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11227                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11228                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11229                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11230                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11231                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11232                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11233                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11234                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11235                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11236                         .Default(RISCV::NoRegister);
11237     if (FReg != RISCV::NoRegister) {
11238       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11239       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11240         unsigned RegNo = FReg - RISCV::F0_F;
11241         unsigned DReg = RISCV::F0_D + RegNo;
11242         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11243       }
11244       if (VT == MVT::f32 || VT == MVT::Other)
11245         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11246       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11247         unsigned RegNo = FReg - RISCV::F0_F;
11248         unsigned HReg = RISCV::F0_H + RegNo;
11249         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11250       }
11251     }
11252   }
11253 
11254   if (Subtarget.hasVInstructions()) {
11255     Register VReg = StringSwitch<Register>(Constraint.lower())
11256                         .Case("{v0}", RISCV::V0)
11257                         .Case("{v1}", RISCV::V1)
11258                         .Case("{v2}", RISCV::V2)
11259                         .Case("{v3}", RISCV::V3)
11260                         .Case("{v4}", RISCV::V4)
11261                         .Case("{v5}", RISCV::V5)
11262                         .Case("{v6}", RISCV::V6)
11263                         .Case("{v7}", RISCV::V7)
11264                         .Case("{v8}", RISCV::V8)
11265                         .Case("{v9}", RISCV::V9)
11266                         .Case("{v10}", RISCV::V10)
11267                         .Case("{v11}", RISCV::V11)
11268                         .Case("{v12}", RISCV::V12)
11269                         .Case("{v13}", RISCV::V13)
11270                         .Case("{v14}", RISCV::V14)
11271                         .Case("{v15}", RISCV::V15)
11272                         .Case("{v16}", RISCV::V16)
11273                         .Case("{v17}", RISCV::V17)
11274                         .Case("{v18}", RISCV::V18)
11275                         .Case("{v19}", RISCV::V19)
11276                         .Case("{v20}", RISCV::V20)
11277                         .Case("{v21}", RISCV::V21)
11278                         .Case("{v22}", RISCV::V22)
11279                         .Case("{v23}", RISCV::V23)
11280                         .Case("{v24}", RISCV::V24)
11281                         .Case("{v25}", RISCV::V25)
11282                         .Case("{v26}", RISCV::V26)
11283                         .Case("{v27}", RISCV::V27)
11284                         .Case("{v28}", RISCV::V28)
11285                         .Case("{v29}", RISCV::V29)
11286                         .Case("{v30}", RISCV::V30)
11287                         .Case("{v31}", RISCV::V31)
11288                         .Default(RISCV::NoRegister);
11289     if (VReg != RISCV::NoRegister) {
11290       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11291         return std::make_pair(VReg, &RISCV::VMRegClass);
11292       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11293         return std::make_pair(VReg, &RISCV::VRRegClass);
11294       for (const auto *RC :
11295            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11296         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11297           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11298           return std::make_pair(VReg, RC);
11299         }
11300       }
11301     }
11302   }
11303 
11304   std::pair<Register, const TargetRegisterClass *> Res =
11305       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11306 
11307   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11308   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11309   // Subtarget into account.
11310   if (Res.second == &RISCV::GPRF16RegClass ||
11311       Res.second == &RISCV::GPRF32RegClass ||
11312       Res.second == &RISCV::GPRF64RegClass)
11313     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11314 
11315   return Res;
11316 }
11317 
11318 unsigned
11319 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11320   // Currently only support length 1 constraints.
11321   if (ConstraintCode.size() == 1) {
11322     switch (ConstraintCode[0]) {
11323     case 'A':
11324       return InlineAsm::Constraint_A;
11325     default:
11326       break;
11327     }
11328   }
11329 
11330   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11331 }
11332 
11333 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11334     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11335     SelectionDAG &DAG) const {
11336   // Currently only support length 1 constraints.
11337   if (Constraint.length() == 1) {
11338     switch (Constraint[0]) {
11339     case 'I':
11340       // Validate & create a 12-bit signed immediate operand.
11341       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11342         uint64_t CVal = C->getSExtValue();
11343         if (isInt<12>(CVal))
11344           Ops.push_back(
11345               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11346       }
11347       return;
11348     case 'J':
11349       // Validate & create an integer zero operand.
11350       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11351         if (C->getZExtValue() == 0)
11352           Ops.push_back(
11353               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11354       return;
11355     case 'K':
11356       // Validate & create a 5-bit unsigned immediate operand.
11357       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11358         uint64_t CVal = C->getZExtValue();
11359         if (isUInt<5>(CVal))
11360           Ops.push_back(
11361               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11362       }
11363       return;
11364     case 'S':
11365       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11366         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11367                                                  GA->getValueType(0)));
11368       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11369         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11370                                                 BA->getValueType(0)));
11371       }
11372       return;
11373     default:
11374       break;
11375     }
11376   }
11377   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11378 }
11379 
11380 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11381                                                    Instruction *Inst,
11382                                                    AtomicOrdering Ord) const {
11383   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11384     return Builder.CreateFence(Ord);
11385   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11386     return Builder.CreateFence(AtomicOrdering::Release);
11387   return nullptr;
11388 }
11389 
11390 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11391                                                     Instruction *Inst,
11392                                                     AtomicOrdering Ord) const {
11393   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11394     return Builder.CreateFence(AtomicOrdering::Acquire);
11395   return nullptr;
11396 }
11397 
11398 TargetLowering::AtomicExpansionKind
11399 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11400   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11401   // point operations can't be used in an lr/sc sequence without breaking the
11402   // forward-progress guarantee.
11403   if (AI->isFloatingPointOperation())
11404     return AtomicExpansionKind::CmpXChg;
11405 
11406   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11407   if (Size == 8 || Size == 16)
11408     return AtomicExpansionKind::MaskedIntrinsic;
11409   return AtomicExpansionKind::None;
11410 }
11411 
11412 static Intrinsic::ID
11413 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11414   if (XLen == 32) {
11415     switch (BinOp) {
11416     default:
11417       llvm_unreachable("Unexpected AtomicRMW BinOp");
11418     case AtomicRMWInst::Xchg:
11419       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11420     case AtomicRMWInst::Add:
11421       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11422     case AtomicRMWInst::Sub:
11423       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11424     case AtomicRMWInst::Nand:
11425       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11426     case AtomicRMWInst::Max:
11427       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11428     case AtomicRMWInst::Min:
11429       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11430     case AtomicRMWInst::UMax:
11431       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11432     case AtomicRMWInst::UMin:
11433       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11434     }
11435   }
11436 
11437   if (XLen == 64) {
11438     switch (BinOp) {
11439     default:
11440       llvm_unreachable("Unexpected AtomicRMW BinOp");
11441     case AtomicRMWInst::Xchg:
11442       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11443     case AtomicRMWInst::Add:
11444       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11445     case AtomicRMWInst::Sub:
11446       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11447     case AtomicRMWInst::Nand:
11448       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11449     case AtomicRMWInst::Max:
11450       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11451     case AtomicRMWInst::Min:
11452       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11453     case AtomicRMWInst::UMax:
11454       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11455     case AtomicRMWInst::UMin:
11456       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11457     }
11458   }
11459 
11460   llvm_unreachable("Unexpected XLen\n");
11461 }
11462 
11463 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11464     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11465     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11466   unsigned XLen = Subtarget.getXLen();
11467   Value *Ordering =
11468       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11469   Type *Tys[] = {AlignedAddr->getType()};
11470   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11471       AI->getModule(),
11472       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11473 
11474   if (XLen == 64) {
11475     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11476     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11477     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11478   }
11479 
11480   Value *Result;
11481 
11482   // Must pass the shift amount needed to sign extend the loaded value prior
11483   // to performing a signed comparison for min/max. ShiftAmt is the number of
11484   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11485   // is the number of bits to left+right shift the value in order to
11486   // sign-extend.
11487   if (AI->getOperation() == AtomicRMWInst::Min ||
11488       AI->getOperation() == AtomicRMWInst::Max) {
11489     const DataLayout &DL = AI->getModule()->getDataLayout();
11490     unsigned ValWidth =
11491         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11492     Value *SextShamt =
11493         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11494     Result = Builder.CreateCall(LrwOpScwLoop,
11495                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11496   } else {
11497     Result =
11498         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11499   }
11500 
11501   if (XLen == 64)
11502     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11503   return Result;
11504 }
11505 
11506 TargetLowering::AtomicExpansionKind
11507 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11508     AtomicCmpXchgInst *CI) const {
11509   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11510   if (Size == 8 || Size == 16)
11511     return AtomicExpansionKind::MaskedIntrinsic;
11512   return AtomicExpansionKind::None;
11513 }
11514 
11515 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11516     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11517     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11518   unsigned XLen = Subtarget.getXLen();
11519   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11520   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11521   if (XLen == 64) {
11522     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11523     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11524     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11525     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11526   }
11527   Type *Tys[] = {AlignedAddr->getType()};
11528   Function *MaskedCmpXchg =
11529       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11530   Value *Result = Builder.CreateCall(
11531       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11532   if (XLen == 64)
11533     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11534   return Result;
11535 }
11536 
11537 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11538   return false;
11539 }
11540 
11541 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11542                                                EVT VT) const {
11543   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11544     return false;
11545 
11546   switch (FPVT.getSimpleVT().SimpleTy) {
11547   case MVT::f16:
11548     return Subtarget.hasStdExtZfh();
11549   case MVT::f32:
11550     return Subtarget.hasStdExtF();
11551   case MVT::f64:
11552     return Subtarget.hasStdExtD();
11553   default:
11554     return false;
11555   }
11556 }
11557 
11558 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11559   // If we are using the small code model, we can reduce size of jump table
11560   // entry to 4 bytes.
11561   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11562       getTargetMachine().getCodeModel() == CodeModel::Small) {
11563     return MachineJumpTableInfo::EK_Custom32;
11564   }
11565   return TargetLowering::getJumpTableEncoding();
11566 }
11567 
11568 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11569     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11570     unsigned uid, MCContext &Ctx) const {
11571   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11572          getTargetMachine().getCodeModel() == CodeModel::Small);
11573   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11574 }
11575 
11576 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11577                                                      EVT VT) const {
11578   VT = VT.getScalarType();
11579 
11580   if (!VT.isSimple())
11581     return false;
11582 
11583   switch (VT.getSimpleVT().SimpleTy) {
11584   case MVT::f16:
11585     return Subtarget.hasStdExtZfh();
11586   case MVT::f32:
11587     return Subtarget.hasStdExtF();
11588   case MVT::f64:
11589     return Subtarget.hasStdExtD();
11590   default:
11591     break;
11592   }
11593 
11594   return false;
11595 }
11596 
11597 Register RISCVTargetLowering::getExceptionPointerRegister(
11598     const Constant *PersonalityFn) const {
11599   return RISCV::X10;
11600 }
11601 
11602 Register RISCVTargetLowering::getExceptionSelectorRegister(
11603     const Constant *PersonalityFn) const {
11604   return RISCV::X11;
11605 }
11606 
11607 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11608   // Return false to suppress the unnecessary extensions if the LibCall
11609   // arguments or return value is f32 type for LP64 ABI.
11610   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11611   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11612     return false;
11613 
11614   return true;
11615 }
11616 
11617 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11618   if (Subtarget.is64Bit() && Type == MVT::i32)
11619     return true;
11620 
11621   return IsSigned;
11622 }
11623 
11624 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11625                                                  SDValue C) const {
11626   // Check integral scalar types.
11627   if (VT.isScalarInteger()) {
11628     // Omit the optimization if the sub target has the M extension and the data
11629     // size exceeds XLen.
11630     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11631       return false;
11632     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11633       // Break the MUL to a SLLI and an ADD/SUB.
11634       const APInt &Imm = ConstNode->getAPIntValue();
11635       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11636           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11637         return true;
11638       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11639       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11640           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11641            (Imm - 8).isPowerOf2()))
11642         return true;
11643       // Omit the following optimization if the sub target has the M extension
11644       // and the data size >= XLen.
11645       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11646         return false;
11647       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11648       // a pair of LUI/ADDI.
11649       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11650         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11651         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11652             (1 - ImmS).isPowerOf2())
11653         return true;
11654       }
11655     }
11656   }
11657 
11658   return false;
11659 }
11660 
11661 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11662                                                       SDValue ConstNode) const {
11663   // Let the DAGCombiner decide for vectors.
11664   EVT VT = AddNode.getValueType();
11665   if (VT.isVector())
11666     return true;
11667 
11668   // Let the DAGCombiner decide for larger types.
11669   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11670     return true;
11671 
11672   // It is worse if c1 is simm12 while c1*c2 is not.
11673   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11674   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11675   const APInt &C1 = C1Node->getAPIntValue();
11676   const APInt &C2 = C2Node->getAPIntValue();
11677   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11678     return false;
11679 
11680   // Default to true and let the DAGCombiner decide.
11681   return true;
11682 }
11683 
11684 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11685     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11686     bool *Fast) const {
11687   if (!VT.isVector())
11688     return false;
11689 
11690   EVT ElemVT = VT.getVectorElementType();
11691   if (Alignment >= ElemVT.getStoreSize()) {
11692     if (Fast)
11693       *Fast = true;
11694     return true;
11695   }
11696 
11697   return false;
11698 }
11699 
11700 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11701     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11702     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11703   bool IsABIRegCopy = CC.hasValue();
11704   EVT ValueVT = Val.getValueType();
11705   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11706     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11707     // and cast to f32.
11708     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11709     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11710     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11711                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11712     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11713     Parts[0] = Val;
11714     return true;
11715   }
11716 
11717   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11718     LLVMContext &Context = *DAG.getContext();
11719     EVT ValueEltVT = ValueVT.getVectorElementType();
11720     EVT PartEltVT = PartVT.getVectorElementType();
11721     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11722     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11723     if (PartVTBitSize % ValueVTBitSize == 0) {
11724       assert(PartVTBitSize >= ValueVTBitSize);
11725       // If the element types are different, bitcast to the same element type of
11726       // PartVT first.
11727       // Give an example here, we want copy a <vscale x 1 x i8> value to
11728       // <vscale x 4 x i16>.
11729       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11730       // subvector, then we can bitcast to <vscale x 4 x i16>.
11731       if (ValueEltVT != PartEltVT) {
11732         if (PartVTBitSize > ValueVTBitSize) {
11733           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11734           assert(Count != 0 && "The number of element should not be zero.");
11735           EVT SameEltTypeVT =
11736               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11737           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11738                             DAG.getUNDEF(SameEltTypeVT), Val,
11739                             DAG.getVectorIdxConstant(0, DL));
11740         }
11741         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11742       } else {
11743         Val =
11744             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11745                         Val, DAG.getVectorIdxConstant(0, DL));
11746       }
11747       Parts[0] = Val;
11748       return true;
11749     }
11750   }
11751   return false;
11752 }
11753 
11754 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11755     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11756     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11757   bool IsABIRegCopy = CC.hasValue();
11758   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11759     SDValue Val = Parts[0];
11760 
11761     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11762     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11763     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11764     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11765     return Val;
11766   }
11767 
11768   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11769     LLVMContext &Context = *DAG.getContext();
11770     SDValue Val = Parts[0];
11771     EVT ValueEltVT = ValueVT.getVectorElementType();
11772     EVT PartEltVT = PartVT.getVectorElementType();
11773     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11774     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11775     if (PartVTBitSize % ValueVTBitSize == 0) {
11776       assert(PartVTBitSize >= ValueVTBitSize);
11777       EVT SameEltTypeVT = ValueVT;
11778       // If the element types are different, convert it to the same element type
11779       // of PartVT.
11780       // Give an example here, we want copy a <vscale x 1 x i8> value from
11781       // <vscale x 4 x i16>.
11782       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11783       // then we can extract <vscale x 1 x i8>.
11784       if (ValueEltVT != PartEltVT) {
11785         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11786         assert(Count != 0 && "The number of element should not be zero.");
11787         SameEltTypeVT =
11788             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11789         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11790       }
11791       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11792                         DAG.getVectorIdxConstant(0, DL));
11793       return Val;
11794     }
11795   }
11796   return SDValue();
11797 }
11798 
11799 SDValue
11800 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11801                                    SelectionDAG &DAG,
11802                                    SmallVectorImpl<SDNode *> &Created) const {
11803   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11804   if (isIntDivCheap(N->getValueType(0), Attr))
11805     return SDValue(N, 0); // Lower SDIV as SDIV
11806 
11807   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11808          "Unexpected divisor!");
11809 
11810   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11811   if (!Subtarget.hasStdExtZbt())
11812     return SDValue();
11813 
11814   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11815   // Besides, more critical path instructions will be generated when dividing
11816   // by 2. So we keep using the original DAGs for these cases.
11817   unsigned Lg2 = Divisor.countTrailingZeros();
11818   if (Lg2 == 1 || Lg2 >= 12)
11819     return SDValue();
11820 
11821   // fold (sdiv X, pow2)
11822   EVT VT = N->getValueType(0);
11823   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11824     return SDValue();
11825 
11826   SDLoc DL(N);
11827   SDValue N0 = N->getOperand(0);
11828   SDValue Zero = DAG.getConstant(0, DL, VT);
11829   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11830 
11831   // Add (N0 < 0) ? Pow2 - 1 : 0;
11832   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11833   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11834   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11835 
11836   Created.push_back(Cmp.getNode());
11837   Created.push_back(Add.getNode());
11838   Created.push_back(Sel.getNode());
11839 
11840   // Divide by pow2.
11841   SDValue SRA =
11842       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11843 
11844   // If we're dividing by a positive value, we're done.  Otherwise, we must
11845   // negate the result.
11846   if (Divisor.isNonNegative())
11847     return SRA;
11848 
11849   Created.push_back(SRA.getNode());
11850   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11851 }
11852 
11853 #define GET_REGISTER_MATCHER
11854 #include "RISCVGenAsmMatcher.inc"
11855 
11856 Register
11857 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11858                                        const MachineFunction &MF) const {
11859   Register Reg = MatchRegisterAltName(RegName);
11860   if (Reg == RISCV::NoRegister)
11861     Reg = MatchRegisterName(RegName);
11862   if (Reg == RISCV::NoRegister)
11863     report_fatal_error(
11864         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11865   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11866   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11867     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11868                              StringRef(RegName) + "\"."));
11869   return Reg;
11870 }
11871 
11872 namespace llvm {
11873 namespace RISCVVIntrinsicsTable {
11874 
11875 #define GET_RISCVVIntrinsicsTable_IMPL
11876 #include "RISCVGenSearchableTables.inc"
11877 
11878 } // namespace RISCVVIntrinsicsTable
11879 
11880 } // namespace llvm
11881