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     if (Subtarget.is64Bit()) {
255       setOperationAction(ISD::ROTL, MVT::i32, Custom);
256       setOperationAction(ISD::ROTR, MVT::i32, Custom);
257     }
258   } else {
259     setOperationAction(ISD::ROTL, XLenVT, Expand);
260     setOperationAction(ISD::ROTR, XLenVT, Expand);
261   }
262 
263   if (Subtarget.hasStdExtZbp()) {
264     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
265     // more combining.
266     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
267     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
268     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
269     // BSWAP i8 doesn't exist.
270     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
271     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
272 
273     if (Subtarget.is64Bit()) {
274       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
275       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
276     }
277   } else {
278     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
279     // pattern match it directly in isel.
280     setOperationAction(ISD::BSWAP, XLenVT,
281                        Subtarget.hasStdExtZbb() ? Legal : Expand);
282   }
283 
284   if (Subtarget.hasStdExtZbb()) {
285     setOperationAction(ISD::SMIN, XLenVT, Legal);
286     setOperationAction(ISD::SMAX, XLenVT, Legal);
287     setOperationAction(ISD::UMIN, XLenVT, Legal);
288     setOperationAction(ISD::UMAX, XLenVT, Legal);
289 
290     if (Subtarget.is64Bit()) {
291       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
292       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
294       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
295     }
296   } else {
297     setOperationAction(ISD::CTTZ, XLenVT, Expand);
298     setOperationAction(ISD::CTLZ, XLenVT, Expand);
299     setOperationAction(ISD::CTPOP, XLenVT, Expand);
300   }
301 
302   if (Subtarget.hasStdExtZbt()) {
303     setOperationAction(ISD::FSHL, XLenVT, Custom);
304     setOperationAction(ISD::FSHR, XLenVT, Custom);
305     setOperationAction(ISD::SELECT, XLenVT, Legal);
306 
307     if (Subtarget.is64Bit()) {
308       setOperationAction(ISD::FSHL, MVT::i32, Custom);
309       setOperationAction(ISD::FSHR, MVT::i32, Custom);
310     }
311   } else {
312     setOperationAction(ISD::SELECT, XLenVT, Custom);
313   }
314 
315   static const ISD::CondCode FPCCToExpand[] = {
316       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
317       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
318       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
319 
320   static const ISD::NodeType FPOpToExpand[] = {
321       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
322       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
323 
324   if (Subtarget.hasStdExtZfh())
325     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
326 
327   if (Subtarget.hasStdExtZfh()) {
328     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
329     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
330     setOperationAction(ISD::LRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
332     setOperationAction(ISD::LROUND, MVT::f16, Legal);
333     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
339     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
345     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
348     for (auto CC : FPCCToExpand)
349       setCondCodeAction(CC, MVT::f16, Expand);
350     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT, MVT::f16, Custom);
352     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
353 
354     setOperationAction(ISD::FREM,       MVT::f16, Promote);
355     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
356     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
357     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
358     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
359     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
360     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
361     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
362     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
363     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
364     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
365     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
366     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
367     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
368     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
369     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
370     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
371     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
372 
373     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
374     // complete support for all operations in LegalizeDAG.
375 
376     // We need to custom promote this.
377     if (Subtarget.is64Bit())
378       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
379   }
380 
381   if (Subtarget.hasStdExtF()) {
382     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
383     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
384     setOperationAction(ISD::LRINT, MVT::f32, Legal);
385     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
386     setOperationAction(ISD::LROUND, MVT::f32, Legal);
387     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
388     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
389     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
390     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
391     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
392     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
393     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
400     for (auto CC : FPCCToExpand)
401       setCondCodeAction(CC, MVT::f32, Expand);
402     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
403     setOperationAction(ISD::SELECT, MVT::f32, Custom);
404     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
405     for (auto Op : FPOpToExpand)
406       setOperationAction(Op, MVT::f32, Expand);
407     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
408     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
409   }
410 
411   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
412     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
413 
414   if (Subtarget.hasStdExtD()) {
415     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
416     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
417     setOperationAction(ISD::LRINT, MVT::f64, Legal);
418     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
419     setOperationAction(ISD::LROUND, MVT::f64, Legal);
420     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
421     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
422     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
423     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
424     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
425     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
426     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
431     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
435     for (auto CC : FPCCToExpand)
436       setCondCodeAction(CC, MVT::f64, Expand);
437     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
438     setOperationAction(ISD::SELECT, MVT::f64, Custom);
439     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
440     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
441     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442     for (auto Op : FPOpToExpand)
443       setOperationAction(Op, MVT::f64, Expand);
444     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
445     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
446   }
447 
448   if (Subtarget.is64Bit()) {
449     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
450     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
451     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
452     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
453   }
454 
455   if (Subtarget.hasStdExtF()) {
456     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
457     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
458 
459     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
460     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
461     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
462     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
463 
464     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
465     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
466   }
467 
468   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
469   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
470   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
471   setOperationAction(ISD::JumpTable, XLenVT, Custom);
472 
473   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
474 
475   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
476   // Unfortunately this can't be determined just from the ISA naming string.
477   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
478                      Subtarget.is64Bit() ? Legal : Custom);
479 
480   setOperationAction(ISD::TRAP, MVT::Other, Legal);
481   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
483   if (Subtarget.is64Bit())
484     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
485 
486   if (Subtarget.hasStdExtA()) {
487     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
488     setMinCmpXchgSizeInBits(32);
489   } else {
490     setMaxAtomicSizeInBitsSupported(0);
491   }
492 
493   setBooleanContents(ZeroOrOneBooleanContent);
494 
495   if (Subtarget.hasVInstructions()) {
496     setBooleanVectorContents(ZeroOrOneBooleanContent);
497 
498     setOperationAction(ISD::VSCALE, XLenVT, Custom);
499 
500     // RVV intrinsics may have illegal operands.
501     // We also need to custom legalize vmv.x.s.
502     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
503     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
504     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
505     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
506     if (Subtarget.is64Bit()) {
507       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
508     } else {
509       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
510       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
511     }
512 
513     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
514     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
515 
516     static const unsigned IntegerVPOps[] = {
517         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
518         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
519         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
520         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
521         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
522         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
523         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
524         ISD::VP_SELECT};
525 
526     static const unsigned FloatingPointVPOps[] = {
527         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
528         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
529         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
530 
531     if (!Subtarget.is64Bit()) {
532       // We must custom-lower certain vXi64 operations on RV32 due to the vector
533       // element type being illegal.
534       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
535       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
536 
537       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
538       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
539       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
540       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
541       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
542       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
543       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
544       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
545 
546       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
547       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
548       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
549       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
550       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
551       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
552       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
553       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
554     }
555 
556     for (MVT VT : BoolVecVTs) {
557       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
558 
559       // Mask VTs are custom-expanded into a series of standard nodes
560       setOperationAction(ISD::TRUNCATE, VT, Custom);
561       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
562       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
563       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
564 
565       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
566       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
567 
568       setOperationAction(ISD::SELECT, VT, Custom);
569       setOperationAction(ISD::SELECT_CC, VT, Expand);
570       setOperationAction(ISD::VSELECT, VT, Expand);
571       setOperationAction(ISD::VP_SELECT, VT, Expand);
572 
573       setOperationAction(ISD::VP_AND, VT, Custom);
574       setOperationAction(ISD::VP_OR, VT, Custom);
575       setOperationAction(ISD::VP_XOR, VT, Custom);
576 
577       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
578       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
579       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
580 
581       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
582       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
583       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
584 
585       // RVV has native int->float & float->int conversions where the
586       // element type sizes are within one power-of-two of each other. Any
587       // wider distances between type sizes have to be lowered as sequences
588       // which progressively narrow the gap in stages.
589       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
590       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
591       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
592       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
593 
594       // Expand all extending loads to types larger than this, and truncating
595       // stores from types larger than this.
596       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
597         setTruncStoreAction(OtherVT, VT, Expand);
598         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
599         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
600         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
601       }
602     }
603 
604     for (MVT VT : IntVecVTs) {
605       if (VT.getVectorElementType() == MVT::i64 &&
606           !Subtarget.hasVInstructionsI64())
607         continue;
608 
609       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
610       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
611 
612       // Vectors implement MULHS/MULHU.
613       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
614       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
615 
616       setOperationAction(ISD::SMIN, VT, Legal);
617       setOperationAction(ISD::SMAX, VT, Legal);
618       setOperationAction(ISD::UMIN, VT, Legal);
619       setOperationAction(ISD::UMAX, VT, Legal);
620 
621       setOperationAction(ISD::ROTL, VT, Expand);
622       setOperationAction(ISD::ROTR, VT, Expand);
623 
624       setOperationAction(ISD::CTTZ, VT, Expand);
625       setOperationAction(ISD::CTLZ, VT, Expand);
626       setOperationAction(ISD::CTPOP, VT, Expand);
627 
628       setOperationAction(ISD::BSWAP, VT, Expand);
629 
630       // Custom-lower extensions and truncations from/to mask types.
631       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
632       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
633       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
634 
635       // RVV has native int->float & float->int conversions where the
636       // element type sizes are within one power-of-two of each other. Any
637       // wider distances between type sizes have to be lowered as sequences
638       // which progressively narrow the gap in stages.
639       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
640       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
641       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
642       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
643 
644       setOperationAction(ISD::SADDSAT, VT, Legal);
645       setOperationAction(ISD::UADDSAT, VT, Legal);
646       setOperationAction(ISD::SSUBSAT, VT, Legal);
647       setOperationAction(ISD::USUBSAT, VT, Legal);
648 
649       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
650       // nodes which truncate by one power of two at a time.
651       setOperationAction(ISD::TRUNCATE, VT, Custom);
652 
653       // Custom-lower insert/extract operations to simplify patterns.
654       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
655       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
656 
657       // Custom-lower reduction operations to set up the corresponding custom
658       // nodes' operands.
659       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
660       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
661       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
662       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
663       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
664       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
665       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
666       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
667 
668       for (unsigned VPOpc : IntegerVPOps)
669         setOperationAction(VPOpc, VT, Custom);
670 
671       setOperationAction(ISD::LOAD, VT, Custom);
672       setOperationAction(ISD::STORE, VT, Custom);
673 
674       setOperationAction(ISD::MLOAD, VT, Custom);
675       setOperationAction(ISD::MSTORE, VT, Custom);
676       setOperationAction(ISD::MGATHER, VT, Custom);
677       setOperationAction(ISD::MSCATTER, VT, Custom);
678 
679       setOperationAction(ISD::VP_LOAD, VT, Custom);
680       setOperationAction(ISD::VP_STORE, VT, Custom);
681       setOperationAction(ISD::VP_GATHER, VT, Custom);
682       setOperationAction(ISD::VP_SCATTER, VT, Custom);
683 
684       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
685       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
686       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
687 
688       setOperationAction(ISD::SELECT, VT, Custom);
689       setOperationAction(ISD::SELECT_CC, VT, Expand);
690 
691       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
692       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
693 
694       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
695         setTruncStoreAction(VT, OtherVT, Expand);
696         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
697         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
698         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
699       }
700 
701       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
702       // type that can represent the value exactly.
703       if (VT.getVectorElementType() != MVT::i64) {
704         MVT FloatEltVT =
705             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
706         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
707         if (isTypeLegal(FloatVT)) {
708           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
709           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
710         }
711       }
712     }
713 
714     // Expand various CCs to best match the RVV ISA, which natively supports UNE
715     // but no other unordered comparisons, and supports all ordered comparisons
716     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
717     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
718     // and we pattern-match those back to the "original", swapping operands once
719     // more. This way we catch both operations and both "vf" and "fv" forms with
720     // fewer patterns.
721     static const ISD::CondCode VFPCCToExpand[] = {
722         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
723         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
724         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
725     };
726 
727     // Sets common operation actions on RVV floating-point vector types.
728     const auto SetCommonVFPActions = [&](MVT VT) {
729       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
730       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
731       // sizes are within one power-of-two of each other. Therefore conversions
732       // between vXf16 and vXf64 must be lowered as sequences which convert via
733       // vXf32.
734       setOperationAction(ISD::FP_ROUND, VT, Custom);
735       setOperationAction(ISD::FP_EXTEND, VT, Custom);
736       // Custom-lower insert/extract operations to simplify patterns.
737       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
738       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739       // Expand various condition codes (explained above).
740       for (auto CC : VFPCCToExpand)
741         setCondCodeAction(CC, VT, Expand);
742 
743       setOperationAction(ISD::FMINNUM, VT, Legal);
744       setOperationAction(ISD::FMAXNUM, VT, Legal);
745 
746       setOperationAction(ISD::FTRUNC, VT, Custom);
747       setOperationAction(ISD::FCEIL, VT, Custom);
748       setOperationAction(ISD::FFLOOR, VT, Custom);
749 
750       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
751       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
752       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
753       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
754 
755       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
756 
757       setOperationAction(ISD::LOAD, VT, Custom);
758       setOperationAction(ISD::STORE, VT, Custom);
759 
760       setOperationAction(ISD::MLOAD, VT, Custom);
761       setOperationAction(ISD::MSTORE, VT, Custom);
762       setOperationAction(ISD::MGATHER, VT, Custom);
763       setOperationAction(ISD::MSCATTER, VT, Custom);
764 
765       setOperationAction(ISD::VP_LOAD, VT, Custom);
766       setOperationAction(ISD::VP_STORE, VT, Custom);
767       setOperationAction(ISD::VP_GATHER, VT, Custom);
768       setOperationAction(ISD::VP_SCATTER, VT, Custom);
769 
770       setOperationAction(ISD::SELECT, VT, Custom);
771       setOperationAction(ISD::SELECT_CC, VT, Expand);
772 
773       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
774       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
775       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
776 
777       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
778 
779       for (unsigned VPOpc : FloatingPointVPOps)
780         setOperationAction(VPOpc, VT, Custom);
781     };
782 
783     // Sets common extload/truncstore actions on RVV floating-point vector
784     // types.
785     const auto SetCommonVFPExtLoadTruncStoreActions =
786         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
787           for (auto SmallVT : SmallerVTs) {
788             setTruncStoreAction(VT, SmallVT, Expand);
789             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
790           }
791         };
792 
793     if (Subtarget.hasVInstructionsF16())
794       for (MVT VT : F16VecVTs)
795         SetCommonVFPActions(VT);
796 
797     for (MVT VT : F32VecVTs) {
798       if (Subtarget.hasVInstructionsF32())
799         SetCommonVFPActions(VT);
800       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
801     }
802 
803     for (MVT VT : F64VecVTs) {
804       if (Subtarget.hasVInstructionsF64())
805         SetCommonVFPActions(VT);
806       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
807       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
808     }
809 
810     if (Subtarget.useRVVForFixedLengthVectors()) {
811       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
812         if (!useRVVForFixedLengthVectorVT(VT))
813           continue;
814 
815         // By default everything must be expanded.
816         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
817           setOperationAction(Op, VT, Expand);
818         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
819           setTruncStoreAction(VT, OtherVT, Expand);
820           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
821           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
822           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
823         }
824 
825         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
826         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
827         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
828 
829         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
830         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
831 
832         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
833         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
834 
835         setOperationAction(ISD::LOAD, VT, Custom);
836         setOperationAction(ISD::STORE, VT, Custom);
837 
838         setOperationAction(ISD::SETCC, VT, Custom);
839 
840         setOperationAction(ISD::SELECT, VT, Custom);
841 
842         setOperationAction(ISD::TRUNCATE, VT, Custom);
843 
844         setOperationAction(ISD::BITCAST, VT, Custom);
845 
846         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
847         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
848         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
849 
850         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
851         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
852         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
853 
854         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
855         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
856         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
857         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
858 
859         // Operations below are different for between masks and other vectors.
860         if (VT.getVectorElementType() == MVT::i1) {
861           setOperationAction(ISD::VP_AND, VT, Custom);
862           setOperationAction(ISD::VP_OR, VT, Custom);
863           setOperationAction(ISD::VP_XOR, VT, Custom);
864           setOperationAction(ISD::AND, VT, Custom);
865           setOperationAction(ISD::OR, VT, Custom);
866           setOperationAction(ISD::XOR, VT, Custom);
867           continue;
868         }
869 
870         // Use SPLAT_VECTOR to prevent type legalization from destroying the
871         // splats when type legalizing i64 scalar on RV32.
872         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
873         // improvements first.
874         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
875           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
876           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
877         }
878 
879         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
880         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
881 
882         setOperationAction(ISD::MLOAD, VT, Custom);
883         setOperationAction(ISD::MSTORE, VT, Custom);
884         setOperationAction(ISD::MGATHER, VT, Custom);
885         setOperationAction(ISD::MSCATTER, VT, Custom);
886 
887         setOperationAction(ISD::VP_LOAD, VT, Custom);
888         setOperationAction(ISD::VP_STORE, VT, Custom);
889         setOperationAction(ISD::VP_GATHER, VT, Custom);
890         setOperationAction(ISD::VP_SCATTER, VT, Custom);
891 
892         setOperationAction(ISD::ADD, VT, Custom);
893         setOperationAction(ISD::MUL, VT, Custom);
894         setOperationAction(ISD::SUB, VT, Custom);
895         setOperationAction(ISD::AND, VT, Custom);
896         setOperationAction(ISD::OR, VT, Custom);
897         setOperationAction(ISD::XOR, VT, Custom);
898         setOperationAction(ISD::SDIV, VT, Custom);
899         setOperationAction(ISD::SREM, VT, Custom);
900         setOperationAction(ISD::UDIV, VT, Custom);
901         setOperationAction(ISD::UREM, VT, Custom);
902         setOperationAction(ISD::SHL, VT, Custom);
903         setOperationAction(ISD::SRA, VT, Custom);
904         setOperationAction(ISD::SRL, VT, Custom);
905 
906         setOperationAction(ISD::SMIN, VT, Custom);
907         setOperationAction(ISD::SMAX, VT, Custom);
908         setOperationAction(ISD::UMIN, VT, Custom);
909         setOperationAction(ISD::UMAX, VT, Custom);
910         setOperationAction(ISD::ABS,  VT, Custom);
911 
912         setOperationAction(ISD::MULHS, VT, Custom);
913         setOperationAction(ISD::MULHU, VT, Custom);
914 
915         setOperationAction(ISD::SADDSAT, VT, Custom);
916         setOperationAction(ISD::UADDSAT, VT, Custom);
917         setOperationAction(ISD::SSUBSAT, VT, Custom);
918         setOperationAction(ISD::USUBSAT, VT, Custom);
919 
920         setOperationAction(ISD::VSELECT, VT, Custom);
921         setOperationAction(ISD::SELECT_CC, VT, Expand);
922 
923         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
924         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
925         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
926 
927         // Custom-lower reduction operations to set up the corresponding custom
928         // nodes' operands.
929         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
930         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
933         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
934 
935         for (unsigned VPOpc : IntegerVPOps)
936           setOperationAction(VPOpc, VT, Custom);
937 
938         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
939         // type that can represent the value exactly.
940         if (VT.getVectorElementType() != MVT::i64) {
941           MVT FloatEltVT =
942               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
943           EVT FloatVT =
944               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
945           if (isTypeLegal(FloatVT)) {
946             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
947             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
948           }
949         }
950       }
951 
952       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
953         if (!useRVVForFixedLengthVectorVT(VT))
954           continue;
955 
956         // By default everything must be expanded.
957         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
958           setOperationAction(Op, VT, Expand);
959         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
960           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
961           setTruncStoreAction(VT, OtherVT, Expand);
962         }
963 
964         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
965         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
966         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
967 
968         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
969         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
970         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
971         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
972         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
973 
974         setOperationAction(ISD::LOAD, VT, Custom);
975         setOperationAction(ISD::STORE, VT, Custom);
976         setOperationAction(ISD::MLOAD, VT, Custom);
977         setOperationAction(ISD::MSTORE, VT, Custom);
978         setOperationAction(ISD::MGATHER, VT, Custom);
979         setOperationAction(ISD::MSCATTER, VT, Custom);
980 
981         setOperationAction(ISD::VP_LOAD, VT, Custom);
982         setOperationAction(ISD::VP_STORE, VT, Custom);
983         setOperationAction(ISD::VP_GATHER, VT, Custom);
984         setOperationAction(ISD::VP_SCATTER, VT, Custom);
985 
986         setOperationAction(ISD::FADD, VT, Custom);
987         setOperationAction(ISD::FSUB, VT, Custom);
988         setOperationAction(ISD::FMUL, VT, Custom);
989         setOperationAction(ISD::FDIV, VT, Custom);
990         setOperationAction(ISD::FNEG, VT, Custom);
991         setOperationAction(ISD::FABS, VT, Custom);
992         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
993         setOperationAction(ISD::FSQRT, VT, Custom);
994         setOperationAction(ISD::FMA, VT, Custom);
995         setOperationAction(ISD::FMINNUM, VT, Custom);
996         setOperationAction(ISD::FMAXNUM, VT, Custom);
997 
998         setOperationAction(ISD::FP_ROUND, VT, Custom);
999         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1000 
1001         setOperationAction(ISD::FTRUNC, VT, Custom);
1002         setOperationAction(ISD::FCEIL, VT, Custom);
1003         setOperationAction(ISD::FFLOOR, VT, Custom);
1004 
1005         for (auto CC : VFPCCToExpand)
1006           setCondCodeAction(CC, VT, Expand);
1007 
1008         setOperationAction(ISD::VSELECT, VT, Custom);
1009         setOperationAction(ISD::SELECT, VT, Custom);
1010         setOperationAction(ISD::SELECT_CC, VT, Expand);
1011 
1012         setOperationAction(ISD::BITCAST, VT, Custom);
1013 
1014         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1015         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1016         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1018 
1019         for (unsigned VPOpc : FloatingPointVPOps)
1020           setOperationAction(VPOpc, VT, Custom);
1021       }
1022 
1023       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1024       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1025       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1026       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1028       if (Subtarget.hasStdExtZfh())
1029         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1030       if (Subtarget.hasStdExtF())
1031         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1032       if (Subtarget.hasStdExtD())
1033         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1034     }
1035   }
1036 
1037   // Function alignments.
1038   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1039   setMinFunctionAlignment(FunctionAlignment);
1040   setPrefFunctionAlignment(FunctionAlignment);
1041 
1042   setMinimumJumpTableEntries(5);
1043 
1044   // Jumps are expensive, compared to logic
1045   setJumpIsExpensive();
1046 
1047   setTargetDAGCombine(ISD::ADD);
1048   setTargetDAGCombine(ISD::SUB);
1049   setTargetDAGCombine(ISD::AND);
1050   setTargetDAGCombine(ISD::OR);
1051   setTargetDAGCombine(ISD::XOR);
1052   setTargetDAGCombine(ISD::ANY_EXTEND);
1053   if (Subtarget.hasStdExtF()) {
1054     setTargetDAGCombine(ISD::ZERO_EXTEND);
1055     setTargetDAGCombine(ISD::FP_TO_SINT);
1056     setTargetDAGCombine(ISD::FP_TO_UINT);
1057     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1058     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1059   }
1060   if (Subtarget.hasVInstructions()) {
1061     setTargetDAGCombine(ISD::FCOPYSIGN);
1062     setTargetDAGCombine(ISD::MGATHER);
1063     setTargetDAGCombine(ISD::MSCATTER);
1064     setTargetDAGCombine(ISD::VP_GATHER);
1065     setTargetDAGCombine(ISD::VP_SCATTER);
1066     setTargetDAGCombine(ISD::SRA);
1067     setTargetDAGCombine(ISD::SRL);
1068     setTargetDAGCombine(ISD::SHL);
1069     setTargetDAGCombine(ISD::STORE);
1070   }
1071 }
1072 
1073 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1074                                             LLVMContext &Context,
1075                                             EVT VT) const {
1076   if (!VT.isVector())
1077     return getPointerTy(DL);
1078   if (Subtarget.hasVInstructions() &&
1079       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1080     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1081   return VT.changeVectorElementTypeToInteger();
1082 }
1083 
1084 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1085   return Subtarget.getXLenVT();
1086 }
1087 
1088 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1089                                              const CallInst &I,
1090                                              MachineFunction &MF,
1091                                              unsigned Intrinsic) const {
1092   auto &DL = I.getModule()->getDataLayout();
1093   switch (Intrinsic) {
1094   default:
1095     return false;
1096   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1101   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1102   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1103   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1104   case Intrinsic::riscv_masked_cmpxchg_i32: {
1105     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1106     Info.opc = ISD::INTRINSIC_W_CHAIN;
1107     Info.memVT = MVT::getVT(PtrTy->getElementType());
1108     Info.ptrVal = I.getArgOperand(0);
1109     Info.offset = 0;
1110     Info.align = Align(4);
1111     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1112                  MachineMemOperand::MOVolatile;
1113     return true;
1114   }
1115   case Intrinsic::riscv_masked_strided_load:
1116     Info.opc = ISD::INTRINSIC_W_CHAIN;
1117     Info.ptrVal = I.getArgOperand(1);
1118     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1119     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1120     Info.size = MemoryLocation::UnknownSize;
1121     Info.flags |= MachineMemOperand::MOLoad;
1122     return true;
1123   case Intrinsic::riscv_masked_strided_store:
1124     Info.opc = ISD::INTRINSIC_VOID;
1125     Info.ptrVal = I.getArgOperand(1);
1126     Info.memVT =
1127         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1128     Info.align = Align(
1129         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1130         8);
1131     Info.size = MemoryLocation::UnknownSize;
1132     Info.flags |= MachineMemOperand::MOStore;
1133     return true;
1134   }
1135 }
1136 
1137 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1138                                                 const AddrMode &AM, Type *Ty,
1139                                                 unsigned AS,
1140                                                 Instruction *I) const {
1141   // No global is ever allowed as a base.
1142   if (AM.BaseGV)
1143     return false;
1144 
1145   // Require a 12-bit signed offset.
1146   if (!isInt<12>(AM.BaseOffs))
1147     return false;
1148 
1149   switch (AM.Scale) {
1150   case 0: // "r+i" or just "i", depending on HasBaseReg.
1151     break;
1152   case 1:
1153     if (!AM.HasBaseReg) // allow "r+i".
1154       break;
1155     return false; // disallow "r+r" or "r+r+i".
1156   default:
1157     return false;
1158   }
1159 
1160   return true;
1161 }
1162 
1163 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1164   return isInt<12>(Imm);
1165 }
1166 
1167 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1168   return isInt<12>(Imm);
1169 }
1170 
1171 // On RV32, 64-bit integers are split into their high and low parts and held
1172 // in two different registers, so the trunc is free since the low register can
1173 // just be used.
1174 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1175   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1176     return false;
1177   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1178   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1179   return (SrcBits == 64 && DestBits == 32);
1180 }
1181 
1182 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1183   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1184       !SrcVT.isInteger() || !DstVT.isInteger())
1185     return false;
1186   unsigned SrcBits = SrcVT.getSizeInBits();
1187   unsigned DestBits = DstVT.getSizeInBits();
1188   return (SrcBits == 64 && DestBits == 32);
1189 }
1190 
1191 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1192   // Zexts are free if they can be combined with a load.
1193   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1194   // poorly with type legalization of compares preferring sext.
1195   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1196     EVT MemVT = LD->getMemoryVT();
1197     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1198         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1199          LD->getExtensionType() == ISD::ZEXTLOAD))
1200       return true;
1201   }
1202 
1203   return TargetLowering::isZExtFree(Val, VT2);
1204 }
1205 
1206 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1207   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1208 }
1209 
1210 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1211   return Subtarget.hasStdExtZbb();
1212 }
1213 
1214 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1215   return Subtarget.hasStdExtZbb();
1216 }
1217 
1218 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1219   EVT VT = Y.getValueType();
1220 
1221   // FIXME: Support vectors once we have tests.
1222   if (VT.isVector())
1223     return false;
1224 
1225   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1226 }
1227 
1228 /// Check if sinking \p I's operands to I's basic block is profitable, because
1229 /// the operands can be folded into a target instruction, e.g.
1230 /// splats of scalars can fold into vector instructions.
1231 bool RISCVTargetLowering::shouldSinkOperands(
1232     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1233   using namespace llvm::PatternMatch;
1234 
1235   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1236     return false;
1237 
1238   auto IsSinker = [&](Instruction *I, int Operand) {
1239     switch (I->getOpcode()) {
1240     case Instruction::Add:
1241     case Instruction::Sub:
1242     case Instruction::Mul:
1243     case Instruction::And:
1244     case Instruction::Or:
1245     case Instruction::Xor:
1246     case Instruction::FAdd:
1247     case Instruction::FSub:
1248     case Instruction::FMul:
1249     case Instruction::FDiv:
1250     case Instruction::ICmp:
1251     case Instruction::FCmp:
1252       return true;
1253     case Instruction::Shl:
1254     case Instruction::LShr:
1255     case Instruction::AShr:
1256     case Instruction::UDiv:
1257     case Instruction::SDiv:
1258     case Instruction::URem:
1259     case Instruction::SRem:
1260       return Operand == 1;
1261     case Instruction::Call:
1262       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1263         switch (II->getIntrinsicID()) {
1264         case Intrinsic::fma:
1265           return Operand == 0 || Operand == 1;
1266         // FIXME: Our patterns can only match vx/vf instructions when the splat
1267         // it on the RHS, because TableGen doesn't recognize our VP operations
1268         // as commutative.
1269         case Intrinsic::vp_add:
1270         case Intrinsic::vp_mul:
1271         case Intrinsic::vp_and:
1272         case Intrinsic::vp_or:
1273         case Intrinsic::vp_xor:
1274         case Intrinsic::vp_fadd:
1275         case Intrinsic::vp_fsub:
1276         case Intrinsic::vp_fmul:
1277         case Intrinsic::vp_fdiv:
1278         case Intrinsic::vp_shl:
1279         case Intrinsic::vp_lshr:
1280         case Intrinsic::vp_ashr:
1281         case Intrinsic::vp_udiv:
1282         case Intrinsic::vp_sdiv:
1283         case Intrinsic::vp_urem:
1284         case Intrinsic::vp_srem:
1285           return Operand == 1;
1286         // ... the one exception is vp.sub which has explicit patterns for both
1287         // LHS and RHS (as vrsub).
1288         case Intrinsic::vp_sub:
1289           return Operand == 0 || Operand == 1;
1290         default:
1291           return false;
1292         }
1293       }
1294       return false;
1295     default:
1296       return false;
1297     }
1298   };
1299 
1300   for (auto OpIdx : enumerate(I->operands())) {
1301     if (!IsSinker(I, OpIdx.index()))
1302       continue;
1303 
1304     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1305     // Make sure we are not already sinking this operand
1306     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1307       continue;
1308 
1309     // We are looking for a splat that can be sunk.
1310     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1311                              m_Undef(), m_ZeroMask())))
1312       continue;
1313 
1314     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1315     // and vector registers
1316     for (Use &U : Op->uses()) {
1317       Instruction *Insn = cast<Instruction>(U.getUser());
1318       if (!IsSinker(Insn, U.getOperandNo()))
1319         return false;
1320     }
1321 
1322     Ops.push_back(&Op->getOperandUse(0));
1323     Ops.push_back(&OpIdx.value());
1324   }
1325   return true;
1326 }
1327 
1328 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1329                                        bool ForCodeSize) const {
1330   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1331   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1332     return false;
1333   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1334     return false;
1335   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1336     return false;
1337   return Imm.isZero();
1338 }
1339 
1340 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1341   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1342          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1343          (VT == MVT::f64 && Subtarget.hasStdExtD());
1344 }
1345 
1346 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1347                                                       CallingConv::ID CC,
1348                                                       EVT VT) const {
1349   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1350   // We might still end up using a GPR but that will be decided based on ABI.
1351   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1352   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1353     return MVT::f32;
1354 
1355   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1356 }
1357 
1358 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1359                                                            CallingConv::ID CC,
1360                                                            EVT VT) const {
1361   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1362   // We might still end up using a GPR but that will be decided based on ABI.
1363   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1364   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1365     return 1;
1366 
1367   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1368 }
1369 
1370 // Changes the condition code and swaps operands if necessary, so the SetCC
1371 // operation matches one of the comparisons supported directly by branches
1372 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1373 // with 1/-1.
1374 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1375                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1376   // Convert X > -1 to X >= 0.
1377   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1378     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1379     CC = ISD::SETGE;
1380     return;
1381   }
1382   // Convert X < 1 to 0 >= X.
1383   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1384     RHS = LHS;
1385     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1386     CC = ISD::SETGE;
1387     return;
1388   }
1389 
1390   switch (CC) {
1391   default:
1392     break;
1393   case ISD::SETGT:
1394   case ISD::SETLE:
1395   case ISD::SETUGT:
1396   case ISD::SETULE:
1397     CC = ISD::getSetCCSwappedOperands(CC);
1398     std::swap(LHS, RHS);
1399     break;
1400   }
1401 }
1402 
1403 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1404   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1405   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1406   if (VT.getVectorElementType() == MVT::i1)
1407     KnownSize *= 8;
1408 
1409   switch (KnownSize) {
1410   default:
1411     llvm_unreachable("Invalid LMUL.");
1412   case 8:
1413     return RISCVII::VLMUL::LMUL_F8;
1414   case 16:
1415     return RISCVII::VLMUL::LMUL_F4;
1416   case 32:
1417     return RISCVII::VLMUL::LMUL_F2;
1418   case 64:
1419     return RISCVII::VLMUL::LMUL_1;
1420   case 128:
1421     return RISCVII::VLMUL::LMUL_2;
1422   case 256:
1423     return RISCVII::VLMUL::LMUL_4;
1424   case 512:
1425     return RISCVII::VLMUL::LMUL_8;
1426   }
1427 }
1428 
1429 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1430   switch (LMul) {
1431   default:
1432     llvm_unreachable("Invalid LMUL.");
1433   case RISCVII::VLMUL::LMUL_F8:
1434   case RISCVII::VLMUL::LMUL_F4:
1435   case RISCVII::VLMUL::LMUL_F2:
1436   case RISCVII::VLMUL::LMUL_1:
1437     return RISCV::VRRegClassID;
1438   case RISCVII::VLMUL::LMUL_2:
1439     return RISCV::VRM2RegClassID;
1440   case RISCVII::VLMUL::LMUL_4:
1441     return RISCV::VRM4RegClassID;
1442   case RISCVII::VLMUL::LMUL_8:
1443     return RISCV::VRM8RegClassID;
1444   }
1445 }
1446 
1447 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1448   RISCVII::VLMUL LMUL = getLMUL(VT);
1449   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1450       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1451       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1452       LMUL == RISCVII::VLMUL::LMUL_1) {
1453     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1454                   "Unexpected subreg numbering");
1455     return RISCV::sub_vrm1_0 + Index;
1456   }
1457   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1458     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1459                   "Unexpected subreg numbering");
1460     return RISCV::sub_vrm2_0 + Index;
1461   }
1462   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1463     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1464                   "Unexpected subreg numbering");
1465     return RISCV::sub_vrm4_0 + Index;
1466   }
1467   llvm_unreachable("Invalid vector type.");
1468 }
1469 
1470 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1471   if (VT.getVectorElementType() == MVT::i1)
1472     return RISCV::VRRegClassID;
1473   return getRegClassIDForLMUL(getLMUL(VT));
1474 }
1475 
1476 // Attempt to decompose a subvector insert/extract between VecVT and
1477 // SubVecVT via subregister indices. Returns the subregister index that
1478 // can perform the subvector insert/extract with the given element index, as
1479 // well as the index corresponding to any leftover subvectors that must be
1480 // further inserted/extracted within the register class for SubVecVT.
1481 std::pair<unsigned, unsigned>
1482 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1483     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1484     const RISCVRegisterInfo *TRI) {
1485   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1486                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1487                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1488                 "Register classes not ordered");
1489   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1490   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1491   // Try to compose a subregister index that takes us from the incoming
1492   // LMUL>1 register class down to the outgoing one. At each step we half
1493   // the LMUL:
1494   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1495   // Note that this is not guaranteed to find a subregister index, such as
1496   // when we are extracting from one VR type to another.
1497   unsigned SubRegIdx = RISCV::NoSubRegister;
1498   for (const unsigned RCID :
1499        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1500     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1501       VecVT = VecVT.getHalfNumVectorElementsVT();
1502       bool IsHi =
1503           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1504       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1505                                             getSubregIndexByMVT(VecVT, IsHi));
1506       if (IsHi)
1507         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1508     }
1509   return {SubRegIdx, InsertExtractIdx};
1510 }
1511 
1512 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1513 // stores for those types.
1514 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1515   return !Subtarget.useRVVForFixedLengthVectors() ||
1516          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1517 }
1518 
1519 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1520   if (ScalarTy->isPointerTy())
1521     return true;
1522 
1523   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1524       ScalarTy->isIntegerTy(32))
1525     return true;
1526 
1527   if (ScalarTy->isIntegerTy(64))
1528     return Subtarget.hasVInstructionsI64();
1529 
1530   if (ScalarTy->isHalfTy())
1531     return Subtarget.hasVInstructionsF16();
1532   if (ScalarTy->isFloatTy())
1533     return Subtarget.hasVInstructionsF32();
1534   if (ScalarTy->isDoubleTy())
1535     return Subtarget.hasVInstructionsF64();
1536 
1537   return false;
1538 }
1539 
1540 static bool useRVVForFixedLengthVectorVT(MVT VT,
1541                                          const RISCVSubtarget &Subtarget) {
1542   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1543   if (!Subtarget.useRVVForFixedLengthVectors())
1544     return false;
1545 
1546   // We only support a set of vector types with a consistent maximum fixed size
1547   // across all supported vector element types to avoid legalization issues.
1548   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1549   // fixed-length vector type we support is 1024 bytes.
1550   if (VT.getFixedSizeInBits() > 1024 * 8)
1551     return false;
1552 
1553   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1554 
1555   MVT EltVT = VT.getVectorElementType();
1556 
1557   // Don't use RVV for vectors we cannot scalarize if required.
1558   switch (EltVT.SimpleTy) {
1559   // i1 is supported but has different rules.
1560   default:
1561     return false;
1562   case MVT::i1:
1563     // Masks can only use a single register.
1564     if (VT.getVectorNumElements() > MinVLen)
1565       return false;
1566     MinVLen /= 8;
1567     break;
1568   case MVT::i8:
1569   case MVT::i16:
1570   case MVT::i32:
1571     break;
1572   case MVT::i64:
1573     if (!Subtarget.hasVInstructionsI64())
1574       return false;
1575     break;
1576   case MVT::f16:
1577     if (!Subtarget.hasVInstructionsF16())
1578       return false;
1579     break;
1580   case MVT::f32:
1581     if (!Subtarget.hasVInstructionsF32())
1582       return false;
1583     break;
1584   case MVT::f64:
1585     if (!Subtarget.hasVInstructionsF64())
1586       return false;
1587     break;
1588   }
1589 
1590   // Reject elements larger than ELEN.
1591   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1592     return false;
1593 
1594   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1595   // Don't use RVV for types that don't fit.
1596   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1597     return false;
1598 
1599   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1600   // the base fixed length RVV support in place.
1601   if (!VT.isPow2VectorType())
1602     return false;
1603 
1604   return true;
1605 }
1606 
1607 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1608   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1609 }
1610 
1611 // Return the largest legal scalable vector type that matches VT's element type.
1612 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1613                                             const RISCVSubtarget &Subtarget) {
1614   // This may be called before legal types are setup.
1615   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1616           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1617          "Expected legal fixed length vector!");
1618 
1619   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1620   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1621 
1622   MVT EltVT = VT.getVectorElementType();
1623   switch (EltVT.SimpleTy) {
1624   default:
1625     llvm_unreachable("unexpected element type for RVV container");
1626   case MVT::i1:
1627   case MVT::i8:
1628   case MVT::i16:
1629   case MVT::i32:
1630   case MVT::i64:
1631   case MVT::f16:
1632   case MVT::f32:
1633   case MVT::f64: {
1634     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1635     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1636     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1637     unsigned NumElts =
1638         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1639     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1640     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1641     return MVT::getScalableVectorVT(EltVT, NumElts);
1642   }
1643   }
1644 }
1645 
1646 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1647                                             const RISCVSubtarget &Subtarget) {
1648   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1649                                           Subtarget);
1650 }
1651 
1652 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1653   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1654 }
1655 
1656 // Grow V to consume an entire RVV register.
1657 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1658                                        const RISCVSubtarget &Subtarget) {
1659   assert(VT.isScalableVector() &&
1660          "Expected to convert into a scalable vector!");
1661   assert(V.getValueType().isFixedLengthVector() &&
1662          "Expected a fixed length vector operand!");
1663   SDLoc DL(V);
1664   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1665   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1666 }
1667 
1668 // Shrink V so it's just big enough to maintain a VT's worth of data.
1669 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1670                                          const RISCVSubtarget &Subtarget) {
1671   assert(VT.isFixedLengthVector() &&
1672          "Expected to convert into a fixed length vector!");
1673   assert(V.getValueType().isScalableVector() &&
1674          "Expected a scalable vector operand!");
1675   SDLoc DL(V);
1676   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1677   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1678 }
1679 
1680 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1681 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1682 // the vector type that it is contained in.
1683 static std::pair<SDValue, SDValue>
1684 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1685                 const RISCVSubtarget &Subtarget) {
1686   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1687   MVT XLenVT = Subtarget.getXLenVT();
1688   SDValue VL = VecVT.isFixedLengthVector()
1689                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1690                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1691   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1692   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1693   return {Mask, VL};
1694 }
1695 
1696 // As above but assuming the given type is a scalable vector type.
1697 static std::pair<SDValue, SDValue>
1698 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1699                         const RISCVSubtarget &Subtarget) {
1700   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1701   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1702 }
1703 
1704 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1705 // of either is (currently) supported. This can get us into an infinite loop
1706 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1707 // as a ..., etc.
1708 // Until either (or both) of these can reliably lower any node, reporting that
1709 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1710 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1711 // which is not desirable.
1712 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1713     EVT VT, unsigned DefinedValues) const {
1714   return false;
1715 }
1716 
1717 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1718   // Only splats are currently supported.
1719   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1720     return true;
1721 
1722   return false;
1723 }
1724 
1725 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1726                                   const RISCVSubtarget &Subtarget) {
1727   // RISCV FP-to-int conversions saturate to the destination register size, but
1728   // don't produce 0 for nan. We can use a conversion instruction and fix the
1729   // nan case with a compare and a select.
1730   SDValue Src = Op.getOperand(0);
1731 
1732   EVT DstVT = Op.getValueType();
1733   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1734 
1735   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1736   unsigned Opc;
1737   if (SatVT == DstVT)
1738     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1739   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1740     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1741   else
1742     return SDValue();
1743   // FIXME: Support other SatVTs by clamping before or after the conversion.
1744 
1745   SDLoc DL(Op);
1746   SDValue FpToInt = DAG.getNode(
1747       Opc, DL, DstVT, Src,
1748       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1749 
1750   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1751   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1752 }
1753 
1754 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1755 // and back. Taking care to avoid converting values that are nan or already
1756 // correct.
1757 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1758 // have FRM dependencies modeled yet.
1759 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1760   MVT VT = Op.getSimpleValueType();
1761   assert(VT.isVector() && "Unexpected type");
1762 
1763   SDLoc DL(Op);
1764 
1765   // Freeze the source since we are increasing the number of uses.
1766   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1767 
1768   // Truncate to integer and convert back to FP.
1769   MVT IntVT = VT.changeVectorElementTypeToInteger();
1770   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1771   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1772 
1773   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1774 
1775   if (Op.getOpcode() == ISD::FCEIL) {
1776     // If the truncated value is the greater than or equal to the original
1777     // value, we've computed the ceil. Otherwise, we went the wrong way and
1778     // need to increase by 1.
1779     // FIXME: This should use a masked operation. Handle here or in isel?
1780     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1781                                  DAG.getConstantFP(1.0, DL, VT));
1782     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1783     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1784   } else if (Op.getOpcode() == ISD::FFLOOR) {
1785     // If the truncated value is the less than or equal to the original value,
1786     // we've computed the floor. Otherwise, we went the wrong way and need to
1787     // decrease by 1.
1788     // FIXME: This should use a masked operation. Handle here or in isel?
1789     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1790                                  DAG.getConstantFP(1.0, DL, VT));
1791     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1792     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1793   }
1794 
1795   // Restore the original sign so that -0.0 is preserved.
1796   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1797 
1798   // Determine the largest integer that can be represented exactly. This and
1799   // values larger than it don't have any fractional bits so don't need to
1800   // be converted.
1801   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1802   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1803   APFloat MaxVal = APFloat(FltSem);
1804   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1805                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1806   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1807 
1808   // If abs(Src) was larger than MaxVal or nan, keep it.
1809   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1810   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1811   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1812 }
1813 
1814 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1815                                  const RISCVSubtarget &Subtarget) {
1816   MVT VT = Op.getSimpleValueType();
1817   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1818 
1819   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1820 
1821   SDLoc DL(Op);
1822   SDValue Mask, VL;
1823   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1824 
1825   unsigned Opc =
1826       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1827   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1828   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1829 }
1830 
1831 struct VIDSequence {
1832   int64_t StepNumerator;
1833   unsigned StepDenominator;
1834   int64_t Addend;
1835 };
1836 
1837 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1838 // to the (non-zero) step S and start value X. This can be then lowered as the
1839 // RVV sequence (VID * S) + X, for example.
1840 // The step S is represented as an integer numerator divided by a positive
1841 // denominator. Note that the implementation currently only identifies
1842 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1843 // cannot detect 2/3, for example.
1844 // Note that this method will also match potentially unappealing index
1845 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1846 // determine whether this is worth generating code for.
1847 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1848   unsigned NumElts = Op.getNumOperands();
1849   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1850   if (!Op.getValueType().isInteger())
1851     return None;
1852 
1853   Optional<unsigned> SeqStepDenom;
1854   Optional<int64_t> SeqStepNum, SeqAddend;
1855   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1856   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1857   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1858     // Assume undef elements match the sequence; we just have to be careful
1859     // when interpolating across them.
1860     if (Op.getOperand(Idx).isUndef())
1861       continue;
1862     // The BUILD_VECTOR must be all constants.
1863     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1864       return None;
1865 
1866     uint64_t Val = Op.getConstantOperandVal(Idx) &
1867                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1868 
1869     if (PrevElt) {
1870       // Calculate the step since the last non-undef element, and ensure
1871       // it's consistent across the entire sequence.
1872       unsigned IdxDiff = Idx - PrevElt->second;
1873       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1874 
1875       // A zero-value value difference means that we're somewhere in the middle
1876       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1877       // step change before evaluating the sequence.
1878       if (ValDiff != 0) {
1879         int64_t Remainder = ValDiff % IdxDiff;
1880         // Normalize the step if it's greater than 1.
1881         if (Remainder != ValDiff) {
1882           // The difference must cleanly divide the element span.
1883           if (Remainder != 0)
1884             return None;
1885           ValDiff /= IdxDiff;
1886           IdxDiff = 1;
1887         }
1888 
1889         if (!SeqStepNum)
1890           SeqStepNum = ValDiff;
1891         else if (ValDiff != SeqStepNum)
1892           return None;
1893 
1894         if (!SeqStepDenom)
1895           SeqStepDenom = IdxDiff;
1896         else if (IdxDiff != *SeqStepDenom)
1897           return None;
1898       }
1899     }
1900 
1901     // Record and/or check any addend.
1902     if (SeqStepNum && SeqStepDenom) {
1903       uint64_t ExpectedVal =
1904           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1905       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1906       if (!SeqAddend)
1907         SeqAddend = Addend;
1908       else if (SeqAddend != Addend)
1909         return None;
1910     }
1911 
1912     // Record this non-undef element for later.
1913     if (!PrevElt || PrevElt->first != Val)
1914       PrevElt = std::make_pair(Val, Idx);
1915   }
1916   // We need to have logged both a step and an addend for this to count as
1917   // a legal index sequence.
1918   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1919     return None;
1920 
1921   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1922 }
1923 
1924 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1925                                  const RISCVSubtarget &Subtarget) {
1926   MVT VT = Op.getSimpleValueType();
1927   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1928 
1929   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1930 
1931   SDLoc DL(Op);
1932   SDValue Mask, VL;
1933   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1934 
1935   MVT XLenVT = Subtarget.getXLenVT();
1936   unsigned NumElts = Op.getNumOperands();
1937 
1938   if (VT.getVectorElementType() == MVT::i1) {
1939     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1940       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1941       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1942     }
1943 
1944     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1945       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1946       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1947     }
1948 
1949     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1950     // scalar integer chunks whose bit-width depends on the number of mask
1951     // bits and XLEN.
1952     // First, determine the most appropriate scalar integer type to use. This
1953     // is at most XLenVT, but may be shrunk to a smaller vector element type
1954     // according to the size of the final vector - use i8 chunks rather than
1955     // XLenVT if we're producing a v8i1. This results in more consistent
1956     // codegen across RV32 and RV64.
1957     unsigned NumViaIntegerBits =
1958         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1959     NumViaIntegerBits = std::min(NumViaIntegerBits,
1960                                  Subtarget.getMaxELENForFixedLengthVectors());
1961     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1962       // If we have to use more than one INSERT_VECTOR_ELT then this
1963       // optimization is likely to increase code size; avoid peforming it in
1964       // such a case. We can use a load from a constant pool in this case.
1965       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1966         return SDValue();
1967       // Now we can create our integer vector type. Note that it may be larger
1968       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1969       MVT IntegerViaVecVT =
1970           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1971                            divideCeil(NumElts, NumViaIntegerBits));
1972 
1973       uint64_t Bits = 0;
1974       unsigned BitPos = 0, IntegerEltIdx = 0;
1975       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1976 
1977       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1978         // Once we accumulate enough bits to fill our scalar type, insert into
1979         // our vector and clear our accumulated data.
1980         if (I != 0 && I % NumViaIntegerBits == 0) {
1981           if (NumViaIntegerBits <= 32)
1982             Bits = SignExtend64(Bits, 32);
1983           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1984           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1985                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1986           Bits = 0;
1987           BitPos = 0;
1988           IntegerEltIdx++;
1989         }
1990         SDValue V = Op.getOperand(I);
1991         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1992         Bits |= ((uint64_t)BitValue << BitPos);
1993       }
1994 
1995       // Insert the (remaining) scalar value into position in our integer
1996       // vector type.
1997       if (NumViaIntegerBits <= 32)
1998         Bits = SignExtend64(Bits, 32);
1999       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2000       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2001                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2002 
2003       if (NumElts < NumViaIntegerBits) {
2004         // If we're producing a smaller vector than our minimum legal integer
2005         // type, bitcast to the equivalent (known-legal) mask type, and extract
2006         // our final mask.
2007         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2008         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2009         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2010                           DAG.getConstant(0, DL, XLenVT));
2011       } else {
2012         // Else we must have produced an integer type with the same size as the
2013         // mask type; bitcast for the final result.
2014         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2015         Vec = DAG.getBitcast(VT, Vec);
2016       }
2017 
2018       return Vec;
2019     }
2020 
2021     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2022     // vector type, we have a legal equivalently-sized i8 type, so we can use
2023     // that.
2024     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2025     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2026 
2027     SDValue WideVec;
2028     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2029       // For a splat, perform a scalar truncate before creating the wider
2030       // vector.
2031       assert(Splat.getValueType() == XLenVT &&
2032              "Unexpected type for i1 splat value");
2033       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2034                           DAG.getConstant(1, DL, XLenVT));
2035       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2036     } else {
2037       SmallVector<SDValue, 8> Ops(Op->op_values());
2038       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2039       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2040       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2041     }
2042 
2043     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2044   }
2045 
2046   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2047     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2048                                         : RISCVISD::VMV_V_X_VL;
2049     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2050     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2051   }
2052 
2053   // Try and match index sequences, which we can lower to the vid instruction
2054   // with optional modifications. An all-undef vector is matched by
2055   // getSplatValue, above.
2056   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2057     int64_t StepNumerator = SimpleVID->StepNumerator;
2058     unsigned StepDenominator = SimpleVID->StepDenominator;
2059     int64_t Addend = SimpleVID->Addend;
2060 
2061     assert(StepNumerator != 0 && "Invalid step");
2062     bool Negate = false;
2063     int64_t SplatStepVal = StepNumerator;
2064     unsigned StepOpcode = ISD::MUL;
2065     if (StepNumerator != 1) {
2066       if (isPowerOf2_64(std::abs(StepNumerator))) {
2067         Negate = StepNumerator < 0;
2068         StepOpcode = ISD::SHL;
2069         SplatStepVal = Log2_64(std::abs(StepNumerator));
2070       }
2071     }
2072 
2073     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2074     // threshold since it's the immediate value many RVV instructions accept.
2075     // There is no vmul.vi instruction so ensure multiply constant can fit in
2076     // a single addi instruction.
2077     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2078          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2079         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2080       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2081       // Convert right out of the scalable type so we can use standard ISD
2082       // nodes for the rest of the computation. If we used scalable types with
2083       // these, we'd lose the fixed-length vector info and generate worse
2084       // vsetvli code.
2085       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2086       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2087           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2088         SDValue SplatStep = DAG.getSplatVector(
2089             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2090         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2091       }
2092       if (StepDenominator != 1) {
2093         SDValue SplatStep = DAG.getSplatVector(
2094             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2095         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2096       }
2097       if (Addend != 0 || Negate) {
2098         SDValue SplatAddend =
2099             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2100         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2101       }
2102       return VID;
2103     }
2104   }
2105 
2106   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2107   // when re-interpreted as a vector with a larger element type. For example,
2108   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2109   // could be instead splat as
2110   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2111   // TODO: This optimization could also work on non-constant splats, but it
2112   // would require bit-manipulation instructions to construct the splat value.
2113   SmallVector<SDValue> Sequence;
2114   unsigned EltBitSize = VT.getScalarSizeInBits();
2115   const auto *BV = cast<BuildVectorSDNode>(Op);
2116   if (VT.isInteger() && EltBitSize < 64 &&
2117       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2118       BV->getRepeatedSequence(Sequence) &&
2119       (Sequence.size() * EltBitSize) <= 64) {
2120     unsigned SeqLen = Sequence.size();
2121     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2122     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2123     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2124             ViaIntVT == MVT::i64) &&
2125            "Unexpected sequence type");
2126 
2127     unsigned EltIdx = 0;
2128     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2129     uint64_t SplatValue = 0;
2130     // Construct the amalgamated value which can be splatted as this larger
2131     // vector type.
2132     for (const auto &SeqV : Sequence) {
2133       if (!SeqV.isUndef())
2134         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2135                        << (EltIdx * EltBitSize));
2136       EltIdx++;
2137     }
2138 
2139     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2140     // achieve better constant materializion.
2141     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2142       SplatValue = SignExtend64(SplatValue, 32);
2143 
2144     // Since we can't introduce illegal i64 types at this stage, we can only
2145     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2146     // way we can use RVV instructions to splat.
2147     assert((ViaIntVT.bitsLE(XLenVT) ||
2148             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2149            "Unexpected bitcast sequence");
2150     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2151       SDValue ViaVL =
2152           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2153       MVT ViaContainerVT =
2154           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2155       SDValue Splat =
2156           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2157                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2158       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2159       return DAG.getBitcast(VT, Splat);
2160     }
2161   }
2162 
2163   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2164   // which constitute a large proportion of the elements. In such cases we can
2165   // splat a vector with the dominant element and make up the shortfall with
2166   // INSERT_VECTOR_ELTs.
2167   // Note that this includes vectors of 2 elements by association. The
2168   // upper-most element is the "dominant" one, allowing us to use a splat to
2169   // "insert" the upper element, and an insert of the lower element at position
2170   // 0, which improves codegen.
2171   SDValue DominantValue;
2172   unsigned MostCommonCount = 0;
2173   DenseMap<SDValue, unsigned> ValueCounts;
2174   unsigned NumUndefElts =
2175       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2176 
2177   // Track the number of scalar loads we know we'd be inserting, estimated as
2178   // any non-zero floating-point constant. Other kinds of element are either
2179   // already in registers or are materialized on demand. The threshold at which
2180   // a vector load is more desirable than several scalar materializion and
2181   // vector-insertion instructions is not known.
2182   unsigned NumScalarLoads = 0;
2183 
2184   for (SDValue V : Op->op_values()) {
2185     if (V.isUndef())
2186       continue;
2187 
2188     ValueCounts.insert(std::make_pair(V, 0));
2189     unsigned &Count = ValueCounts[V];
2190 
2191     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2192       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2193 
2194     // Is this value dominant? In case of a tie, prefer the highest element as
2195     // it's cheaper to insert near the beginning of a vector than it is at the
2196     // end.
2197     if (++Count >= MostCommonCount) {
2198       DominantValue = V;
2199       MostCommonCount = Count;
2200     }
2201   }
2202 
2203   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2204   unsigned NumDefElts = NumElts - NumUndefElts;
2205   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2206 
2207   // Don't perform this optimization when optimizing for size, since
2208   // materializing elements and inserting them tends to cause code bloat.
2209   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2210       ((MostCommonCount > DominantValueCountThreshold) ||
2211        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2212     // Start by splatting the most common element.
2213     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2214 
2215     DenseSet<SDValue> Processed{DominantValue};
2216     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2217     for (const auto &OpIdx : enumerate(Op->ops())) {
2218       const SDValue &V = OpIdx.value();
2219       if (V.isUndef() || !Processed.insert(V).second)
2220         continue;
2221       if (ValueCounts[V] == 1) {
2222         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2223                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2224       } else {
2225         // Blend in all instances of this value using a VSELECT, using a
2226         // mask where each bit signals whether that element is the one
2227         // we're after.
2228         SmallVector<SDValue> Ops;
2229         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2230           return DAG.getConstant(V == V1, DL, XLenVT);
2231         });
2232         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2233                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2234                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2235       }
2236     }
2237 
2238     return Vec;
2239   }
2240 
2241   return SDValue();
2242 }
2243 
2244 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2245                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2246   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2247     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2248     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2249     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2250     // node in order to try and match RVV vector/scalar instructions.
2251     if ((LoC >> 31) == HiC)
2252       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2253 
2254     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2255     // vmv.v.x whose EEW = 32 to lower it.
2256     auto *Const = dyn_cast<ConstantSDNode>(VL);
2257     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2258       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2259       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2260       // access the subtarget here now.
2261       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2262       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2263     }
2264   }
2265 
2266   // Fall back to a stack store and stride x0 vector load.
2267   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2268 }
2269 
2270 // Called by type legalization to handle splat of i64 on RV32.
2271 // FIXME: We can optimize this when the type has sign or zero bits in one
2272 // of the halves.
2273 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2274                                    SDValue VL, SelectionDAG &DAG) {
2275   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2276   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2277                            DAG.getConstant(0, DL, MVT::i32));
2278   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2279                            DAG.getConstant(1, DL, MVT::i32));
2280   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2281 }
2282 
2283 // This function lowers a splat of a scalar operand Splat with the vector
2284 // length VL. It ensures the final sequence is type legal, which is useful when
2285 // lowering a splat after type legalization.
2286 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2287                                 SelectionDAG &DAG,
2288                                 const RISCVSubtarget &Subtarget) {
2289   if (VT.isFloatingPoint()) {
2290     // If VL is 1, we could use vfmv.s.f.
2291     if (isOneConstant(VL))
2292       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2293                          Scalar, VL);
2294     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2295   }
2296 
2297   MVT XLenVT = Subtarget.getXLenVT();
2298 
2299   // Simplest case is that the operand needs to be promoted to XLenVT.
2300   if (Scalar.getValueType().bitsLE(XLenVT)) {
2301     // If the operand is a constant, sign extend to increase our chances
2302     // of being able to use a .vi instruction. ANY_EXTEND would become a
2303     // a zero extend and the simm5 check in isel would fail.
2304     // FIXME: Should we ignore the upper bits in isel instead?
2305     unsigned ExtOpc =
2306         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2307     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2308     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2309     // If VL is 1 and the scalar value won't benefit from immediate, we could
2310     // use vmv.s.x.
2311     if (isOneConstant(VL) &&
2312         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2313       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2314                          VL);
2315     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2316   }
2317 
2318   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2319          "Unexpected scalar for splat lowering!");
2320 
2321   if (isOneConstant(VL) && isNullConstant(Scalar))
2322     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2323                        DAG.getConstant(0, DL, XLenVT), VL);
2324 
2325   // Otherwise use the more complicated splatting algorithm.
2326   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2327 }
2328 
2329 // Is the mask a slidedown that shifts in undefs.
2330 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2331   int Size = Mask.size();
2332 
2333   // Elements shifted in should be undef.
2334   auto CheckUndefs = [&](int Shift) {
2335     for (int i = Size - Shift; i != Size; ++i)
2336       if (Mask[i] >= 0)
2337         return false;
2338     return true;
2339   };
2340 
2341   // Elements should be shifted or undef.
2342   auto MatchShift = [&](int Shift) {
2343     for (int i = 0; i != Size - Shift; ++i)
2344        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2345          return false;
2346     return true;
2347   };
2348 
2349   // Try all possible shifts.
2350   for (int Shift = 1; Shift != Size; ++Shift)
2351     if (CheckUndefs(Shift) && MatchShift(Shift))
2352       return Shift;
2353 
2354   // No match.
2355   return -1;
2356 }
2357 
2358 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2359                                 const RISCVSubtarget &Subtarget) {
2360   // We need to be able to widen elements to the next larger integer type.
2361   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2362     return false;
2363 
2364   int Size = Mask.size();
2365   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2366 
2367   int Srcs[] = {-1, -1};
2368   for (int i = 0; i != Size; ++i) {
2369     // Ignore undef elements.
2370     if (Mask[i] < 0)
2371       continue;
2372 
2373     // Is this an even or odd element.
2374     int Pol = i % 2;
2375 
2376     // Ensure we consistently use the same source for this element polarity.
2377     int Src = Mask[i] / Size;
2378     if (Srcs[Pol] < 0)
2379       Srcs[Pol] = Src;
2380     if (Srcs[Pol] != Src)
2381       return false;
2382 
2383     // Make sure the element within the source is appropriate for this element
2384     // in the destination.
2385     int Elt = Mask[i] % Size;
2386     if (Elt != i / 2)
2387       return false;
2388   }
2389 
2390   // We need to find a source for each polarity and they can't be the same.
2391   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2392     return false;
2393 
2394   // Swap the sources if the second source was in the even polarity.
2395   SwapSources = Srcs[0] > Srcs[1];
2396 
2397   return true;
2398 }
2399 
2400 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2401                                    const RISCVSubtarget &Subtarget) {
2402   SDValue V1 = Op.getOperand(0);
2403   SDValue V2 = Op.getOperand(1);
2404   SDLoc DL(Op);
2405   MVT XLenVT = Subtarget.getXLenVT();
2406   MVT VT = Op.getSimpleValueType();
2407   unsigned NumElts = VT.getVectorNumElements();
2408   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2409 
2410   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2411 
2412   SDValue TrueMask, VL;
2413   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2414 
2415   if (SVN->isSplat()) {
2416     const int Lane = SVN->getSplatIndex();
2417     if (Lane >= 0) {
2418       MVT SVT = VT.getVectorElementType();
2419 
2420       // Turn splatted vector load into a strided load with an X0 stride.
2421       SDValue V = V1;
2422       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2423       // with undef.
2424       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2425       int Offset = Lane;
2426       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2427         int OpElements =
2428             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2429         V = V.getOperand(Offset / OpElements);
2430         Offset %= OpElements;
2431       }
2432 
2433       // We need to ensure the load isn't atomic or volatile.
2434       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2435         auto *Ld = cast<LoadSDNode>(V);
2436         Offset *= SVT.getStoreSize();
2437         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2438                                                    TypeSize::Fixed(Offset), DL);
2439 
2440         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2441         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2442           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2443           SDValue IntID =
2444               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2445           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2446                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2447           SDValue NewLoad = DAG.getMemIntrinsicNode(
2448               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2449               DAG.getMachineFunction().getMachineMemOperand(
2450                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2451           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2452           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2453         }
2454 
2455         // Otherwise use a scalar load and splat. This will give the best
2456         // opportunity to fold a splat into the operation. ISel can turn it into
2457         // the x0 strided load if we aren't able to fold away the select.
2458         if (SVT.isFloatingPoint())
2459           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2460                           Ld->getPointerInfo().getWithOffset(Offset),
2461                           Ld->getOriginalAlign(),
2462                           Ld->getMemOperand()->getFlags());
2463         else
2464           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2465                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2466                              Ld->getOriginalAlign(),
2467                              Ld->getMemOperand()->getFlags());
2468         DAG.makeEquivalentMemoryOrdering(Ld, V);
2469 
2470         unsigned Opc =
2471             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2472         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2473         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2474       }
2475 
2476       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2477       assert(Lane < (int)NumElts && "Unexpected lane!");
2478       SDValue Gather =
2479           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2480                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2481       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2482     }
2483   }
2484 
2485   ArrayRef<int> Mask = SVN->getMask();
2486 
2487   // Try to match as a slidedown.
2488   int SlideAmt = matchShuffleAsSlideDown(Mask);
2489   if (SlideAmt >= 0) {
2490     // TODO: Should we reduce the VL to account for the upper undef elements?
2491     // Requires additional vsetvlis, but might be faster to execute.
2492     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2493     SDValue SlideDown =
2494         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2495                     DAG.getUNDEF(ContainerVT), V1,
2496                     DAG.getConstant(SlideAmt, DL, XLenVT),
2497                     TrueMask, VL);
2498     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2499   }
2500 
2501   // Detect an interleave shuffle and lower to
2502   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2503   bool SwapSources;
2504   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2505     // Swap sources if needed.
2506     if (SwapSources)
2507       std::swap(V1, V2);
2508 
2509     // Extract the lower half of the vectors.
2510     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2511     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2512                      DAG.getConstant(0, DL, XLenVT));
2513     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2514                      DAG.getConstant(0, DL, XLenVT));
2515 
2516     // Double the element width and halve the number of elements in an int type.
2517     unsigned EltBits = VT.getScalarSizeInBits();
2518     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2519     MVT WideIntVT =
2520         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2521     // Convert this to a scalable vector. We need to base this on the
2522     // destination size to ensure there's always a type with a smaller LMUL.
2523     MVT WideIntContainerVT =
2524         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2525 
2526     // Convert sources to scalable vectors with the same element count as the
2527     // larger type.
2528     MVT HalfContainerVT = MVT::getVectorVT(
2529         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2530     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2531     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2532 
2533     // Cast sources to integer.
2534     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2535     MVT IntHalfVT =
2536         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2537     V1 = DAG.getBitcast(IntHalfVT, V1);
2538     V2 = DAG.getBitcast(IntHalfVT, V2);
2539 
2540     // Freeze V2 since we use it twice and we need to be sure that the add and
2541     // multiply see the same value.
2542     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2543 
2544     // Recreate TrueMask using the widened type's element count.
2545     MVT MaskVT =
2546         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2547     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2548 
2549     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2550     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2551                               V2, TrueMask, VL);
2552     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2553     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2554                                      DAG.getAllOnesConstant(DL, XLenVT));
2555     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2556                                    V2, Multiplier, TrueMask, VL);
2557     // Add the new copies to our previous addition giving us 2^eltbits copies of
2558     // V2. This is equivalent to shifting V2 left by eltbits. This should
2559     // combine with the vwmulu.vv above to form vwmaccu.vv.
2560     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2561                       TrueMask, VL);
2562     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2563     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2564     // vector VT.
2565     ContainerVT =
2566         MVT::getVectorVT(VT.getVectorElementType(),
2567                          WideIntContainerVT.getVectorElementCount() * 2);
2568     Add = DAG.getBitcast(ContainerVT, Add);
2569     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2570   }
2571 
2572   // Detect shuffles which can be re-expressed as vector selects; these are
2573   // shuffles in which each element in the destination is taken from an element
2574   // at the corresponding index in either source vectors.
2575   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2576     int MaskIndex = MaskIdx.value();
2577     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2578   });
2579 
2580   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2581 
2582   SmallVector<SDValue> MaskVals;
2583   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2584   // merged with a second vrgather.
2585   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2586 
2587   // By default we preserve the original operand order, and use a mask to
2588   // select LHS as true and RHS as false. However, since RVV vector selects may
2589   // feature splats but only on the LHS, we may choose to invert our mask and
2590   // instead select between RHS and LHS.
2591   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2592   bool InvertMask = IsSelect == SwapOps;
2593 
2594   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2595   // half.
2596   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2597 
2598   // Now construct the mask that will be used by the vselect or blended
2599   // vrgather operation. For vrgathers, construct the appropriate indices into
2600   // each vector.
2601   for (int MaskIndex : Mask) {
2602     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2603     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2604     if (!IsSelect) {
2605       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2606       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2607                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2608                                      : DAG.getUNDEF(XLenVT));
2609       GatherIndicesRHS.push_back(
2610           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2611                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2612       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2613         ++LHSIndexCounts[MaskIndex];
2614       if (!IsLHSOrUndefIndex)
2615         ++RHSIndexCounts[MaskIndex - NumElts];
2616     }
2617   }
2618 
2619   if (SwapOps) {
2620     std::swap(V1, V2);
2621     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2622   }
2623 
2624   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2625   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2626   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2627 
2628   if (IsSelect)
2629     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2630 
2631   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2632     // On such a large vector we're unable to use i8 as the index type.
2633     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2634     // may involve vector splitting if we're already at LMUL=8, or our
2635     // user-supplied maximum fixed-length LMUL.
2636     return SDValue();
2637   }
2638 
2639   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2640   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2641   MVT IndexVT = VT.changeTypeToInteger();
2642   // Since we can't introduce illegal index types at this stage, use i16 and
2643   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2644   // than XLenVT.
2645   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2646     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2647     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2648   }
2649 
2650   MVT IndexContainerVT =
2651       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2652 
2653   SDValue Gather;
2654   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2655   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2656   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2657     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2658   } else {
2659     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2660     // If only one index is used, we can use a "splat" vrgather.
2661     // TODO: We can splat the most-common index and fix-up any stragglers, if
2662     // that's beneficial.
2663     if (LHSIndexCounts.size() == 1) {
2664       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2665       Gather =
2666           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2667                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2668     } else {
2669       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2670       LHSIndices =
2671           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2672 
2673       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2674                            TrueMask, VL);
2675     }
2676   }
2677 
2678   // If a second vector operand is used by this shuffle, blend it in with an
2679   // additional vrgather.
2680   if (!V2.isUndef()) {
2681     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2682     // If only one index is used, we can use a "splat" vrgather.
2683     // TODO: We can splat the most-common index and fix-up any stragglers, if
2684     // that's beneficial.
2685     if (RHSIndexCounts.size() == 1) {
2686       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2687       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2688                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2689     } else {
2690       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2691       RHSIndices =
2692           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2693       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2694                        VL);
2695     }
2696 
2697     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2698     SelectMask =
2699         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2700 
2701     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2702                          Gather, VL);
2703   }
2704 
2705   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2706 }
2707 
2708 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2709                                      SDLoc DL, SelectionDAG &DAG,
2710                                      const RISCVSubtarget &Subtarget) {
2711   if (VT.isScalableVector())
2712     return DAG.getFPExtendOrRound(Op, DL, VT);
2713   assert(VT.isFixedLengthVector() &&
2714          "Unexpected value type for RVV FP extend/round lowering");
2715   SDValue Mask, VL;
2716   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2717   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2718                         ? RISCVISD::FP_EXTEND_VL
2719                         : RISCVISD::FP_ROUND_VL;
2720   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2721 }
2722 
2723 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2724 // the exponent.
2725 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2726   MVT VT = Op.getSimpleValueType();
2727   unsigned EltSize = VT.getScalarSizeInBits();
2728   SDValue Src = Op.getOperand(0);
2729   SDLoc DL(Op);
2730 
2731   // We need a FP type that can represent the value.
2732   // TODO: Use f16 for i8 when possible?
2733   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2734   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2735 
2736   // Legal types should have been checked in the RISCVTargetLowering
2737   // constructor.
2738   // TODO: Splitting may make sense in some cases.
2739   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2740          "Expected legal float type!");
2741 
2742   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2743   // The trailing zero count is equal to log2 of this single bit value.
2744   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2745     SDValue Neg =
2746         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2747     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2748   }
2749 
2750   // We have a legal FP type, convert to it.
2751   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2752   // Bitcast to integer and shift the exponent to the LSB.
2753   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2754   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2755   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2756   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2757                               DAG.getConstant(ShiftAmt, DL, IntVT));
2758   // Truncate back to original type to allow vnsrl.
2759   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2760   // The exponent contains log2 of the value in biased form.
2761   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2762 
2763   // For trailing zeros, we just need to subtract the bias.
2764   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2765     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2766                        DAG.getConstant(ExponentBias, DL, VT));
2767 
2768   // For leading zeros, we need to remove the bias and convert from log2 to
2769   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2770   unsigned Adjust = ExponentBias + (EltSize - 1);
2771   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2772 }
2773 
2774 // While RVV has alignment restrictions, we should always be able to load as a
2775 // legal equivalently-sized byte-typed vector instead. This method is
2776 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2777 // the load is already correctly-aligned, it returns SDValue().
2778 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2779                                                     SelectionDAG &DAG) const {
2780   auto *Load = cast<LoadSDNode>(Op);
2781   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2782 
2783   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2784                                      Load->getMemoryVT(),
2785                                      *Load->getMemOperand()))
2786     return SDValue();
2787 
2788   SDLoc DL(Op);
2789   MVT VT = Op.getSimpleValueType();
2790   unsigned EltSizeBits = VT.getScalarSizeInBits();
2791   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2792          "Unexpected unaligned RVV load type");
2793   MVT NewVT =
2794       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2795   assert(NewVT.isValid() &&
2796          "Expecting equally-sized RVV vector types to be legal");
2797   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2798                           Load->getPointerInfo(), Load->getOriginalAlign(),
2799                           Load->getMemOperand()->getFlags());
2800   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2801 }
2802 
2803 // While RVV has alignment restrictions, we should always be able to store as a
2804 // legal equivalently-sized byte-typed vector instead. This method is
2805 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2806 // returns SDValue() if the store is already correctly aligned.
2807 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2808                                                      SelectionDAG &DAG) const {
2809   auto *Store = cast<StoreSDNode>(Op);
2810   assert(Store && Store->getValue().getValueType().isVector() &&
2811          "Expected vector store");
2812 
2813   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2814                                      Store->getMemoryVT(),
2815                                      *Store->getMemOperand()))
2816     return SDValue();
2817 
2818   SDLoc DL(Op);
2819   SDValue StoredVal = Store->getValue();
2820   MVT VT = StoredVal.getSimpleValueType();
2821   unsigned EltSizeBits = VT.getScalarSizeInBits();
2822   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2823          "Unexpected unaligned RVV store type");
2824   MVT NewVT =
2825       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2826   assert(NewVT.isValid() &&
2827          "Expecting equally-sized RVV vector types to be legal");
2828   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2829   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2830                       Store->getPointerInfo(), Store->getOriginalAlign(),
2831                       Store->getMemOperand()->getFlags());
2832 }
2833 
2834 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2835                                             SelectionDAG &DAG) const {
2836   switch (Op.getOpcode()) {
2837   default:
2838     report_fatal_error("unimplemented operand");
2839   case ISD::GlobalAddress:
2840     return lowerGlobalAddress(Op, DAG);
2841   case ISD::BlockAddress:
2842     return lowerBlockAddress(Op, DAG);
2843   case ISD::ConstantPool:
2844     return lowerConstantPool(Op, DAG);
2845   case ISD::JumpTable:
2846     return lowerJumpTable(Op, DAG);
2847   case ISD::GlobalTLSAddress:
2848     return lowerGlobalTLSAddress(Op, DAG);
2849   case ISD::SELECT:
2850     return lowerSELECT(Op, DAG);
2851   case ISD::BRCOND:
2852     return lowerBRCOND(Op, DAG);
2853   case ISD::VASTART:
2854     return lowerVASTART(Op, DAG);
2855   case ISD::FRAMEADDR:
2856     return lowerFRAMEADDR(Op, DAG);
2857   case ISD::RETURNADDR:
2858     return lowerRETURNADDR(Op, DAG);
2859   case ISD::SHL_PARTS:
2860     return lowerShiftLeftParts(Op, DAG);
2861   case ISD::SRA_PARTS:
2862     return lowerShiftRightParts(Op, DAG, true);
2863   case ISD::SRL_PARTS:
2864     return lowerShiftRightParts(Op, DAG, false);
2865   case ISD::BITCAST: {
2866     SDLoc DL(Op);
2867     EVT VT = Op.getValueType();
2868     SDValue Op0 = Op.getOperand(0);
2869     EVT Op0VT = Op0.getValueType();
2870     MVT XLenVT = Subtarget.getXLenVT();
2871     if (VT.isFixedLengthVector()) {
2872       // We can handle fixed length vector bitcasts with a simple replacement
2873       // in isel.
2874       if (Op0VT.isFixedLengthVector())
2875         return Op;
2876       // When bitcasting from scalar to fixed-length vector, insert the scalar
2877       // into a one-element vector of the result type, and perform a vector
2878       // bitcast.
2879       if (!Op0VT.isVector()) {
2880         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2881         if (!isTypeLegal(BVT))
2882           return SDValue();
2883         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2884                                               DAG.getUNDEF(BVT), Op0,
2885                                               DAG.getConstant(0, DL, XLenVT)));
2886       }
2887       return SDValue();
2888     }
2889     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2890     // thus: bitcast the vector to a one-element vector type whose element type
2891     // is the same as the result type, and extract the first element.
2892     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2893       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2894       if (!isTypeLegal(BVT))
2895         return SDValue();
2896       SDValue BVec = DAG.getBitcast(BVT, Op0);
2897       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2898                          DAG.getConstant(0, DL, XLenVT));
2899     }
2900     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2901       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2902       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2903       return FPConv;
2904     }
2905     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2906         Subtarget.hasStdExtF()) {
2907       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2908       SDValue FPConv =
2909           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2910       return FPConv;
2911     }
2912     return SDValue();
2913   }
2914   case ISD::INTRINSIC_WO_CHAIN:
2915     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2916   case ISD::INTRINSIC_W_CHAIN:
2917     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2918   case ISD::INTRINSIC_VOID:
2919     return LowerINTRINSIC_VOID(Op, DAG);
2920   case ISD::BSWAP:
2921   case ISD::BITREVERSE: {
2922     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2923     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2924     MVT VT = Op.getSimpleValueType();
2925     SDLoc DL(Op);
2926     // Start with the maximum immediate value which is the bitwidth - 1.
2927     unsigned Imm = VT.getSizeInBits() - 1;
2928     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2929     if (Op.getOpcode() == ISD::BSWAP)
2930       Imm &= ~0x7U;
2931     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2932                        DAG.getConstant(Imm, DL, VT));
2933   }
2934   case ISD::FSHL:
2935   case ISD::FSHR: {
2936     MVT VT = Op.getSimpleValueType();
2937     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2938     SDLoc DL(Op);
2939     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2940     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2941     // accidentally setting the extra bit.
2942     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2943     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2944                                 DAG.getConstant(ShAmtWidth, DL, VT));
2945     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2946     // instruction use different orders. fshl will return its first operand for
2947     // shift of zero, fshr will return its second operand. fsl and fsr both
2948     // return rs1 so the ISD nodes need to have different operand orders.
2949     // Shift amount is in rs2.
2950     SDValue Op0 = Op.getOperand(0);
2951     SDValue Op1 = Op.getOperand(1);
2952     unsigned Opc = RISCVISD::FSL;
2953     if (Op.getOpcode() == ISD::FSHR) {
2954       std::swap(Op0, Op1);
2955       Opc = RISCVISD::FSR;
2956     }
2957     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
2958   }
2959   case ISD::TRUNCATE: {
2960     SDLoc DL(Op);
2961     MVT VT = Op.getSimpleValueType();
2962     // Only custom-lower vector truncates
2963     if (!VT.isVector())
2964       return Op;
2965 
2966     // Truncates to mask types are handled differently
2967     if (VT.getVectorElementType() == MVT::i1)
2968       return lowerVectorMaskTrunc(Op, DAG);
2969 
2970     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2971     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2972     // truncate by one power of two at a time.
2973     MVT DstEltVT = VT.getVectorElementType();
2974 
2975     SDValue Src = Op.getOperand(0);
2976     MVT SrcVT = Src.getSimpleValueType();
2977     MVT SrcEltVT = SrcVT.getVectorElementType();
2978 
2979     assert(DstEltVT.bitsLT(SrcEltVT) &&
2980            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2981            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2982            "Unexpected vector truncate lowering");
2983 
2984     MVT ContainerVT = SrcVT;
2985     if (SrcVT.isFixedLengthVector()) {
2986       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2987       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2988     }
2989 
2990     SDValue Result = Src;
2991     SDValue Mask, VL;
2992     std::tie(Mask, VL) =
2993         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2994     LLVMContext &Context = *DAG.getContext();
2995     const ElementCount Count = ContainerVT.getVectorElementCount();
2996     do {
2997       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2998       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2999       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3000                            Mask, VL);
3001     } while (SrcEltVT != DstEltVT);
3002 
3003     if (SrcVT.isFixedLengthVector())
3004       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3005 
3006     return Result;
3007   }
3008   case ISD::ANY_EXTEND:
3009   case ISD::ZERO_EXTEND:
3010     if (Op.getOperand(0).getValueType().isVector() &&
3011         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3012       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3013     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3014   case ISD::SIGN_EXTEND:
3015     if (Op.getOperand(0).getValueType().isVector() &&
3016         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3017       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3018     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3019   case ISD::SPLAT_VECTOR_PARTS:
3020     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3021   case ISD::INSERT_VECTOR_ELT:
3022     return lowerINSERT_VECTOR_ELT(Op, DAG);
3023   case ISD::EXTRACT_VECTOR_ELT:
3024     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3025   case ISD::VSCALE: {
3026     MVT VT = Op.getSimpleValueType();
3027     SDLoc DL(Op);
3028     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3029     // We define our scalable vector types for lmul=1 to use a 64 bit known
3030     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3031     // vscale as VLENB / 8.
3032     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3033     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3034       // We assume VLENB is a multiple of 8. We manually choose the best shift
3035       // here because SimplifyDemandedBits isn't always able to simplify it.
3036       uint64_t Val = Op.getConstantOperandVal(0);
3037       if (isPowerOf2_64(Val)) {
3038         uint64_t Log2 = Log2_64(Val);
3039         if (Log2 < 3)
3040           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3041                              DAG.getConstant(3 - Log2, DL, VT));
3042         if (Log2 > 3)
3043           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3044                              DAG.getConstant(Log2 - 3, DL, VT));
3045         return VLENB;
3046       }
3047       // If the multiplier is a multiple of 8, scale it down to avoid needing
3048       // to shift the VLENB value.
3049       if ((Val % 8) == 0)
3050         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3051                            DAG.getConstant(Val / 8, DL, VT));
3052     }
3053 
3054     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3055                                  DAG.getConstant(3, DL, VT));
3056     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3057   }
3058   case ISD::FPOWI: {
3059     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3060     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3061     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3062         Op.getOperand(1).getValueType() == MVT::i32) {
3063       SDLoc DL(Op);
3064       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3065       SDValue Powi =
3066           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3067       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3068                          DAG.getIntPtrConstant(0, DL));
3069     }
3070     return SDValue();
3071   }
3072   case ISD::FP_EXTEND: {
3073     // RVV can only do fp_extend to types double the size as the source. We
3074     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3075     // via f32.
3076     SDLoc DL(Op);
3077     MVT VT = Op.getSimpleValueType();
3078     SDValue Src = Op.getOperand(0);
3079     MVT SrcVT = Src.getSimpleValueType();
3080 
3081     // Prepare any fixed-length vector operands.
3082     MVT ContainerVT = VT;
3083     if (SrcVT.isFixedLengthVector()) {
3084       ContainerVT = getContainerForFixedLengthVector(VT);
3085       MVT SrcContainerVT =
3086           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3087       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3088     }
3089 
3090     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3091         SrcVT.getVectorElementType() != MVT::f16) {
3092       // For scalable vectors, we only need to close the gap between
3093       // vXf16->vXf64.
3094       if (!VT.isFixedLengthVector())
3095         return Op;
3096       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3097       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3098       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3099     }
3100 
3101     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3102     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3103     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3104         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3105 
3106     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3107                                            DL, DAG, Subtarget);
3108     if (VT.isFixedLengthVector())
3109       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3110     return Extend;
3111   }
3112   case ISD::FP_ROUND: {
3113     // RVV can only do fp_round to types half the size as the source. We
3114     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3115     // conversion instruction.
3116     SDLoc DL(Op);
3117     MVT VT = Op.getSimpleValueType();
3118     SDValue Src = Op.getOperand(0);
3119     MVT SrcVT = Src.getSimpleValueType();
3120 
3121     // Prepare any fixed-length vector operands.
3122     MVT ContainerVT = VT;
3123     if (VT.isFixedLengthVector()) {
3124       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3125       ContainerVT =
3126           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3127       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3128     }
3129 
3130     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3131         SrcVT.getVectorElementType() != MVT::f64) {
3132       // For scalable vectors, we only need to close the gap between
3133       // vXf64<->vXf16.
3134       if (!VT.isFixedLengthVector())
3135         return Op;
3136       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3137       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3138       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3139     }
3140 
3141     SDValue Mask, VL;
3142     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3143 
3144     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3145     SDValue IntermediateRound =
3146         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3147     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3148                                           DL, DAG, Subtarget);
3149 
3150     if (VT.isFixedLengthVector())
3151       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3152     return Round;
3153   }
3154   case ISD::FP_TO_SINT:
3155   case ISD::FP_TO_UINT:
3156   case ISD::SINT_TO_FP:
3157   case ISD::UINT_TO_FP: {
3158     // RVV can only do fp<->int conversions to types half/double the size as
3159     // the source. We custom-lower any conversions that do two hops into
3160     // sequences.
3161     MVT VT = Op.getSimpleValueType();
3162     if (!VT.isVector())
3163       return Op;
3164     SDLoc DL(Op);
3165     SDValue Src = Op.getOperand(0);
3166     MVT EltVT = VT.getVectorElementType();
3167     MVT SrcVT = Src.getSimpleValueType();
3168     MVT SrcEltVT = SrcVT.getVectorElementType();
3169     unsigned EltSize = EltVT.getSizeInBits();
3170     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3171     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3172            "Unexpected vector element types");
3173 
3174     bool IsInt2FP = SrcEltVT.isInteger();
3175     // Widening conversions
3176     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3177       if (IsInt2FP) {
3178         // Do a regular integer sign/zero extension then convert to float.
3179         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3180                                       VT.getVectorElementCount());
3181         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3182                                  ? ISD::ZERO_EXTEND
3183                                  : ISD::SIGN_EXTEND;
3184         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3185         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3186       }
3187       // FP2Int
3188       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3189       // Do one doubling fp_extend then complete the operation by converting
3190       // to int.
3191       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3192       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3193       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3194     }
3195 
3196     // Narrowing conversions
3197     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3198       if (IsInt2FP) {
3199         // One narrowing int_to_fp, then an fp_round.
3200         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3201         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3202         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3203         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3204       }
3205       // FP2Int
3206       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3207       // representable by the integer, the result is poison.
3208       MVT IVecVT =
3209           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3210                            VT.getVectorElementCount());
3211       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3212       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3213     }
3214 
3215     // Scalable vectors can exit here. Patterns will handle equally-sized
3216     // conversions halving/doubling ones.
3217     if (!VT.isFixedLengthVector())
3218       return Op;
3219 
3220     // For fixed-length vectors we lower to a custom "VL" node.
3221     unsigned RVVOpc = 0;
3222     switch (Op.getOpcode()) {
3223     default:
3224       llvm_unreachable("Impossible opcode");
3225     case ISD::FP_TO_SINT:
3226       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3227       break;
3228     case ISD::FP_TO_UINT:
3229       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3230       break;
3231     case ISD::SINT_TO_FP:
3232       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3233       break;
3234     case ISD::UINT_TO_FP:
3235       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3236       break;
3237     }
3238 
3239     MVT ContainerVT, SrcContainerVT;
3240     // Derive the reference container type from the larger vector type.
3241     if (SrcEltSize > EltSize) {
3242       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3243       ContainerVT =
3244           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3245     } else {
3246       ContainerVT = getContainerForFixedLengthVector(VT);
3247       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3248     }
3249 
3250     SDValue Mask, VL;
3251     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3252 
3253     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3254     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3255     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3256   }
3257   case ISD::FP_TO_SINT_SAT:
3258   case ISD::FP_TO_UINT_SAT:
3259     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3260   case ISD::FTRUNC:
3261   case ISD::FCEIL:
3262   case ISD::FFLOOR:
3263     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3264   case ISD::VECREDUCE_ADD:
3265   case ISD::VECREDUCE_UMAX:
3266   case ISD::VECREDUCE_SMAX:
3267   case ISD::VECREDUCE_UMIN:
3268   case ISD::VECREDUCE_SMIN:
3269     return lowerVECREDUCE(Op, DAG);
3270   case ISD::VECREDUCE_AND:
3271   case ISD::VECREDUCE_OR:
3272   case ISD::VECREDUCE_XOR:
3273     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3274       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3275     return lowerVECREDUCE(Op, DAG);
3276   case ISD::VECREDUCE_FADD:
3277   case ISD::VECREDUCE_SEQ_FADD:
3278   case ISD::VECREDUCE_FMIN:
3279   case ISD::VECREDUCE_FMAX:
3280     return lowerFPVECREDUCE(Op, DAG);
3281   case ISD::VP_REDUCE_ADD:
3282   case ISD::VP_REDUCE_UMAX:
3283   case ISD::VP_REDUCE_SMAX:
3284   case ISD::VP_REDUCE_UMIN:
3285   case ISD::VP_REDUCE_SMIN:
3286   case ISD::VP_REDUCE_FADD:
3287   case ISD::VP_REDUCE_SEQ_FADD:
3288   case ISD::VP_REDUCE_FMIN:
3289   case ISD::VP_REDUCE_FMAX:
3290     return lowerVPREDUCE(Op, DAG);
3291   case ISD::VP_REDUCE_AND:
3292   case ISD::VP_REDUCE_OR:
3293   case ISD::VP_REDUCE_XOR:
3294     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3295       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3296     return lowerVPREDUCE(Op, DAG);
3297   case ISD::INSERT_SUBVECTOR:
3298     return lowerINSERT_SUBVECTOR(Op, DAG);
3299   case ISD::EXTRACT_SUBVECTOR:
3300     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3301   case ISD::STEP_VECTOR:
3302     return lowerSTEP_VECTOR(Op, DAG);
3303   case ISD::VECTOR_REVERSE:
3304     return lowerVECTOR_REVERSE(Op, DAG);
3305   case ISD::BUILD_VECTOR:
3306     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3307   case ISD::SPLAT_VECTOR:
3308     if (Op.getValueType().getVectorElementType() == MVT::i1)
3309       return lowerVectorMaskSplat(Op, DAG);
3310     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3311   case ISD::VECTOR_SHUFFLE:
3312     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3313   case ISD::CONCAT_VECTORS: {
3314     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3315     // better than going through the stack, as the default expansion does.
3316     SDLoc DL(Op);
3317     MVT VT = Op.getSimpleValueType();
3318     unsigned NumOpElts =
3319         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3320     SDValue Vec = DAG.getUNDEF(VT);
3321     for (const auto &OpIdx : enumerate(Op->ops())) {
3322       SDValue SubVec = OpIdx.value();
3323       // Don't insert undef subvectors.
3324       if (SubVec.isUndef())
3325         continue;
3326       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3327                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3328     }
3329     return Vec;
3330   }
3331   case ISD::LOAD:
3332     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3333       return V;
3334     if (Op.getValueType().isFixedLengthVector())
3335       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3336     return Op;
3337   case ISD::STORE:
3338     if (auto V = expandUnalignedRVVStore(Op, DAG))
3339       return V;
3340     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3341       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3342     return Op;
3343   case ISD::MLOAD:
3344   case ISD::VP_LOAD:
3345     return lowerMaskedLoad(Op, DAG);
3346   case ISD::MSTORE:
3347   case ISD::VP_STORE:
3348     return lowerMaskedStore(Op, DAG);
3349   case ISD::SETCC:
3350     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3351   case ISD::ADD:
3352     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3353   case ISD::SUB:
3354     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3355   case ISD::MUL:
3356     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3357   case ISD::MULHS:
3358     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3359   case ISD::MULHU:
3360     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3361   case ISD::AND:
3362     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3363                                               RISCVISD::AND_VL);
3364   case ISD::OR:
3365     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3366                                               RISCVISD::OR_VL);
3367   case ISD::XOR:
3368     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3369                                               RISCVISD::XOR_VL);
3370   case ISD::SDIV:
3371     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3372   case ISD::SREM:
3373     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3374   case ISD::UDIV:
3375     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3376   case ISD::UREM:
3377     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3378   case ISD::SHL:
3379   case ISD::SRA:
3380   case ISD::SRL:
3381     if (Op.getSimpleValueType().isFixedLengthVector())
3382       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3383     // This can be called for an i32 shift amount that needs to be promoted.
3384     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3385            "Unexpected custom legalisation");
3386     return SDValue();
3387   case ISD::SADDSAT:
3388     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3389   case ISD::UADDSAT:
3390     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3391   case ISD::SSUBSAT:
3392     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3393   case ISD::USUBSAT:
3394     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3395   case ISD::FADD:
3396     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3397   case ISD::FSUB:
3398     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3399   case ISD::FMUL:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3401   case ISD::FDIV:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3403   case ISD::FNEG:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3405   case ISD::FABS:
3406     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3407   case ISD::FSQRT:
3408     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3409   case ISD::FMA:
3410     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3411   case ISD::SMIN:
3412     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3413   case ISD::SMAX:
3414     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3415   case ISD::UMIN:
3416     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3417   case ISD::UMAX:
3418     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3419   case ISD::FMINNUM:
3420     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3421   case ISD::FMAXNUM:
3422     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3423   case ISD::ABS:
3424     return lowerABS(Op, DAG);
3425   case ISD::CTLZ_ZERO_UNDEF:
3426   case ISD::CTTZ_ZERO_UNDEF:
3427     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3428   case ISD::VSELECT:
3429     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3430   case ISD::FCOPYSIGN:
3431     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3432   case ISD::MGATHER:
3433   case ISD::VP_GATHER:
3434     return lowerMaskedGather(Op, DAG);
3435   case ISD::MSCATTER:
3436   case ISD::VP_SCATTER:
3437     return lowerMaskedScatter(Op, DAG);
3438   case ISD::FLT_ROUNDS_:
3439     return lowerGET_ROUNDING(Op, DAG);
3440   case ISD::SET_ROUNDING:
3441     return lowerSET_ROUNDING(Op, DAG);
3442   case ISD::VP_SELECT:
3443     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3444   case ISD::VP_ADD:
3445     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3446   case ISD::VP_SUB:
3447     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3448   case ISD::VP_MUL:
3449     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3450   case ISD::VP_SDIV:
3451     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3452   case ISD::VP_UDIV:
3453     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3454   case ISD::VP_SREM:
3455     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3456   case ISD::VP_UREM:
3457     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3458   case ISD::VP_AND:
3459     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3460   case ISD::VP_OR:
3461     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3462   case ISD::VP_XOR:
3463     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3464   case ISD::VP_ASHR:
3465     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3466   case ISD::VP_LSHR:
3467     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3468   case ISD::VP_SHL:
3469     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3470   case ISD::VP_FADD:
3471     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3472   case ISD::VP_FSUB:
3473     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3474   case ISD::VP_FMUL:
3475     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3476   case ISD::VP_FDIV:
3477     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3478   }
3479 }
3480 
3481 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3482                              SelectionDAG &DAG, unsigned Flags) {
3483   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3484 }
3485 
3486 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3487                              SelectionDAG &DAG, unsigned Flags) {
3488   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3489                                    Flags);
3490 }
3491 
3492 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3493                              SelectionDAG &DAG, unsigned Flags) {
3494   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3495                                    N->getOffset(), Flags);
3496 }
3497 
3498 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3499                              SelectionDAG &DAG, unsigned Flags) {
3500   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3501 }
3502 
3503 template <class NodeTy>
3504 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3505                                      bool IsLocal) const {
3506   SDLoc DL(N);
3507   EVT Ty = getPointerTy(DAG.getDataLayout());
3508 
3509   if (isPositionIndependent()) {
3510     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3511     if (IsLocal)
3512       // Use PC-relative addressing to access the symbol. This generates the
3513       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3514       // %pcrel_lo(auipc)).
3515       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3516 
3517     // Use PC-relative addressing to access the GOT for this symbol, then load
3518     // the address from the GOT. This generates the pattern (PseudoLA sym),
3519     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3520     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3521   }
3522 
3523   switch (getTargetMachine().getCodeModel()) {
3524   default:
3525     report_fatal_error("Unsupported code model for lowering");
3526   case CodeModel::Small: {
3527     // Generate a sequence for accessing addresses within the first 2 GiB of
3528     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3529     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3530     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3531     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3532     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3533   }
3534   case CodeModel::Medium: {
3535     // Generate a sequence for accessing addresses within any 2GiB range within
3536     // the address space. This generates the pattern (PseudoLLA sym), which
3537     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3538     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3539     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3540   }
3541   }
3542 }
3543 
3544 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3545                                                 SelectionDAG &DAG) const {
3546   SDLoc DL(Op);
3547   EVT Ty = Op.getValueType();
3548   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3549   int64_t Offset = N->getOffset();
3550   MVT XLenVT = Subtarget.getXLenVT();
3551 
3552   const GlobalValue *GV = N->getGlobal();
3553   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3554   SDValue Addr = getAddr(N, DAG, IsLocal);
3555 
3556   // In order to maximise the opportunity for common subexpression elimination,
3557   // emit a separate ADD node for the global address offset instead of folding
3558   // it in the global address node. Later peephole optimisations may choose to
3559   // fold it back in when profitable.
3560   if (Offset != 0)
3561     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3562                        DAG.getConstant(Offset, DL, XLenVT));
3563   return Addr;
3564 }
3565 
3566 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3567                                                SelectionDAG &DAG) const {
3568   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3569 
3570   return getAddr(N, DAG);
3571 }
3572 
3573 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3574                                                SelectionDAG &DAG) const {
3575   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3576 
3577   return getAddr(N, DAG);
3578 }
3579 
3580 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3581                                             SelectionDAG &DAG) const {
3582   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3583 
3584   return getAddr(N, DAG);
3585 }
3586 
3587 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3588                                               SelectionDAG &DAG,
3589                                               bool UseGOT) const {
3590   SDLoc DL(N);
3591   EVT Ty = getPointerTy(DAG.getDataLayout());
3592   const GlobalValue *GV = N->getGlobal();
3593   MVT XLenVT = Subtarget.getXLenVT();
3594 
3595   if (UseGOT) {
3596     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3597     // load the address from the GOT and add the thread pointer. This generates
3598     // the pattern (PseudoLA_TLS_IE sym), which expands to
3599     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3600     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3601     SDValue Load =
3602         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3603 
3604     // Add the thread pointer.
3605     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3606     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3607   }
3608 
3609   // Generate a sequence for accessing the address relative to the thread
3610   // pointer, with the appropriate adjustment for the thread pointer offset.
3611   // This generates the pattern
3612   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3613   SDValue AddrHi =
3614       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3615   SDValue AddrAdd =
3616       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3617   SDValue AddrLo =
3618       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3619 
3620   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3621   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3622   SDValue MNAdd = SDValue(
3623       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3624       0);
3625   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3626 }
3627 
3628 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3629                                                SelectionDAG &DAG) const {
3630   SDLoc DL(N);
3631   EVT Ty = getPointerTy(DAG.getDataLayout());
3632   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3633   const GlobalValue *GV = N->getGlobal();
3634 
3635   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3636   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3637   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3638   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3639   SDValue Load =
3640       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3641 
3642   // Prepare argument list to generate call.
3643   ArgListTy Args;
3644   ArgListEntry Entry;
3645   Entry.Node = Load;
3646   Entry.Ty = CallTy;
3647   Args.push_back(Entry);
3648 
3649   // Setup call to __tls_get_addr.
3650   TargetLowering::CallLoweringInfo CLI(DAG);
3651   CLI.setDebugLoc(DL)
3652       .setChain(DAG.getEntryNode())
3653       .setLibCallee(CallingConv::C, CallTy,
3654                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3655                     std::move(Args));
3656 
3657   return LowerCallTo(CLI).first;
3658 }
3659 
3660 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3661                                                    SelectionDAG &DAG) const {
3662   SDLoc DL(Op);
3663   EVT Ty = Op.getValueType();
3664   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3665   int64_t Offset = N->getOffset();
3666   MVT XLenVT = Subtarget.getXLenVT();
3667 
3668   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3669 
3670   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3671       CallingConv::GHC)
3672     report_fatal_error("In GHC calling convention TLS is not supported");
3673 
3674   SDValue Addr;
3675   switch (Model) {
3676   case TLSModel::LocalExec:
3677     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3678     break;
3679   case TLSModel::InitialExec:
3680     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3681     break;
3682   case TLSModel::LocalDynamic:
3683   case TLSModel::GeneralDynamic:
3684     Addr = getDynamicTLSAddr(N, DAG);
3685     break;
3686   }
3687 
3688   // In order to maximise the opportunity for common subexpression elimination,
3689   // emit a separate ADD node for the global address offset instead of folding
3690   // it in the global address node. Later peephole optimisations may choose to
3691   // fold it back in when profitable.
3692   if (Offset != 0)
3693     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3694                        DAG.getConstant(Offset, DL, XLenVT));
3695   return Addr;
3696 }
3697 
3698 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3699   SDValue CondV = Op.getOperand(0);
3700   SDValue TrueV = Op.getOperand(1);
3701   SDValue FalseV = Op.getOperand(2);
3702   SDLoc DL(Op);
3703   MVT VT = Op.getSimpleValueType();
3704   MVT XLenVT = Subtarget.getXLenVT();
3705 
3706   // Lower vector SELECTs to VSELECTs by splatting the condition.
3707   if (VT.isVector()) {
3708     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3709     SDValue CondSplat = VT.isScalableVector()
3710                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3711                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3712     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3713   }
3714 
3715   // If the result type is XLenVT and CondV is the output of a SETCC node
3716   // which also operated on XLenVT inputs, then merge the SETCC node into the
3717   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3718   // compare+branch instructions. i.e.:
3719   // (select (setcc lhs, rhs, cc), truev, falsev)
3720   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3721   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3722       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3723     SDValue LHS = CondV.getOperand(0);
3724     SDValue RHS = CondV.getOperand(1);
3725     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3726     ISD::CondCode CCVal = CC->get();
3727 
3728     // Special case for a select of 2 constants that have a diffence of 1.
3729     // Normally this is done by DAGCombine, but if the select is introduced by
3730     // type legalization or op legalization, we miss it. Restricting to SETLT
3731     // case for now because that is what signed saturating add/sub need.
3732     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3733     // but we would probably want to swap the true/false values if the condition
3734     // is SETGE/SETLE to avoid an XORI.
3735     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3736         CCVal == ISD::SETLT) {
3737       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3738       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3739       if (TrueVal - 1 == FalseVal)
3740         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3741       if (TrueVal + 1 == FalseVal)
3742         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3743     }
3744 
3745     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3746 
3747     SDValue TargetCC = DAG.getCondCode(CCVal);
3748     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3749     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3750   }
3751 
3752   // Otherwise:
3753   // (select condv, truev, falsev)
3754   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3755   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3756   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3757 
3758   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3759 
3760   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3761 }
3762 
3763 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3764   SDValue CondV = Op.getOperand(1);
3765   SDLoc DL(Op);
3766   MVT XLenVT = Subtarget.getXLenVT();
3767 
3768   if (CondV.getOpcode() == ISD::SETCC &&
3769       CondV.getOperand(0).getValueType() == XLenVT) {
3770     SDValue LHS = CondV.getOperand(0);
3771     SDValue RHS = CondV.getOperand(1);
3772     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3773 
3774     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3775 
3776     SDValue TargetCC = DAG.getCondCode(CCVal);
3777     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3778                        LHS, RHS, TargetCC, Op.getOperand(2));
3779   }
3780 
3781   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3782                      CondV, DAG.getConstant(0, DL, XLenVT),
3783                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3784 }
3785 
3786 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3787   MachineFunction &MF = DAG.getMachineFunction();
3788   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3789 
3790   SDLoc DL(Op);
3791   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3792                                  getPointerTy(MF.getDataLayout()));
3793 
3794   // vastart just stores the address of the VarArgsFrameIndex slot into the
3795   // memory location argument.
3796   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3797   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3798                       MachinePointerInfo(SV));
3799 }
3800 
3801 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3802                                             SelectionDAG &DAG) const {
3803   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3804   MachineFunction &MF = DAG.getMachineFunction();
3805   MachineFrameInfo &MFI = MF.getFrameInfo();
3806   MFI.setFrameAddressIsTaken(true);
3807   Register FrameReg = RI.getFrameRegister(MF);
3808   int XLenInBytes = Subtarget.getXLen() / 8;
3809 
3810   EVT VT = Op.getValueType();
3811   SDLoc DL(Op);
3812   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3813   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3814   while (Depth--) {
3815     int Offset = -(XLenInBytes * 2);
3816     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3817                               DAG.getIntPtrConstant(Offset, DL));
3818     FrameAddr =
3819         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3820   }
3821   return FrameAddr;
3822 }
3823 
3824 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3825                                              SelectionDAG &DAG) const {
3826   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3827   MachineFunction &MF = DAG.getMachineFunction();
3828   MachineFrameInfo &MFI = MF.getFrameInfo();
3829   MFI.setReturnAddressIsTaken(true);
3830   MVT XLenVT = Subtarget.getXLenVT();
3831   int XLenInBytes = Subtarget.getXLen() / 8;
3832 
3833   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3834     return SDValue();
3835 
3836   EVT VT = Op.getValueType();
3837   SDLoc DL(Op);
3838   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3839   if (Depth) {
3840     int Off = -XLenInBytes;
3841     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3842     SDValue Offset = DAG.getConstant(Off, DL, VT);
3843     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3844                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3845                        MachinePointerInfo());
3846   }
3847 
3848   // Return the value of the return address register, marking it an implicit
3849   // live-in.
3850   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3851   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3852 }
3853 
3854 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3855                                                  SelectionDAG &DAG) const {
3856   SDLoc DL(Op);
3857   SDValue Lo = Op.getOperand(0);
3858   SDValue Hi = Op.getOperand(1);
3859   SDValue Shamt = Op.getOperand(2);
3860   EVT VT = Lo.getValueType();
3861 
3862   // if Shamt-XLEN < 0: // Shamt < XLEN
3863   //   Lo = Lo << Shamt
3864   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3865   // else:
3866   //   Lo = 0
3867   //   Hi = Lo << (Shamt-XLEN)
3868 
3869   SDValue Zero = DAG.getConstant(0, DL, VT);
3870   SDValue One = DAG.getConstant(1, DL, VT);
3871   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3872   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3873   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3874   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3875 
3876   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3877   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3878   SDValue ShiftRightLo =
3879       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3880   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3881   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3882   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3883 
3884   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3885 
3886   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3887   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3888 
3889   SDValue Parts[2] = {Lo, Hi};
3890   return DAG.getMergeValues(Parts, DL);
3891 }
3892 
3893 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3894                                                   bool IsSRA) const {
3895   SDLoc DL(Op);
3896   SDValue Lo = Op.getOperand(0);
3897   SDValue Hi = Op.getOperand(1);
3898   SDValue Shamt = Op.getOperand(2);
3899   EVT VT = Lo.getValueType();
3900 
3901   // SRA expansion:
3902   //   if Shamt-XLEN < 0: // Shamt < XLEN
3903   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3904   //     Hi = Hi >>s Shamt
3905   //   else:
3906   //     Lo = Hi >>s (Shamt-XLEN);
3907   //     Hi = Hi >>s (XLEN-1)
3908   //
3909   // SRL expansion:
3910   //   if Shamt-XLEN < 0: // Shamt < XLEN
3911   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3912   //     Hi = Hi >>u Shamt
3913   //   else:
3914   //     Lo = Hi >>u (Shamt-XLEN);
3915   //     Hi = 0;
3916 
3917   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3918 
3919   SDValue Zero = DAG.getConstant(0, DL, VT);
3920   SDValue One = DAG.getConstant(1, DL, VT);
3921   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3922   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3923   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3924   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3925 
3926   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3927   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3928   SDValue ShiftLeftHi =
3929       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3930   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3931   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3932   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3933   SDValue HiFalse =
3934       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3935 
3936   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3937 
3938   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3939   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3940 
3941   SDValue Parts[2] = {Lo, Hi};
3942   return DAG.getMergeValues(Parts, DL);
3943 }
3944 
3945 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3946 // legal equivalently-sized i8 type, so we can use that as a go-between.
3947 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3948                                                   SelectionDAG &DAG) const {
3949   SDLoc DL(Op);
3950   MVT VT = Op.getSimpleValueType();
3951   SDValue SplatVal = Op.getOperand(0);
3952   // All-zeros or all-ones splats are handled specially.
3953   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3954     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3955     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3956   }
3957   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3958     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3959     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3960   }
3961   MVT XLenVT = Subtarget.getXLenVT();
3962   assert(SplatVal.getValueType() == XLenVT &&
3963          "Unexpected type for i1 splat value");
3964   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3965   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3966                          DAG.getConstant(1, DL, XLenVT));
3967   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3968   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3969   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3970 }
3971 
3972 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3973 // illegal (currently only vXi64 RV32).
3974 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3975 // them to SPLAT_VECTOR_I64
3976 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3977                                                      SelectionDAG &DAG) const {
3978   SDLoc DL(Op);
3979   MVT VecVT = Op.getSimpleValueType();
3980   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3981          "Unexpected SPLAT_VECTOR_PARTS lowering");
3982 
3983   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3984   SDValue Lo = Op.getOperand(0);
3985   SDValue Hi = Op.getOperand(1);
3986 
3987   if (VecVT.isFixedLengthVector()) {
3988     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3989     SDLoc DL(Op);
3990     SDValue Mask, VL;
3991     std::tie(Mask, VL) =
3992         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3993 
3994     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3995     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3996   }
3997 
3998   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3999     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4000     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4001     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4002     // node in order to try and match RVV vector/scalar instructions.
4003     if ((LoC >> 31) == HiC)
4004       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4005   }
4006 
4007   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4008   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4009       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4010       Hi.getConstantOperandVal(1) == 31)
4011     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4012 
4013   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4014   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4015                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4016 }
4017 
4018 // Custom-lower extensions from mask vectors by using a vselect either with 1
4019 // for zero/any-extension or -1 for sign-extension:
4020 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4021 // Note that any-extension is lowered identically to zero-extension.
4022 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4023                                                 int64_t ExtTrueVal) const {
4024   SDLoc DL(Op);
4025   MVT VecVT = Op.getSimpleValueType();
4026   SDValue Src = Op.getOperand(0);
4027   // Only custom-lower extensions from mask types
4028   assert(Src.getValueType().isVector() &&
4029          Src.getValueType().getVectorElementType() == MVT::i1);
4030 
4031   MVT XLenVT = Subtarget.getXLenVT();
4032   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4033   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4034 
4035   if (VecVT.isScalableVector()) {
4036     // Be careful not to introduce illegal scalar types at this stage, and be
4037     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4038     // illegal and must be expanded. Since we know that the constants are
4039     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4040     bool IsRV32E64 =
4041         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4042 
4043     if (!IsRV32E64) {
4044       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4045       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4046     } else {
4047       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4048       SplatTrueVal =
4049           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4050     }
4051 
4052     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4053   }
4054 
4055   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4056   MVT I1ContainerVT =
4057       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4058 
4059   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4060 
4061   SDValue Mask, VL;
4062   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4063 
4064   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4065   SplatTrueVal =
4066       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4067   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4068                                SplatTrueVal, SplatZero, VL);
4069 
4070   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4071 }
4072 
4073 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4074     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4075   MVT ExtVT = Op.getSimpleValueType();
4076   // Only custom-lower extensions from fixed-length vector types.
4077   if (!ExtVT.isFixedLengthVector())
4078     return Op;
4079   MVT VT = Op.getOperand(0).getSimpleValueType();
4080   // Grab the canonical container type for the extended type. Infer the smaller
4081   // type from that to ensure the same number of vector elements, as we know
4082   // the LMUL will be sufficient to hold the smaller type.
4083   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4084   // Get the extended container type manually to ensure the same number of
4085   // vector elements between source and dest.
4086   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4087                                      ContainerExtVT.getVectorElementCount());
4088 
4089   SDValue Op1 =
4090       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4091 
4092   SDLoc DL(Op);
4093   SDValue Mask, VL;
4094   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4095 
4096   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4097 
4098   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4099 }
4100 
4101 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4102 // setcc operation:
4103 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4104 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4105                                                   SelectionDAG &DAG) const {
4106   SDLoc DL(Op);
4107   EVT MaskVT = Op.getValueType();
4108   // Only expect to custom-lower truncations to mask types
4109   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4110          "Unexpected type for vector mask lowering");
4111   SDValue Src = Op.getOperand(0);
4112   MVT VecVT = Src.getSimpleValueType();
4113 
4114   // If this is a fixed vector, we need to convert it to a scalable vector.
4115   MVT ContainerVT = VecVT;
4116   if (VecVT.isFixedLengthVector()) {
4117     ContainerVT = getContainerForFixedLengthVector(VecVT);
4118     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4119   }
4120 
4121   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4122   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4123 
4124   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4125   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4126 
4127   if (VecVT.isScalableVector()) {
4128     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4129     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4130   }
4131 
4132   SDValue Mask, VL;
4133   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4134 
4135   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4136   SDValue Trunc =
4137       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4138   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4139                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4140   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4141 }
4142 
4143 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4144 // first position of a vector, and that vector is slid up to the insert index.
4145 // By limiting the active vector length to index+1 and merging with the
4146 // original vector (with an undisturbed tail policy for elements >= VL), we
4147 // achieve the desired result of leaving all elements untouched except the one
4148 // at VL-1, which is replaced with the desired value.
4149 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4150                                                     SelectionDAG &DAG) const {
4151   SDLoc DL(Op);
4152   MVT VecVT = Op.getSimpleValueType();
4153   SDValue Vec = Op.getOperand(0);
4154   SDValue Val = Op.getOperand(1);
4155   SDValue Idx = Op.getOperand(2);
4156 
4157   if (VecVT.getVectorElementType() == MVT::i1) {
4158     // FIXME: For now we just promote to an i8 vector and insert into that,
4159     // but this is probably not optimal.
4160     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4161     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4162     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4163     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4164   }
4165 
4166   MVT ContainerVT = VecVT;
4167   // If the operand is a fixed-length vector, convert to a scalable one.
4168   if (VecVT.isFixedLengthVector()) {
4169     ContainerVT = getContainerForFixedLengthVector(VecVT);
4170     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4171   }
4172 
4173   MVT XLenVT = Subtarget.getXLenVT();
4174 
4175   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4176   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4177   // Even i64-element vectors on RV32 can be lowered without scalar
4178   // legalization if the most-significant 32 bits of the value are not affected
4179   // by the sign-extension of the lower 32 bits.
4180   // TODO: We could also catch sign extensions of a 32-bit value.
4181   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4182     const auto *CVal = cast<ConstantSDNode>(Val);
4183     if (isInt<32>(CVal->getSExtValue())) {
4184       IsLegalInsert = true;
4185       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4186     }
4187   }
4188 
4189   SDValue Mask, VL;
4190   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4191 
4192   SDValue ValInVec;
4193 
4194   if (IsLegalInsert) {
4195     unsigned Opc =
4196         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4197     if (isNullConstant(Idx)) {
4198       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4199       if (!VecVT.isFixedLengthVector())
4200         return Vec;
4201       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4202     }
4203     ValInVec =
4204         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4205   } else {
4206     // On RV32, i64-element vectors must be specially handled to place the
4207     // value at element 0, by using two vslide1up instructions in sequence on
4208     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4209     // this.
4210     SDValue One = DAG.getConstant(1, DL, XLenVT);
4211     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4212     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4213     MVT I32ContainerVT =
4214         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4215     SDValue I32Mask =
4216         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4217     // Limit the active VL to two.
4218     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4219     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4220     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4221     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4222                            InsertI64VL);
4223     // First slide in the hi value, then the lo in underneath it.
4224     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4225                            ValHi, I32Mask, InsertI64VL);
4226     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4227                            ValLo, I32Mask, InsertI64VL);
4228     // Bitcast back to the right container type.
4229     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4230   }
4231 
4232   // Now that the value is in a vector, slide it into position.
4233   SDValue InsertVL =
4234       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4235   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4236                                 ValInVec, Idx, Mask, InsertVL);
4237   if (!VecVT.isFixedLengthVector())
4238     return Slideup;
4239   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4240 }
4241 
4242 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4243 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4244 // types this is done using VMV_X_S to allow us to glean information about the
4245 // sign bits of the result.
4246 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4247                                                      SelectionDAG &DAG) const {
4248   SDLoc DL(Op);
4249   SDValue Idx = Op.getOperand(1);
4250   SDValue Vec = Op.getOperand(0);
4251   EVT EltVT = Op.getValueType();
4252   MVT VecVT = Vec.getSimpleValueType();
4253   MVT XLenVT = Subtarget.getXLenVT();
4254 
4255   if (VecVT.getVectorElementType() == MVT::i1) {
4256     // FIXME: For now we just promote to an i8 vector and extract from that,
4257     // but this is probably not optimal.
4258     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4259     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4260     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4261   }
4262 
4263   // If this is a fixed vector, we need to convert it to a scalable vector.
4264   MVT ContainerVT = VecVT;
4265   if (VecVT.isFixedLengthVector()) {
4266     ContainerVT = getContainerForFixedLengthVector(VecVT);
4267     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4268   }
4269 
4270   // If the index is 0, the vector is already in the right position.
4271   if (!isNullConstant(Idx)) {
4272     // Use a VL of 1 to avoid processing more elements than we need.
4273     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4274     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4275     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4276     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4277                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4278   }
4279 
4280   if (!EltVT.isInteger()) {
4281     // Floating-point extracts are handled in TableGen.
4282     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4283                        DAG.getConstant(0, DL, XLenVT));
4284   }
4285 
4286   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4287   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4288 }
4289 
4290 // Some RVV intrinsics may claim that they want an integer operand to be
4291 // promoted or expanded.
4292 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4293                                           const RISCVSubtarget &Subtarget) {
4294   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4295           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4296          "Unexpected opcode");
4297 
4298   if (!Subtarget.hasVInstructions())
4299     return SDValue();
4300 
4301   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4302   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4303   SDLoc DL(Op);
4304 
4305   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4306       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4307   if (!II || !II->hasSplatOperand())
4308     return SDValue();
4309 
4310   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4311   assert(SplatOp < Op.getNumOperands());
4312 
4313   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4314   SDValue &ScalarOp = Operands[SplatOp];
4315   MVT OpVT = ScalarOp.getSimpleValueType();
4316   MVT XLenVT = Subtarget.getXLenVT();
4317 
4318   // If this isn't a scalar, or its type is XLenVT we're done.
4319   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4320     return SDValue();
4321 
4322   // Simplest case is that the operand needs to be promoted to XLenVT.
4323   if (OpVT.bitsLT(XLenVT)) {
4324     // If the operand is a constant, sign extend to increase our chances
4325     // of being able to use a .vi instruction. ANY_EXTEND would become a
4326     // a zero extend and the simm5 check in isel would fail.
4327     // FIXME: Should we ignore the upper bits in isel instead?
4328     unsigned ExtOpc =
4329         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4330     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4331     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4332   }
4333 
4334   // Use the previous operand to get the vXi64 VT. The result might be a mask
4335   // VT for compares. Using the previous operand assumes that the previous
4336   // operand will never have a smaller element size than a scalar operand and
4337   // that a widening operation never uses SEW=64.
4338   // NOTE: If this fails the below assert, we can probably just find the
4339   // element count from any operand or result and use it to construct the VT.
4340   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4341   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4342 
4343   // The more complex case is when the scalar is larger than XLenVT.
4344   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4345          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4346 
4347   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4348   // on the instruction to sign-extend since SEW>XLEN.
4349   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4350     if (isInt<32>(CVal->getSExtValue())) {
4351       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4352       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4353     }
4354   }
4355 
4356   // We need to convert the scalar to a splat vector.
4357   // FIXME: Can we implicitly truncate the scalar if it is known to
4358   // be sign extended?
4359   SDValue VL = Op.getOperand(II->VLOperand + 1 + HasChain);
4360   assert(VL.getValueType() == XLenVT);
4361   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4362   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4363 }
4364 
4365 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4366                                                      SelectionDAG &DAG) const {
4367   unsigned IntNo = Op.getConstantOperandVal(0);
4368   SDLoc DL(Op);
4369   MVT XLenVT = Subtarget.getXLenVT();
4370 
4371   switch (IntNo) {
4372   default:
4373     break; // Don't custom lower most intrinsics.
4374   case Intrinsic::thread_pointer: {
4375     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4376     return DAG.getRegister(RISCV::X4, PtrVT);
4377   }
4378   case Intrinsic::riscv_orc_b:
4379     // Lower to the GORCI encoding for orc.b.
4380     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4381                        DAG.getConstant(7, DL, XLenVT));
4382   case Intrinsic::riscv_grev:
4383   case Intrinsic::riscv_gorc: {
4384     unsigned Opc =
4385         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4386     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4387   }
4388   case Intrinsic::riscv_shfl:
4389   case Intrinsic::riscv_unshfl: {
4390     unsigned Opc =
4391         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4392     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4393   }
4394   case Intrinsic::riscv_bcompress:
4395   case Intrinsic::riscv_bdecompress: {
4396     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4397                                                        : RISCVISD::BDECOMPRESS;
4398     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4399   }
4400   case Intrinsic::riscv_bfp:
4401     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4402                        Op.getOperand(2));
4403   case Intrinsic::riscv_fsl:
4404     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4405                        Op.getOperand(2), Op.getOperand(3));
4406   case Intrinsic::riscv_fsr:
4407     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4408                        Op.getOperand(2), Op.getOperand(3));
4409   case Intrinsic::riscv_vmv_x_s:
4410     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4411     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4412                        Op.getOperand(1));
4413   case Intrinsic::riscv_vmv_v_x:
4414     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4415                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4416   case Intrinsic::riscv_vfmv_v_f:
4417     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4418                        Op.getOperand(1), Op.getOperand(2));
4419   case Intrinsic::riscv_vmv_s_x: {
4420     SDValue Scalar = Op.getOperand(2);
4421 
4422     if (Scalar.getValueType().bitsLE(XLenVT)) {
4423       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4424       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4425                          Op.getOperand(1), Scalar, Op.getOperand(3));
4426     }
4427 
4428     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4429 
4430     // This is an i64 value that lives in two scalar registers. We have to
4431     // insert this in a convoluted way. First we build vXi64 splat containing
4432     // the/ two values that we assemble using some bit math. Next we'll use
4433     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4434     // to merge element 0 from our splat into the source vector.
4435     // FIXME: This is probably not the best way to do this, but it is
4436     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4437     // point.
4438     //   sw lo, (a0)
4439     //   sw hi, 4(a0)
4440     //   vlse vX, (a0)
4441     //
4442     //   vid.v      vVid
4443     //   vmseq.vx   mMask, vVid, 0
4444     //   vmerge.vvm vDest, vSrc, vVal, mMask
4445     MVT VT = Op.getSimpleValueType();
4446     SDValue Vec = Op.getOperand(1);
4447     SDValue VL = Op.getOperand(3);
4448 
4449     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4450     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4451                                       DAG.getConstant(0, DL, MVT::i32), VL);
4452 
4453     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4454     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4455     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4456     SDValue SelectCond =
4457         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4458                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4459     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4460                        Vec, VL);
4461   }
4462   case Intrinsic::riscv_vslide1up:
4463   case Intrinsic::riscv_vslide1down:
4464   case Intrinsic::riscv_vslide1up_mask:
4465   case Intrinsic::riscv_vslide1down_mask: {
4466     // We need to special case these when the scalar is larger than XLen.
4467     unsigned NumOps = Op.getNumOperands();
4468     bool IsMasked = NumOps == 7;
4469     unsigned OpOffset = IsMasked ? 1 : 0;
4470     SDValue Scalar = Op.getOperand(2 + OpOffset);
4471     if (Scalar.getValueType().bitsLE(XLenVT))
4472       break;
4473 
4474     // Splatting a sign extended constant is fine.
4475     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4476       if (isInt<32>(CVal->getSExtValue()))
4477         break;
4478 
4479     MVT VT = Op.getSimpleValueType();
4480     assert(VT.getVectorElementType() == MVT::i64 &&
4481            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4482 
4483     // Convert the vector source to the equivalent nxvXi32 vector.
4484     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4485     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4486 
4487     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4488                                    DAG.getConstant(0, DL, XLenVT));
4489     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4490                                    DAG.getConstant(1, DL, XLenVT));
4491 
4492     // Double the VL since we halved SEW.
4493     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4494     SDValue I32VL =
4495         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4496 
4497     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4498     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4499 
4500     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4501     // instructions.
4502     if (IntNo == Intrinsic::riscv_vslide1up ||
4503         IntNo == Intrinsic::riscv_vslide1up_mask) {
4504       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4505                         I32Mask, I32VL);
4506       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4507                         I32Mask, I32VL);
4508     } else {
4509       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4510                         I32Mask, I32VL);
4511       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4512                         I32Mask, I32VL);
4513     }
4514 
4515     // Convert back to nxvXi64.
4516     Vec = DAG.getBitcast(VT, Vec);
4517 
4518     if (!IsMasked)
4519       return Vec;
4520 
4521     // Apply mask after the operation.
4522     SDValue Mask = Op.getOperand(NumOps - 3);
4523     SDValue MaskedOff = Op.getOperand(1);
4524     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4525   }
4526   }
4527 
4528   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4529 }
4530 
4531 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4532                                                     SelectionDAG &DAG) const {
4533   unsigned IntNo = Op.getConstantOperandVal(1);
4534   switch (IntNo) {
4535   default:
4536     break;
4537   case Intrinsic::riscv_masked_strided_load: {
4538     SDLoc DL(Op);
4539     MVT XLenVT = Subtarget.getXLenVT();
4540 
4541     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4542     // the selection of the masked intrinsics doesn't do this for us.
4543     SDValue Mask = Op.getOperand(5);
4544     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4545 
4546     MVT VT = Op->getSimpleValueType(0);
4547     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4548 
4549     SDValue PassThru = Op.getOperand(2);
4550     if (!IsUnmasked) {
4551       MVT MaskVT =
4552           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4553       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4554       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4555     }
4556 
4557     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4558 
4559     SDValue IntID = DAG.getTargetConstant(
4560         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4561         XLenVT);
4562 
4563     auto *Load = cast<MemIntrinsicSDNode>(Op);
4564     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4565     if (!IsUnmasked)
4566       Ops.push_back(PassThru);
4567     Ops.push_back(Op.getOperand(3)); // Ptr
4568     Ops.push_back(Op.getOperand(4)); // Stride
4569     if (!IsUnmasked)
4570       Ops.push_back(Mask);
4571     Ops.push_back(VL);
4572     if (!IsUnmasked) {
4573       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4574       Ops.push_back(Policy);
4575     }
4576 
4577     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4578     SDValue Result =
4579         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4580                                 Load->getMemoryVT(), Load->getMemOperand());
4581     SDValue Chain = Result.getValue(1);
4582     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4583     return DAG.getMergeValues({Result, Chain}, DL);
4584   }
4585   }
4586 
4587   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4588 }
4589 
4590 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4591                                                  SelectionDAG &DAG) const {
4592   unsigned IntNo = Op.getConstantOperandVal(1);
4593   switch (IntNo) {
4594   default:
4595     break;
4596   case Intrinsic::riscv_masked_strided_store: {
4597     SDLoc DL(Op);
4598     MVT XLenVT = Subtarget.getXLenVT();
4599 
4600     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4601     // the selection of the masked intrinsics doesn't do this for us.
4602     SDValue Mask = Op.getOperand(5);
4603     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4604 
4605     SDValue Val = Op.getOperand(2);
4606     MVT VT = Val.getSimpleValueType();
4607     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4608 
4609     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4610     if (!IsUnmasked) {
4611       MVT MaskVT =
4612           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4613       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4614     }
4615 
4616     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4617 
4618     SDValue IntID = DAG.getTargetConstant(
4619         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4620         XLenVT);
4621 
4622     auto *Store = cast<MemIntrinsicSDNode>(Op);
4623     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4624     Ops.push_back(Val);
4625     Ops.push_back(Op.getOperand(3)); // Ptr
4626     Ops.push_back(Op.getOperand(4)); // Stride
4627     if (!IsUnmasked)
4628       Ops.push_back(Mask);
4629     Ops.push_back(VL);
4630 
4631     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4632                                    Ops, Store->getMemoryVT(),
4633                                    Store->getMemOperand());
4634   }
4635   }
4636 
4637   return SDValue();
4638 }
4639 
4640 static MVT getLMUL1VT(MVT VT) {
4641   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4642          "Unexpected vector MVT");
4643   return MVT::getScalableVectorVT(
4644       VT.getVectorElementType(),
4645       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4646 }
4647 
4648 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4649   switch (ISDOpcode) {
4650   default:
4651     llvm_unreachable("Unhandled reduction");
4652   case ISD::VECREDUCE_ADD:
4653     return RISCVISD::VECREDUCE_ADD_VL;
4654   case ISD::VECREDUCE_UMAX:
4655     return RISCVISD::VECREDUCE_UMAX_VL;
4656   case ISD::VECREDUCE_SMAX:
4657     return RISCVISD::VECREDUCE_SMAX_VL;
4658   case ISD::VECREDUCE_UMIN:
4659     return RISCVISD::VECREDUCE_UMIN_VL;
4660   case ISD::VECREDUCE_SMIN:
4661     return RISCVISD::VECREDUCE_SMIN_VL;
4662   case ISD::VECREDUCE_AND:
4663     return RISCVISD::VECREDUCE_AND_VL;
4664   case ISD::VECREDUCE_OR:
4665     return RISCVISD::VECREDUCE_OR_VL;
4666   case ISD::VECREDUCE_XOR:
4667     return RISCVISD::VECREDUCE_XOR_VL;
4668   }
4669 }
4670 
4671 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4672                                                          SelectionDAG &DAG,
4673                                                          bool IsVP) const {
4674   SDLoc DL(Op);
4675   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4676   MVT VecVT = Vec.getSimpleValueType();
4677   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4678           Op.getOpcode() == ISD::VECREDUCE_OR ||
4679           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4680           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4681           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4682           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4683          "Unexpected reduction lowering");
4684 
4685   MVT XLenVT = Subtarget.getXLenVT();
4686   assert(Op.getValueType() == XLenVT &&
4687          "Expected reduction output to be legalized to XLenVT");
4688 
4689   MVT ContainerVT = VecVT;
4690   if (VecVT.isFixedLengthVector()) {
4691     ContainerVT = getContainerForFixedLengthVector(VecVT);
4692     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4693   }
4694 
4695   SDValue Mask, VL;
4696   if (IsVP) {
4697     Mask = Op.getOperand(2);
4698     VL = Op.getOperand(3);
4699   } else {
4700     std::tie(Mask, VL) =
4701         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4702   }
4703 
4704   unsigned BaseOpc;
4705   ISD::CondCode CC;
4706   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4707 
4708   switch (Op.getOpcode()) {
4709   default:
4710     llvm_unreachable("Unhandled reduction");
4711   case ISD::VECREDUCE_AND:
4712   case ISD::VP_REDUCE_AND: {
4713     // vcpop ~x == 0
4714     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4715     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4716     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4717     CC = ISD::SETEQ;
4718     BaseOpc = ISD::AND;
4719     break;
4720   }
4721   case ISD::VECREDUCE_OR:
4722   case ISD::VP_REDUCE_OR:
4723     // vcpop x != 0
4724     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4725     CC = ISD::SETNE;
4726     BaseOpc = ISD::OR;
4727     break;
4728   case ISD::VECREDUCE_XOR:
4729   case ISD::VP_REDUCE_XOR: {
4730     // ((vcpop x) & 1) != 0
4731     SDValue One = DAG.getConstant(1, DL, XLenVT);
4732     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4733     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4734     CC = ISD::SETNE;
4735     BaseOpc = ISD::XOR;
4736     break;
4737   }
4738   }
4739 
4740   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4741 
4742   if (!IsVP)
4743     return SetCC;
4744 
4745   // Now include the start value in the operation.
4746   // Note that we must return the start value when no elements are operated
4747   // upon. The vcpop instructions we've emitted in each case above will return
4748   // 0 for an inactive vector, and so we've already received the neutral value:
4749   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4750   // can simply include the start value.
4751   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4752 }
4753 
4754 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4755                                             SelectionDAG &DAG) const {
4756   SDLoc DL(Op);
4757   SDValue Vec = Op.getOperand(0);
4758   EVT VecEVT = Vec.getValueType();
4759 
4760   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4761 
4762   // Due to ordering in legalize types we may have a vector type that needs to
4763   // be split. Do that manually so we can get down to a legal type.
4764   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4765          TargetLowering::TypeSplitVector) {
4766     SDValue Lo, Hi;
4767     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4768     VecEVT = Lo.getValueType();
4769     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4770   }
4771 
4772   // TODO: The type may need to be widened rather than split. Or widened before
4773   // it can be split.
4774   if (!isTypeLegal(VecEVT))
4775     return SDValue();
4776 
4777   MVT VecVT = VecEVT.getSimpleVT();
4778   MVT VecEltVT = VecVT.getVectorElementType();
4779   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4780 
4781   MVT ContainerVT = VecVT;
4782   if (VecVT.isFixedLengthVector()) {
4783     ContainerVT = getContainerForFixedLengthVector(VecVT);
4784     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4785   }
4786 
4787   MVT M1VT = getLMUL1VT(ContainerVT);
4788   MVT XLenVT = Subtarget.getXLenVT();
4789 
4790   SDValue Mask, VL;
4791   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4792 
4793   SDValue NeutralElem =
4794       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4795   SDValue IdentitySplat = lowerScalarSplat(
4796       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4797   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4798                                   IdentitySplat, Mask, VL);
4799   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4800                              DAG.getConstant(0, DL, XLenVT));
4801   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4802 }
4803 
4804 // Given a reduction op, this function returns the matching reduction opcode,
4805 // the vector SDValue and the scalar SDValue required to lower this to a
4806 // RISCVISD node.
4807 static std::tuple<unsigned, SDValue, SDValue>
4808 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4809   SDLoc DL(Op);
4810   auto Flags = Op->getFlags();
4811   unsigned Opcode = Op.getOpcode();
4812   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4813   switch (Opcode) {
4814   default:
4815     llvm_unreachable("Unhandled reduction");
4816   case ISD::VECREDUCE_FADD: {
4817     // Use positive zero if we can. It is cheaper to materialize.
4818     SDValue Zero =
4819         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4820     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4821   }
4822   case ISD::VECREDUCE_SEQ_FADD:
4823     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4824                            Op.getOperand(0));
4825   case ISD::VECREDUCE_FMIN:
4826     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4827                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4828   case ISD::VECREDUCE_FMAX:
4829     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4830                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4831   }
4832 }
4833 
4834 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4835                                               SelectionDAG &DAG) const {
4836   SDLoc DL(Op);
4837   MVT VecEltVT = Op.getSimpleValueType();
4838 
4839   unsigned RVVOpcode;
4840   SDValue VectorVal, ScalarVal;
4841   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4842       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4843   MVT VecVT = VectorVal.getSimpleValueType();
4844 
4845   MVT ContainerVT = VecVT;
4846   if (VecVT.isFixedLengthVector()) {
4847     ContainerVT = getContainerForFixedLengthVector(VecVT);
4848     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4849   }
4850 
4851   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4852   MVT XLenVT = Subtarget.getXLenVT();
4853 
4854   SDValue Mask, VL;
4855   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4856 
4857   SDValue ScalarSplat = lowerScalarSplat(
4858       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4859   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4860                                   VectorVal, ScalarSplat, Mask, VL);
4861   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4862                      DAG.getConstant(0, DL, XLenVT));
4863 }
4864 
4865 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4866   switch (ISDOpcode) {
4867   default:
4868     llvm_unreachable("Unhandled reduction");
4869   case ISD::VP_REDUCE_ADD:
4870     return RISCVISD::VECREDUCE_ADD_VL;
4871   case ISD::VP_REDUCE_UMAX:
4872     return RISCVISD::VECREDUCE_UMAX_VL;
4873   case ISD::VP_REDUCE_SMAX:
4874     return RISCVISD::VECREDUCE_SMAX_VL;
4875   case ISD::VP_REDUCE_UMIN:
4876     return RISCVISD::VECREDUCE_UMIN_VL;
4877   case ISD::VP_REDUCE_SMIN:
4878     return RISCVISD::VECREDUCE_SMIN_VL;
4879   case ISD::VP_REDUCE_AND:
4880     return RISCVISD::VECREDUCE_AND_VL;
4881   case ISD::VP_REDUCE_OR:
4882     return RISCVISD::VECREDUCE_OR_VL;
4883   case ISD::VP_REDUCE_XOR:
4884     return RISCVISD::VECREDUCE_XOR_VL;
4885   case ISD::VP_REDUCE_FADD:
4886     return RISCVISD::VECREDUCE_FADD_VL;
4887   case ISD::VP_REDUCE_SEQ_FADD:
4888     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4889   case ISD::VP_REDUCE_FMAX:
4890     return RISCVISD::VECREDUCE_FMAX_VL;
4891   case ISD::VP_REDUCE_FMIN:
4892     return RISCVISD::VECREDUCE_FMIN_VL;
4893   }
4894 }
4895 
4896 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4897                                            SelectionDAG &DAG) const {
4898   SDLoc DL(Op);
4899   SDValue Vec = Op.getOperand(1);
4900   EVT VecEVT = Vec.getValueType();
4901 
4902   // TODO: The type may need to be widened rather than split. Or widened before
4903   // it can be split.
4904   if (!isTypeLegal(VecEVT))
4905     return SDValue();
4906 
4907   MVT VecVT = VecEVT.getSimpleVT();
4908   MVT VecEltVT = VecVT.getVectorElementType();
4909   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4910 
4911   MVT ContainerVT = VecVT;
4912   if (VecVT.isFixedLengthVector()) {
4913     ContainerVT = getContainerForFixedLengthVector(VecVT);
4914     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4915   }
4916 
4917   SDValue VL = Op.getOperand(3);
4918   SDValue Mask = Op.getOperand(2);
4919 
4920   MVT M1VT = getLMUL1VT(ContainerVT);
4921   MVT XLenVT = Subtarget.getXLenVT();
4922   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4923 
4924   SDValue StartSplat =
4925       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4926                        DL, DAG, Subtarget);
4927   SDValue Reduction =
4928       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4929   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4930                              DAG.getConstant(0, DL, XLenVT));
4931   if (!VecVT.isInteger())
4932     return Elt0;
4933   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4934 }
4935 
4936 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4937                                                    SelectionDAG &DAG) const {
4938   SDValue Vec = Op.getOperand(0);
4939   SDValue SubVec = Op.getOperand(1);
4940   MVT VecVT = Vec.getSimpleValueType();
4941   MVT SubVecVT = SubVec.getSimpleValueType();
4942 
4943   SDLoc DL(Op);
4944   MVT XLenVT = Subtarget.getXLenVT();
4945   unsigned OrigIdx = Op.getConstantOperandVal(2);
4946   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4947 
4948   // We don't have the ability to slide mask vectors up indexed by their i1
4949   // elements; the smallest we can do is i8. Often we are able to bitcast to
4950   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4951   // into a scalable one, we might not necessarily have enough scalable
4952   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4953   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4954       (OrigIdx != 0 || !Vec.isUndef())) {
4955     if (VecVT.getVectorMinNumElements() >= 8 &&
4956         SubVecVT.getVectorMinNumElements() >= 8) {
4957       assert(OrigIdx % 8 == 0 && "Invalid index");
4958       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4959              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4960              "Unexpected mask vector lowering");
4961       OrigIdx /= 8;
4962       SubVecVT =
4963           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4964                            SubVecVT.isScalableVector());
4965       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4966                                VecVT.isScalableVector());
4967       Vec = DAG.getBitcast(VecVT, Vec);
4968       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4969     } else {
4970       // We can't slide this mask vector up indexed by its i1 elements.
4971       // This poses a problem when we wish to insert a scalable vector which
4972       // can't be re-expressed as a larger type. Just choose the slow path and
4973       // extend to a larger type, then truncate back down.
4974       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4975       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4976       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4977       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4978       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4979                         Op.getOperand(2));
4980       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4981       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4982     }
4983   }
4984 
4985   // If the subvector vector is a fixed-length type, we cannot use subregister
4986   // manipulation to simplify the codegen; we don't know which register of a
4987   // LMUL group contains the specific subvector as we only know the minimum
4988   // register size. Therefore we must slide the vector group up the full
4989   // amount.
4990   if (SubVecVT.isFixedLengthVector()) {
4991     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
4992       return Op;
4993     MVT ContainerVT = VecVT;
4994     if (VecVT.isFixedLengthVector()) {
4995       ContainerVT = getContainerForFixedLengthVector(VecVT);
4996       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4997     }
4998     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4999                          DAG.getUNDEF(ContainerVT), SubVec,
5000                          DAG.getConstant(0, DL, XLenVT));
5001     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5002       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5003       return DAG.getBitcast(Op.getValueType(), SubVec);
5004     }
5005     SDValue Mask =
5006         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5007     // Set the vector length to only the number of elements we care about. Note
5008     // that for slideup this includes the offset.
5009     SDValue VL =
5010         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5011     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5012     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5013                                   SubVec, SlideupAmt, Mask, VL);
5014     if (VecVT.isFixedLengthVector())
5015       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5016     return DAG.getBitcast(Op.getValueType(), Slideup);
5017   }
5018 
5019   unsigned SubRegIdx, RemIdx;
5020   std::tie(SubRegIdx, RemIdx) =
5021       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5022           VecVT, SubVecVT, OrigIdx, TRI);
5023 
5024   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5025   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5026                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5027                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5028 
5029   // 1. If the Idx has been completely eliminated and this subvector's size is
5030   // a vector register or a multiple thereof, or the surrounding elements are
5031   // undef, then this is a subvector insert which naturally aligns to a vector
5032   // register. These can easily be handled using subregister manipulation.
5033   // 2. If the subvector is smaller than a vector register, then the insertion
5034   // must preserve the undisturbed elements of the register. We do this by
5035   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5036   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5037   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5038   // LMUL=1 type back into the larger vector (resolving to another subregister
5039   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5040   // to avoid allocating a large register group to hold our subvector.
5041   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5042     return Op;
5043 
5044   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5045   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5046   // (in our case undisturbed). This means we can set up a subvector insertion
5047   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5048   // size of the subvector.
5049   MVT InterSubVT = VecVT;
5050   SDValue AlignedExtract = Vec;
5051   unsigned AlignedIdx = OrigIdx - RemIdx;
5052   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5053     InterSubVT = getLMUL1VT(VecVT);
5054     // Extract a subvector equal to the nearest full vector register type. This
5055     // should resolve to a EXTRACT_SUBREG instruction.
5056     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5057                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5058   }
5059 
5060   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5061   // For scalable vectors this must be further multiplied by vscale.
5062   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5063 
5064   SDValue Mask, VL;
5065   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5066 
5067   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5068   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5069   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5070   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5071 
5072   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5073                        DAG.getUNDEF(InterSubVT), SubVec,
5074                        DAG.getConstant(0, DL, XLenVT));
5075 
5076   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5077                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5078 
5079   // If required, insert this subvector back into the correct vector register.
5080   // This should resolve to an INSERT_SUBREG instruction.
5081   if (VecVT.bitsGT(InterSubVT))
5082     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5083                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5084 
5085   // We might have bitcast from a mask type: cast back to the original type if
5086   // required.
5087   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5088 }
5089 
5090 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5091                                                     SelectionDAG &DAG) const {
5092   SDValue Vec = Op.getOperand(0);
5093   MVT SubVecVT = Op.getSimpleValueType();
5094   MVT VecVT = Vec.getSimpleValueType();
5095 
5096   SDLoc DL(Op);
5097   MVT XLenVT = Subtarget.getXLenVT();
5098   unsigned OrigIdx = Op.getConstantOperandVal(1);
5099   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5100 
5101   // We don't have the ability to slide mask vectors down indexed by their i1
5102   // elements; the smallest we can do is i8. Often we are able to bitcast to
5103   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5104   // from a scalable one, we might not necessarily have enough scalable
5105   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5106   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5107     if (VecVT.getVectorMinNumElements() >= 8 &&
5108         SubVecVT.getVectorMinNumElements() >= 8) {
5109       assert(OrigIdx % 8 == 0 && "Invalid index");
5110       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5111              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5112              "Unexpected mask vector lowering");
5113       OrigIdx /= 8;
5114       SubVecVT =
5115           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5116                            SubVecVT.isScalableVector());
5117       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5118                                VecVT.isScalableVector());
5119       Vec = DAG.getBitcast(VecVT, Vec);
5120     } else {
5121       // We can't slide this mask vector down, indexed by its i1 elements.
5122       // This poses a problem when we wish to extract a scalable vector which
5123       // can't be re-expressed as a larger type. Just choose the slow path and
5124       // extend to a larger type, then truncate back down.
5125       // TODO: We could probably improve this when extracting certain fixed
5126       // from fixed, where we can extract as i8 and shift the correct element
5127       // right to reach the desired subvector?
5128       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5129       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5130       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5131       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5132                         Op.getOperand(1));
5133       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5134       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5135     }
5136   }
5137 
5138   // If the subvector vector is a fixed-length type, we cannot use subregister
5139   // manipulation to simplify the codegen; we don't know which register of a
5140   // LMUL group contains the specific subvector as we only know the minimum
5141   // register size. Therefore we must slide the vector group down the full
5142   // amount.
5143   if (SubVecVT.isFixedLengthVector()) {
5144     // With an index of 0 this is a cast-like subvector, which can be performed
5145     // with subregister operations.
5146     if (OrigIdx == 0)
5147       return Op;
5148     MVT ContainerVT = VecVT;
5149     if (VecVT.isFixedLengthVector()) {
5150       ContainerVT = getContainerForFixedLengthVector(VecVT);
5151       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5152     }
5153     SDValue Mask =
5154         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5155     // Set the vector length to only the number of elements we care about. This
5156     // avoids sliding down elements we're going to discard straight away.
5157     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5158     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5159     SDValue Slidedown =
5160         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5161                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5162     // Now we can use a cast-like subvector extract to get the result.
5163     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5164                             DAG.getConstant(0, DL, XLenVT));
5165     return DAG.getBitcast(Op.getValueType(), Slidedown);
5166   }
5167 
5168   unsigned SubRegIdx, RemIdx;
5169   std::tie(SubRegIdx, RemIdx) =
5170       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5171           VecVT, SubVecVT, OrigIdx, TRI);
5172 
5173   // If the Idx has been completely eliminated then this is a subvector extract
5174   // which naturally aligns to a vector register. These can easily be handled
5175   // using subregister manipulation.
5176   if (RemIdx == 0)
5177     return Op;
5178 
5179   // Else we must shift our vector register directly to extract the subvector.
5180   // Do this using VSLIDEDOWN.
5181 
5182   // If the vector type is an LMUL-group type, extract a subvector equal to the
5183   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5184   // instruction.
5185   MVT InterSubVT = VecVT;
5186   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5187     InterSubVT = getLMUL1VT(VecVT);
5188     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5189                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5190   }
5191 
5192   // Slide this vector register down by the desired number of elements in order
5193   // to place the desired subvector starting at element 0.
5194   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5195   // For scalable vectors this must be further multiplied by vscale.
5196   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5197 
5198   SDValue Mask, VL;
5199   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5200   SDValue Slidedown =
5201       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5202                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5203 
5204   // Now the vector is in the right position, extract our final subvector. This
5205   // should resolve to a COPY.
5206   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5207                           DAG.getConstant(0, DL, XLenVT));
5208 
5209   // We might have bitcast from a mask type: cast back to the original type if
5210   // required.
5211   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5212 }
5213 
5214 // Lower step_vector to the vid instruction. Any non-identity step value must
5215 // be accounted for my manual expansion.
5216 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5217                                               SelectionDAG &DAG) const {
5218   SDLoc DL(Op);
5219   MVT VT = Op.getSimpleValueType();
5220   MVT XLenVT = Subtarget.getXLenVT();
5221   SDValue Mask, VL;
5222   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5223   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5224   uint64_t StepValImm = Op.getConstantOperandVal(0);
5225   if (StepValImm != 1) {
5226     if (isPowerOf2_64(StepValImm)) {
5227       SDValue StepVal =
5228           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5229                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5230       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5231     } else {
5232       SDValue StepVal = lowerScalarSplat(
5233           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5234           DL, DAG, Subtarget);
5235       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5236     }
5237   }
5238   return StepVec;
5239 }
5240 
5241 // Implement vector_reverse using vrgather.vv with indices determined by
5242 // subtracting the id of each element from (VLMAX-1). This will convert
5243 // the indices like so:
5244 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5245 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5246 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5247                                                  SelectionDAG &DAG) const {
5248   SDLoc DL(Op);
5249   MVT VecVT = Op.getSimpleValueType();
5250   unsigned EltSize = VecVT.getScalarSizeInBits();
5251   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5252 
5253   unsigned MaxVLMAX = 0;
5254   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5255   if (VectorBitsMax != 0)
5256     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5257 
5258   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5259   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5260 
5261   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5262   // to use vrgatherei16.vv.
5263   // TODO: It's also possible to use vrgatherei16.vv for other types to
5264   // decrease register width for the index calculation.
5265   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5266     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5267     // Reverse each half, then reassemble them in reverse order.
5268     // NOTE: It's also possible that after splitting that VLMAX no longer
5269     // requires vrgatherei16.vv.
5270     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5271       SDValue Lo, Hi;
5272       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5273       EVT LoVT, HiVT;
5274       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5275       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5276       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5277       // Reassemble the low and high pieces reversed.
5278       // FIXME: This is a CONCAT_VECTORS.
5279       SDValue Res =
5280           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5281                       DAG.getIntPtrConstant(0, DL));
5282       return DAG.getNode(
5283           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5284           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5285     }
5286 
5287     // Just promote the int type to i16 which will double the LMUL.
5288     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5289     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5290   }
5291 
5292   MVT XLenVT = Subtarget.getXLenVT();
5293   SDValue Mask, VL;
5294   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5295 
5296   // Calculate VLMAX-1 for the desired SEW.
5297   unsigned MinElts = VecVT.getVectorMinNumElements();
5298   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5299                               DAG.getConstant(MinElts, DL, XLenVT));
5300   SDValue VLMinus1 =
5301       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5302 
5303   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5304   bool IsRV32E64 =
5305       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5306   SDValue SplatVL;
5307   if (!IsRV32E64)
5308     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5309   else
5310     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5311 
5312   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5313   SDValue Indices =
5314       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5315 
5316   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5317 }
5318 
5319 SDValue
5320 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5321                                                      SelectionDAG &DAG) const {
5322   SDLoc DL(Op);
5323   auto *Load = cast<LoadSDNode>(Op);
5324 
5325   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5326                                         Load->getMemoryVT(),
5327                                         *Load->getMemOperand()) &&
5328          "Expecting a correctly-aligned load");
5329 
5330   MVT VT = Op.getSimpleValueType();
5331   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5332 
5333   SDValue VL =
5334       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5335 
5336   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5337   SDValue NewLoad = DAG.getMemIntrinsicNode(
5338       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5339       Load->getMemoryVT(), Load->getMemOperand());
5340 
5341   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5342   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5343 }
5344 
5345 SDValue
5346 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5347                                                       SelectionDAG &DAG) const {
5348   SDLoc DL(Op);
5349   auto *Store = cast<StoreSDNode>(Op);
5350 
5351   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5352                                         Store->getMemoryVT(),
5353                                         *Store->getMemOperand()) &&
5354          "Expecting a correctly-aligned store");
5355 
5356   SDValue StoreVal = Store->getValue();
5357   MVT VT = StoreVal.getSimpleValueType();
5358 
5359   // If the size less than a byte, we need to pad with zeros to make a byte.
5360   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5361     VT = MVT::v8i1;
5362     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5363                            DAG.getConstant(0, DL, VT), StoreVal,
5364                            DAG.getIntPtrConstant(0, DL));
5365   }
5366 
5367   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5368 
5369   SDValue VL =
5370       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5371 
5372   SDValue NewValue =
5373       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5374   return DAG.getMemIntrinsicNode(
5375       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5376       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5377       Store->getMemoryVT(), Store->getMemOperand());
5378 }
5379 
5380 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5381                                              SelectionDAG &DAG) const {
5382   SDLoc DL(Op);
5383   MVT VT = Op.getSimpleValueType();
5384 
5385   const auto *MemSD = cast<MemSDNode>(Op);
5386   EVT MemVT = MemSD->getMemoryVT();
5387   MachineMemOperand *MMO = MemSD->getMemOperand();
5388   SDValue Chain = MemSD->getChain();
5389   SDValue BasePtr = MemSD->getBasePtr();
5390 
5391   SDValue Mask, PassThru, VL;
5392   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5393     Mask = VPLoad->getMask();
5394     PassThru = DAG.getUNDEF(VT);
5395     VL = VPLoad->getVectorLength();
5396   } else {
5397     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5398     Mask = MLoad->getMask();
5399     PassThru = MLoad->getPassThru();
5400   }
5401 
5402   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5403 
5404   MVT XLenVT = Subtarget.getXLenVT();
5405 
5406   MVT ContainerVT = VT;
5407   if (VT.isFixedLengthVector()) {
5408     ContainerVT = getContainerForFixedLengthVector(VT);
5409     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5410     if (!IsUnmasked) {
5411       MVT MaskVT =
5412           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5413       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5414     }
5415   }
5416 
5417   if (!VL)
5418     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5419 
5420   unsigned IntID =
5421       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5422   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5423   if (!IsUnmasked)
5424     Ops.push_back(PassThru);
5425   Ops.push_back(BasePtr);
5426   if (!IsUnmasked)
5427     Ops.push_back(Mask);
5428   Ops.push_back(VL);
5429   if (!IsUnmasked)
5430     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5431 
5432   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5433 
5434   SDValue Result =
5435       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5436   Chain = Result.getValue(1);
5437 
5438   if (VT.isFixedLengthVector())
5439     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5440 
5441   return DAG.getMergeValues({Result, Chain}, DL);
5442 }
5443 
5444 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5445                                               SelectionDAG &DAG) const {
5446   SDLoc DL(Op);
5447 
5448   const auto *MemSD = cast<MemSDNode>(Op);
5449   EVT MemVT = MemSD->getMemoryVT();
5450   MachineMemOperand *MMO = MemSD->getMemOperand();
5451   SDValue Chain = MemSD->getChain();
5452   SDValue BasePtr = MemSD->getBasePtr();
5453   SDValue Val, Mask, VL;
5454 
5455   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5456     Val = VPStore->getValue();
5457     Mask = VPStore->getMask();
5458     VL = VPStore->getVectorLength();
5459   } else {
5460     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5461     Val = MStore->getValue();
5462     Mask = MStore->getMask();
5463   }
5464 
5465   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5466 
5467   MVT VT = Val.getSimpleValueType();
5468   MVT XLenVT = Subtarget.getXLenVT();
5469 
5470   MVT ContainerVT = VT;
5471   if (VT.isFixedLengthVector()) {
5472     ContainerVT = getContainerForFixedLengthVector(VT);
5473 
5474     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5475     if (!IsUnmasked) {
5476       MVT MaskVT =
5477           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5478       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5479     }
5480   }
5481 
5482   if (!VL)
5483     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5484 
5485   unsigned IntID =
5486       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5487   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5488   Ops.push_back(Val);
5489   Ops.push_back(BasePtr);
5490   if (!IsUnmasked)
5491     Ops.push_back(Mask);
5492   Ops.push_back(VL);
5493 
5494   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5495                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5496 }
5497 
5498 SDValue
5499 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5500                                                       SelectionDAG &DAG) const {
5501   MVT InVT = Op.getOperand(0).getSimpleValueType();
5502   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5503 
5504   MVT VT = Op.getSimpleValueType();
5505 
5506   SDValue Op1 =
5507       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5508   SDValue Op2 =
5509       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5510 
5511   SDLoc DL(Op);
5512   SDValue VL =
5513       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5514 
5515   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5516   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5517 
5518   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5519                             Op.getOperand(2), Mask, VL);
5520 
5521   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5522 }
5523 
5524 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5525     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5526   MVT VT = Op.getSimpleValueType();
5527 
5528   if (VT.getVectorElementType() == MVT::i1)
5529     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5530 
5531   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5532 }
5533 
5534 SDValue
5535 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5536                                                       SelectionDAG &DAG) const {
5537   unsigned Opc;
5538   switch (Op.getOpcode()) {
5539   default: llvm_unreachable("Unexpected opcode!");
5540   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5541   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5542   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5543   }
5544 
5545   return lowerToScalableOp(Op, DAG, Opc);
5546 }
5547 
5548 // Lower vector ABS to smax(X, sub(0, X)).
5549 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5550   SDLoc DL(Op);
5551   MVT VT = Op.getSimpleValueType();
5552   SDValue X = Op.getOperand(0);
5553 
5554   assert(VT.isFixedLengthVector() && "Unexpected type");
5555 
5556   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5557   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5558 
5559   SDValue Mask, VL;
5560   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5561 
5562   SDValue SplatZero =
5563       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5564                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5565   SDValue NegX =
5566       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5567   SDValue Max =
5568       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5569 
5570   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5571 }
5572 
5573 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5574     SDValue Op, SelectionDAG &DAG) const {
5575   SDLoc DL(Op);
5576   MVT VT = Op.getSimpleValueType();
5577   SDValue Mag = Op.getOperand(0);
5578   SDValue Sign = Op.getOperand(1);
5579   assert(Mag.getValueType() == Sign.getValueType() &&
5580          "Can only handle COPYSIGN with matching types.");
5581 
5582   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5583   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5584   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5585 
5586   SDValue Mask, VL;
5587   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5588 
5589   SDValue CopySign =
5590       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5591 
5592   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5593 }
5594 
5595 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5596     SDValue Op, SelectionDAG &DAG) const {
5597   MVT VT = Op.getSimpleValueType();
5598   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5599 
5600   MVT I1ContainerVT =
5601       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5602 
5603   SDValue CC =
5604       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5605   SDValue Op1 =
5606       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5607   SDValue Op2 =
5608       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5609 
5610   SDLoc DL(Op);
5611   SDValue Mask, VL;
5612   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5613 
5614   SDValue Select =
5615       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5616 
5617   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5618 }
5619 
5620 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5621                                                unsigned NewOpc,
5622                                                bool HasMask) const {
5623   MVT VT = Op.getSimpleValueType();
5624   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5625 
5626   // Create list of operands by converting existing ones to scalable types.
5627   SmallVector<SDValue, 6> Ops;
5628   for (const SDValue &V : Op->op_values()) {
5629     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5630 
5631     // Pass through non-vector operands.
5632     if (!V.getValueType().isVector()) {
5633       Ops.push_back(V);
5634       continue;
5635     }
5636 
5637     // "cast" fixed length vector to a scalable vector.
5638     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5639            "Only fixed length vectors are supported!");
5640     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5641   }
5642 
5643   SDLoc DL(Op);
5644   SDValue Mask, VL;
5645   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5646   if (HasMask)
5647     Ops.push_back(Mask);
5648   Ops.push_back(VL);
5649 
5650   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5651   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5652 }
5653 
5654 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5655 // * Operands of each node are assumed to be in the same order.
5656 // * The EVL operand is promoted from i32 to i64 on RV64.
5657 // * Fixed-length vectors are converted to their scalable-vector container
5658 //   types.
5659 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5660                                        unsigned RISCVISDOpc) const {
5661   SDLoc DL(Op);
5662   MVT VT = Op.getSimpleValueType();
5663   SmallVector<SDValue, 4> Ops;
5664 
5665   for (const auto &OpIdx : enumerate(Op->ops())) {
5666     SDValue V = OpIdx.value();
5667     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5668     // Pass through operands which aren't fixed-length vectors.
5669     if (!V.getValueType().isFixedLengthVector()) {
5670       Ops.push_back(V);
5671       continue;
5672     }
5673     // "cast" fixed length vector to a scalable vector.
5674     MVT OpVT = V.getSimpleValueType();
5675     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5676     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5677            "Only fixed length vectors are supported!");
5678     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5679   }
5680 
5681   if (!VT.isFixedLengthVector())
5682     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5683 
5684   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5685 
5686   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5687 
5688   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5689 }
5690 
5691 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5692                                             unsigned MaskOpc,
5693                                             unsigned VecOpc) const {
5694   MVT VT = Op.getSimpleValueType();
5695   if (VT.getVectorElementType() != MVT::i1)
5696     return lowerVPOp(Op, DAG, VecOpc);
5697 
5698   // It is safe to drop mask parameter as masked-off elements are undef.
5699   SDValue Op1 = Op->getOperand(0);
5700   SDValue Op2 = Op->getOperand(1);
5701   SDValue VL = Op->getOperand(3);
5702 
5703   MVT ContainerVT = VT;
5704   const bool IsFixed = VT.isFixedLengthVector();
5705   if (IsFixed) {
5706     ContainerVT = getContainerForFixedLengthVector(VT);
5707     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5708     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5709   }
5710 
5711   SDLoc DL(Op);
5712   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5713   if (!IsFixed)
5714     return Val;
5715   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5716 }
5717 
5718 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5719 // matched to a RVV indexed load. The RVV indexed load instructions only
5720 // support the "unsigned unscaled" addressing mode; indices are implicitly
5721 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5722 // signed or scaled indexing is extended to the XLEN value type and scaled
5723 // accordingly.
5724 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5725                                                SelectionDAG &DAG) const {
5726   SDLoc DL(Op);
5727   MVT VT = Op.getSimpleValueType();
5728 
5729   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5730   EVT MemVT = MemSD->getMemoryVT();
5731   MachineMemOperand *MMO = MemSD->getMemOperand();
5732   SDValue Chain = MemSD->getChain();
5733   SDValue BasePtr = MemSD->getBasePtr();
5734 
5735   ISD::LoadExtType LoadExtType;
5736   SDValue Index, Mask, PassThru, VL;
5737 
5738   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5739     Index = VPGN->getIndex();
5740     Mask = VPGN->getMask();
5741     PassThru = DAG.getUNDEF(VT);
5742     VL = VPGN->getVectorLength();
5743     // VP doesn't support extending loads.
5744     LoadExtType = ISD::NON_EXTLOAD;
5745   } else {
5746     // Else it must be a MGATHER.
5747     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5748     Index = MGN->getIndex();
5749     Mask = MGN->getMask();
5750     PassThru = MGN->getPassThru();
5751     LoadExtType = MGN->getExtensionType();
5752   }
5753 
5754   MVT IndexVT = Index.getSimpleValueType();
5755   MVT XLenVT = Subtarget.getXLenVT();
5756 
5757   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5758          "Unexpected VTs!");
5759   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5760   // Targets have to explicitly opt-in for extending vector loads.
5761   assert(LoadExtType == ISD::NON_EXTLOAD &&
5762          "Unexpected extending MGATHER/VP_GATHER");
5763   (void)LoadExtType;
5764 
5765   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5766   // the selection of the masked intrinsics doesn't do this for us.
5767   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5768 
5769   MVT ContainerVT = VT;
5770   if (VT.isFixedLengthVector()) {
5771     // We need to use the larger of the result and index type to determine the
5772     // scalable type to use so we don't increase LMUL for any operand/result.
5773     if (VT.bitsGE(IndexVT)) {
5774       ContainerVT = getContainerForFixedLengthVector(VT);
5775       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5776                                  ContainerVT.getVectorElementCount());
5777     } else {
5778       IndexVT = getContainerForFixedLengthVector(IndexVT);
5779       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5780                                      IndexVT.getVectorElementCount());
5781     }
5782 
5783     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5784 
5785     if (!IsUnmasked) {
5786       MVT MaskVT =
5787           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5788       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5789       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5790     }
5791   }
5792 
5793   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5794       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5795       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5796   }
5797 
5798   if (!VL)
5799     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5800 
5801   unsigned IntID =
5802       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5803   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5804   if (!IsUnmasked)
5805     Ops.push_back(PassThru);
5806   Ops.push_back(BasePtr);
5807   Ops.push_back(Index);
5808   if (!IsUnmasked)
5809     Ops.push_back(Mask);
5810   Ops.push_back(VL);
5811   if (!IsUnmasked)
5812     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5813 
5814   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5815   SDValue Result =
5816       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5817   Chain = Result.getValue(1);
5818 
5819   if (VT.isFixedLengthVector())
5820     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5821 
5822   return DAG.getMergeValues({Result, Chain}, DL);
5823 }
5824 
5825 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5826 // matched to a RVV indexed store. The RVV indexed store instructions only
5827 // support the "unsigned unscaled" addressing mode; indices are implicitly
5828 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5829 // signed or scaled indexing is extended to the XLEN value type and scaled
5830 // accordingly.
5831 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5832                                                 SelectionDAG &DAG) const {
5833   SDLoc DL(Op);
5834   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5835   EVT MemVT = MemSD->getMemoryVT();
5836   MachineMemOperand *MMO = MemSD->getMemOperand();
5837   SDValue Chain = MemSD->getChain();
5838   SDValue BasePtr = MemSD->getBasePtr();
5839 
5840   bool IsTruncatingStore = false;
5841   SDValue Index, Mask, Val, VL;
5842 
5843   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5844     Index = VPSN->getIndex();
5845     Mask = VPSN->getMask();
5846     Val = VPSN->getValue();
5847     VL = VPSN->getVectorLength();
5848     // VP doesn't support truncating stores.
5849     IsTruncatingStore = false;
5850   } else {
5851     // Else it must be a MSCATTER.
5852     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5853     Index = MSN->getIndex();
5854     Mask = MSN->getMask();
5855     Val = MSN->getValue();
5856     IsTruncatingStore = MSN->isTruncatingStore();
5857   }
5858 
5859   MVT VT = Val.getSimpleValueType();
5860   MVT IndexVT = Index.getSimpleValueType();
5861   MVT XLenVT = Subtarget.getXLenVT();
5862 
5863   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5864          "Unexpected VTs!");
5865   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5866   // Targets have to explicitly opt-in for extending vector loads and
5867   // truncating vector stores.
5868   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5869   (void)IsTruncatingStore;
5870 
5871   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5872   // the selection of the masked intrinsics doesn't do this for us.
5873   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5874 
5875   MVT ContainerVT = VT;
5876   if (VT.isFixedLengthVector()) {
5877     // We need to use the larger of the value and index type to determine the
5878     // scalable type to use so we don't increase LMUL for any operand/result.
5879     if (VT.bitsGE(IndexVT)) {
5880       ContainerVT = getContainerForFixedLengthVector(VT);
5881       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5882                                  ContainerVT.getVectorElementCount());
5883     } else {
5884       IndexVT = getContainerForFixedLengthVector(IndexVT);
5885       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5886                                      IndexVT.getVectorElementCount());
5887     }
5888 
5889     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5890     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5891 
5892     if (!IsUnmasked) {
5893       MVT MaskVT =
5894           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5895       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5896     }
5897   }
5898 
5899   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5900       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5901       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5902   }
5903 
5904   if (!VL)
5905     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5906 
5907   unsigned IntID =
5908       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5909   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5910   Ops.push_back(Val);
5911   Ops.push_back(BasePtr);
5912   Ops.push_back(Index);
5913   if (!IsUnmasked)
5914     Ops.push_back(Mask);
5915   Ops.push_back(VL);
5916 
5917   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5918                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5919 }
5920 
5921 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5922                                                SelectionDAG &DAG) const {
5923   const MVT XLenVT = Subtarget.getXLenVT();
5924   SDLoc DL(Op);
5925   SDValue Chain = Op->getOperand(0);
5926   SDValue SysRegNo = DAG.getTargetConstant(
5927       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5928   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5929   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5930 
5931   // Encoding used for rounding mode in RISCV differs from that used in
5932   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5933   // table, which consists of a sequence of 4-bit fields, each representing
5934   // corresponding FLT_ROUNDS mode.
5935   static const int Table =
5936       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5937       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5938       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5939       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5940       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5941 
5942   SDValue Shift =
5943       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5944   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5945                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5946   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5947                                DAG.getConstant(7, DL, XLenVT));
5948 
5949   return DAG.getMergeValues({Masked, Chain}, DL);
5950 }
5951 
5952 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5953                                                SelectionDAG &DAG) const {
5954   const MVT XLenVT = Subtarget.getXLenVT();
5955   SDLoc DL(Op);
5956   SDValue Chain = Op->getOperand(0);
5957   SDValue RMValue = Op->getOperand(1);
5958   SDValue SysRegNo = DAG.getTargetConstant(
5959       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5960 
5961   // Encoding used for rounding mode in RISCV differs from that used in
5962   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5963   // a table, which consists of a sequence of 4-bit fields, each representing
5964   // corresponding RISCV mode.
5965   static const unsigned Table =
5966       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5967       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5968       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5969       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5970       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5971 
5972   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5973                               DAG.getConstant(2, DL, XLenVT));
5974   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5975                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5976   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5977                         DAG.getConstant(0x7, DL, XLenVT));
5978   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5979                      RMValue);
5980 }
5981 
5982 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
5983   switch (IntNo) {
5984   default:
5985     llvm_unreachable("Unexpected Intrinsic");
5986   case Intrinsic::riscv_grev:
5987     return RISCVISD::GREVW;
5988   case Intrinsic::riscv_gorc:
5989     return RISCVISD::GORCW;
5990   case Intrinsic::riscv_bcompress:
5991     return RISCVISD::BCOMPRESSW;
5992   case Intrinsic::riscv_bdecompress:
5993     return RISCVISD::BDECOMPRESSW;
5994   case Intrinsic::riscv_bfp:
5995     return RISCVISD::BFPW;
5996   case Intrinsic::riscv_fsl:
5997     return RISCVISD::FSLW;
5998   case Intrinsic::riscv_fsr:
5999     return RISCVISD::FSRW;
6000   }
6001 }
6002 
6003 // Converts the given intrinsic to a i64 operation with any extension.
6004 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6005                                          unsigned IntNo) {
6006   SDLoc DL(N);
6007   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6008   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6009   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6010   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6011   // ReplaceNodeResults requires we maintain the same type for the return value.
6012   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6013 }
6014 
6015 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6016 // form of the given Opcode.
6017 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6018   switch (Opcode) {
6019   default:
6020     llvm_unreachable("Unexpected opcode");
6021   case ISD::SHL:
6022     return RISCVISD::SLLW;
6023   case ISD::SRA:
6024     return RISCVISD::SRAW;
6025   case ISD::SRL:
6026     return RISCVISD::SRLW;
6027   case ISD::SDIV:
6028     return RISCVISD::DIVW;
6029   case ISD::UDIV:
6030     return RISCVISD::DIVUW;
6031   case ISD::UREM:
6032     return RISCVISD::REMUW;
6033   case ISD::ROTL:
6034     return RISCVISD::ROLW;
6035   case ISD::ROTR:
6036     return RISCVISD::RORW;
6037   case RISCVISD::GREV:
6038     return RISCVISD::GREVW;
6039   case RISCVISD::GORC:
6040     return RISCVISD::GORCW;
6041   }
6042 }
6043 
6044 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6045 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6046 // otherwise be promoted to i64, making it difficult to select the
6047 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6048 // type i8/i16/i32 is lost.
6049 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6050                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6051   SDLoc DL(N);
6052   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6053   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6054   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6055   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6056   // ReplaceNodeResults requires we maintain the same type for the return value.
6057   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6058 }
6059 
6060 // Converts the given 32-bit operation to a i64 operation with signed extension
6061 // semantic to reduce the signed extension instructions.
6062 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6063   SDLoc DL(N);
6064   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6065   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6066   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6067   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6068                                DAG.getValueType(MVT::i32));
6069   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6070 }
6071 
6072 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6073                                              SmallVectorImpl<SDValue> &Results,
6074                                              SelectionDAG &DAG) const {
6075   SDLoc DL(N);
6076   switch (N->getOpcode()) {
6077   default:
6078     llvm_unreachable("Don't know how to custom type legalize this operation!");
6079   case ISD::STRICT_FP_TO_SINT:
6080   case ISD::STRICT_FP_TO_UINT:
6081   case ISD::FP_TO_SINT:
6082   case ISD::FP_TO_UINT: {
6083     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6084            "Unexpected custom legalisation");
6085     bool IsStrict = N->isStrictFPOpcode();
6086     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6087                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6088     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6089     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6090         TargetLowering::TypeSoftenFloat) {
6091       if (!isTypeLegal(Op0.getValueType()))
6092         return;
6093       if (IsStrict) {
6094         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6095                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6096         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6097         SDValue Res = DAG.getNode(
6098             Opc, DL, VTs, N->getOperand(0), Op0,
6099             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6100         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6101         Results.push_back(Res.getValue(1));
6102         return;
6103       }
6104       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6105       SDValue Res =
6106           DAG.getNode(Opc, DL, MVT::i64, Op0,
6107                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6108       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6109       return;
6110     }
6111     // If the FP type needs to be softened, emit a library call using the 'si'
6112     // version. If we left it to default legalization we'd end up with 'di'. If
6113     // the FP type doesn't need to be softened just let generic type
6114     // legalization promote the result type.
6115     RTLIB::Libcall LC;
6116     if (IsSigned)
6117       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6118     else
6119       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6120     MakeLibCallOptions CallOptions;
6121     EVT OpVT = Op0.getValueType();
6122     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6123     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6124     SDValue Result;
6125     std::tie(Result, Chain) =
6126         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6127     Results.push_back(Result);
6128     if (IsStrict)
6129       Results.push_back(Chain);
6130     break;
6131   }
6132   case ISD::READCYCLECOUNTER: {
6133     assert(!Subtarget.is64Bit() &&
6134            "READCYCLECOUNTER only has custom type legalization on riscv32");
6135 
6136     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6137     SDValue RCW =
6138         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6139 
6140     Results.push_back(
6141         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6142     Results.push_back(RCW.getValue(2));
6143     break;
6144   }
6145   case ISD::MUL: {
6146     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6147     unsigned XLen = Subtarget.getXLen();
6148     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6149     if (Size > XLen) {
6150       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6151       SDValue LHS = N->getOperand(0);
6152       SDValue RHS = N->getOperand(1);
6153       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6154 
6155       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6156       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6157       // We need exactly one side to be unsigned.
6158       if (LHSIsU == RHSIsU)
6159         return;
6160 
6161       auto MakeMULPair = [&](SDValue S, SDValue U) {
6162         MVT XLenVT = Subtarget.getXLenVT();
6163         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6164         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6165         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6166         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6167         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6168       };
6169 
6170       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6171       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6172 
6173       // The other operand should be signed, but still prefer MULH when
6174       // possible.
6175       if (RHSIsU && LHSIsS && !RHSIsS)
6176         Results.push_back(MakeMULPair(LHS, RHS));
6177       else if (LHSIsU && RHSIsS && !LHSIsS)
6178         Results.push_back(MakeMULPair(RHS, LHS));
6179 
6180       return;
6181     }
6182     LLVM_FALLTHROUGH;
6183   }
6184   case ISD::ADD:
6185   case ISD::SUB:
6186     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6187            "Unexpected custom legalisation");
6188     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6189     break;
6190   case ISD::SHL:
6191   case ISD::SRA:
6192   case ISD::SRL:
6193     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6194            "Unexpected custom legalisation");
6195     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6196       Results.push_back(customLegalizeToWOp(N, DAG));
6197       break;
6198     }
6199 
6200     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6201     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6202     // shift amount.
6203     if (N->getOpcode() == ISD::SHL) {
6204       SDLoc DL(N);
6205       SDValue NewOp0 =
6206           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6207       SDValue NewOp1 =
6208           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6209       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6210       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6211                                    DAG.getValueType(MVT::i32));
6212       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6213     }
6214 
6215     break;
6216   case ISD::ROTL:
6217   case ISD::ROTR:
6218     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6219            "Unexpected custom legalisation");
6220     Results.push_back(customLegalizeToWOp(N, DAG));
6221     break;
6222   case ISD::CTTZ:
6223   case ISD::CTTZ_ZERO_UNDEF:
6224   case ISD::CTLZ:
6225   case ISD::CTLZ_ZERO_UNDEF: {
6226     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6227            "Unexpected custom legalisation");
6228 
6229     SDValue NewOp0 =
6230         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6231     bool IsCTZ =
6232         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6233     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6234     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6235     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6236     return;
6237   }
6238   case ISD::SDIV:
6239   case ISD::UDIV:
6240   case ISD::UREM: {
6241     MVT VT = N->getSimpleValueType(0);
6242     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6243            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6244            "Unexpected custom legalisation");
6245     // Don't promote division/remainder by constant since we should expand those
6246     // to multiply by magic constant.
6247     // FIXME: What if the expansion is disabled for minsize.
6248     if (N->getOperand(1).getOpcode() == ISD::Constant)
6249       return;
6250 
6251     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6252     // the upper 32 bits. For other types we need to sign or zero extend
6253     // based on the opcode.
6254     unsigned ExtOpc = ISD::ANY_EXTEND;
6255     if (VT != MVT::i32)
6256       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6257                                            : ISD::ZERO_EXTEND;
6258 
6259     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6260     break;
6261   }
6262   case ISD::UADDO:
6263   case ISD::USUBO: {
6264     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6265            "Unexpected custom legalisation");
6266     bool IsAdd = N->getOpcode() == ISD::UADDO;
6267     // Create an ADDW or SUBW.
6268     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6269     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6270     SDValue Res =
6271         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6272     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6273                       DAG.getValueType(MVT::i32));
6274 
6275     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6276     // Since the inputs are sign extended from i32, this is equivalent to
6277     // comparing the lower 32 bits.
6278     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6279     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6280                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6281 
6282     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6283     Results.push_back(Overflow);
6284     return;
6285   }
6286   case ISD::UADDSAT:
6287   case ISD::USUBSAT: {
6288     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6289            "Unexpected custom legalisation");
6290     if (Subtarget.hasStdExtZbb()) {
6291       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6292       // sign extend allows overflow of the lower 32 bits to be detected on
6293       // the promoted size.
6294       SDValue LHS =
6295           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6296       SDValue RHS =
6297           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6298       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6299       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6300       return;
6301     }
6302 
6303     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6304     // promotion for UADDO/USUBO.
6305     Results.push_back(expandAddSubSat(N, DAG));
6306     return;
6307   }
6308   case ISD::BITCAST: {
6309     EVT VT = N->getValueType(0);
6310     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6311     SDValue Op0 = N->getOperand(0);
6312     EVT Op0VT = Op0.getValueType();
6313     MVT XLenVT = Subtarget.getXLenVT();
6314     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6315       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6316       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6317     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6318                Subtarget.hasStdExtF()) {
6319       SDValue FPConv =
6320           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6321       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6322     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6323                isTypeLegal(Op0VT)) {
6324       // Custom-legalize bitcasts from fixed-length vector types to illegal
6325       // scalar types in order to improve codegen. Bitcast the vector to a
6326       // one-element vector type whose element type is the same as the result
6327       // type, and extract the first element.
6328       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6329       if (isTypeLegal(BVT)) {
6330         SDValue BVec = DAG.getBitcast(BVT, Op0);
6331         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6332                                       DAG.getConstant(0, DL, XLenVT)));
6333       }
6334     }
6335     break;
6336   }
6337   case RISCVISD::GREV:
6338   case RISCVISD::GORC: {
6339     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6340            "Unexpected custom legalisation");
6341     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6342     // This is similar to customLegalizeToWOp, except that we pass the second
6343     // operand (a TargetConstant) straight through: it is already of type
6344     // XLenVT.
6345     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6346     SDValue NewOp0 =
6347         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6348     SDValue NewOp1 =
6349         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6350     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6351     // ReplaceNodeResults requires we maintain the same type for the return
6352     // value.
6353     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6354     break;
6355   }
6356   case RISCVISD::SHFL: {
6357     // There is no SHFLIW instruction, but we can just promote the operation.
6358     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6359            "Unexpected custom legalisation");
6360     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6361     SDValue NewOp0 =
6362         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6363     SDValue NewOp1 =
6364         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6365     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6366     // ReplaceNodeResults requires we maintain the same type for the return
6367     // value.
6368     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6369     break;
6370   }
6371   case ISD::BSWAP:
6372   case ISD::BITREVERSE: {
6373     MVT VT = N->getSimpleValueType(0);
6374     MVT XLenVT = Subtarget.getXLenVT();
6375     assert((VT == MVT::i8 || VT == MVT::i16 ||
6376             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6377            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6378     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6379     unsigned Imm = VT.getSizeInBits() - 1;
6380     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6381     if (N->getOpcode() == ISD::BSWAP)
6382       Imm &= ~0x7U;
6383     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6384     SDValue GREVI =
6385         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6386     // ReplaceNodeResults requires we maintain the same type for the return
6387     // value.
6388     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6389     break;
6390   }
6391   case ISD::FSHL:
6392   case ISD::FSHR: {
6393     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6394            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6395     SDValue NewOp0 =
6396         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6397     SDValue NewOp1 =
6398         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6399     SDValue NewShAmt =
6400         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6401     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6402     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6403     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6404                            DAG.getConstant(0x1f, DL, MVT::i64));
6405     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6406     // instruction use different orders. fshl will return its first operand for
6407     // shift of zero, fshr will return its second operand. fsl and fsr both
6408     // return rs1 so the ISD nodes need to have different operand orders.
6409     // Shift amount is in rs2.
6410     unsigned Opc = RISCVISD::FSLW;
6411     if (N->getOpcode() == ISD::FSHR) {
6412       std::swap(NewOp0, NewOp1);
6413       Opc = RISCVISD::FSRW;
6414     }
6415     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6416     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6417     break;
6418   }
6419   case ISD::EXTRACT_VECTOR_ELT: {
6420     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6421     // type is illegal (currently only vXi64 RV32).
6422     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6423     // transferred to the destination register. We issue two of these from the
6424     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6425     // first element.
6426     SDValue Vec = N->getOperand(0);
6427     SDValue Idx = N->getOperand(1);
6428 
6429     // The vector type hasn't been legalized yet so we can't issue target
6430     // specific nodes if it needs legalization.
6431     // FIXME: We would manually legalize if it's important.
6432     if (!isTypeLegal(Vec.getValueType()))
6433       return;
6434 
6435     MVT VecVT = Vec.getSimpleValueType();
6436 
6437     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6438            VecVT.getVectorElementType() == MVT::i64 &&
6439            "Unexpected EXTRACT_VECTOR_ELT legalization");
6440 
6441     // If this is a fixed vector, we need to convert it to a scalable vector.
6442     MVT ContainerVT = VecVT;
6443     if (VecVT.isFixedLengthVector()) {
6444       ContainerVT = getContainerForFixedLengthVector(VecVT);
6445       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6446     }
6447 
6448     MVT XLenVT = Subtarget.getXLenVT();
6449 
6450     // Use a VL of 1 to avoid processing more elements than we need.
6451     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6452     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6453     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6454 
6455     // Unless the index is known to be 0, we must slide the vector down to get
6456     // the desired element into index 0.
6457     if (!isNullConstant(Idx)) {
6458       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6459                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6460     }
6461 
6462     // Extract the lower XLEN bits of the correct vector element.
6463     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6464 
6465     // To extract the upper XLEN bits of the vector element, shift the first
6466     // element right by 32 bits and re-extract the lower XLEN bits.
6467     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6468                                      DAG.getConstant(32, DL, XLenVT), VL);
6469     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6470                                  ThirtyTwoV, Mask, VL);
6471 
6472     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6473 
6474     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6475     break;
6476   }
6477   case ISD::INTRINSIC_WO_CHAIN: {
6478     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6479     switch (IntNo) {
6480     default:
6481       llvm_unreachable(
6482           "Don't know how to custom type legalize this intrinsic!");
6483     case Intrinsic::riscv_grev:
6484     case Intrinsic::riscv_gorc:
6485     case Intrinsic::riscv_bcompress:
6486     case Intrinsic::riscv_bdecompress:
6487     case Intrinsic::riscv_bfp: {
6488       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6489              "Unexpected custom legalisation");
6490       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6491       break;
6492     }
6493     case Intrinsic::riscv_fsl:
6494     case Intrinsic::riscv_fsr: {
6495       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6496              "Unexpected custom legalisation");
6497       SDValue NewOp1 =
6498           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6499       SDValue NewOp2 =
6500           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6501       SDValue NewOp3 =
6502           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6503       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6504       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6505       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6506       break;
6507     }
6508     case Intrinsic::riscv_orc_b: {
6509       // Lower to the GORCI encoding for orc.b with the operand extended.
6510       SDValue NewOp =
6511           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6512       // If Zbp is enabled, use GORCIW which will sign extend the result.
6513       unsigned Opc =
6514           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6515       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6516                                 DAG.getConstant(7, DL, MVT::i64));
6517       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6518       return;
6519     }
6520     case Intrinsic::riscv_shfl:
6521     case Intrinsic::riscv_unshfl: {
6522       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6523              "Unexpected custom legalisation");
6524       SDValue NewOp1 =
6525           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6526       SDValue NewOp2 =
6527           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6528       unsigned Opc =
6529           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6530       if (isa<ConstantSDNode>(N->getOperand(2))) {
6531         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6532                              DAG.getConstant(0xf, DL, MVT::i64));
6533         Opc =
6534             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6535       }
6536       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6537       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6538       break;
6539     }
6540     case Intrinsic::riscv_vmv_x_s: {
6541       EVT VT = N->getValueType(0);
6542       MVT XLenVT = Subtarget.getXLenVT();
6543       if (VT.bitsLT(XLenVT)) {
6544         // Simple case just extract using vmv.x.s and truncate.
6545         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6546                                       Subtarget.getXLenVT(), N->getOperand(1));
6547         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6548         return;
6549       }
6550 
6551       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6552              "Unexpected custom legalization");
6553 
6554       // We need to do the move in two steps.
6555       SDValue Vec = N->getOperand(1);
6556       MVT VecVT = Vec.getSimpleValueType();
6557 
6558       // First extract the lower XLEN bits of the element.
6559       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6560 
6561       // To extract the upper XLEN bits of the vector element, shift the first
6562       // element right by 32 bits and re-extract the lower XLEN bits.
6563       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6564       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6565       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6566       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6567                                        DAG.getConstant(32, DL, XLenVT), VL);
6568       SDValue LShr32 =
6569           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6570       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6571 
6572       Results.push_back(
6573           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6574       break;
6575     }
6576     }
6577     break;
6578   }
6579   case ISD::VECREDUCE_ADD:
6580   case ISD::VECREDUCE_AND:
6581   case ISD::VECREDUCE_OR:
6582   case ISD::VECREDUCE_XOR:
6583   case ISD::VECREDUCE_SMAX:
6584   case ISD::VECREDUCE_UMAX:
6585   case ISD::VECREDUCE_SMIN:
6586   case ISD::VECREDUCE_UMIN:
6587     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6588       Results.push_back(V);
6589     break;
6590   case ISD::VP_REDUCE_ADD:
6591   case ISD::VP_REDUCE_AND:
6592   case ISD::VP_REDUCE_OR:
6593   case ISD::VP_REDUCE_XOR:
6594   case ISD::VP_REDUCE_SMAX:
6595   case ISD::VP_REDUCE_UMAX:
6596   case ISD::VP_REDUCE_SMIN:
6597   case ISD::VP_REDUCE_UMIN:
6598     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6599       Results.push_back(V);
6600     break;
6601   case ISD::FLT_ROUNDS_: {
6602     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6603     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6604     Results.push_back(Res.getValue(0));
6605     Results.push_back(Res.getValue(1));
6606     break;
6607   }
6608   }
6609 }
6610 
6611 // A structure to hold one of the bit-manipulation patterns below. Together, a
6612 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6613 //   (or (and (shl x, 1), 0xAAAAAAAA),
6614 //       (and (srl x, 1), 0x55555555))
6615 struct RISCVBitmanipPat {
6616   SDValue Op;
6617   unsigned ShAmt;
6618   bool IsSHL;
6619 
6620   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6621     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6622   }
6623 };
6624 
6625 // Matches patterns of the form
6626 //   (and (shl x, C2), (C1 << C2))
6627 //   (and (srl x, C2), C1)
6628 //   (shl (and x, C1), C2)
6629 //   (srl (and x, (C1 << C2)), C2)
6630 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6631 // The expected masks for each shift amount are specified in BitmanipMasks where
6632 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6633 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6634 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6635 // XLen is 64.
6636 static Optional<RISCVBitmanipPat>
6637 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6638   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6639          "Unexpected number of masks");
6640   Optional<uint64_t> Mask;
6641   // Optionally consume a mask around the shift operation.
6642   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6643     Mask = Op.getConstantOperandVal(1);
6644     Op = Op.getOperand(0);
6645   }
6646   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6647     return None;
6648   bool IsSHL = Op.getOpcode() == ISD::SHL;
6649 
6650   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6651     return None;
6652   uint64_t ShAmt = Op.getConstantOperandVal(1);
6653 
6654   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6655   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6656     return None;
6657   // If we don't have enough masks for 64 bit, then we must be trying to
6658   // match SHFL so we're only allowed to shift 1/4 of the width.
6659   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6660     return None;
6661 
6662   SDValue Src = Op.getOperand(0);
6663 
6664   // The expected mask is shifted left when the AND is found around SHL
6665   // patterns.
6666   //   ((x >> 1) & 0x55555555)
6667   //   ((x << 1) & 0xAAAAAAAA)
6668   bool SHLExpMask = IsSHL;
6669 
6670   if (!Mask) {
6671     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6672     // the mask is all ones: consume that now.
6673     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6674       Mask = Src.getConstantOperandVal(1);
6675       Src = Src.getOperand(0);
6676       // The expected mask is now in fact shifted left for SRL, so reverse the
6677       // decision.
6678       //   ((x & 0xAAAAAAAA) >> 1)
6679       //   ((x & 0x55555555) << 1)
6680       SHLExpMask = !SHLExpMask;
6681     } else {
6682       // Use a default shifted mask of all-ones if there's no AND, truncated
6683       // down to the expected width. This simplifies the logic later on.
6684       Mask = maskTrailingOnes<uint64_t>(Width);
6685       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6686     }
6687   }
6688 
6689   unsigned MaskIdx = Log2_32(ShAmt);
6690   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6691 
6692   if (SHLExpMask)
6693     ExpMask <<= ShAmt;
6694 
6695   if (Mask != ExpMask)
6696     return None;
6697 
6698   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6699 }
6700 
6701 // Matches any of the following bit-manipulation patterns:
6702 //   (and (shl x, 1), (0x55555555 << 1))
6703 //   (and (srl x, 1), 0x55555555)
6704 //   (shl (and x, 0x55555555), 1)
6705 //   (srl (and x, (0x55555555 << 1)), 1)
6706 // where the shift amount and mask may vary thus:
6707 //   [1]  = 0x55555555 / 0xAAAAAAAA
6708 //   [2]  = 0x33333333 / 0xCCCCCCCC
6709 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6710 //   [8]  = 0x00FF00FF / 0xFF00FF00
6711 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6712 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6713 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6714   // These are the unshifted masks which we use to match bit-manipulation
6715   // patterns. They may be shifted left in certain circumstances.
6716   static const uint64_t BitmanipMasks[] = {
6717       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6718       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6719 
6720   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6721 }
6722 
6723 // Match the following pattern as a GREVI(W) operation
6724 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6725 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6726                                const RISCVSubtarget &Subtarget) {
6727   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6728   EVT VT = Op.getValueType();
6729 
6730   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6731     auto LHS = matchGREVIPat(Op.getOperand(0));
6732     auto RHS = matchGREVIPat(Op.getOperand(1));
6733     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6734       SDLoc DL(Op);
6735       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6736                          DAG.getConstant(LHS->ShAmt, DL, VT));
6737     }
6738   }
6739   return SDValue();
6740 }
6741 
6742 // Matches any the following pattern as a GORCI(W) operation
6743 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6744 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6745 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6746 // Note that with the variant of 3.,
6747 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6748 // the inner pattern will first be matched as GREVI and then the outer
6749 // pattern will be matched to GORC via the first rule above.
6750 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6751 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6752                                const RISCVSubtarget &Subtarget) {
6753   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6754   EVT VT = Op.getValueType();
6755 
6756   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6757     SDLoc DL(Op);
6758     SDValue Op0 = Op.getOperand(0);
6759     SDValue Op1 = Op.getOperand(1);
6760 
6761     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6762       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6763           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6764           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6765         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6766       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6767       if ((Reverse.getOpcode() == ISD::ROTL ||
6768            Reverse.getOpcode() == ISD::ROTR) &&
6769           Reverse.getOperand(0) == X &&
6770           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6771         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6772         if (RotAmt == (VT.getSizeInBits() / 2))
6773           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6774                              DAG.getConstant(RotAmt, DL, VT));
6775       }
6776       return SDValue();
6777     };
6778 
6779     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6780     if (SDValue V = MatchOROfReverse(Op0, Op1))
6781       return V;
6782     if (SDValue V = MatchOROfReverse(Op1, Op0))
6783       return V;
6784 
6785     // OR is commutable so canonicalize its OR operand to the left
6786     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6787       std::swap(Op0, Op1);
6788     if (Op0.getOpcode() != ISD::OR)
6789       return SDValue();
6790     SDValue OrOp0 = Op0.getOperand(0);
6791     SDValue OrOp1 = Op0.getOperand(1);
6792     auto LHS = matchGREVIPat(OrOp0);
6793     // OR is commutable so swap the operands and try again: x might have been
6794     // on the left
6795     if (!LHS) {
6796       std::swap(OrOp0, OrOp1);
6797       LHS = matchGREVIPat(OrOp0);
6798     }
6799     auto RHS = matchGREVIPat(Op1);
6800     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6801       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6802                          DAG.getConstant(LHS->ShAmt, DL, VT));
6803     }
6804   }
6805   return SDValue();
6806 }
6807 
6808 // Matches any of the following bit-manipulation patterns:
6809 //   (and (shl x, 1), (0x22222222 << 1))
6810 //   (and (srl x, 1), 0x22222222)
6811 //   (shl (and x, 0x22222222), 1)
6812 //   (srl (and x, (0x22222222 << 1)), 1)
6813 // where the shift amount and mask may vary thus:
6814 //   [1]  = 0x22222222 / 0x44444444
6815 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6816 //   [4]  = 0x00F000F0 / 0x0F000F00
6817 //   [8]  = 0x0000FF00 / 0x00FF0000
6818 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6819 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6820   // These are the unshifted masks which we use to match bit-manipulation
6821   // patterns. They may be shifted left in certain circumstances.
6822   static const uint64_t BitmanipMasks[] = {
6823       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6824       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6825 
6826   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6827 }
6828 
6829 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6830 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6831                                const RISCVSubtarget &Subtarget) {
6832   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6833   EVT VT = Op.getValueType();
6834 
6835   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6836     return SDValue();
6837 
6838   SDValue Op0 = Op.getOperand(0);
6839   SDValue Op1 = Op.getOperand(1);
6840 
6841   // Or is commutable so canonicalize the second OR to the LHS.
6842   if (Op0.getOpcode() != ISD::OR)
6843     std::swap(Op0, Op1);
6844   if (Op0.getOpcode() != ISD::OR)
6845     return SDValue();
6846 
6847   // We found an inner OR, so our operands are the operands of the inner OR
6848   // and the other operand of the outer OR.
6849   SDValue A = Op0.getOperand(0);
6850   SDValue B = Op0.getOperand(1);
6851   SDValue C = Op1;
6852 
6853   auto Match1 = matchSHFLPat(A);
6854   auto Match2 = matchSHFLPat(B);
6855 
6856   // If neither matched, we failed.
6857   if (!Match1 && !Match2)
6858     return SDValue();
6859 
6860   // We had at least one match. if one failed, try the remaining C operand.
6861   if (!Match1) {
6862     std::swap(A, C);
6863     Match1 = matchSHFLPat(A);
6864     if (!Match1)
6865       return SDValue();
6866   } else if (!Match2) {
6867     std::swap(B, C);
6868     Match2 = matchSHFLPat(B);
6869     if (!Match2)
6870       return SDValue();
6871   }
6872   assert(Match1 && Match2);
6873 
6874   // Make sure our matches pair up.
6875   if (!Match1->formsPairWith(*Match2))
6876     return SDValue();
6877 
6878   // All the remains is to make sure C is an AND with the same input, that masks
6879   // out the bits that are being shuffled.
6880   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6881       C.getOperand(0) != Match1->Op)
6882     return SDValue();
6883 
6884   uint64_t Mask = C.getConstantOperandVal(1);
6885 
6886   static const uint64_t BitmanipMasks[] = {
6887       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6888       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6889   };
6890 
6891   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6892   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6893   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6894 
6895   if (Mask != ExpMask)
6896     return SDValue();
6897 
6898   SDLoc DL(Op);
6899   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6900                      DAG.getConstant(Match1->ShAmt, DL, VT));
6901 }
6902 
6903 // Optimize (add (shl x, c0), (shl y, c1)) ->
6904 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6905 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6906                                   const RISCVSubtarget &Subtarget) {
6907   // Perform this optimization only in the zba extension.
6908   if (!Subtarget.hasStdExtZba())
6909     return SDValue();
6910 
6911   // Skip for vector types and larger types.
6912   EVT VT = N->getValueType(0);
6913   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6914     return SDValue();
6915 
6916   // The two operand nodes must be SHL and have no other use.
6917   SDValue N0 = N->getOperand(0);
6918   SDValue N1 = N->getOperand(1);
6919   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6920       !N0->hasOneUse() || !N1->hasOneUse())
6921     return SDValue();
6922 
6923   // Check c0 and c1.
6924   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6925   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6926   if (!N0C || !N1C)
6927     return SDValue();
6928   int64_t C0 = N0C->getSExtValue();
6929   int64_t C1 = N1C->getSExtValue();
6930   if (C0 <= 0 || C1 <= 0)
6931     return SDValue();
6932 
6933   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6934   int64_t Bits = std::min(C0, C1);
6935   int64_t Diff = std::abs(C0 - C1);
6936   if (Diff != 1 && Diff != 2 && Diff != 3)
6937     return SDValue();
6938 
6939   // Build nodes.
6940   SDLoc DL(N);
6941   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6942   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6943   SDValue NA0 =
6944       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6945   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6946   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6947 }
6948 
6949 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6950 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6951 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6952 // not undo itself, but they are redundant.
6953 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6954   SDValue Src = N->getOperand(0);
6955 
6956   if (Src.getOpcode() != N->getOpcode())
6957     return SDValue();
6958 
6959   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6960       !isa<ConstantSDNode>(Src.getOperand(1)))
6961     return SDValue();
6962 
6963   unsigned ShAmt1 = N->getConstantOperandVal(1);
6964   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6965   Src = Src.getOperand(0);
6966 
6967   unsigned CombinedShAmt;
6968   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6969     CombinedShAmt = ShAmt1 | ShAmt2;
6970   else
6971     CombinedShAmt = ShAmt1 ^ ShAmt2;
6972 
6973   if (CombinedShAmt == 0)
6974     return Src;
6975 
6976   SDLoc DL(N);
6977   return DAG.getNode(
6978       N->getOpcode(), DL, N->getValueType(0), Src,
6979       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6980 }
6981 
6982 // Combine a constant select operand into its use:
6983 //
6984 // (and (select cond, -1, c), x)
6985 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6986 // (or  (select cond, 0, c), x)
6987 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6988 // (xor (select cond, 0, c), x)
6989 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6990 // (add (select cond, 0, c), x)
6991 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6992 // (sub x, (select cond, 0, c))
6993 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6994 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6995                                    SelectionDAG &DAG, bool AllOnes) {
6996   EVT VT = N->getValueType(0);
6997 
6998   // Skip vectors.
6999   if (VT.isVector())
7000     return SDValue();
7001 
7002   if ((Slct.getOpcode() != ISD::SELECT &&
7003        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7004       !Slct.hasOneUse())
7005     return SDValue();
7006 
7007   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7008     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7009   };
7010 
7011   bool SwapSelectOps;
7012   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7013   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7014   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7015   SDValue NonConstantVal;
7016   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7017     SwapSelectOps = false;
7018     NonConstantVal = FalseVal;
7019   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7020     SwapSelectOps = true;
7021     NonConstantVal = TrueVal;
7022   } else
7023     return SDValue();
7024 
7025   // Slct is now know to be the desired identity constant when CC is true.
7026   TrueVal = OtherOp;
7027   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7028   // Unless SwapSelectOps says the condition should be false.
7029   if (SwapSelectOps)
7030     std::swap(TrueVal, FalseVal);
7031 
7032   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7033     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7034                        {Slct.getOperand(0), Slct.getOperand(1),
7035                         Slct.getOperand(2), TrueVal, FalseVal});
7036 
7037   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7038                      {Slct.getOperand(0), TrueVal, FalseVal});
7039 }
7040 
7041 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7042 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7043                                               bool AllOnes) {
7044   SDValue N0 = N->getOperand(0);
7045   SDValue N1 = N->getOperand(1);
7046   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7047     return Result;
7048   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7049     return Result;
7050   return SDValue();
7051 }
7052 
7053 // Transform (add (mul x, c0), c1) ->
7054 //           (add (mul (add x, c1/c0), c0), c1%c0).
7055 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7056 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7057 // to an infinite loop in DAGCombine if transformed.
7058 // Or transform (add (mul x, c0), c1) ->
7059 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7060 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7061 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7062 // lead to an infinite loop in DAGCombine if transformed.
7063 // Or transform (add (mul x, c0), c1) ->
7064 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7065 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7066 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7067 // lead to an infinite loop in DAGCombine if transformed.
7068 // Or transform (add (mul x, c0), c1) ->
7069 //              (mul (add x, c1/c0), c0).
7070 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7071 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7072                                      const RISCVSubtarget &Subtarget) {
7073   // Skip for vector types and larger types.
7074   EVT VT = N->getValueType(0);
7075   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7076     return SDValue();
7077   // The first operand node must be a MUL and has no other use.
7078   SDValue N0 = N->getOperand(0);
7079   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7080     return SDValue();
7081   // Check if c0 and c1 match above conditions.
7082   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7083   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7084   if (!N0C || !N1C)
7085     return SDValue();
7086   int64_t C0 = N0C->getSExtValue();
7087   int64_t C1 = N1C->getSExtValue();
7088   int64_t CA, CB;
7089   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7090     return SDValue();
7091   // Search for proper CA (non-zero) and CB that both are simm12.
7092   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7093       !isInt<12>(C0 * (C1 / C0))) {
7094     CA = C1 / C0;
7095     CB = C1 % C0;
7096   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7097              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7098     CA = C1 / C0 + 1;
7099     CB = C1 % C0 - C0;
7100   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7101              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7102     CA = C1 / C0 - 1;
7103     CB = C1 % C0 + C0;
7104   } else
7105     return SDValue();
7106   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7107   SDLoc DL(N);
7108   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7109                              DAG.getConstant(CA, DL, VT));
7110   SDValue New1 =
7111       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7112   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7113 }
7114 
7115 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7116                                  const RISCVSubtarget &Subtarget) {
7117   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7118     return V;
7119   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7120     return V;
7121   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7122   //      (select lhs, rhs, cc, x, (add x, y))
7123   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7124 }
7125 
7126 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7127   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7128   //      (select lhs, rhs, cc, x, (sub x, y))
7129   SDValue N0 = N->getOperand(0);
7130   SDValue N1 = N->getOperand(1);
7131   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7132 }
7133 
7134 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7135   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7136   //      (select lhs, rhs, cc, x, (and x, y))
7137   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7138 }
7139 
7140 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7141                                 const RISCVSubtarget &Subtarget) {
7142   if (Subtarget.hasStdExtZbp()) {
7143     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7144       return GREV;
7145     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7146       return GORC;
7147     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7148       return SHFL;
7149   }
7150 
7151   // fold (or (select cond, 0, y), x) ->
7152   //      (select cond, x, (or x, y))
7153   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7154 }
7155 
7156 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7157   // fold (xor (select cond, 0, y), x) ->
7158   //      (select cond, x, (xor x, y))
7159   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7160 }
7161 
7162 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7163 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7164 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7165 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7166 // ADDW/SUBW/MULW.
7167 static SDValue performANY_EXTENDCombine(SDNode *N,
7168                                         TargetLowering::DAGCombinerInfo &DCI,
7169                                         const RISCVSubtarget &Subtarget) {
7170   if (!Subtarget.is64Bit())
7171     return SDValue();
7172 
7173   SelectionDAG &DAG = DCI.DAG;
7174 
7175   SDValue Src = N->getOperand(0);
7176   EVT VT = N->getValueType(0);
7177   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7178     return SDValue();
7179 
7180   // The opcode must be one that can implicitly sign_extend.
7181   // FIXME: Additional opcodes.
7182   switch (Src.getOpcode()) {
7183   default:
7184     return SDValue();
7185   case ISD::MUL:
7186     if (!Subtarget.hasStdExtM())
7187       return SDValue();
7188     LLVM_FALLTHROUGH;
7189   case ISD::ADD:
7190   case ISD::SUB:
7191     break;
7192   }
7193 
7194   // Only handle cases where the result is used by a CopyToReg. That likely
7195   // means the value is a liveout of the basic block. This helps prevent
7196   // infinite combine loops like PR51206.
7197   if (none_of(N->uses(),
7198               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7199     return SDValue();
7200 
7201   SmallVector<SDNode *, 4> SetCCs;
7202   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7203                             UE = Src.getNode()->use_end();
7204        UI != UE; ++UI) {
7205     SDNode *User = *UI;
7206     if (User == N)
7207       continue;
7208     if (UI.getUse().getResNo() != Src.getResNo())
7209       continue;
7210     // All i32 setccs are legalized by sign extending operands.
7211     if (User->getOpcode() == ISD::SETCC) {
7212       SetCCs.push_back(User);
7213       continue;
7214     }
7215     // We don't know if we can extend this user.
7216     break;
7217   }
7218 
7219   // If we don't have any SetCCs, this isn't worthwhile.
7220   if (SetCCs.empty())
7221     return SDValue();
7222 
7223   SDLoc DL(N);
7224   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7225   DCI.CombineTo(N, SExt);
7226 
7227   // Promote all the setccs.
7228   for (SDNode *SetCC : SetCCs) {
7229     SmallVector<SDValue, 4> Ops;
7230 
7231     for (unsigned j = 0; j != 2; ++j) {
7232       SDValue SOp = SetCC->getOperand(j);
7233       if (SOp == Src)
7234         Ops.push_back(SExt);
7235       else
7236         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7237     }
7238 
7239     Ops.push_back(SetCC->getOperand(2));
7240     DCI.CombineTo(SetCC,
7241                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7242   }
7243   return SDValue(N, 0);
7244 }
7245 
7246 // Try to form VWMUL or VWMULU.
7247 // FIXME: Support VWMULSU.
7248 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7249                                        bool Commute) {
7250   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7251   SDValue Op0 = N->getOperand(0);
7252   SDValue Op1 = N->getOperand(1);
7253   if (Commute)
7254     std::swap(Op0, Op1);
7255 
7256   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7257   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7258   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7259     return SDValue();
7260 
7261   SDValue Mask = N->getOperand(2);
7262   SDValue VL = N->getOperand(3);
7263 
7264   // Make sure the mask and VL match.
7265   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7266     return SDValue();
7267 
7268   MVT VT = N->getSimpleValueType(0);
7269 
7270   // Determine the narrow size for a widening multiply.
7271   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7272   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7273                                   VT.getVectorElementCount());
7274 
7275   SDLoc DL(N);
7276 
7277   // See if the other operand is the same opcode.
7278   if (Op0.getOpcode() == Op1.getOpcode()) {
7279     if (!Op1.hasOneUse())
7280       return SDValue();
7281 
7282     // Make sure the mask and VL match.
7283     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7284       return SDValue();
7285 
7286     Op1 = Op1.getOperand(0);
7287   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7288     // The operand is a splat of a scalar.
7289 
7290     // The VL must be the same.
7291     if (Op1.getOperand(1) != VL)
7292       return SDValue();
7293 
7294     // Get the scalar value.
7295     Op1 = Op1.getOperand(0);
7296 
7297     // See if have enough sign bits or zero bits in the scalar to use a
7298     // widening multiply by splatting to smaller element size.
7299     unsigned EltBits = VT.getScalarSizeInBits();
7300     unsigned ScalarBits = Op1.getValueSizeInBits();
7301     // Make sure we're getting all element bits from the scalar register.
7302     // FIXME: Support implicit sign extension of vmv.v.x?
7303     if (ScalarBits < EltBits)
7304       return SDValue();
7305 
7306     if (IsSignExt) {
7307       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7308         return SDValue();
7309     } else {
7310       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7311       if (!DAG.MaskedValueIsZero(Op1, Mask))
7312         return SDValue();
7313     }
7314 
7315     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7316   } else
7317     return SDValue();
7318 
7319   Op0 = Op0.getOperand(0);
7320 
7321   // Re-introduce narrower extends if needed.
7322   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7323   if (Op0.getValueType() != NarrowVT)
7324     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7325   if (Op1.getValueType() != NarrowVT)
7326     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7327 
7328   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7329   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7330 }
7331 
7332 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7333   switch (Op.getOpcode()) {
7334   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7335   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7336   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7337   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7338   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7339   }
7340 
7341   return RISCVFPRndMode::Invalid;
7342 }
7343 
7344 // Fold
7345 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7346 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7347 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7348 //   (fp_to_int (fceil X))      -> fcvt X, rup
7349 //   (fp_to_int (fround X))     -> fcvt X, rmm
7350 static SDValue performFP_TO_INTCombine(SDNode *N,
7351                                        TargetLowering::DAGCombinerInfo &DCI,
7352                                        const RISCVSubtarget &Subtarget) {
7353   SelectionDAG &DAG = DCI.DAG;
7354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7355   MVT XLenVT = Subtarget.getXLenVT();
7356 
7357   // Only handle XLen or i32 types. Other types narrower than XLen will
7358   // eventually be legalized to XLenVT.
7359   EVT VT = N->getValueType(0);
7360   if (VT != MVT::i32 && VT != XLenVT)
7361     return SDValue();
7362 
7363   SDValue Src = N->getOperand(0);
7364 
7365   // Ensure the FP type is also legal.
7366   if (!TLI.isTypeLegal(Src.getValueType()))
7367     return SDValue();
7368 
7369   // Don't do this for f16 with Zfhmin and not Zfh.
7370   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7371     return SDValue();
7372 
7373   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7374   if (FRM == RISCVFPRndMode::Invalid)
7375     return SDValue();
7376 
7377   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7378 
7379   unsigned Opc;
7380   if (VT == XLenVT)
7381     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7382   else
7383     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7384 
7385   SDLoc DL(N);
7386   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7387                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7388   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7389 }
7390 
7391 // Fold
7392 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7393 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7394 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7395 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7396 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7397 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7398                                        TargetLowering::DAGCombinerInfo &DCI,
7399                                        const RISCVSubtarget &Subtarget) {
7400   SelectionDAG &DAG = DCI.DAG;
7401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7402   MVT XLenVT = Subtarget.getXLenVT();
7403 
7404   // Only handle XLen types. Other types narrower than XLen will eventually be
7405   // legalized to XLenVT.
7406   EVT DstVT = N->getValueType(0);
7407   if (DstVT != XLenVT)
7408     return SDValue();
7409 
7410   SDValue Src = N->getOperand(0);
7411 
7412   // Ensure the FP type is also legal.
7413   if (!TLI.isTypeLegal(Src.getValueType()))
7414     return SDValue();
7415 
7416   // Don't do this for f16 with Zfhmin and not Zfh.
7417   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7418     return SDValue();
7419 
7420   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7421 
7422   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7423   if (FRM == RISCVFPRndMode::Invalid)
7424     return SDValue();
7425 
7426   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7427 
7428   unsigned Opc;
7429   if (SatVT == DstVT)
7430     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7431   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7432     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7433   else
7434     return SDValue();
7435   // FIXME: Support other SatVTs by clamping before or after the conversion.
7436 
7437   Src = Src.getOperand(0);
7438 
7439   SDLoc DL(N);
7440   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7441                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7442 
7443   // RISCV FP-to-int conversions saturate to the destination register size, but
7444   // don't produce 0 for nan.
7445   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7446   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7447 }
7448 
7449 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7450                                                DAGCombinerInfo &DCI) const {
7451   SelectionDAG &DAG = DCI.DAG;
7452 
7453   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7454   // bits are demanded. N will be added to the Worklist if it was not deleted.
7455   // Caller should return SDValue(N, 0) if this returns true.
7456   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7457     SDValue Op = N->getOperand(OpNo);
7458     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7459     if (!SimplifyDemandedBits(Op, Mask, DCI))
7460       return false;
7461 
7462     if (N->getOpcode() != ISD::DELETED_NODE)
7463       DCI.AddToWorklist(N);
7464     return true;
7465   };
7466 
7467   switch (N->getOpcode()) {
7468   default:
7469     break;
7470   case RISCVISD::SplitF64: {
7471     SDValue Op0 = N->getOperand(0);
7472     // If the input to SplitF64 is just BuildPairF64 then the operation is
7473     // redundant. Instead, use BuildPairF64's operands directly.
7474     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7475       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7476 
7477     SDLoc DL(N);
7478 
7479     // It's cheaper to materialise two 32-bit integers than to load a double
7480     // from the constant pool and transfer it to integer registers through the
7481     // stack.
7482     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7483       APInt V = C->getValueAPF().bitcastToAPInt();
7484       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7485       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7486       return DCI.CombineTo(N, Lo, Hi);
7487     }
7488 
7489     // This is a target-specific version of a DAGCombine performed in
7490     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7491     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7492     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7493     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7494         !Op0.getNode()->hasOneUse())
7495       break;
7496     SDValue NewSplitF64 =
7497         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7498                     Op0.getOperand(0));
7499     SDValue Lo = NewSplitF64.getValue(0);
7500     SDValue Hi = NewSplitF64.getValue(1);
7501     APInt SignBit = APInt::getSignMask(32);
7502     if (Op0.getOpcode() == ISD::FNEG) {
7503       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7504                                   DAG.getConstant(SignBit, DL, MVT::i32));
7505       return DCI.CombineTo(N, Lo, NewHi);
7506     }
7507     assert(Op0.getOpcode() == ISD::FABS);
7508     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7509                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7510     return DCI.CombineTo(N, Lo, NewHi);
7511   }
7512   case RISCVISD::SLLW:
7513   case RISCVISD::SRAW:
7514   case RISCVISD::SRLW:
7515   case RISCVISD::ROLW:
7516   case RISCVISD::RORW: {
7517     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7518     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7519         SimplifyDemandedLowBitsHelper(1, 5))
7520       return SDValue(N, 0);
7521     break;
7522   }
7523   case RISCVISD::CLZW:
7524   case RISCVISD::CTZW: {
7525     // Only the lower 32 bits of the first operand are read
7526     if (SimplifyDemandedLowBitsHelper(0, 32))
7527       return SDValue(N, 0);
7528     break;
7529   }
7530   case RISCVISD::GREV:
7531   case RISCVISD::GORC: {
7532     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7533     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7534     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7535     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7536       return SDValue(N, 0);
7537 
7538     return combineGREVI_GORCI(N, DAG);
7539   }
7540   case RISCVISD::GREVW:
7541   case RISCVISD::GORCW: {
7542     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7543     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7544         SimplifyDemandedLowBitsHelper(1, 5))
7545       return SDValue(N, 0);
7546 
7547     return combineGREVI_GORCI(N, DAG);
7548   }
7549   case RISCVISD::SHFL:
7550   case RISCVISD::UNSHFL: {
7551     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7552     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7553     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7554     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7555       return SDValue(N, 0);
7556 
7557     break;
7558   }
7559   case RISCVISD::SHFLW:
7560   case RISCVISD::UNSHFLW: {
7561     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7562     SDValue LHS = N->getOperand(0);
7563     SDValue RHS = N->getOperand(1);
7564     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7565     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7566     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7567         SimplifyDemandedLowBitsHelper(1, 4))
7568       return SDValue(N, 0);
7569 
7570     break;
7571   }
7572   case RISCVISD::BCOMPRESSW:
7573   case RISCVISD::BDECOMPRESSW: {
7574     // Only the lower 32 bits of LHS and RHS are read.
7575     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7576         SimplifyDemandedLowBitsHelper(1, 32))
7577       return SDValue(N, 0);
7578 
7579     break;
7580   }
7581   case RISCVISD::FMV_X_ANYEXTH:
7582   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7583     SDLoc DL(N);
7584     SDValue Op0 = N->getOperand(0);
7585     MVT VT = N->getSimpleValueType(0);
7586     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7587     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7588     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7589     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7590          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7591         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7592          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7593       assert(Op0.getOperand(0).getValueType() == VT &&
7594              "Unexpected value type!");
7595       return Op0.getOperand(0);
7596     }
7597 
7598     // This is a target-specific version of a DAGCombine performed in
7599     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7600     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7601     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7602     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7603         !Op0.getNode()->hasOneUse())
7604       break;
7605     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7606     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7607     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7608     if (Op0.getOpcode() == ISD::FNEG)
7609       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7610                          DAG.getConstant(SignBit, DL, VT));
7611 
7612     assert(Op0.getOpcode() == ISD::FABS);
7613     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7614                        DAG.getConstant(~SignBit, DL, VT));
7615   }
7616   case ISD::ADD:
7617     return performADDCombine(N, DAG, Subtarget);
7618   case ISD::SUB:
7619     return performSUBCombine(N, DAG);
7620   case ISD::AND:
7621     return performANDCombine(N, DAG);
7622   case ISD::OR:
7623     return performORCombine(N, DAG, Subtarget);
7624   case ISD::XOR:
7625     return performXORCombine(N, DAG);
7626   case ISD::ANY_EXTEND:
7627     return performANY_EXTENDCombine(N, DCI, Subtarget);
7628   case ISD::ZERO_EXTEND:
7629     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7630     // type legalization. This is safe because fp_to_uint produces poison if
7631     // it overflows.
7632     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7633       SDValue Src = N->getOperand(0);
7634       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7635           isTypeLegal(Src.getOperand(0).getValueType()))
7636         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7637                            Src.getOperand(0));
7638       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7639           isTypeLegal(Src.getOperand(1).getValueType())) {
7640         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7641         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7642                                   Src.getOperand(0), Src.getOperand(1));
7643         DCI.CombineTo(N, Res);
7644         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7645         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7646         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7647       }
7648     }
7649     return SDValue();
7650   case RISCVISD::SELECT_CC: {
7651     // Transform
7652     SDValue LHS = N->getOperand(0);
7653     SDValue RHS = N->getOperand(1);
7654     SDValue TrueV = N->getOperand(3);
7655     SDValue FalseV = N->getOperand(4);
7656 
7657     // If the True and False values are the same, we don't need a select_cc.
7658     if (TrueV == FalseV)
7659       return TrueV;
7660 
7661     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7662     if (!ISD::isIntEqualitySetCC(CCVal))
7663       break;
7664 
7665     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7666     //      (select_cc X, Y, lt, trueV, falseV)
7667     // Sometimes the setcc is introduced after select_cc has been formed.
7668     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7669         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7670       // If we're looking for eq 0 instead of ne 0, we need to invert the
7671       // condition.
7672       bool Invert = CCVal == ISD::SETEQ;
7673       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7674       if (Invert)
7675         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7676 
7677       SDLoc DL(N);
7678       RHS = LHS.getOperand(1);
7679       LHS = LHS.getOperand(0);
7680       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7681 
7682       SDValue TargetCC = DAG.getCondCode(CCVal);
7683       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7684                          {LHS, RHS, TargetCC, TrueV, FalseV});
7685     }
7686 
7687     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7688     //      (select_cc X, Y, eq/ne, trueV, falseV)
7689     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7690       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7691                          {LHS.getOperand(0), LHS.getOperand(1),
7692                           N->getOperand(2), TrueV, FalseV});
7693     // (select_cc X, 1, setne, trueV, falseV) ->
7694     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7695     // This can occur when legalizing some floating point comparisons.
7696     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7697     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7698       SDLoc DL(N);
7699       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7700       SDValue TargetCC = DAG.getCondCode(CCVal);
7701       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7702       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7703                          {LHS, RHS, TargetCC, TrueV, FalseV});
7704     }
7705 
7706     break;
7707   }
7708   case RISCVISD::BR_CC: {
7709     SDValue LHS = N->getOperand(1);
7710     SDValue RHS = N->getOperand(2);
7711     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7712     if (!ISD::isIntEqualitySetCC(CCVal))
7713       break;
7714 
7715     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7716     //      (br_cc X, Y, lt, dest)
7717     // Sometimes the setcc is introduced after br_cc has been formed.
7718     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7719         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7720       // If we're looking for eq 0 instead of ne 0, we need to invert the
7721       // condition.
7722       bool Invert = CCVal == ISD::SETEQ;
7723       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7724       if (Invert)
7725         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7726 
7727       SDLoc DL(N);
7728       RHS = LHS.getOperand(1);
7729       LHS = LHS.getOperand(0);
7730       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7731 
7732       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7733                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7734                          N->getOperand(4));
7735     }
7736 
7737     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7738     //      (br_cc X, Y, eq/ne, trueV, falseV)
7739     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7740       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7741                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7742                          N->getOperand(3), N->getOperand(4));
7743 
7744     // (br_cc X, 1, setne, br_cc) ->
7745     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7746     // This can occur when legalizing some floating point comparisons.
7747     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7748     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7749       SDLoc DL(N);
7750       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7751       SDValue TargetCC = DAG.getCondCode(CCVal);
7752       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7753       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7754                          N->getOperand(0), LHS, RHS, TargetCC,
7755                          N->getOperand(4));
7756     }
7757     break;
7758   }
7759   case ISD::FP_TO_SINT:
7760   case ISD::FP_TO_UINT:
7761     return performFP_TO_INTCombine(N, DCI, Subtarget);
7762   case ISD::FP_TO_SINT_SAT:
7763   case ISD::FP_TO_UINT_SAT:
7764     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7765   case ISD::FCOPYSIGN: {
7766     EVT VT = N->getValueType(0);
7767     if (!VT.isVector())
7768       break;
7769     // There is a form of VFSGNJ which injects the negated sign of its second
7770     // operand. Try and bubble any FNEG up after the extend/round to produce
7771     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7772     // TRUNC=1.
7773     SDValue In2 = N->getOperand(1);
7774     // Avoid cases where the extend/round has multiple uses, as duplicating
7775     // those is typically more expensive than removing a fneg.
7776     if (!In2.hasOneUse())
7777       break;
7778     if (In2.getOpcode() != ISD::FP_EXTEND &&
7779         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7780       break;
7781     In2 = In2.getOperand(0);
7782     if (In2.getOpcode() != ISD::FNEG)
7783       break;
7784     SDLoc DL(N);
7785     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7786     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7787                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7788   }
7789   case ISD::MGATHER:
7790   case ISD::MSCATTER:
7791   case ISD::VP_GATHER:
7792   case ISD::VP_SCATTER: {
7793     if (!DCI.isBeforeLegalize())
7794       break;
7795     SDValue Index, ScaleOp;
7796     bool IsIndexScaled = false;
7797     bool IsIndexSigned = false;
7798     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7799       Index = VPGSN->getIndex();
7800       ScaleOp = VPGSN->getScale();
7801       IsIndexScaled = VPGSN->isIndexScaled();
7802       IsIndexSigned = VPGSN->isIndexSigned();
7803     } else {
7804       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7805       Index = MGSN->getIndex();
7806       ScaleOp = MGSN->getScale();
7807       IsIndexScaled = MGSN->isIndexScaled();
7808       IsIndexSigned = MGSN->isIndexSigned();
7809     }
7810     EVT IndexVT = Index.getValueType();
7811     MVT XLenVT = Subtarget.getXLenVT();
7812     // RISCV indexed loads only support the "unsigned unscaled" addressing
7813     // mode, so anything else must be manually legalized.
7814     bool NeedsIdxLegalization =
7815         IsIndexScaled ||
7816         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7817     if (!NeedsIdxLegalization)
7818       break;
7819 
7820     SDLoc DL(N);
7821 
7822     // Any index legalization should first promote to XLenVT, so we don't lose
7823     // bits when scaling. This may create an illegal index type so we let
7824     // LLVM's legalization take care of the splitting.
7825     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7826     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7827       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7828       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7829                           DL, IndexVT, Index);
7830     }
7831 
7832     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7833     if (IsIndexScaled && Scale != 1) {
7834       // Manually scale the indices by the element size.
7835       // TODO: Sanitize the scale operand here?
7836       // TODO: For VP nodes, should we use VP_SHL here?
7837       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7838       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7839       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7840     }
7841 
7842     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7843     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7844       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7845                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7846                               VPGN->getScale(), VPGN->getMask(),
7847                               VPGN->getVectorLength()},
7848                              VPGN->getMemOperand(), NewIndexTy);
7849     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7850       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7851                               {VPSN->getChain(), VPSN->getValue(),
7852                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7853                                VPSN->getMask(), VPSN->getVectorLength()},
7854                               VPSN->getMemOperand(), NewIndexTy);
7855     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7856       return DAG.getMaskedGather(
7857           N->getVTList(), MGN->getMemoryVT(), DL,
7858           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7859            MGN->getBasePtr(), Index, MGN->getScale()},
7860           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7861     const auto *MSN = cast<MaskedScatterSDNode>(N);
7862     return DAG.getMaskedScatter(
7863         N->getVTList(), MSN->getMemoryVT(), DL,
7864         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7865          Index, MSN->getScale()},
7866         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7867   }
7868   case RISCVISD::SRA_VL:
7869   case RISCVISD::SRL_VL:
7870   case RISCVISD::SHL_VL: {
7871     SDValue ShAmt = N->getOperand(1);
7872     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7873       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7874       SDLoc DL(N);
7875       SDValue VL = N->getOperand(3);
7876       EVT VT = N->getValueType(0);
7877       ShAmt =
7878           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7879       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7880                          N->getOperand(2), N->getOperand(3));
7881     }
7882     break;
7883   }
7884   case ISD::SRA:
7885   case ISD::SRL:
7886   case ISD::SHL: {
7887     SDValue ShAmt = N->getOperand(1);
7888     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7889       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7890       SDLoc DL(N);
7891       EVT VT = N->getValueType(0);
7892       ShAmt =
7893           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7894       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7895     }
7896     break;
7897   }
7898   case RISCVISD::MUL_VL:
7899     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
7900       return V;
7901     // Mul is commutative.
7902     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
7903   case ISD::STORE: {
7904     auto *Store = cast<StoreSDNode>(N);
7905     SDValue Val = Store->getValue();
7906     // Combine store of vmv.x.s to vse with VL of 1.
7907     // FIXME: Support FP.
7908     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7909       SDValue Src = Val.getOperand(0);
7910       EVT VecVT = Src.getValueType();
7911       EVT MemVT = Store->getMemoryVT();
7912       // The memory VT and the element type must match.
7913       if (VecVT.getVectorElementType() == MemVT) {
7914         SDLoc DL(N);
7915         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7916         return DAG.getStoreVP(
7917             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
7918             DAG.getConstant(1, DL, MaskVT),
7919             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
7920             Store->getMemOperand(), Store->getAddressingMode(),
7921             Store->isTruncatingStore(), /*IsCompress*/ false);
7922       }
7923     }
7924 
7925     break;
7926   }
7927   }
7928 
7929   return SDValue();
7930 }
7931 
7932 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7933     const SDNode *N, CombineLevel Level) const {
7934   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7935   // materialised in fewer instructions than `(OP _, c1)`:
7936   //
7937   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7938   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7939   SDValue N0 = N->getOperand(0);
7940   EVT Ty = N0.getValueType();
7941   if (Ty.isScalarInteger() &&
7942       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7943     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7944     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7945     if (C1 && C2) {
7946       const APInt &C1Int = C1->getAPIntValue();
7947       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7948 
7949       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7950       // and the combine should happen, to potentially allow further combines
7951       // later.
7952       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7953           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7954         return true;
7955 
7956       // We can materialise `c1` in an add immediate, so it's "free", and the
7957       // combine should be prevented.
7958       if (C1Int.getMinSignedBits() <= 64 &&
7959           isLegalAddImmediate(C1Int.getSExtValue()))
7960         return false;
7961 
7962       // Neither constant will fit into an immediate, so find materialisation
7963       // costs.
7964       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7965                                               Subtarget.getFeatureBits(),
7966                                               /*CompressionCost*/true);
7967       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7968           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7969           /*CompressionCost*/true);
7970 
7971       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7972       // combine should be prevented.
7973       if (C1Cost < ShiftedC1Cost)
7974         return false;
7975     }
7976   }
7977   return true;
7978 }
7979 
7980 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7981     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7982     TargetLoweringOpt &TLO) const {
7983   // Delay this optimization as late as possible.
7984   if (!TLO.LegalOps)
7985     return false;
7986 
7987   EVT VT = Op.getValueType();
7988   if (VT.isVector())
7989     return false;
7990 
7991   // Only handle AND for now.
7992   if (Op.getOpcode() != ISD::AND)
7993     return false;
7994 
7995   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7996   if (!C)
7997     return false;
7998 
7999   const APInt &Mask = C->getAPIntValue();
8000 
8001   // Clear all non-demanded bits initially.
8002   APInt ShrunkMask = Mask & DemandedBits;
8003 
8004   // Try to make a smaller immediate by setting undemanded bits.
8005 
8006   APInt ExpandedMask = Mask | ~DemandedBits;
8007 
8008   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8009     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8010   };
8011   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8012     if (NewMask == Mask)
8013       return true;
8014     SDLoc DL(Op);
8015     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8016     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8017     return TLO.CombineTo(Op, NewOp);
8018   };
8019 
8020   // If the shrunk mask fits in sign extended 12 bits, let the target
8021   // independent code apply it.
8022   if (ShrunkMask.isSignedIntN(12))
8023     return false;
8024 
8025   // Preserve (and X, 0xffff) when zext.h is supported.
8026   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8027     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8028     if (IsLegalMask(NewMask))
8029       return UseMask(NewMask);
8030   }
8031 
8032   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8033   if (VT == MVT::i64) {
8034     APInt NewMask = APInt(64, 0xffffffff);
8035     if (IsLegalMask(NewMask))
8036       return UseMask(NewMask);
8037   }
8038 
8039   // For the remaining optimizations, we need to be able to make a negative
8040   // number through a combination of mask and undemanded bits.
8041   if (!ExpandedMask.isNegative())
8042     return false;
8043 
8044   // What is the fewest number of bits we need to represent the negative number.
8045   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8046 
8047   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8048   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8049   APInt NewMask = ShrunkMask;
8050   if (MinSignedBits <= 12)
8051     NewMask.setBitsFrom(11);
8052   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8053     NewMask.setBitsFrom(31);
8054   else
8055     return false;
8056 
8057   // Check that our new mask is a subset of the demanded mask.
8058   assert(IsLegalMask(NewMask));
8059   return UseMask(NewMask);
8060 }
8061 
8062 static void computeGREV(APInt &Src, unsigned ShAmt) {
8063   ShAmt &= Src.getBitWidth() - 1;
8064   uint64_t x = Src.getZExtValue();
8065   if (ShAmt & 1)
8066     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8067   if (ShAmt & 2)
8068     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8069   if (ShAmt & 4)
8070     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8071   if (ShAmt & 8)
8072     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8073   if (ShAmt & 16)
8074     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8075   if (ShAmt & 32)
8076     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8077   Src = x;
8078 }
8079 
8080 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8081                                                         KnownBits &Known,
8082                                                         const APInt &DemandedElts,
8083                                                         const SelectionDAG &DAG,
8084                                                         unsigned Depth) const {
8085   unsigned BitWidth = Known.getBitWidth();
8086   unsigned Opc = Op.getOpcode();
8087   assert((Opc >= ISD::BUILTIN_OP_END ||
8088           Opc == ISD::INTRINSIC_WO_CHAIN ||
8089           Opc == ISD::INTRINSIC_W_CHAIN ||
8090           Opc == ISD::INTRINSIC_VOID) &&
8091          "Should use MaskedValueIsZero if you don't know whether Op"
8092          " is a target node!");
8093 
8094   Known.resetAll();
8095   switch (Opc) {
8096   default: break;
8097   case RISCVISD::SELECT_CC: {
8098     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8099     // If we don't know any bits, early out.
8100     if (Known.isUnknown())
8101       break;
8102     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8103 
8104     // Only known if known in both the LHS and RHS.
8105     Known = KnownBits::commonBits(Known, Known2);
8106     break;
8107   }
8108   case RISCVISD::REMUW: {
8109     KnownBits Known2;
8110     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8111     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8112     // We only care about the lower 32 bits.
8113     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8114     // Restore the original width by sign extending.
8115     Known = Known.sext(BitWidth);
8116     break;
8117   }
8118   case RISCVISD::DIVUW: {
8119     KnownBits Known2;
8120     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8121     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8122     // We only care about the lower 32 bits.
8123     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8124     // Restore the original width by sign extending.
8125     Known = Known.sext(BitWidth);
8126     break;
8127   }
8128   case RISCVISD::CTZW: {
8129     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8130     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8131     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8132     Known.Zero.setBitsFrom(LowBits);
8133     break;
8134   }
8135   case RISCVISD::CLZW: {
8136     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8137     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8138     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8139     Known.Zero.setBitsFrom(LowBits);
8140     break;
8141   }
8142   case RISCVISD::GREV:
8143   case RISCVISD::GREVW: {
8144     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8145       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8146       if (Opc == RISCVISD::GREVW)
8147         Known = Known.trunc(32);
8148       unsigned ShAmt = C->getZExtValue();
8149       computeGREV(Known.Zero, ShAmt);
8150       computeGREV(Known.One, ShAmt);
8151       if (Opc == RISCVISD::GREVW)
8152         Known = Known.sext(BitWidth);
8153     }
8154     break;
8155   }
8156   case RISCVISD::READ_VLENB:
8157     // We assume VLENB is at least 16 bytes.
8158     Known.Zero.setLowBits(4);
8159     // We assume VLENB is no more than 65536 / 8 bytes.
8160     Known.Zero.setBitsFrom(14);
8161     break;
8162   case ISD::INTRINSIC_W_CHAIN: {
8163     unsigned IntNo = Op.getConstantOperandVal(1);
8164     switch (IntNo) {
8165     default:
8166       // We can't do anything for most intrinsics.
8167       break;
8168     case Intrinsic::riscv_vsetvli:
8169     case Intrinsic::riscv_vsetvlimax:
8170       // Assume that VL output is positive and would fit in an int32_t.
8171       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8172       if (BitWidth >= 32)
8173         Known.Zero.setBitsFrom(31);
8174       break;
8175     }
8176     break;
8177   }
8178   }
8179 }
8180 
8181 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8182     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8183     unsigned Depth) const {
8184   switch (Op.getOpcode()) {
8185   default:
8186     break;
8187   case RISCVISD::SELECT_CC: {
8188     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8189     if (Tmp == 1) return 1;  // Early out.
8190     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8191     return std::min(Tmp, Tmp2);
8192   }
8193   case RISCVISD::SLLW:
8194   case RISCVISD::SRAW:
8195   case RISCVISD::SRLW:
8196   case RISCVISD::DIVW:
8197   case RISCVISD::DIVUW:
8198   case RISCVISD::REMUW:
8199   case RISCVISD::ROLW:
8200   case RISCVISD::RORW:
8201   case RISCVISD::GREVW:
8202   case RISCVISD::GORCW:
8203   case RISCVISD::FSLW:
8204   case RISCVISD::FSRW:
8205   case RISCVISD::SHFLW:
8206   case RISCVISD::UNSHFLW:
8207   case RISCVISD::BCOMPRESSW:
8208   case RISCVISD::BDECOMPRESSW:
8209   case RISCVISD::BFPW:
8210   case RISCVISD::FCVT_W_RV64:
8211   case RISCVISD::FCVT_WU_RV64:
8212   case RISCVISD::STRICT_FCVT_W_RV64:
8213   case RISCVISD::STRICT_FCVT_WU_RV64:
8214     // TODO: As the result is sign-extended, this is conservatively correct. A
8215     // more precise answer could be calculated for SRAW depending on known
8216     // bits in the shift amount.
8217     return 33;
8218   case RISCVISD::SHFL:
8219   case RISCVISD::UNSHFL: {
8220     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8221     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8222     // will stay within the upper 32 bits. If there were more than 32 sign bits
8223     // before there will be at least 33 sign bits after.
8224     if (Op.getValueType() == MVT::i64 &&
8225         isa<ConstantSDNode>(Op.getOperand(1)) &&
8226         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8227       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8228       if (Tmp > 32)
8229         return 33;
8230     }
8231     break;
8232   }
8233   case RISCVISD::VMV_X_S:
8234     // The number of sign bits of the scalar result is computed by obtaining the
8235     // element type of the input vector operand, subtracting its width from the
8236     // XLEN, and then adding one (sign bit within the element type). If the
8237     // element type is wider than XLen, the least-significant XLEN bits are
8238     // taken.
8239     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
8240       return 1;
8241     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
8242   }
8243 
8244   return 1;
8245 }
8246 
8247 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8248                                                   MachineBasicBlock *BB) {
8249   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8250 
8251   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8252   // Should the count have wrapped while it was being read, we need to try
8253   // again.
8254   // ...
8255   // read:
8256   // rdcycleh x3 # load high word of cycle
8257   // rdcycle  x2 # load low word of cycle
8258   // rdcycleh x4 # load high word of cycle
8259   // bne x3, x4, read # check if high word reads match, otherwise try again
8260   // ...
8261 
8262   MachineFunction &MF = *BB->getParent();
8263   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8264   MachineFunction::iterator It = ++BB->getIterator();
8265 
8266   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8267   MF.insert(It, LoopMBB);
8268 
8269   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8270   MF.insert(It, DoneMBB);
8271 
8272   // Transfer the remainder of BB and its successor edges to DoneMBB.
8273   DoneMBB->splice(DoneMBB->begin(), BB,
8274                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8275   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8276 
8277   BB->addSuccessor(LoopMBB);
8278 
8279   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8280   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8281   Register LoReg = MI.getOperand(0).getReg();
8282   Register HiReg = MI.getOperand(1).getReg();
8283   DebugLoc DL = MI.getDebugLoc();
8284 
8285   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8286   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8287       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8288       .addReg(RISCV::X0);
8289   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8290       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8291       .addReg(RISCV::X0);
8292   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8293       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8294       .addReg(RISCV::X0);
8295 
8296   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8297       .addReg(HiReg)
8298       .addReg(ReadAgainReg)
8299       .addMBB(LoopMBB);
8300 
8301   LoopMBB->addSuccessor(LoopMBB);
8302   LoopMBB->addSuccessor(DoneMBB);
8303 
8304   MI.eraseFromParent();
8305 
8306   return DoneMBB;
8307 }
8308 
8309 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8310                                              MachineBasicBlock *BB) {
8311   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8312 
8313   MachineFunction &MF = *BB->getParent();
8314   DebugLoc DL = MI.getDebugLoc();
8315   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8316   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8317   Register LoReg = MI.getOperand(0).getReg();
8318   Register HiReg = MI.getOperand(1).getReg();
8319   Register SrcReg = MI.getOperand(2).getReg();
8320   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8321   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8322 
8323   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8324                           RI);
8325   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8326   MachineMemOperand *MMOLo =
8327       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8328   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8329       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8330   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8331       .addFrameIndex(FI)
8332       .addImm(0)
8333       .addMemOperand(MMOLo);
8334   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8335       .addFrameIndex(FI)
8336       .addImm(4)
8337       .addMemOperand(MMOHi);
8338   MI.eraseFromParent(); // The pseudo instruction is gone now.
8339   return BB;
8340 }
8341 
8342 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8343                                                  MachineBasicBlock *BB) {
8344   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8345          "Unexpected instruction");
8346 
8347   MachineFunction &MF = *BB->getParent();
8348   DebugLoc DL = MI.getDebugLoc();
8349   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8350   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8351   Register DstReg = MI.getOperand(0).getReg();
8352   Register LoReg = MI.getOperand(1).getReg();
8353   Register HiReg = MI.getOperand(2).getReg();
8354   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8355   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8356 
8357   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8358   MachineMemOperand *MMOLo =
8359       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8360   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8361       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8362   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8363       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8364       .addFrameIndex(FI)
8365       .addImm(0)
8366       .addMemOperand(MMOLo);
8367   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8368       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8369       .addFrameIndex(FI)
8370       .addImm(4)
8371       .addMemOperand(MMOHi);
8372   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8373   MI.eraseFromParent(); // The pseudo instruction is gone now.
8374   return BB;
8375 }
8376 
8377 static bool isSelectPseudo(MachineInstr &MI) {
8378   switch (MI.getOpcode()) {
8379   default:
8380     return false;
8381   case RISCV::Select_GPR_Using_CC_GPR:
8382   case RISCV::Select_FPR16_Using_CC_GPR:
8383   case RISCV::Select_FPR32_Using_CC_GPR:
8384   case RISCV::Select_FPR64_Using_CC_GPR:
8385     return true;
8386   }
8387 }
8388 
8389 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8390                                         unsigned RelOpcode, unsigned EqOpcode,
8391                                         const RISCVSubtarget &Subtarget) {
8392   DebugLoc DL = MI.getDebugLoc();
8393   Register DstReg = MI.getOperand(0).getReg();
8394   Register Src1Reg = MI.getOperand(1).getReg();
8395   Register Src2Reg = MI.getOperand(2).getReg();
8396   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8397   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8398   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8399 
8400   // Save the current FFLAGS.
8401   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8402 
8403   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8404                  .addReg(Src1Reg)
8405                  .addReg(Src2Reg);
8406   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8407     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8408 
8409   // Restore the FFLAGS.
8410   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8411       .addReg(SavedFFlags, RegState::Kill);
8412 
8413   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8414   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8415                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8416                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8417   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8418     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8419 
8420   // Erase the pseudoinstruction.
8421   MI.eraseFromParent();
8422   return BB;
8423 }
8424 
8425 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8426                                            MachineBasicBlock *BB,
8427                                            const RISCVSubtarget &Subtarget) {
8428   // To "insert" Select_* instructions, we actually have to insert the triangle
8429   // control-flow pattern.  The incoming instructions know the destination vreg
8430   // to set, the condition code register to branch on, the true/false values to
8431   // select between, and the condcode to use to select the appropriate branch.
8432   //
8433   // We produce the following control flow:
8434   //     HeadMBB
8435   //     |  \
8436   //     |  IfFalseMBB
8437   //     | /
8438   //    TailMBB
8439   //
8440   // When we find a sequence of selects we attempt to optimize their emission
8441   // by sharing the control flow. Currently we only handle cases where we have
8442   // multiple selects with the exact same condition (same LHS, RHS and CC).
8443   // The selects may be interleaved with other instructions if the other
8444   // instructions meet some requirements we deem safe:
8445   // - They are debug instructions. Otherwise,
8446   // - They do not have side-effects, do not access memory and their inputs do
8447   //   not depend on the results of the select pseudo-instructions.
8448   // The TrueV/FalseV operands of the selects cannot depend on the result of
8449   // previous selects in the sequence.
8450   // These conditions could be further relaxed. See the X86 target for a
8451   // related approach and more information.
8452   Register LHS = MI.getOperand(1).getReg();
8453   Register RHS = MI.getOperand(2).getReg();
8454   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8455 
8456   SmallVector<MachineInstr *, 4> SelectDebugValues;
8457   SmallSet<Register, 4> SelectDests;
8458   SelectDests.insert(MI.getOperand(0).getReg());
8459 
8460   MachineInstr *LastSelectPseudo = &MI;
8461 
8462   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8463        SequenceMBBI != E; ++SequenceMBBI) {
8464     if (SequenceMBBI->isDebugInstr())
8465       continue;
8466     else if (isSelectPseudo(*SequenceMBBI)) {
8467       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8468           SequenceMBBI->getOperand(2).getReg() != RHS ||
8469           SequenceMBBI->getOperand(3).getImm() != CC ||
8470           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8471           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8472         break;
8473       LastSelectPseudo = &*SequenceMBBI;
8474       SequenceMBBI->collectDebugValues(SelectDebugValues);
8475       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8476     } else {
8477       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8478           SequenceMBBI->mayLoadOrStore())
8479         break;
8480       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8481             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8482           }))
8483         break;
8484     }
8485   }
8486 
8487   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8488   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8489   DebugLoc DL = MI.getDebugLoc();
8490   MachineFunction::iterator I = ++BB->getIterator();
8491 
8492   MachineBasicBlock *HeadMBB = BB;
8493   MachineFunction *F = BB->getParent();
8494   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8495   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8496 
8497   F->insert(I, IfFalseMBB);
8498   F->insert(I, TailMBB);
8499 
8500   // Transfer debug instructions associated with the selects to TailMBB.
8501   for (MachineInstr *DebugInstr : SelectDebugValues) {
8502     TailMBB->push_back(DebugInstr->removeFromParent());
8503   }
8504 
8505   // Move all instructions after the sequence to TailMBB.
8506   TailMBB->splice(TailMBB->end(), HeadMBB,
8507                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8508   // Update machine-CFG edges by transferring all successors of the current
8509   // block to the new block which will contain the Phi nodes for the selects.
8510   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8511   // Set the successors for HeadMBB.
8512   HeadMBB->addSuccessor(IfFalseMBB);
8513   HeadMBB->addSuccessor(TailMBB);
8514 
8515   // Insert appropriate branch.
8516   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8517     .addReg(LHS)
8518     .addReg(RHS)
8519     .addMBB(TailMBB);
8520 
8521   // IfFalseMBB just falls through to TailMBB.
8522   IfFalseMBB->addSuccessor(TailMBB);
8523 
8524   // Create PHIs for all of the select pseudo-instructions.
8525   auto SelectMBBI = MI.getIterator();
8526   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8527   auto InsertionPoint = TailMBB->begin();
8528   while (SelectMBBI != SelectEnd) {
8529     auto Next = std::next(SelectMBBI);
8530     if (isSelectPseudo(*SelectMBBI)) {
8531       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8532       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8533               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8534           .addReg(SelectMBBI->getOperand(4).getReg())
8535           .addMBB(HeadMBB)
8536           .addReg(SelectMBBI->getOperand(5).getReg())
8537           .addMBB(IfFalseMBB);
8538       SelectMBBI->eraseFromParent();
8539     }
8540     SelectMBBI = Next;
8541   }
8542 
8543   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8544   return TailMBB;
8545 }
8546 
8547 MachineBasicBlock *
8548 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8549                                                  MachineBasicBlock *BB) const {
8550   switch (MI.getOpcode()) {
8551   default:
8552     llvm_unreachable("Unexpected instr type to insert");
8553   case RISCV::ReadCycleWide:
8554     assert(!Subtarget.is64Bit() &&
8555            "ReadCycleWrite is only to be used on riscv32");
8556     return emitReadCycleWidePseudo(MI, BB);
8557   case RISCV::Select_GPR_Using_CC_GPR:
8558   case RISCV::Select_FPR16_Using_CC_GPR:
8559   case RISCV::Select_FPR32_Using_CC_GPR:
8560   case RISCV::Select_FPR64_Using_CC_GPR:
8561     return emitSelectPseudo(MI, BB, Subtarget);
8562   case RISCV::BuildPairF64Pseudo:
8563     return emitBuildPairF64Pseudo(MI, BB);
8564   case RISCV::SplitF64Pseudo:
8565     return emitSplitF64Pseudo(MI, BB);
8566   case RISCV::PseudoQuietFLE_H:
8567     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8568   case RISCV::PseudoQuietFLT_H:
8569     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8570   case RISCV::PseudoQuietFLE_S:
8571     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8572   case RISCV::PseudoQuietFLT_S:
8573     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8574   case RISCV::PseudoQuietFLE_D:
8575     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8576   case RISCV::PseudoQuietFLT_D:
8577     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8578   }
8579 }
8580 
8581 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8582                                                         SDNode *Node) const {
8583   // Add FRM dependency to any instructions with dynamic rounding mode.
8584   unsigned Opc = MI.getOpcode();
8585   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8586   if (Idx < 0)
8587     return;
8588   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8589     return;
8590   // If the instruction already reads FRM, don't add another read.
8591   if (MI.readsRegister(RISCV::FRM))
8592     return;
8593   MI.addOperand(
8594       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8595 }
8596 
8597 // Calling Convention Implementation.
8598 // The expectations for frontend ABI lowering vary from target to target.
8599 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8600 // details, but this is a longer term goal. For now, we simply try to keep the
8601 // role of the frontend as simple and well-defined as possible. The rules can
8602 // be summarised as:
8603 // * Never split up large scalar arguments. We handle them here.
8604 // * If a hardfloat calling convention is being used, and the struct may be
8605 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8606 // available, then pass as two separate arguments. If either the GPRs or FPRs
8607 // are exhausted, then pass according to the rule below.
8608 // * If a struct could never be passed in registers or directly in a stack
8609 // slot (as it is larger than 2*XLEN and the floating point rules don't
8610 // apply), then pass it using a pointer with the byval attribute.
8611 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8612 // word-sized array or a 2*XLEN scalar (depending on alignment).
8613 // * The frontend can determine whether a struct is returned by reference or
8614 // not based on its size and fields. If it will be returned by reference, the
8615 // frontend must modify the prototype so a pointer with the sret annotation is
8616 // passed as the first argument. This is not necessary for large scalar
8617 // returns.
8618 // * Struct return values and varargs should be coerced to structs containing
8619 // register-size fields in the same situations they would be for fixed
8620 // arguments.
8621 
8622 static const MCPhysReg ArgGPRs[] = {
8623   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8624   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8625 };
8626 static const MCPhysReg ArgFPR16s[] = {
8627   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8628   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8629 };
8630 static const MCPhysReg ArgFPR32s[] = {
8631   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8632   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8633 };
8634 static const MCPhysReg ArgFPR64s[] = {
8635   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8636   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8637 };
8638 // This is an interim calling convention and it may be changed in the future.
8639 static const MCPhysReg ArgVRs[] = {
8640     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8641     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8642     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8643 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8644                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8645                                      RISCV::V20M2, RISCV::V22M2};
8646 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8647                                      RISCV::V20M4};
8648 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8649 
8650 // Pass a 2*XLEN argument that has been split into two XLEN values through
8651 // registers or the stack as necessary.
8652 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8653                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8654                                 MVT ValVT2, MVT LocVT2,
8655                                 ISD::ArgFlagsTy ArgFlags2) {
8656   unsigned XLenInBytes = XLen / 8;
8657   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8658     // At least one half can be passed via register.
8659     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8660                                      VA1.getLocVT(), CCValAssign::Full));
8661   } else {
8662     // Both halves must be passed on the stack, with proper alignment.
8663     Align StackAlign =
8664         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8665     State.addLoc(
8666         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8667                             State.AllocateStack(XLenInBytes, StackAlign),
8668                             VA1.getLocVT(), CCValAssign::Full));
8669     State.addLoc(CCValAssign::getMem(
8670         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8671         LocVT2, CCValAssign::Full));
8672     return false;
8673   }
8674 
8675   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8676     // The second half can also be passed via register.
8677     State.addLoc(
8678         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8679   } else {
8680     // The second half is passed via the stack, without additional alignment.
8681     State.addLoc(CCValAssign::getMem(
8682         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8683         LocVT2, CCValAssign::Full));
8684   }
8685 
8686   return false;
8687 }
8688 
8689 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8690                                Optional<unsigned> FirstMaskArgument,
8691                                CCState &State, const RISCVTargetLowering &TLI) {
8692   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8693   if (RC == &RISCV::VRRegClass) {
8694     // Assign the first mask argument to V0.
8695     // This is an interim calling convention and it may be changed in the
8696     // future.
8697     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8698       return State.AllocateReg(RISCV::V0);
8699     return State.AllocateReg(ArgVRs);
8700   }
8701   if (RC == &RISCV::VRM2RegClass)
8702     return State.AllocateReg(ArgVRM2s);
8703   if (RC == &RISCV::VRM4RegClass)
8704     return State.AllocateReg(ArgVRM4s);
8705   if (RC == &RISCV::VRM8RegClass)
8706     return State.AllocateReg(ArgVRM8s);
8707   llvm_unreachable("Unhandled register class for ValueType");
8708 }
8709 
8710 // Implements the RISC-V calling convention. Returns true upon failure.
8711 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8712                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8713                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8714                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8715                      Optional<unsigned> FirstMaskArgument) {
8716   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8717   assert(XLen == 32 || XLen == 64);
8718   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8719 
8720   // Any return value split in to more than two values can't be returned
8721   // directly. Vectors are returned via the available vector registers.
8722   if (!LocVT.isVector() && IsRet && ValNo > 1)
8723     return true;
8724 
8725   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8726   // variadic argument, or if no F16/F32 argument registers are available.
8727   bool UseGPRForF16_F32 = true;
8728   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8729   // variadic argument, or if no F64 argument registers are available.
8730   bool UseGPRForF64 = true;
8731 
8732   switch (ABI) {
8733   default:
8734     llvm_unreachable("Unexpected ABI");
8735   case RISCVABI::ABI_ILP32:
8736   case RISCVABI::ABI_LP64:
8737     break;
8738   case RISCVABI::ABI_ILP32F:
8739   case RISCVABI::ABI_LP64F:
8740     UseGPRForF16_F32 = !IsFixed;
8741     break;
8742   case RISCVABI::ABI_ILP32D:
8743   case RISCVABI::ABI_LP64D:
8744     UseGPRForF16_F32 = !IsFixed;
8745     UseGPRForF64 = !IsFixed;
8746     break;
8747   }
8748 
8749   // FPR16, FPR32, and FPR64 alias each other.
8750   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8751     UseGPRForF16_F32 = true;
8752     UseGPRForF64 = true;
8753   }
8754 
8755   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8756   // similar local variables rather than directly checking against the target
8757   // ABI.
8758 
8759   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8760     LocVT = XLenVT;
8761     LocInfo = CCValAssign::BCvt;
8762   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8763     LocVT = MVT::i64;
8764     LocInfo = CCValAssign::BCvt;
8765   }
8766 
8767   // If this is a variadic argument, the RISC-V calling convention requires
8768   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8769   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8770   // be used regardless of whether the original argument was split during
8771   // legalisation or not. The argument will not be passed by registers if the
8772   // original type is larger than 2*XLEN, so the register alignment rule does
8773   // not apply.
8774   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8775   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8776       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8777     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8778     // Skip 'odd' register if necessary.
8779     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8780       State.AllocateReg(ArgGPRs);
8781   }
8782 
8783   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8784   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8785       State.getPendingArgFlags();
8786 
8787   assert(PendingLocs.size() == PendingArgFlags.size() &&
8788          "PendingLocs and PendingArgFlags out of sync");
8789 
8790   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8791   // registers are exhausted.
8792   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8793     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8794            "Can't lower f64 if it is split");
8795     // Depending on available argument GPRS, f64 may be passed in a pair of
8796     // GPRs, split between a GPR and the stack, or passed completely on the
8797     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8798     // cases.
8799     Register Reg = State.AllocateReg(ArgGPRs);
8800     LocVT = MVT::i32;
8801     if (!Reg) {
8802       unsigned StackOffset = State.AllocateStack(8, Align(8));
8803       State.addLoc(
8804           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8805       return false;
8806     }
8807     if (!State.AllocateReg(ArgGPRs))
8808       State.AllocateStack(4, Align(4));
8809     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8810     return false;
8811   }
8812 
8813   // Fixed-length vectors are located in the corresponding scalable-vector
8814   // container types.
8815   if (ValVT.isFixedLengthVector())
8816     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8817 
8818   // Split arguments might be passed indirectly, so keep track of the pending
8819   // values. Split vectors are passed via a mix of registers and indirectly, so
8820   // treat them as we would any other argument.
8821   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8822     LocVT = XLenVT;
8823     LocInfo = CCValAssign::Indirect;
8824     PendingLocs.push_back(
8825         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8826     PendingArgFlags.push_back(ArgFlags);
8827     if (!ArgFlags.isSplitEnd()) {
8828       return false;
8829     }
8830   }
8831 
8832   // If the split argument only had two elements, it should be passed directly
8833   // in registers or on the stack.
8834   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8835       PendingLocs.size() <= 2) {
8836     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8837     // Apply the normal calling convention rules to the first half of the
8838     // split argument.
8839     CCValAssign VA = PendingLocs[0];
8840     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8841     PendingLocs.clear();
8842     PendingArgFlags.clear();
8843     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8844                                ArgFlags);
8845   }
8846 
8847   // Allocate to a register if possible, or else a stack slot.
8848   Register Reg;
8849   unsigned StoreSizeBytes = XLen / 8;
8850   Align StackAlign = Align(XLen / 8);
8851 
8852   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8853     Reg = State.AllocateReg(ArgFPR16s);
8854   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8855     Reg = State.AllocateReg(ArgFPR32s);
8856   else if (ValVT == MVT::f64 && !UseGPRForF64)
8857     Reg = State.AllocateReg(ArgFPR64s);
8858   else if (ValVT.isVector()) {
8859     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8860     if (!Reg) {
8861       // For return values, the vector must be passed fully via registers or
8862       // via the stack.
8863       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8864       // but we're using all of them.
8865       if (IsRet)
8866         return true;
8867       // Try using a GPR to pass the address
8868       if ((Reg = State.AllocateReg(ArgGPRs))) {
8869         LocVT = XLenVT;
8870         LocInfo = CCValAssign::Indirect;
8871       } else if (ValVT.isScalableVector()) {
8872         LocVT = XLenVT;
8873         LocInfo = CCValAssign::Indirect;
8874       } else {
8875         // Pass fixed-length vectors on the stack.
8876         LocVT = ValVT;
8877         StoreSizeBytes = ValVT.getStoreSize();
8878         // Align vectors to their element sizes, being careful for vXi1
8879         // vectors.
8880         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8881       }
8882     }
8883   } else {
8884     Reg = State.AllocateReg(ArgGPRs);
8885   }
8886 
8887   unsigned StackOffset =
8888       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8889 
8890   // If we reach this point and PendingLocs is non-empty, we must be at the
8891   // end of a split argument that must be passed indirectly.
8892   if (!PendingLocs.empty()) {
8893     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8894     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8895 
8896     for (auto &It : PendingLocs) {
8897       if (Reg)
8898         It.convertToReg(Reg);
8899       else
8900         It.convertToMem(StackOffset);
8901       State.addLoc(It);
8902     }
8903     PendingLocs.clear();
8904     PendingArgFlags.clear();
8905     return false;
8906   }
8907 
8908   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8909           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8910          "Expected an XLenVT or vector types at this stage");
8911 
8912   if (Reg) {
8913     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8914     return false;
8915   }
8916 
8917   // When a floating-point value is passed on the stack, no bit-conversion is
8918   // needed.
8919   if (ValVT.isFloatingPoint()) {
8920     LocVT = ValVT;
8921     LocInfo = CCValAssign::Full;
8922   }
8923   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8924   return false;
8925 }
8926 
8927 template <typename ArgTy>
8928 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8929   for (const auto &ArgIdx : enumerate(Args)) {
8930     MVT ArgVT = ArgIdx.value().VT;
8931     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8932       return ArgIdx.index();
8933   }
8934   return None;
8935 }
8936 
8937 void RISCVTargetLowering::analyzeInputArgs(
8938     MachineFunction &MF, CCState &CCInfo,
8939     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8940     RISCVCCAssignFn Fn) const {
8941   unsigned NumArgs = Ins.size();
8942   FunctionType *FType = MF.getFunction().getFunctionType();
8943 
8944   Optional<unsigned> FirstMaskArgument;
8945   if (Subtarget.hasVInstructions())
8946     FirstMaskArgument = preAssignMask(Ins);
8947 
8948   for (unsigned i = 0; i != NumArgs; ++i) {
8949     MVT ArgVT = Ins[i].VT;
8950     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8951 
8952     Type *ArgTy = nullptr;
8953     if (IsRet)
8954       ArgTy = FType->getReturnType();
8955     else if (Ins[i].isOrigArg())
8956       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8957 
8958     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8959     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8960            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8961            FirstMaskArgument)) {
8962       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8963                         << EVT(ArgVT).getEVTString() << '\n');
8964       llvm_unreachable(nullptr);
8965     }
8966   }
8967 }
8968 
8969 void RISCVTargetLowering::analyzeOutputArgs(
8970     MachineFunction &MF, CCState &CCInfo,
8971     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8972     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8973   unsigned NumArgs = Outs.size();
8974 
8975   Optional<unsigned> FirstMaskArgument;
8976   if (Subtarget.hasVInstructions())
8977     FirstMaskArgument = preAssignMask(Outs);
8978 
8979   for (unsigned i = 0; i != NumArgs; i++) {
8980     MVT ArgVT = Outs[i].VT;
8981     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8982     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8983 
8984     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8985     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8986            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8987            FirstMaskArgument)) {
8988       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8989                         << EVT(ArgVT).getEVTString() << "\n");
8990       llvm_unreachable(nullptr);
8991     }
8992   }
8993 }
8994 
8995 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8996 // values.
8997 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8998                                    const CCValAssign &VA, const SDLoc &DL,
8999                                    const RISCVSubtarget &Subtarget) {
9000   switch (VA.getLocInfo()) {
9001   default:
9002     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9003   case CCValAssign::Full:
9004     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9005       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9006     break;
9007   case CCValAssign::BCvt:
9008     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9009       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9010     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9011       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9012     else
9013       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9014     break;
9015   }
9016   return Val;
9017 }
9018 
9019 // The caller is responsible for loading the full value if the argument is
9020 // passed with CCValAssign::Indirect.
9021 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9022                                 const CCValAssign &VA, const SDLoc &DL,
9023                                 const RISCVTargetLowering &TLI) {
9024   MachineFunction &MF = DAG.getMachineFunction();
9025   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9026   EVT LocVT = VA.getLocVT();
9027   SDValue Val;
9028   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9029   Register VReg = RegInfo.createVirtualRegister(RC);
9030   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9031   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9032 
9033   if (VA.getLocInfo() == CCValAssign::Indirect)
9034     return Val;
9035 
9036   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9037 }
9038 
9039 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9040                                    const CCValAssign &VA, const SDLoc &DL,
9041                                    const RISCVSubtarget &Subtarget) {
9042   EVT LocVT = VA.getLocVT();
9043 
9044   switch (VA.getLocInfo()) {
9045   default:
9046     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9047   case CCValAssign::Full:
9048     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9049       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9050     break;
9051   case CCValAssign::BCvt:
9052     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9053       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9054     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9055       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9056     else
9057       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9058     break;
9059   }
9060   return Val;
9061 }
9062 
9063 // The caller is responsible for loading the full value if the argument is
9064 // passed with CCValAssign::Indirect.
9065 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9066                                 const CCValAssign &VA, const SDLoc &DL) {
9067   MachineFunction &MF = DAG.getMachineFunction();
9068   MachineFrameInfo &MFI = MF.getFrameInfo();
9069   EVT LocVT = VA.getLocVT();
9070   EVT ValVT = VA.getValVT();
9071   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9072   if (ValVT.isScalableVector()) {
9073     // When the value is a scalable vector, we save the pointer which points to
9074     // the scalable vector value in the stack. The ValVT will be the pointer
9075     // type, instead of the scalable vector type.
9076     ValVT = LocVT;
9077   }
9078   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9079                                  /*IsImmutable=*/true);
9080   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9081   SDValue Val;
9082 
9083   ISD::LoadExtType ExtType;
9084   switch (VA.getLocInfo()) {
9085   default:
9086     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9087   case CCValAssign::Full:
9088   case CCValAssign::Indirect:
9089   case CCValAssign::BCvt:
9090     ExtType = ISD::NON_EXTLOAD;
9091     break;
9092   }
9093   Val = DAG.getExtLoad(
9094       ExtType, DL, LocVT, Chain, FIN,
9095       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9096   return Val;
9097 }
9098 
9099 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9100                                        const CCValAssign &VA, const SDLoc &DL) {
9101   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9102          "Unexpected VA");
9103   MachineFunction &MF = DAG.getMachineFunction();
9104   MachineFrameInfo &MFI = MF.getFrameInfo();
9105   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9106 
9107   if (VA.isMemLoc()) {
9108     // f64 is passed on the stack.
9109     int FI =
9110         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9111     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9112     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9113                        MachinePointerInfo::getFixedStack(MF, FI));
9114   }
9115 
9116   assert(VA.isRegLoc() && "Expected register VA assignment");
9117 
9118   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9119   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9120   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9121   SDValue Hi;
9122   if (VA.getLocReg() == RISCV::X17) {
9123     // Second half of f64 is passed on the stack.
9124     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9125     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9126     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9127                      MachinePointerInfo::getFixedStack(MF, FI));
9128   } else {
9129     // Second half of f64 is passed in another GPR.
9130     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9131     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9132     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9133   }
9134   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9135 }
9136 
9137 // FastCC has less than 1% performance improvement for some particular
9138 // benchmark. But theoretically, it may has benenfit for some cases.
9139 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9140                             unsigned ValNo, MVT ValVT, MVT LocVT,
9141                             CCValAssign::LocInfo LocInfo,
9142                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9143                             bool IsFixed, bool IsRet, Type *OrigTy,
9144                             const RISCVTargetLowering &TLI,
9145                             Optional<unsigned> FirstMaskArgument) {
9146 
9147   // X5 and X6 might be used for save-restore libcall.
9148   static const MCPhysReg GPRList[] = {
9149       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9150       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9151       RISCV::X29, RISCV::X30, RISCV::X31};
9152 
9153   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9154     if (unsigned Reg = State.AllocateReg(GPRList)) {
9155       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9156       return false;
9157     }
9158   }
9159 
9160   if (LocVT == MVT::f16) {
9161     static const MCPhysReg FPR16List[] = {
9162         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9163         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9164         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9165         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9166     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9167       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9168       return false;
9169     }
9170   }
9171 
9172   if (LocVT == MVT::f32) {
9173     static const MCPhysReg FPR32List[] = {
9174         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9175         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9176         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9177         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9178     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9179       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9180       return false;
9181     }
9182   }
9183 
9184   if (LocVT == MVT::f64) {
9185     static const MCPhysReg FPR64List[] = {
9186         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9187         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9188         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9189         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9190     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9191       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9192       return false;
9193     }
9194   }
9195 
9196   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9197     unsigned Offset4 = State.AllocateStack(4, Align(4));
9198     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9199     return false;
9200   }
9201 
9202   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9203     unsigned Offset5 = State.AllocateStack(8, Align(8));
9204     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9205     return false;
9206   }
9207 
9208   if (LocVT.isVector()) {
9209     if (unsigned Reg =
9210             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9211       // Fixed-length vectors are located in the corresponding scalable-vector
9212       // container types.
9213       if (ValVT.isFixedLengthVector())
9214         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9215       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9216     } else {
9217       // Try and pass the address via a "fast" GPR.
9218       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9219         LocInfo = CCValAssign::Indirect;
9220         LocVT = TLI.getSubtarget().getXLenVT();
9221         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9222       } else if (ValVT.isFixedLengthVector()) {
9223         auto StackAlign =
9224             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9225         unsigned StackOffset =
9226             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9227         State.addLoc(
9228             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9229       } else {
9230         // Can't pass scalable vectors on the stack.
9231         return true;
9232       }
9233     }
9234 
9235     return false;
9236   }
9237 
9238   return true; // CC didn't match.
9239 }
9240 
9241 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9242                          CCValAssign::LocInfo LocInfo,
9243                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9244 
9245   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9246     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9247     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9248     static const MCPhysReg GPRList[] = {
9249         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9250         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9251     if (unsigned Reg = State.AllocateReg(GPRList)) {
9252       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9253       return false;
9254     }
9255   }
9256 
9257   if (LocVT == MVT::f32) {
9258     // Pass in STG registers: F1, ..., F6
9259     //                        fs0 ... fs5
9260     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9261                                           RISCV::F18_F, RISCV::F19_F,
9262                                           RISCV::F20_F, RISCV::F21_F};
9263     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9264       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9265       return false;
9266     }
9267   }
9268 
9269   if (LocVT == MVT::f64) {
9270     // Pass in STG registers: D1, ..., D6
9271     //                        fs6 ... fs11
9272     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9273                                           RISCV::F24_D, RISCV::F25_D,
9274                                           RISCV::F26_D, RISCV::F27_D};
9275     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9276       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9277       return false;
9278     }
9279   }
9280 
9281   report_fatal_error("No registers left in GHC calling convention");
9282   return true;
9283 }
9284 
9285 // Transform physical registers into virtual registers.
9286 SDValue RISCVTargetLowering::LowerFormalArguments(
9287     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9288     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9289     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9290 
9291   MachineFunction &MF = DAG.getMachineFunction();
9292 
9293   switch (CallConv) {
9294   default:
9295     report_fatal_error("Unsupported calling convention");
9296   case CallingConv::C:
9297   case CallingConv::Fast:
9298     break;
9299   case CallingConv::GHC:
9300     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9301         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9302       report_fatal_error(
9303         "GHC calling convention requires the F and D instruction set extensions");
9304   }
9305 
9306   const Function &Func = MF.getFunction();
9307   if (Func.hasFnAttribute("interrupt")) {
9308     if (!Func.arg_empty())
9309       report_fatal_error(
9310         "Functions with the interrupt attribute cannot have arguments!");
9311 
9312     StringRef Kind =
9313       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9314 
9315     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9316       report_fatal_error(
9317         "Function interrupt attribute argument not supported!");
9318   }
9319 
9320   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9321   MVT XLenVT = Subtarget.getXLenVT();
9322   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9323   // Used with vargs to acumulate store chains.
9324   std::vector<SDValue> OutChains;
9325 
9326   // Assign locations to all of the incoming arguments.
9327   SmallVector<CCValAssign, 16> ArgLocs;
9328   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9329 
9330   if (CallConv == CallingConv::GHC)
9331     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9332   else
9333     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9334                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9335                                                    : CC_RISCV);
9336 
9337   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9338     CCValAssign &VA = ArgLocs[i];
9339     SDValue ArgValue;
9340     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9341     // case.
9342     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9343       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9344     else if (VA.isRegLoc())
9345       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9346     else
9347       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9348 
9349     if (VA.getLocInfo() == CCValAssign::Indirect) {
9350       // If the original argument was split and passed by reference (e.g. i128
9351       // on RV32), we need to load all parts of it here (using the same
9352       // address). Vectors may be partly split to registers and partly to the
9353       // stack, in which case the base address is partly offset and subsequent
9354       // stores are relative to that.
9355       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9356                                    MachinePointerInfo()));
9357       unsigned ArgIndex = Ins[i].OrigArgIndex;
9358       unsigned ArgPartOffset = Ins[i].PartOffset;
9359       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9360       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9361         CCValAssign &PartVA = ArgLocs[i + 1];
9362         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9363         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9364         if (PartVA.getValVT().isScalableVector())
9365           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9366         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9367         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9368                                      MachinePointerInfo()));
9369         ++i;
9370       }
9371       continue;
9372     }
9373     InVals.push_back(ArgValue);
9374   }
9375 
9376   if (IsVarArg) {
9377     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9378     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9379     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9380     MachineFrameInfo &MFI = MF.getFrameInfo();
9381     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9382     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9383 
9384     // Offset of the first variable argument from stack pointer, and size of
9385     // the vararg save area. For now, the varargs save area is either zero or
9386     // large enough to hold a0-a7.
9387     int VaArgOffset, VarArgsSaveSize;
9388 
9389     // If all registers are allocated, then all varargs must be passed on the
9390     // stack and we don't need to save any argregs.
9391     if (ArgRegs.size() == Idx) {
9392       VaArgOffset = CCInfo.getNextStackOffset();
9393       VarArgsSaveSize = 0;
9394     } else {
9395       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9396       VaArgOffset = -VarArgsSaveSize;
9397     }
9398 
9399     // Record the frame index of the first variable argument
9400     // which is a value necessary to VASTART.
9401     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9402     RVFI->setVarArgsFrameIndex(FI);
9403 
9404     // If saving an odd number of registers then create an extra stack slot to
9405     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9406     // offsets to even-numbered registered remain 2*XLEN-aligned.
9407     if (Idx % 2) {
9408       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9409       VarArgsSaveSize += XLenInBytes;
9410     }
9411 
9412     // Copy the integer registers that may have been used for passing varargs
9413     // to the vararg save area.
9414     for (unsigned I = Idx; I < ArgRegs.size();
9415          ++I, VaArgOffset += XLenInBytes) {
9416       const Register Reg = RegInfo.createVirtualRegister(RC);
9417       RegInfo.addLiveIn(ArgRegs[I], Reg);
9418       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9419       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9420       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9421       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9422                                    MachinePointerInfo::getFixedStack(MF, FI));
9423       cast<StoreSDNode>(Store.getNode())
9424           ->getMemOperand()
9425           ->setValue((Value *)nullptr);
9426       OutChains.push_back(Store);
9427     }
9428     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9429   }
9430 
9431   // All stores are grouped in one node to allow the matching between
9432   // the size of Ins and InVals. This only happens for vararg functions.
9433   if (!OutChains.empty()) {
9434     OutChains.push_back(Chain);
9435     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9436   }
9437 
9438   return Chain;
9439 }
9440 
9441 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9442 /// for tail call optimization.
9443 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9444 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9445     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9446     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9447 
9448   auto &Callee = CLI.Callee;
9449   auto CalleeCC = CLI.CallConv;
9450   auto &Outs = CLI.Outs;
9451   auto &Caller = MF.getFunction();
9452   auto CallerCC = Caller.getCallingConv();
9453 
9454   // Exception-handling functions need a special set of instructions to
9455   // indicate a return to the hardware. Tail-calling another function would
9456   // probably break this.
9457   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9458   // should be expanded as new function attributes are introduced.
9459   if (Caller.hasFnAttribute("interrupt"))
9460     return false;
9461 
9462   // Do not tail call opt if the stack is used to pass parameters.
9463   if (CCInfo.getNextStackOffset() != 0)
9464     return false;
9465 
9466   // Do not tail call opt if any parameters need to be passed indirectly.
9467   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9468   // passed indirectly. So the address of the value will be passed in a
9469   // register, or if not available, then the address is put on the stack. In
9470   // order to pass indirectly, space on the stack often needs to be allocated
9471   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9472   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9473   // are passed CCValAssign::Indirect.
9474   for (auto &VA : ArgLocs)
9475     if (VA.getLocInfo() == CCValAssign::Indirect)
9476       return false;
9477 
9478   // Do not tail call opt if either caller or callee uses struct return
9479   // semantics.
9480   auto IsCallerStructRet = Caller.hasStructRetAttr();
9481   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9482   if (IsCallerStructRet || IsCalleeStructRet)
9483     return false;
9484 
9485   // Externally-defined functions with weak linkage should not be
9486   // tail-called. The behaviour of branch instructions in this situation (as
9487   // used for tail calls) is implementation-defined, so we cannot rely on the
9488   // linker replacing the tail call with a return.
9489   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9490     const GlobalValue *GV = G->getGlobal();
9491     if (GV->hasExternalWeakLinkage())
9492       return false;
9493   }
9494 
9495   // The callee has to preserve all registers the caller needs to preserve.
9496   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9497   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9498   if (CalleeCC != CallerCC) {
9499     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9500     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9501       return false;
9502   }
9503 
9504   // Byval parameters hand the function a pointer directly into the stack area
9505   // we want to reuse during a tail call. Working around this *is* possible
9506   // but less efficient and uglier in LowerCall.
9507   for (auto &Arg : Outs)
9508     if (Arg.Flags.isByVal())
9509       return false;
9510 
9511   return true;
9512 }
9513 
9514 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9515   return DAG.getDataLayout().getPrefTypeAlign(
9516       VT.getTypeForEVT(*DAG.getContext()));
9517 }
9518 
9519 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9520 // and output parameter nodes.
9521 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9522                                        SmallVectorImpl<SDValue> &InVals) const {
9523   SelectionDAG &DAG = CLI.DAG;
9524   SDLoc &DL = CLI.DL;
9525   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9526   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9527   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9528   SDValue Chain = CLI.Chain;
9529   SDValue Callee = CLI.Callee;
9530   bool &IsTailCall = CLI.IsTailCall;
9531   CallingConv::ID CallConv = CLI.CallConv;
9532   bool IsVarArg = CLI.IsVarArg;
9533   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9534   MVT XLenVT = Subtarget.getXLenVT();
9535 
9536   MachineFunction &MF = DAG.getMachineFunction();
9537 
9538   // Analyze the operands of the call, assigning locations to each operand.
9539   SmallVector<CCValAssign, 16> ArgLocs;
9540   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9541 
9542   if (CallConv == CallingConv::GHC)
9543     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9544   else
9545     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9546                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9547                                                     : CC_RISCV);
9548 
9549   // Check if it's really possible to do a tail call.
9550   if (IsTailCall)
9551     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9552 
9553   if (IsTailCall)
9554     ++NumTailCalls;
9555   else if (CLI.CB && CLI.CB->isMustTailCall())
9556     report_fatal_error("failed to perform tail call elimination on a call "
9557                        "site marked musttail");
9558 
9559   // Get a count of how many bytes are to be pushed on the stack.
9560   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9561 
9562   // Create local copies for byval args
9563   SmallVector<SDValue, 8> ByValArgs;
9564   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9565     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9566     if (!Flags.isByVal())
9567       continue;
9568 
9569     SDValue Arg = OutVals[i];
9570     unsigned Size = Flags.getByValSize();
9571     Align Alignment = Flags.getNonZeroByValAlign();
9572 
9573     int FI =
9574         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9575     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9576     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9577 
9578     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9579                           /*IsVolatile=*/false,
9580                           /*AlwaysInline=*/false, IsTailCall,
9581                           MachinePointerInfo(), MachinePointerInfo());
9582     ByValArgs.push_back(FIPtr);
9583   }
9584 
9585   if (!IsTailCall)
9586     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9587 
9588   // Copy argument values to their designated locations.
9589   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9590   SmallVector<SDValue, 8> MemOpChains;
9591   SDValue StackPtr;
9592   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9593     CCValAssign &VA = ArgLocs[i];
9594     SDValue ArgValue = OutVals[i];
9595     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9596 
9597     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9598     bool IsF64OnRV32DSoftABI =
9599         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9600     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9601       SDValue SplitF64 = DAG.getNode(
9602           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9603       SDValue Lo = SplitF64.getValue(0);
9604       SDValue Hi = SplitF64.getValue(1);
9605 
9606       Register RegLo = VA.getLocReg();
9607       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9608 
9609       if (RegLo == RISCV::X17) {
9610         // Second half of f64 is passed on the stack.
9611         // Work out the address of the stack slot.
9612         if (!StackPtr.getNode())
9613           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9614         // Emit the store.
9615         MemOpChains.push_back(
9616             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9617       } else {
9618         // Second half of f64 is passed in another GPR.
9619         assert(RegLo < RISCV::X31 && "Invalid register pair");
9620         Register RegHigh = RegLo + 1;
9621         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9622       }
9623       continue;
9624     }
9625 
9626     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9627     // as any other MemLoc.
9628 
9629     // Promote the value if needed.
9630     // For now, only handle fully promoted and indirect arguments.
9631     if (VA.getLocInfo() == CCValAssign::Indirect) {
9632       // Store the argument in a stack slot and pass its address.
9633       Align StackAlign =
9634           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9635                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9636       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9637       // If the original argument was split (e.g. i128), we need
9638       // to store the required parts of it here (and pass just one address).
9639       // Vectors may be partly split to registers and partly to the stack, in
9640       // which case the base address is partly offset and subsequent stores are
9641       // relative to that.
9642       unsigned ArgIndex = Outs[i].OrigArgIndex;
9643       unsigned ArgPartOffset = Outs[i].PartOffset;
9644       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9645       // Calculate the total size to store. We don't have access to what we're
9646       // actually storing other than performing the loop and collecting the
9647       // info.
9648       SmallVector<std::pair<SDValue, SDValue>> Parts;
9649       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9650         SDValue PartValue = OutVals[i + 1];
9651         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9652         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9653         EVT PartVT = PartValue.getValueType();
9654         if (PartVT.isScalableVector())
9655           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9656         StoredSize += PartVT.getStoreSize();
9657         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9658         Parts.push_back(std::make_pair(PartValue, Offset));
9659         ++i;
9660       }
9661       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9662       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9663       MemOpChains.push_back(
9664           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9665                        MachinePointerInfo::getFixedStack(MF, FI)));
9666       for (const auto &Part : Parts) {
9667         SDValue PartValue = Part.first;
9668         SDValue PartOffset = Part.second;
9669         SDValue Address =
9670             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9671         MemOpChains.push_back(
9672             DAG.getStore(Chain, DL, PartValue, Address,
9673                          MachinePointerInfo::getFixedStack(MF, FI)));
9674       }
9675       ArgValue = SpillSlot;
9676     } else {
9677       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9678     }
9679 
9680     // Use local copy if it is a byval arg.
9681     if (Flags.isByVal())
9682       ArgValue = ByValArgs[j++];
9683 
9684     if (VA.isRegLoc()) {
9685       // Queue up the argument copies and emit them at the end.
9686       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9687     } else {
9688       assert(VA.isMemLoc() && "Argument not register or memory");
9689       assert(!IsTailCall && "Tail call not allowed if stack is used "
9690                             "for passing parameters");
9691 
9692       // Work out the address of the stack slot.
9693       if (!StackPtr.getNode())
9694         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9695       SDValue Address =
9696           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9697                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9698 
9699       // Emit the store.
9700       MemOpChains.push_back(
9701           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9702     }
9703   }
9704 
9705   // Join the stores, which are independent of one another.
9706   if (!MemOpChains.empty())
9707     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9708 
9709   SDValue Glue;
9710 
9711   // Build a sequence of copy-to-reg nodes, chained and glued together.
9712   for (auto &Reg : RegsToPass) {
9713     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9714     Glue = Chain.getValue(1);
9715   }
9716 
9717   // Validate that none of the argument registers have been marked as
9718   // reserved, if so report an error. Do the same for the return address if this
9719   // is not a tailcall.
9720   validateCCReservedRegs(RegsToPass, MF);
9721   if (!IsTailCall &&
9722       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9723     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9724         MF.getFunction(),
9725         "Return address register required, but has been reserved."});
9726 
9727   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9728   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9729   // split it and then direct call can be matched by PseudoCALL.
9730   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9731     const GlobalValue *GV = S->getGlobal();
9732 
9733     unsigned OpFlags = RISCVII::MO_CALL;
9734     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9735       OpFlags = RISCVII::MO_PLT;
9736 
9737     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9738   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9739     unsigned OpFlags = RISCVII::MO_CALL;
9740 
9741     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9742                                                  nullptr))
9743       OpFlags = RISCVII::MO_PLT;
9744 
9745     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9746   }
9747 
9748   // The first call operand is the chain and the second is the target address.
9749   SmallVector<SDValue, 8> Ops;
9750   Ops.push_back(Chain);
9751   Ops.push_back(Callee);
9752 
9753   // Add argument registers to the end of the list so that they are
9754   // known live into the call.
9755   for (auto &Reg : RegsToPass)
9756     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9757 
9758   if (!IsTailCall) {
9759     // Add a register mask operand representing the call-preserved registers.
9760     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9761     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9762     assert(Mask && "Missing call preserved mask for calling convention");
9763     Ops.push_back(DAG.getRegisterMask(Mask));
9764   }
9765 
9766   // Glue the call to the argument copies, if any.
9767   if (Glue.getNode())
9768     Ops.push_back(Glue);
9769 
9770   // Emit the call.
9771   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9772 
9773   if (IsTailCall) {
9774     MF.getFrameInfo().setHasTailCall();
9775     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9776   }
9777 
9778   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9779   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9780   Glue = Chain.getValue(1);
9781 
9782   // Mark the end of the call, which is glued to the call itself.
9783   Chain = DAG.getCALLSEQ_END(Chain,
9784                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9785                              DAG.getConstant(0, DL, PtrVT, true),
9786                              Glue, DL);
9787   Glue = Chain.getValue(1);
9788 
9789   // Assign locations to each value returned by this call.
9790   SmallVector<CCValAssign, 16> RVLocs;
9791   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9792   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9793 
9794   // Copy all of the result registers out of their specified physreg.
9795   for (auto &VA : RVLocs) {
9796     // Copy the value out
9797     SDValue RetValue =
9798         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9799     // Glue the RetValue to the end of the call sequence
9800     Chain = RetValue.getValue(1);
9801     Glue = RetValue.getValue(2);
9802 
9803     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9804       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9805       SDValue RetValue2 =
9806           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9807       Chain = RetValue2.getValue(1);
9808       Glue = RetValue2.getValue(2);
9809       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9810                              RetValue2);
9811     }
9812 
9813     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9814 
9815     InVals.push_back(RetValue);
9816   }
9817 
9818   return Chain;
9819 }
9820 
9821 bool RISCVTargetLowering::CanLowerReturn(
9822     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9823     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9824   SmallVector<CCValAssign, 16> RVLocs;
9825   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9826 
9827   Optional<unsigned> FirstMaskArgument;
9828   if (Subtarget.hasVInstructions())
9829     FirstMaskArgument = preAssignMask(Outs);
9830 
9831   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9832     MVT VT = Outs[i].VT;
9833     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9834     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9835     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9836                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9837                  *this, FirstMaskArgument))
9838       return false;
9839   }
9840   return true;
9841 }
9842 
9843 SDValue
9844 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9845                                  bool IsVarArg,
9846                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9847                                  const SmallVectorImpl<SDValue> &OutVals,
9848                                  const SDLoc &DL, SelectionDAG &DAG) const {
9849   const MachineFunction &MF = DAG.getMachineFunction();
9850   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9851 
9852   // Stores the assignment of the return value to a location.
9853   SmallVector<CCValAssign, 16> RVLocs;
9854 
9855   // Info about the registers and stack slot.
9856   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9857                  *DAG.getContext());
9858 
9859   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9860                     nullptr, CC_RISCV);
9861 
9862   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9863     report_fatal_error("GHC functions return void only");
9864 
9865   SDValue Glue;
9866   SmallVector<SDValue, 4> RetOps(1, Chain);
9867 
9868   // Copy the result values into the output registers.
9869   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9870     SDValue Val = OutVals[i];
9871     CCValAssign &VA = RVLocs[i];
9872     assert(VA.isRegLoc() && "Can only return in registers!");
9873 
9874     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9875       // Handle returning f64 on RV32D with a soft float ABI.
9876       assert(VA.isRegLoc() && "Expected return via registers");
9877       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9878                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9879       SDValue Lo = SplitF64.getValue(0);
9880       SDValue Hi = SplitF64.getValue(1);
9881       Register RegLo = VA.getLocReg();
9882       assert(RegLo < RISCV::X31 && "Invalid register pair");
9883       Register RegHi = RegLo + 1;
9884 
9885       if (STI.isRegisterReservedByUser(RegLo) ||
9886           STI.isRegisterReservedByUser(RegHi))
9887         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9888             MF.getFunction(),
9889             "Return value register required, but has been reserved."});
9890 
9891       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9892       Glue = Chain.getValue(1);
9893       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9894       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9895       Glue = Chain.getValue(1);
9896       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9897     } else {
9898       // Handle a 'normal' return.
9899       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9900       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9901 
9902       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9903         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9904             MF.getFunction(),
9905             "Return value register required, but has been reserved."});
9906 
9907       // Guarantee that all emitted copies are stuck together.
9908       Glue = Chain.getValue(1);
9909       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9910     }
9911   }
9912 
9913   RetOps[0] = Chain; // Update chain.
9914 
9915   // Add the glue node if we have it.
9916   if (Glue.getNode()) {
9917     RetOps.push_back(Glue);
9918   }
9919 
9920   unsigned RetOpc = RISCVISD::RET_FLAG;
9921   // Interrupt service routines use different return instructions.
9922   const Function &Func = DAG.getMachineFunction().getFunction();
9923   if (Func.hasFnAttribute("interrupt")) {
9924     if (!Func.getReturnType()->isVoidTy())
9925       report_fatal_error(
9926           "Functions with the interrupt attribute must have void return type!");
9927 
9928     MachineFunction &MF = DAG.getMachineFunction();
9929     StringRef Kind =
9930       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9931 
9932     if (Kind == "user")
9933       RetOpc = RISCVISD::URET_FLAG;
9934     else if (Kind == "supervisor")
9935       RetOpc = RISCVISD::SRET_FLAG;
9936     else
9937       RetOpc = RISCVISD::MRET_FLAG;
9938   }
9939 
9940   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9941 }
9942 
9943 void RISCVTargetLowering::validateCCReservedRegs(
9944     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9945     MachineFunction &MF) const {
9946   const Function &F = MF.getFunction();
9947   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9948 
9949   if (llvm::any_of(Regs, [&STI](auto Reg) {
9950         return STI.isRegisterReservedByUser(Reg.first);
9951       }))
9952     F.getContext().diagnose(DiagnosticInfoUnsupported{
9953         F, "Argument register required, but has been reserved."});
9954 }
9955 
9956 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9957   return CI->isTailCall();
9958 }
9959 
9960 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9961 #define NODE_NAME_CASE(NODE)                                                   \
9962   case RISCVISD::NODE:                                                         \
9963     return "RISCVISD::" #NODE;
9964   // clang-format off
9965   switch ((RISCVISD::NodeType)Opcode) {
9966   case RISCVISD::FIRST_NUMBER:
9967     break;
9968   NODE_NAME_CASE(RET_FLAG)
9969   NODE_NAME_CASE(URET_FLAG)
9970   NODE_NAME_CASE(SRET_FLAG)
9971   NODE_NAME_CASE(MRET_FLAG)
9972   NODE_NAME_CASE(CALL)
9973   NODE_NAME_CASE(SELECT_CC)
9974   NODE_NAME_CASE(BR_CC)
9975   NODE_NAME_CASE(BuildPairF64)
9976   NODE_NAME_CASE(SplitF64)
9977   NODE_NAME_CASE(TAIL)
9978   NODE_NAME_CASE(MULHSU)
9979   NODE_NAME_CASE(SLLW)
9980   NODE_NAME_CASE(SRAW)
9981   NODE_NAME_CASE(SRLW)
9982   NODE_NAME_CASE(DIVW)
9983   NODE_NAME_CASE(DIVUW)
9984   NODE_NAME_CASE(REMUW)
9985   NODE_NAME_CASE(ROLW)
9986   NODE_NAME_CASE(RORW)
9987   NODE_NAME_CASE(CLZW)
9988   NODE_NAME_CASE(CTZW)
9989   NODE_NAME_CASE(FSLW)
9990   NODE_NAME_CASE(FSRW)
9991   NODE_NAME_CASE(FSL)
9992   NODE_NAME_CASE(FSR)
9993   NODE_NAME_CASE(FMV_H_X)
9994   NODE_NAME_CASE(FMV_X_ANYEXTH)
9995   NODE_NAME_CASE(FMV_W_X_RV64)
9996   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9997   NODE_NAME_CASE(FCVT_X)
9998   NODE_NAME_CASE(FCVT_XU)
9999   NODE_NAME_CASE(FCVT_W_RV64)
10000   NODE_NAME_CASE(FCVT_WU_RV64)
10001   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10002   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10003   NODE_NAME_CASE(READ_CYCLE_WIDE)
10004   NODE_NAME_CASE(GREV)
10005   NODE_NAME_CASE(GREVW)
10006   NODE_NAME_CASE(GORC)
10007   NODE_NAME_CASE(GORCW)
10008   NODE_NAME_CASE(SHFL)
10009   NODE_NAME_CASE(SHFLW)
10010   NODE_NAME_CASE(UNSHFL)
10011   NODE_NAME_CASE(UNSHFLW)
10012   NODE_NAME_CASE(BFP)
10013   NODE_NAME_CASE(BFPW)
10014   NODE_NAME_CASE(BCOMPRESS)
10015   NODE_NAME_CASE(BCOMPRESSW)
10016   NODE_NAME_CASE(BDECOMPRESS)
10017   NODE_NAME_CASE(BDECOMPRESSW)
10018   NODE_NAME_CASE(VMV_V_X_VL)
10019   NODE_NAME_CASE(VFMV_V_F_VL)
10020   NODE_NAME_CASE(VMV_X_S)
10021   NODE_NAME_CASE(VMV_S_X_VL)
10022   NODE_NAME_CASE(VFMV_S_F_VL)
10023   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10024   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10025   NODE_NAME_CASE(READ_VLENB)
10026   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10027   NODE_NAME_CASE(VSLIDEUP_VL)
10028   NODE_NAME_CASE(VSLIDE1UP_VL)
10029   NODE_NAME_CASE(VSLIDEDOWN_VL)
10030   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10031   NODE_NAME_CASE(VID_VL)
10032   NODE_NAME_CASE(VFNCVT_ROD_VL)
10033   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10034   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10035   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10036   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10037   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10038   NODE_NAME_CASE(VECREDUCE_AND_VL)
10039   NODE_NAME_CASE(VECREDUCE_OR_VL)
10040   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10041   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10042   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10043   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10044   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10045   NODE_NAME_CASE(ADD_VL)
10046   NODE_NAME_CASE(AND_VL)
10047   NODE_NAME_CASE(MUL_VL)
10048   NODE_NAME_CASE(OR_VL)
10049   NODE_NAME_CASE(SDIV_VL)
10050   NODE_NAME_CASE(SHL_VL)
10051   NODE_NAME_CASE(SREM_VL)
10052   NODE_NAME_CASE(SRA_VL)
10053   NODE_NAME_CASE(SRL_VL)
10054   NODE_NAME_CASE(SUB_VL)
10055   NODE_NAME_CASE(UDIV_VL)
10056   NODE_NAME_CASE(UREM_VL)
10057   NODE_NAME_CASE(XOR_VL)
10058   NODE_NAME_CASE(SADDSAT_VL)
10059   NODE_NAME_CASE(UADDSAT_VL)
10060   NODE_NAME_CASE(SSUBSAT_VL)
10061   NODE_NAME_CASE(USUBSAT_VL)
10062   NODE_NAME_CASE(FADD_VL)
10063   NODE_NAME_CASE(FSUB_VL)
10064   NODE_NAME_CASE(FMUL_VL)
10065   NODE_NAME_CASE(FDIV_VL)
10066   NODE_NAME_CASE(FNEG_VL)
10067   NODE_NAME_CASE(FABS_VL)
10068   NODE_NAME_CASE(FSQRT_VL)
10069   NODE_NAME_CASE(FMA_VL)
10070   NODE_NAME_CASE(FCOPYSIGN_VL)
10071   NODE_NAME_CASE(SMIN_VL)
10072   NODE_NAME_CASE(SMAX_VL)
10073   NODE_NAME_CASE(UMIN_VL)
10074   NODE_NAME_CASE(UMAX_VL)
10075   NODE_NAME_CASE(FMINNUM_VL)
10076   NODE_NAME_CASE(FMAXNUM_VL)
10077   NODE_NAME_CASE(MULHS_VL)
10078   NODE_NAME_CASE(MULHU_VL)
10079   NODE_NAME_CASE(FP_TO_SINT_VL)
10080   NODE_NAME_CASE(FP_TO_UINT_VL)
10081   NODE_NAME_CASE(SINT_TO_FP_VL)
10082   NODE_NAME_CASE(UINT_TO_FP_VL)
10083   NODE_NAME_CASE(FP_EXTEND_VL)
10084   NODE_NAME_CASE(FP_ROUND_VL)
10085   NODE_NAME_CASE(VWMUL_VL)
10086   NODE_NAME_CASE(VWMULU_VL)
10087   NODE_NAME_CASE(VWADDU_VL)
10088   NODE_NAME_CASE(SETCC_VL)
10089   NODE_NAME_CASE(VSELECT_VL)
10090   NODE_NAME_CASE(VMAND_VL)
10091   NODE_NAME_CASE(VMOR_VL)
10092   NODE_NAME_CASE(VMXOR_VL)
10093   NODE_NAME_CASE(VMCLR_VL)
10094   NODE_NAME_CASE(VMSET_VL)
10095   NODE_NAME_CASE(VRGATHER_VX_VL)
10096   NODE_NAME_CASE(VRGATHER_VV_VL)
10097   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10098   NODE_NAME_CASE(VSEXT_VL)
10099   NODE_NAME_CASE(VZEXT_VL)
10100   NODE_NAME_CASE(VCPOP_VL)
10101   NODE_NAME_CASE(VLE_VL)
10102   NODE_NAME_CASE(VSE_VL)
10103   NODE_NAME_CASE(READ_CSR)
10104   NODE_NAME_CASE(WRITE_CSR)
10105   NODE_NAME_CASE(SWAP_CSR)
10106   }
10107   // clang-format on
10108   return nullptr;
10109 #undef NODE_NAME_CASE
10110 }
10111 
10112 /// getConstraintType - Given a constraint letter, return the type of
10113 /// constraint it is for this target.
10114 RISCVTargetLowering::ConstraintType
10115 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10116   if (Constraint.size() == 1) {
10117     switch (Constraint[0]) {
10118     default:
10119       break;
10120     case 'f':
10121       return C_RegisterClass;
10122     case 'I':
10123     case 'J':
10124     case 'K':
10125       return C_Immediate;
10126     case 'A':
10127       return C_Memory;
10128     case 'S': // A symbolic address
10129       return C_Other;
10130     }
10131   } else {
10132     if (Constraint == "vr" || Constraint == "vm")
10133       return C_RegisterClass;
10134   }
10135   return TargetLowering::getConstraintType(Constraint);
10136 }
10137 
10138 std::pair<unsigned, const TargetRegisterClass *>
10139 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10140                                                   StringRef Constraint,
10141                                                   MVT VT) const {
10142   // First, see if this is a constraint that directly corresponds to a
10143   // RISCV register class.
10144   if (Constraint.size() == 1) {
10145     switch (Constraint[0]) {
10146     case 'r':
10147       // TODO: Support fixed vectors up to XLen for P extension?
10148       if (VT.isVector())
10149         break;
10150       return std::make_pair(0U, &RISCV::GPRRegClass);
10151     case 'f':
10152       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10153         return std::make_pair(0U, &RISCV::FPR16RegClass);
10154       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10155         return std::make_pair(0U, &RISCV::FPR32RegClass);
10156       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10157         return std::make_pair(0U, &RISCV::FPR64RegClass);
10158       break;
10159     default:
10160       break;
10161     }
10162   } else if (Constraint == "vr") {
10163     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10164                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10165       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10166         return std::make_pair(0U, RC);
10167     }
10168   } else if (Constraint == "vm") {
10169     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10170       return std::make_pair(0U, &RISCV::VMV0RegClass);
10171   }
10172 
10173   // Clang will correctly decode the usage of register name aliases into their
10174   // official names. However, other frontends like `rustc` do not. This allows
10175   // users of these frontends to use the ABI names for registers in LLVM-style
10176   // register constraints.
10177   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10178                                .Case("{zero}", RISCV::X0)
10179                                .Case("{ra}", RISCV::X1)
10180                                .Case("{sp}", RISCV::X2)
10181                                .Case("{gp}", RISCV::X3)
10182                                .Case("{tp}", RISCV::X4)
10183                                .Case("{t0}", RISCV::X5)
10184                                .Case("{t1}", RISCV::X6)
10185                                .Case("{t2}", RISCV::X7)
10186                                .Cases("{s0}", "{fp}", RISCV::X8)
10187                                .Case("{s1}", RISCV::X9)
10188                                .Case("{a0}", RISCV::X10)
10189                                .Case("{a1}", RISCV::X11)
10190                                .Case("{a2}", RISCV::X12)
10191                                .Case("{a3}", RISCV::X13)
10192                                .Case("{a4}", RISCV::X14)
10193                                .Case("{a5}", RISCV::X15)
10194                                .Case("{a6}", RISCV::X16)
10195                                .Case("{a7}", RISCV::X17)
10196                                .Case("{s2}", RISCV::X18)
10197                                .Case("{s3}", RISCV::X19)
10198                                .Case("{s4}", RISCV::X20)
10199                                .Case("{s5}", RISCV::X21)
10200                                .Case("{s6}", RISCV::X22)
10201                                .Case("{s7}", RISCV::X23)
10202                                .Case("{s8}", RISCV::X24)
10203                                .Case("{s9}", RISCV::X25)
10204                                .Case("{s10}", RISCV::X26)
10205                                .Case("{s11}", RISCV::X27)
10206                                .Case("{t3}", RISCV::X28)
10207                                .Case("{t4}", RISCV::X29)
10208                                .Case("{t5}", RISCV::X30)
10209                                .Case("{t6}", RISCV::X31)
10210                                .Default(RISCV::NoRegister);
10211   if (XRegFromAlias != RISCV::NoRegister)
10212     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10213 
10214   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10215   // TableGen record rather than the AsmName to choose registers for InlineAsm
10216   // constraints, plus we want to match those names to the widest floating point
10217   // register type available, manually select floating point registers here.
10218   //
10219   // The second case is the ABI name of the register, so that frontends can also
10220   // use the ABI names in register constraint lists.
10221   if (Subtarget.hasStdExtF()) {
10222     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10223                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10224                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10225                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10226                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10227                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10228                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10229                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10230                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10231                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10232                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10233                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10234                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10235                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10236                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10237                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10238                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10239                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10240                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10241                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10242                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10243                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10244                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10245                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10246                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10247                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10248                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10249                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10250                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10251                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10252                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10253                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10254                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10255                         .Default(RISCV::NoRegister);
10256     if (FReg != RISCV::NoRegister) {
10257       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10258       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10259         unsigned RegNo = FReg - RISCV::F0_F;
10260         unsigned DReg = RISCV::F0_D + RegNo;
10261         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10262       }
10263       if (VT == MVT::f32 || VT == MVT::Other)
10264         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10265       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10266         unsigned RegNo = FReg - RISCV::F0_F;
10267         unsigned HReg = RISCV::F0_H + RegNo;
10268         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10269       }
10270     }
10271   }
10272 
10273   if (Subtarget.hasVInstructions()) {
10274     Register VReg = StringSwitch<Register>(Constraint.lower())
10275                         .Case("{v0}", RISCV::V0)
10276                         .Case("{v1}", RISCV::V1)
10277                         .Case("{v2}", RISCV::V2)
10278                         .Case("{v3}", RISCV::V3)
10279                         .Case("{v4}", RISCV::V4)
10280                         .Case("{v5}", RISCV::V5)
10281                         .Case("{v6}", RISCV::V6)
10282                         .Case("{v7}", RISCV::V7)
10283                         .Case("{v8}", RISCV::V8)
10284                         .Case("{v9}", RISCV::V9)
10285                         .Case("{v10}", RISCV::V10)
10286                         .Case("{v11}", RISCV::V11)
10287                         .Case("{v12}", RISCV::V12)
10288                         .Case("{v13}", RISCV::V13)
10289                         .Case("{v14}", RISCV::V14)
10290                         .Case("{v15}", RISCV::V15)
10291                         .Case("{v16}", RISCV::V16)
10292                         .Case("{v17}", RISCV::V17)
10293                         .Case("{v18}", RISCV::V18)
10294                         .Case("{v19}", RISCV::V19)
10295                         .Case("{v20}", RISCV::V20)
10296                         .Case("{v21}", RISCV::V21)
10297                         .Case("{v22}", RISCV::V22)
10298                         .Case("{v23}", RISCV::V23)
10299                         .Case("{v24}", RISCV::V24)
10300                         .Case("{v25}", RISCV::V25)
10301                         .Case("{v26}", RISCV::V26)
10302                         .Case("{v27}", RISCV::V27)
10303                         .Case("{v28}", RISCV::V28)
10304                         .Case("{v29}", RISCV::V29)
10305                         .Case("{v30}", RISCV::V30)
10306                         .Case("{v31}", RISCV::V31)
10307                         .Default(RISCV::NoRegister);
10308     if (VReg != RISCV::NoRegister) {
10309       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10310         return std::make_pair(VReg, &RISCV::VMRegClass);
10311       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10312         return std::make_pair(VReg, &RISCV::VRRegClass);
10313       for (const auto *RC :
10314            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10315         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10316           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10317           return std::make_pair(VReg, RC);
10318         }
10319       }
10320     }
10321   }
10322 
10323   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10324 }
10325 
10326 unsigned
10327 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10328   // Currently only support length 1 constraints.
10329   if (ConstraintCode.size() == 1) {
10330     switch (ConstraintCode[0]) {
10331     case 'A':
10332       return InlineAsm::Constraint_A;
10333     default:
10334       break;
10335     }
10336   }
10337 
10338   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10339 }
10340 
10341 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10342     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10343     SelectionDAG &DAG) const {
10344   // Currently only support length 1 constraints.
10345   if (Constraint.length() == 1) {
10346     switch (Constraint[0]) {
10347     case 'I':
10348       // Validate & create a 12-bit signed immediate operand.
10349       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10350         uint64_t CVal = C->getSExtValue();
10351         if (isInt<12>(CVal))
10352           Ops.push_back(
10353               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10354       }
10355       return;
10356     case 'J':
10357       // Validate & create an integer zero operand.
10358       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10359         if (C->getZExtValue() == 0)
10360           Ops.push_back(
10361               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10362       return;
10363     case 'K':
10364       // Validate & create a 5-bit unsigned immediate operand.
10365       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10366         uint64_t CVal = C->getZExtValue();
10367         if (isUInt<5>(CVal))
10368           Ops.push_back(
10369               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10370       }
10371       return;
10372     case 'S':
10373       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10374         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10375                                                  GA->getValueType(0)));
10376       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10377         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10378                                                 BA->getValueType(0)));
10379       }
10380       return;
10381     default:
10382       break;
10383     }
10384   }
10385   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10386 }
10387 
10388 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10389                                                    Instruction *Inst,
10390                                                    AtomicOrdering Ord) const {
10391   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10392     return Builder.CreateFence(Ord);
10393   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10394     return Builder.CreateFence(AtomicOrdering::Release);
10395   return nullptr;
10396 }
10397 
10398 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10399                                                     Instruction *Inst,
10400                                                     AtomicOrdering Ord) const {
10401   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10402     return Builder.CreateFence(AtomicOrdering::Acquire);
10403   return nullptr;
10404 }
10405 
10406 TargetLowering::AtomicExpansionKind
10407 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10408   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10409   // point operations can't be used in an lr/sc sequence without breaking the
10410   // forward-progress guarantee.
10411   if (AI->isFloatingPointOperation())
10412     return AtomicExpansionKind::CmpXChg;
10413 
10414   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10415   if (Size == 8 || Size == 16)
10416     return AtomicExpansionKind::MaskedIntrinsic;
10417   return AtomicExpansionKind::None;
10418 }
10419 
10420 static Intrinsic::ID
10421 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10422   if (XLen == 32) {
10423     switch (BinOp) {
10424     default:
10425       llvm_unreachable("Unexpected AtomicRMW BinOp");
10426     case AtomicRMWInst::Xchg:
10427       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10428     case AtomicRMWInst::Add:
10429       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10430     case AtomicRMWInst::Sub:
10431       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10432     case AtomicRMWInst::Nand:
10433       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10434     case AtomicRMWInst::Max:
10435       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10436     case AtomicRMWInst::Min:
10437       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10438     case AtomicRMWInst::UMax:
10439       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10440     case AtomicRMWInst::UMin:
10441       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10442     }
10443   }
10444 
10445   if (XLen == 64) {
10446     switch (BinOp) {
10447     default:
10448       llvm_unreachable("Unexpected AtomicRMW BinOp");
10449     case AtomicRMWInst::Xchg:
10450       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10451     case AtomicRMWInst::Add:
10452       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10453     case AtomicRMWInst::Sub:
10454       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10455     case AtomicRMWInst::Nand:
10456       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10457     case AtomicRMWInst::Max:
10458       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10459     case AtomicRMWInst::Min:
10460       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10461     case AtomicRMWInst::UMax:
10462       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10463     case AtomicRMWInst::UMin:
10464       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10465     }
10466   }
10467 
10468   llvm_unreachable("Unexpected XLen\n");
10469 }
10470 
10471 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10472     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10473     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10474   unsigned XLen = Subtarget.getXLen();
10475   Value *Ordering =
10476       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10477   Type *Tys[] = {AlignedAddr->getType()};
10478   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10479       AI->getModule(),
10480       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10481 
10482   if (XLen == 64) {
10483     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10484     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10485     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10486   }
10487 
10488   Value *Result;
10489 
10490   // Must pass the shift amount needed to sign extend the loaded value prior
10491   // to performing a signed comparison for min/max. ShiftAmt is the number of
10492   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10493   // is the number of bits to left+right shift the value in order to
10494   // sign-extend.
10495   if (AI->getOperation() == AtomicRMWInst::Min ||
10496       AI->getOperation() == AtomicRMWInst::Max) {
10497     const DataLayout &DL = AI->getModule()->getDataLayout();
10498     unsigned ValWidth =
10499         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10500     Value *SextShamt =
10501         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10502     Result = Builder.CreateCall(LrwOpScwLoop,
10503                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10504   } else {
10505     Result =
10506         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10507   }
10508 
10509   if (XLen == 64)
10510     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10511   return Result;
10512 }
10513 
10514 TargetLowering::AtomicExpansionKind
10515 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10516     AtomicCmpXchgInst *CI) const {
10517   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10518   if (Size == 8 || Size == 16)
10519     return AtomicExpansionKind::MaskedIntrinsic;
10520   return AtomicExpansionKind::None;
10521 }
10522 
10523 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10524     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10525     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10526   unsigned XLen = Subtarget.getXLen();
10527   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10528   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10529   if (XLen == 64) {
10530     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10531     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10532     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10533     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10534   }
10535   Type *Tys[] = {AlignedAddr->getType()};
10536   Function *MaskedCmpXchg =
10537       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10538   Value *Result = Builder.CreateCall(
10539       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10540   if (XLen == 64)
10541     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10542   return Result;
10543 }
10544 
10545 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10546   return false;
10547 }
10548 
10549 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10550                                                EVT VT) const {
10551   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10552     return false;
10553 
10554   switch (FPVT.getSimpleVT().SimpleTy) {
10555   case MVT::f16:
10556     return Subtarget.hasStdExtZfh();
10557   case MVT::f32:
10558     return Subtarget.hasStdExtF();
10559   case MVT::f64:
10560     return Subtarget.hasStdExtD();
10561   default:
10562     return false;
10563   }
10564 }
10565 
10566 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10567   // If we are using the small code model, we can reduce size of jump table
10568   // entry to 4 bytes.
10569   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10570       getTargetMachine().getCodeModel() == CodeModel::Small) {
10571     return MachineJumpTableInfo::EK_Custom32;
10572   }
10573   return TargetLowering::getJumpTableEncoding();
10574 }
10575 
10576 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10577     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10578     unsigned uid, MCContext &Ctx) const {
10579   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10580          getTargetMachine().getCodeModel() == CodeModel::Small);
10581   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10582 }
10583 
10584 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10585                                                      EVT VT) const {
10586   VT = VT.getScalarType();
10587 
10588   if (!VT.isSimple())
10589     return false;
10590 
10591   switch (VT.getSimpleVT().SimpleTy) {
10592   case MVT::f16:
10593     return Subtarget.hasStdExtZfh();
10594   case MVT::f32:
10595     return Subtarget.hasStdExtF();
10596   case MVT::f64:
10597     return Subtarget.hasStdExtD();
10598   default:
10599     break;
10600   }
10601 
10602   return false;
10603 }
10604 
10605 Register RISCVTargetLowering::getExceptionPointerRegister(
10606     const Constant *PersonalityFn) const {
10607   return RISCV::X10;
10608 }
10609 
10610 Register RISCVTargetLowering::getExceptionSelectorRegister(
10611     const Constant *PersonalityFn) const {
10612   return RISCV::X11;
10613 }
10614 
10615 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10616   // Return false to suppress the unnecessary extensions if the LibCall
10617   // arguments or return value is f32 type for LP64 ABI.
10618   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10619   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10620     return false;
10621 
10622   return true;
10623 }
10624 
10625 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10626   if (Subtarget.is64Bit() && Type == MVT::i32)
10627     return true;
10628 
10629   return IsSigned;
10630 }
10631 
10632 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10633                                                  SDValue C) const {
10634   // Check integral scalar types.
10635   if (VT.isScalarInteger()) {
10636     // Omit the optimization if the sub target has the M extension and the data
10637     // size exceeds XLen.
10638     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10639       return false;
10640     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10641       // Break the MUL to a SLLI and an ADD/SUB.
10642       const APInt &Imm = ConstNode->getAPIntValue();
10643       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10644           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10645         return true;
10646       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10647       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10648           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10649            (Imm - 8).isPowerOf2()))
10650         return true;
10651       // Omit the following optimization if the sub target has the M extension
10652       // and the data size >= XLen.
10653       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10654         return false;
10655       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10656       // a pair of LUI/ADDI.
10657       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10658         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10659         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10660             (1 - ImmS).isPowerOf2())
10661         return true;
10662       }
10663     }
10664   }
10665 
10666   return false;
10667 }
10668 
10669 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10670     const SDValue &AddNode, const SDValue &ConstNode) const {
10671   // Let the DAGCombiner decide for vectors.
10672   EVT VT = AddNode.getValueType();
10673   if (VT.isVector())
10674     return true;
10675 
10676   // Let the DAGCombiner decide for larger types.
10677   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10678     return true;
10679 
10680   // It is worse if c1 is simm12 while c1*c2 is not.
10681   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10682   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10683   const APInt &C1 = C1Node->getAPIntValue();
10684   const APInt &C2 = C2Node->getAPIntValue();
10685   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10686     return false;
10687 
10688   // Default to true and let the DAGCombiner decide.
10689   return true;
10690 }
10691 
10692 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10693     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10694     bool *Fast) const {
10695   if (!VT.isVector())
10696     return false;
10697 
10698   EVT ElemVT = VT.getVectorElementType();
10699   if (Alignment >= ElemVT.getStoreSize()) {
10700     if (Fast)
10701       *Fast = true;
10702     return true;
10703   }
10704 
10705   return false;
10706 }
10707 
10708 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10709     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10710     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10711   bool IsABIRegCopy = CC.hasValue();
10712   EVT ValueVT = Val.getValueType();
10713   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10714     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10715     // and cast to f32.
10716     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10717     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10718     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10719                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10720     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10721     Parts[0] = Val;
10722     return true;
10723   }
10724 
10725   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10726     LLVMContext &Context = *DAG.getContext();
10727     EVT ValueEltVT = ValueVT.getVectorElementType();
10728     EVT PartEltVT = PartVT.getVectorElementType();
10729     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10730     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10731     if (PartVTBitSize % ValueVTBitSize == 0) {
10732       assert(PartVTBitSize >= ValueVTBitSize);
10733       // If the element types are different, bitcast to the same element type of
10734       // PartVT first.
10735       // Give an example here, we want copy a <vscale x 1 x i8> value to
10736       // <vscale x 4 x i16>.
10737       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10738       // subvector, then we can bitcast to <vscale x 4 x i16>.
10739       if (ValueEltVT != PartEltVT) {
10740         if (PartVTBitSize > ValueVTBitSize) {
10741           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10742           assert(Count != 0 && "The number of element should not be zero.");
10743           EVT SameEltTypeVT =
10744               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10745           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10746                             DAG.getUNDEF(SameEltTypeVT), Val,
10747                             DAG.getVectorIdxConstant(0, DL));
10748         }
10749         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10750       } else {
10751         Val =
10752             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10753                         Val, DAG.getVectorIdxConstant(0, DL));
10754       }
10755       Parts[0] = Val;
10756       return true;
10757     }
10758   }
10759   return false;
10760 }
10761 
10762 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10763     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10764     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10765   bool IsABIRegCopy = CC.hasValue();
10766   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10767     SDValue Val = Parts[0];
10768 
10769     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10770     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10771     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10772     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10773     return Val;
10774   }
10775 
10776   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10777     LLVMContext &Context = *DAG.getContext();
10778     SDValue Val = Parts[0];
10779     EVT ValueEltVT = ValueVT.getVectorElementType();
10780     EVT PartEltVT = PartVT.getVectorElementType();
10781     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10782     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10783     if (PartVTBitSize % ValueVTBitSize == 0) {
10784       assert(PartVTBitSize >= ValueVTBitSize);
10785       EVT SameEltTypeVT = ValueVT;
10786       // If the element types are different, convert it to the same element type
10787       // of PartVT.
10788       // Give an example here, we want copy a <vscale x 1 x i8> value from
10789       // <vscale x 4 x i16>.
10790       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10791       // then we can extract <vscale x 1 x i8>.
10792       if (ValueEltVT != PartEltVT) {
10793         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10794         assert(Count != 0 && "The number of element should not be zero.");
10795         SameEltTypeVT =
10796             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10797         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10798       }
10799       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10800                         DAG.getVectorIdxConstant(0, DL));
10801       return Val;
10802     }
10803   }
10804   return SDValue();
10805 }
10806 
10807 SDValue
10808 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10809                                    SelectionDAG &DAG,
10810                                    SmallVectorImpl<SDNode *> &Created) const {
10811   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10812   if (isIntDivCheap(N->getValueType(0), Attr))
10813     return SDValue(N, 0); // Lower SDIV as SDIV
10814 
10815   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10816          "Unexpected divisor!");
10817 
10818   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10819   if (!Subtarget.hasStdExtZbt())
10820     return SDValue();
10821 
10822   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10823   // Besides, more critical path instructions will be generated when dividing
10824   // by 2. So we keep using the original DAGs for these cases.
10825   unsigned Lg2 = Divisor.countTrailingZeros();
10826   if (Lg2 == 1 || Lg2 >= 12)
10827     return SDValue();
10828 
10829   // fold (sdiv X, pow2)
10830   EVT VT = N->getValueType(0);
10831   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10832     return SDValue();
10833 
10834   SDLoc DL(N);
10835   SDValue N0 = N->getOperand(0);
10836   SDValue Zero = DAG.getConstant(0, DL, VT);
10837   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10838 
10839   // Add (N0 < 0) ? Pow2 - 1 : 0;
10840   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10841   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10842   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10843 
10844   Created.push_back(Cmp.getNode());
10845   Created.push_back(Add.getNode());
10846   Created.push_back(Sel.getNode());
10847 
10848   // Divide by pow2.
10849   SDValue SRA =
10850       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10851 
10852   // If we're dividing by a positive value, we're done.  Otherwise, we must
10853   // negate the result.
10854   if (Divisor.isNonNegative())
10855     return SRA;
10856 
10857   Created.push_back(SRA.getNode());
10858   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10859 }
10860 
10861 #define GET_REGISTER_MATCHER
10862 #include "RISCVGenAsmMatcher.inc"
10863 
10864 Register
10865 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10866                                        const MachineFunction &MF) const {
10867   Register Reg = MatchRegisterAltName(RegName);
10868   if (Reg == RISCV::NoRegister)
10869     Reg = MatchRegisterName(RegName);
10870   if (Reg == RISCV::NoRegister)
10871     report_fatal_error(
10872         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10873   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10874   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10875     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10876                              StringRef(RegName) + "\"."));
10877   return Reg;
10878 }
10879 
10880 namespace llvm {
10881 namespace RISCVVIntrinsicsTable {
10882 
10883 #define GET_RISCVVIntrinsicsTable_IMPL
10884 #include "RISCVGenSearchableTables.inc"
10885 
10886 } // namespace RISCVVIntrinsicsTable
10887 
10888 } // namespace llvm
10889