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_MERGE,       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_MERGE,
530         ISD::VP_SELECT};
531 
532     if (!Subtarget.is64Bit()) {
533       // We must custom-lower certain vXi64 operations on RV32 due to the vector
534       // element type being illegal.
535       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
537 
538       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
539       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
540       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
541       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
542       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
543       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
544       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
545       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
546 
547       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
548       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
549       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
550       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
551       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
552       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
553       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
554       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
555     }
556 
557     for (MVT VT : BoolVecVTs) {
558       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
559 
560       // Mask VTs are custom-expanded into a series of standard nodes
561       setOperationAction(ISD::TRUNCATE, VT, Custom);
562       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
563       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
564       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
565 
566       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
567       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
568 
569       setOperationAction(ISD::SELECT, VT, Custom);
570       setOperationAction(ISD::SELECT_CC, VT, Expand);
571       setOperationAction(ISD::VSELECT, VT, Expand);
572       setOperationAction(ISD::VP_SELECT, VT, Expand);
573 
574       setOperationAction(ISD::VP_AND, VT, Custom);
575       setOperationAction(ISD::VP_OR, VT, Custom);
576       setOperationAction(ISD::VP_XOR, VT, Custom);
577 
578       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
579       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
580       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
581 
582       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
583       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
584       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
585 
586       // RVV has native int->float & float->int conversions where the
587       // element type sizes are within one power-of-two of each other. Any
588       // wider distances between type sizes have to be lowered as sequences
589       // which progressively narrow the gap in stages.
590       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
591       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
592       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
593       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
594 
595       // Expand all extending loads to types larger than this, and truncating
596       // stores from types larger than this.
597       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
598         setTruncStoreAction(OtherVT, VT, Expand);
599         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
600         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
601         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
602       }
603     }
604 
605     for (MVT VT : IntVecVTs) {
606       if (VT.getVectorElementType() == MVT::i64 &&
607           !Subtarget.hasVInstructionsI64())
608         continue;
609 
610       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
611       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
612 
613       // Vectors implement MULHS/MULHU.
614       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
615       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
616 
617       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
618       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
619         setOperationAction(ISD::MULHU, VT, Expand);
620         setOperationAction(ISD::MULHS, VT, Expand);
621       }
622 
623       setOperationAction(ISD::SMIN, VT, Legal);
624       setOperationAction(ISD::SMAX, VT, Legal);
625       setOperationAction(ISD::UMIN, VT, Legal);
626       setOperationAction(ISD::UMAX, VT, Legal);
627 
628       setOperationAction(ISD::ROTL, VT, Expand);
629       setOperationAction(ISD::ROTR, VT, Expand);
630 
631       setOperationAction(ISD::CTTZ, VT, Expand);
632       setOperationAction(ISD::CTLZ, VT, Expand);
633       setOperationAction(ISD::CTPOP, VT, Expand);
634 
635       setOperationAction(ISD::BSWAP, VT, Expand);
636 
637       // Custom-lower extensions and truncations from/to mask types.
638       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
639       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
640       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
641 
642       // RVV has native int->float & float->int conversions where the
643       // element type sizes are within one power-of-two of each other. Any
644       // wider distances between type sizes have to be lowered as sequences
645       // which progressively narrow the gap in stages.
646       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
647       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
648       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
649       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
650 
651       setOperationAction(ISD::SADDSAT, VT, Legal);
652       setOperationAction(ISD::UADDSAT, VT, Legal);
653       setOperationAction(ISD::SSUBSAT, VT, Legal);
654       setOperationAction(ISD::USUBSAT, VT, Legal);
655 
656       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
657       // nodes which truncate by one power of two at a time.
658       setOperationAction(ISD::TRUNCATE, VT, Custom);
659 
660       // Custom-lower insert/extract operations to simplify patterns.
661       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
662       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
663 
664       // Custom-lower reduction operations to set up the corresponding custom
665       // nodes' operands.
666       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
667       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
668       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
669       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
670       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
671       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
672       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
673       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
674 
675       for (unsigned VPOpc : IntegerVPOps)
676         setOperationAction(VPOpc, VT, Custom);
677 
678       setOperationAction(ISD::LOAD, VT, Custom);
679       setOperationAction(ISD::STORE, VT, Custom);
680 
681       setOperationAction(ISD::MLOAD, VT, Custom);
682       setOperationAction(ISD::MSTORE, VT, Custom);
683       setOperationAction(ISD::MGATHER, VT, Custom);
684       setOperationAction(ISD::MSCATTER, VT, Custom);
685 
686       setOperationAction(ISD::VP_LOAD, VT, Custom);
687       setOperationAction(ISD::VP_STORE, VT, Custom);
688       setOperationAction(ISD::VP_GATHER, VT, Custom);
689       setOperationAction(ISD::VP_SCATTER, VT, Custom);
690 
691       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
692       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
693       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
694 
695       setOperationAction(ISD::SELECT, VT, Custom);
696       setOperationAction(ISD::SELECT_CC, VT, Expand);
697 
698       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
699       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
700 
701       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
702         setTruncStoreAction(VT, OtherVT, Expand);
703         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
704         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
705         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
706       }
707 
708       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
709       // type that can represent the value exactly.
710       if (VT.getVectorElementType() != MVT::i64) {
711         MVT FloatEltVT =
712             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
713         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
714         if (isTypeLegal(FloatVT)) {
715           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
716           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
717         }
718       }
719     }
720 
721     // Expand various CCs to best match the RVV ISA, which natively supports UNE
722     // but no other unordered comparisons, and supports all ordered comparisons
723     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
724     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
725     // and we pattern-match those back to the "original", swapping operands once
726     // more. This way we catch both operations and both "vf" and "fv" forms with
727     // fewer patterns.
728     static const ISD::CondCode VFPCCToExpand[] = {
729         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
730         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
731         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
732     };
733 
734     // Sets common operation actions on RVV floating-point vector types.
735     const auto SetCommonVFPActions = [&](MVT VT) {
736       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
737       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
738       // sizes are within one power-of-two of each other. Therefore conversions
739       // between vXf16 and vXf64 must be lowered as sequences which convert via
740       // vXf32.
741       setOperationAction(ISD::FP_ROUND, VT, Custom);
742       setOperationAction(ISD::FP_EXTEND, VT, Custom);
743       // Custom-lower insert/extract operations to simplify patterns.
744       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
745       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
746       // Expand various condition codes (explained above).
747       for (auto CC : VFPCCToExpand)
748         setCondCodeAction(CC, VT, Expand);
749 
750       setOperationAction(ISD::FMINNUM, VT, Legal);
751       setOperationAction(ISD::FMAXNUM, VT, Legal);
752 
753       setOperationAction(ISD::FTRUNC, VT, Custom);
754       setOperationAction(ISD::FCEIL, VT, Custom);
755       setOperationAction(ISD::FFLOOR, VT, Custom);
756 
757       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
758       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
759       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
760       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
761 
762       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
763 
764       setOperationAction(ISD::LOAD, VT, Custom);
765       setOperationAction(ISD::STORE, VT, Custom);
766 
767       setOperationAction(ISD::MLOAD, VT, Custom);
768       setOperationAction(ISD::MSTORE, VT, Custom);
769       setOperationAction(ISD::MGATHER, VT, Custom);
770       setOperationAction(ISD::MSCATTER, VT, Custom);
771 
772       setOperationAction(ISD::VP_LOAD, VT, Custom);
773       setOperationAction(ISD::VP_STORE, VT, Custom);
774       setOperationAction(ISD::VP_GATHER, VT, Custom);
775       setOperationAction(ISD::VP_SCATTER, VT, Custom);
776 
777       setOperationAction(ISD::SELECT, VT, Custom);
778       setOperationAction(ISD::SELECT_CC, VT, Expand);
779 
780       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
781       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
782       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
783 
784       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
785 
786       for (unsigned VPOpc : FloatingPointVPOps)
787         setOperationAction(VPOpc, VT, Custom);
788     };
789 
790     // Sets common extload/truncstore actions on RVV floating-point vector
791     // types.
792     const auto SetCommonVFPExtLoadTruncStoreActions =
793         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
794           for (auto SmallVT : SmallerVTs) {
795             setTruncStoreAction(VT, SmallVT, Expand);
796             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
797           }
798         };
799 
800     if (Subtarget.hasVInstructionsF16())
801       for (MVT VT : F16VecVTs)
802         SetCommonVFPActions(VT);
803 
804     for (MVT VT : F32VecVTs) {
805       if (Subtarget.hasVInstructionsF32())
806         SetCommonVFPActions(VT);
807       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
808     }
809 
810     for (MVT VT : F64VecVTs) {
811       if (Subtarget.hasVInstructionsF64())
812         SetCommonVFPActions(VT);
813       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
814       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
815     }
816 
817     if (Subtarget.useRVVForFixedLengthVectors()) {
818       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
819         if (!useRVVForFixedLengthVectorVT(VT))
820           continue;
821 
822         // By default everything must be expanded.
823         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
824           setOperationAction(Op, VT, Expand);
825         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
826           setTruncStoreAction(VT, OtherVT, Expand);
827           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
828           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
829           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
830         }
831 
832         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
833         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
834         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
835 
836         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
837         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
838 
839         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
840         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
841 
842         setOperationAction(ISD::LOAD, VT, Custom);
843         setOperationAction(ISD::STORE, VT, Custom);
844 
845         setOperationAction(ISD::SETCC, VT, Custom);
846 
847         setOperationAction(ISD::SELECT, VT, Custom);
848 
849         setOperationAction(ISD::TRUNCATE, VT, Custom);
850 
851         setOperationAction(ISD::BITCAST, VT, Custom);
852 
853         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
854         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
855         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
856 
857         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
858         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
859         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
860 
861         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
862         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
863         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
864         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
865 
866         // Operations below are different for between masks and other vectors.
867         if (VT.getVectorElementType() == MVT::i1) {
868           setOperationAction(ISD::VP_AND, VT, Custom);
869           setOperationAction(ISD::VP_OR, VT, Custom);
870           setOperationAction(ISD::VP_XOR, VT, Custom);
871           setOperationAction(ISD::AND, VT, Custom);
872           setOperationAction(ISD::OR, VT, Custom);
873           setOperationAction(ISD::XOR, VT, Custom);
874           continue;
875         }
876 
877         // Use SPLAT_VECTOR to prevent type legalization from destroying the
878         // splats when type legalizing i64 scalar on RV32.
879         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
880         // improvements first.
881         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
882           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
883           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
884         }
885 
886         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
887         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
888 
889         setOperationAction(ISD::MLOAD, VT, Custom);
890         setOperationAction(ISD::MSTORE, VT, Custom);
891         setOperationAction(ISD::MGATHER, VT, Custom);
892         setOperationAction(ISD::MSCATTER, VT, Custom);
893 
894         setOperationAction(ISD::VP_LOAD, VT, Custom);
895         setOperationAction(ISD::VP_STORE, VT, Custom);
896         setOperationAction(ISD::VP_GATHER, VT, Custom);
897         setOperationAction(ISD::VP_SCATTER, VT, Custom);
898 
899         setOperationAction(ISD::ADD, VT, Custom);
900         setOperationAction(ISD::MUL, VT, Custom);
901         setOperationAction(ISD::SUB, VT, Custom);
902         setOperationAction(ISD::AND, VT, Custom);
903         setOperationAction(ISD::OR, VT, Custom);
904         setOperationAction(ISD::XOR, VT, Custom);
905         setOperationAction(ISD::SDIV, VT, Custom);
906         setOperationAction(ISD::SREM, VT, Custom);
907         setOperationAction(ISD::UDIV, VT, Custom);
908         setOperationAction(ISD::UREM, VT, Custom);
909         setOperationAction(ISD::SHL, VT, Custom);
910         setOperationAction(ISD::SRA, VT, Custom);
911         setOperationAction(ISD::SRL, VT, Custom);
912 
913         setOperationAction(ISD::SMIN, VT, Custom);
914         setOperationAction(ISD::SMAX, VT, Custom);
915         setOperationAction(ISD::UMIN, VT, Custom);
916         setOperationAction(ISD::UMAX, VT, Custom);
917         setOperationAction(ISD::ABS,  VT, Custom);
918 
919         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
920         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
921           setOperationAction(ISD::MULHS, VT, Custom);
922           setOperationAction(ISD::MULHU, VT, Custom);
923         }
924 
925         setOperationAction(ISD::SADDSAT, VT, Custom);
926         setOperationAction(ISD::UADDSAT, VT, Custom);
927         setOperationAction(ISD::SSUBSAT, VT, Custom);
928         setOperationAction(ISD::USUBSAT, VT, Custom);
929 
930         setOperationAction(ISD::VSELECT, VT, Custom);
931         setOperationAction(ISD::SELECT_CC, VT, Expand);
932 
933         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
934         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
935         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
936 
937         // Custom-lower reduction operations to set up the corresponding custom
938         // nodes' operands.
939         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
940         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
941         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
942         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
943         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
944 
945         for (unsigned VPOpc : IntegerVPOps)
946           setOperationAction(VPOpc, VT, Custom);
947 
948         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
949         // type that can represent the value exactly.
950         if (VT.getVectorElementType() != MVT::i64) {
951           MVT FloatEltVT =
952               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
953           EVT FloatVT =
954               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
955           if (isTypeLegal(FloatVT)) {
956             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
957             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
958           }
959         }
960       }
961 
962       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
963         if (!useRVVForFixedLengthVectorVT(VT))
964           continue;
965 
966         // By default everything must be expanded.
967         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
968           setOperationAction(Op, VT, Expand);
969         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
970           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
971           setTruncStoreAction(VT, OtherVT, Expand);
972         }
973 
974         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
975         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
976         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
977 
978         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
979         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
980         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
982         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
983 
984         setOperationAction(ISD::LOAD, VT, Custom);
985         setOperationAction(ISD::STORE, VT, Custom);
986         setOperationAction(ISD::MLOAD, VT, Custom);
987         setOperationAction(ISD::MSTORE, VT, Custom);
988         setOperationAction(ISD::MGATHER, VT, Custom);
989         setOperationAction(ISD::MSCATTER, VT, Custom);
990 
991         setOperationAction(ISD::VP_LOAD, VT, Custom);
992         setOperationAction(ISD::VP_STORE, VT, Custom);
993         setOperationAction(ISD::VP_GATHER, VT, Custom);
994         setOperationAction(ISD::VP_SCATTER, VT, Custom);
995 
996         setOperationAction(ISD::FADD, VT, Custom);
997         setOperationAction(ISD::FSUB, VT, Custom);
998         setOperationAction(ISD::FMUL, VT, Custom);
999         setOperationAction(ISD::FDIV, VT, Custom);
1000         setOperationAction(ISD::FNEG, VT, Custom);
1001         setOperationAction(ISD::FABS, VT, Custom);
1002         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1003         setOperationAction(ISD::FSQRT, VT, Custom);
1004         setOperationAction(ISD::FMA, VT, Custom);
1005         setOperationAction(ISD::FMINNUM, VT, Custom);
1006         setOperationAction(ISD::FMAXNUM, VT, Custom);
1007 
1008         setOperationAction(ISD::FP_ROUND, VT, Custom);
1009         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1010 
1011         setOperationAction(ISD::FTRUNC, VT, Custom);
1012         setOperationAction(ISD::FCEIL, VT, Custom);
1013         setOperationAction(ISD::FFLOOR, VT, Custom);
1014 
1015         for (auto CC : VFPCCToExpand)
1016           setCondCodeAction(CC, VT, Expand);
1017 
1018         setOperationAction(ISD::VSELECT, VT, Custom);
1019         setOperationAction(ISD::SELECT, VT, Custom);
1020         setOperationAction(ISD::SELECT_CC, VT, Expand);
1021 
1022         setOperationAction(ISD::BITCAST, VT, Custom);
1023 
1024         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1025         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1026         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1027         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1028 
1029         for (unsigned VPOpc : FloatingPointVPOps)
1030           setOperationAction(VPOpc, VT, Custom);
1031       }
1032 
1033       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1034       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1035       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1036       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1037       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1038       if (Subtarget.hasStdExtZfh())
1039         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1040       if (Subtarget.hasStdExtF())
1041         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1042       if (Subtarget.hasStdExtD())
1043         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1044     }
1045   }
1046 
1047   // Function alignments.
1048   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1049   setMinFunctionAlignment(FunctionAlignment);
1050   setPrefFunctionAlignment(FunctionAlignment);
1051 
1052   setMinimumJumpTableEntries(5);
1053 
1054   // Jumps are expensive, compared to logic
1055   setJumpIsExpensive();
1056 
1057   setTargetDAGCombine(ISD::ADD);
1058   setTargetDAGCombine(ISD::SUB);
1059   setTargetDAGCombine(ISD::AND);
1060   setTargetDAGCombine(ISD::OR);
1061   setTargetDAGCombine(ISD::XOR);
1062   setTargetDAGCombine(ISD::ANY_EXTEND);
1063   if (Subtarget.hasStdExtF()) {
1064     setTargetDAGCombine(ISD::ZERO_EXTEND);
1065     setTargetDAGCombine(ISD::FP_TO_SINT);
1066     setTargetDAGCombine(ISD::FP_TO_UINT);
1067     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1068     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1069   }
1070   if (Subtarget.hasVInstructions()) {
1071     setTargetDAGCombine(ISD::FCOPYSIGN);
1072     setTargetDAGCombine(ISD::MGATHER);
1073     setTargetDAGCombine(ISD::MSCATTER);
1074     setTargetDAGCombine(ISD::VP_GATHER);
1075     setTargetDAGCombine(ISD::VP_SCATTER);
1076     setTargetDAGCombine(ISD::SRA);
1077     setTargetDAGCombine(ISD::SRL);
1078     setTargetDAGCombine(ISD::SHL);
1079     setTargetDAGCombine(ISD::STORE);
1080   }
1081 }
1082 
1083 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1084                                             LLVMContext &Context,
1085                                             EVT VT) const {
1086   if (!VT.isVector())
1087     return getPointerTy(DL);
1088   if (Subtarget.hasVInstructions() &&
1089       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1090     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1091   return VT.changeVectorElementTypeToInteger();
1092 }
1093 
1094 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1095   return Subtarget.getXLenVT();
1096 }
1097 
1098 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1099                                              const CallInst &I,
1100                                              MachineFunction &MF,
1101                                              unsigned Intrinsic) const {
1102   auto &DL = I.getModule()->getDataLayout();
1103   switch (Intrinsic) {
1104   default:
1105     return false;
1106   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1107   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1108   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1109   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1110   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1111   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1112   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1113   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1114   case Intrinsic::riscv_masked_cmpxchg_i32: {
1115     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1116     Info.opc = ISD::INTRINSIC_W_CHAIN;
1117     Info.memVT = MVT::getVT(PtrTy->getPointerElementType());
1118     Info.ptrVal = I.getArgOperand(0);
1119     Info.offset = 0;
1120     Info.align = Align(4);
1121     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1122                  MachineMemOperand::MOVolatile;
1123     return true;
1124   }
1125   case Intrinsic::riscv_masked_strided_load:
1126     Info.opc = ISD::INTRINSIC_W_CHAIN;
1127     Info.ptrVal = I.getArgOperand(1);
1128     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1129     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1130     Info.size = MemoryLocation::UnknownSize;
1131     Info.flags |= MachineMemOperand::MOLoad;
1132     return true;
1133   case Intrinsic::riscv_masked_strided_store:
1134     Info.opc = ISD::INTRINSIC_VOID;
1135     Info.ptrVal = I.getArgOperand(1);
1136     Info.memVT =
1137         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1138     Info.align = Align(
1139         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1140         8);
1141     Info.size = MemoryLocation::UnknownSize;
1142     Info.flags |= MachineMemOperand::MOStore;
1143     return true;
1144   }
1145 }
1146 
1147 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1148                                                 const AddrMode &AM, Type *Ty,
1149                                                 unsigned AS,
1150                                                 Instruction *I) const {
1151   // No global is ever allowed as a base.
1152   if (AM.BaseGV)
1153     return false;
1154 
1155   // Require a 12-bit signed offset.
1156   if (!isInt<12>(AM.BaseOffs))
1157     return false;
1158 
1159   switch (AM.Scale) {
1160   case 0: // "r+i" or just "i", depending on HasBaseReg.
1161     break;
1162   case 1:
1163     if (!AM.HasBaseReg) // allow "r+i".
1164       break;
1165     return false; // disallow "r+r" or "r+r+i".
1166   default:
1167     return false;
1168   }
1169 
1170   return true;
1171 }
1172 
1173 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1174   return isInt<12>(Imm);
1175 }
1176 
1177 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1178   return isInt<12>(Imm);
1179 }
1180 
1181 // On RV32, 64-bit integers are split into their high and low parts and held
1182 // in two different registers, so the trunc is free since the low register can
1183 // just be used.
1184 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1185   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1186     return false;
1187   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1188   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1189   return (SrcBits == 64 && DestBits == 32);
1190 }
1191 
1192 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1193   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1194       !SrcVT.isInteger() || !DstVT.isInteger())
1195     return false;
1196   unsigned SrcBits = SrcVT.getSizeInBits();
1197   unsigned DestBits = DstVT.getSizeInBits();
1198   return (SrcBits == 64 && DestBits == 32);
1199 }
1200 
1201 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1202   // Zexts are free if they can be combined with a load.
1203   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1204   // poorly with type legalization of compares preferring sext.
1205   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1206     EVT MemVT = LD->getMemoryVT();
1207     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1208         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1209          LD->getExtensionType() == ISD::ZEXTLOAD))
1210       return true;
1211   }
1212 
1213   return TargetLowering::isZExtFree(Val, VT2);
1214 }
1215 
1216 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1217   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1218 }
1219 
1220 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1221   return Subtarget.hasStdExtZbb();
1222 }
1223 
1224 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1225   return Subtarget.hasStdExtZbb();
1226 }
1227 
1228 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1229   EVT VT = Y.getValueType();
1230 
1231   // FIXME: Support vectors once we have tests.
1232   if (VT.isVector())
1233     return false;
1234 
1235   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1236 }
1237 
1238 /// Check if sinking \p I's operands to I's basic block is profitable, because
1239 /// the operands can be folded into a target instruction, e.g.
1240 /// splats of scalars can fold into vector instructions.
1241 bool RISCVTargetLowering::shouldSinkOperands(
1242     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1243   using namespace llvm::PatternMatch;
1244 
1245   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1246     return false;
1247 
1248   auto IsSinker = [&](Instruction *I, int Operand) {
1249     switch (I->getOpcode()) {
1250     case Instruction::Add:
1251     case Instruction::Sub:
1252     case Instruction::Mul:
1253     case Instruction::And:
1254     case Instruction::Or:
1255     case Instruction::Xor:
1256     case Instruction::FAdd:
1257     case Instruction::FSub:
1258     case Instruction::FMul:
1259     case Instruction::FDiv:
1260     case Instruction::ICmp:
1261     case Instruction::FCmp:
1262       return true;
1263     case Instruction::Shl:
1264     case Instruction::LShr:
1265     case Instruction::AShr:
1266     case Instruction::UDiv:
1267     case Instruction::SDiv:
1268     case Instruction::URem:
1269     case Instruction::SRem:
1270       return Operand == 1;
1271     case Instruction::Call:
1272       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1273         switch (II->getIntrinsicID()) {
1274         case Intrinsic::fma:
1275           return Operand == 0 || Operand == 1;
1276         // FIXME: Our patterns can only match vx/vf instructions when the splat
1277         // it on the RHS, because TableGen doesn't recognize our VP operations
1278         // as commutative.
1279         case Intrinsic::vp_add:
1280         case Intrinsic::vp_mul:
1281         case Intrinsic::vp_and:
1282         case Intrinsic::vp_or:
1283         case Intrinsic::vp_xor:
1284         case Intrinsic::vp_fadd:
1285         case Intrinsic::vp_fmul:
1286         case Intrinsic::vp_shl:
1287         case Intrinsic::vp_lshr:
1288         case Intrinsic::vp_ashr:
1289         case Intrinsic::vp_udiv:
1290         case Intrinsic::vp_sdiv:
1291         case Intrinsic::vp_urem:
1292         case Intrinsic::vp_srem:
1293           return Operand == 1;
1294         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1295         // explicit patterns for both LHS and RHS (as 'vr' versions).
1296         case Intrinsic::vp_sub:
1297         case Intrinsic::vp_fsub:
1298         case Intrinsic::vp_fdiv:
1299           return Operand == 0 || Operand == 1;
1300         default:
1301           return false;
1302         }
1303       }
1304       return false;
1305     default:
1306       return false;
1307     }
1308   };
1309 
1310   for (auto OpIdx : enumerate(I->operands())) {
1311     if (!IsSinker(I, OpIdx.index()))
1312       continue;
1313 
1314     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1315     // Make sure we are not already sinking this operand
1316     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1317       continue;
1318 
1319     // We are looking for a splat that can be sunk.
1320     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1321                              m_Undef(), m_ZeroMask())))
1322       continue;
1323 
1324     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1325     // and vector registers
1326     for (Use &U : Op->uses()) {
1327       Instruction *Insn = cast<Instruction>(U.getUser());
1328       if (!IsSinker(Insn, U.getOperandNo()))
1329         return false;
1330     }
1331 
1332     Ops.push_back(&Op->getOperandUse(0));
1333     Ops.push_back(&OpIdx.value());
1334   }
1335   return true;
1336 }
1337 
1338 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1339                                        bool ForCodeSize) const {
1340   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1341   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1342     return false;
1343   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1344     return false;
1345   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1346     return false;
1347   return Imm.isZero();
1348 }
1349 
1350 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1351   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1352          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1353          (VT == MVT::f64 && Subtarget.hasStdExtD());
1354 }
1355 
1356 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1357                                                       CallingConv::ID CC,
1358                                                       EVT VT) const {
1359   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1360   // We might still end up using a GPR but that will be decided based on ABI.
1361   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1362   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1363     return MVT::f32;
1364 
1365   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1366 }
1367 
1368 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1369                                                            CallingConv::ID CC,
1370                                                            EVT VT) const {
1371   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1372   // We might still end up using a GPR but that will be decided based on ABI.
1373   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1374   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1375     return 1;
1376 
1377   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1378 }
1379 
1380 // Changes the condition code and swaps operands if necessary, so the SetCC
1381 // operation matches one of the comparisons supported directly by branches
1382 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1383 // with 1/-1.
1384 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1385                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1386   // Convert X > -1 to X >= 0.
1387   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1388     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1389     CC = ISD::SETGE;
1390     return;
1391   }
1392   // Convert X < 1 to 0 >= X.
1393   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1394     RHS = LHS;
1395     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1396     CC = ISD::SETGE;
1397     return;
1398   }
1399 
1400   switch (CC) {
1401   default:
1402     break;
1403   case ISD::SETGT:
1404   case ISD::SETLE:
1405   case ISD::SETUGT:
1406   case ISD::SETULE:
1407     CC = ISD::getSetCCSwappedOperands(CC);
1408     std::swap(LHS, RHS);
1409     break;
1410   }
1411 }
1412 
1413 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1414   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1415   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1416   if (VT.getVectorElementType() == MVT::i1)
1417     KnownSize *= 8;
1418 
1419   switch (KnownSize) {
1420   default:
1421     llvm_unreachable("Invalid LMUL.");
1422   case 8:
1423     return RISCVII::VLMUL::LMUL_F8;
1424   case 16:
1425     return RISCVII::VLMUL::LMUL_F4;
1426   case 32:
1427     return RISCVII::VLMUL::LMUL_F2;
1428   case 64:
1429     return RISCVII::VLMUL::LMUL_1;
1430   case 128:
1431     return RISCVII::VLMUL::LMUL_2;
1432   case 256:
1433     return RISCVII::VLMUL::LMUL_4;
1434   case 512:
1435     return RISCVII::VLMUL::LMUL_8;
1436   }
1437 }
1438 
1439 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1440   switch (LMul) {
1441   default:
1442     llvm_unreachable("Invalid LMUL.");
1443   case RISCVII::VLMUL::LMUL_F8:
1444   case RISCVII::VLMUL::LMUL_F4:
1445   case RISCVII::VLMUL::LMUL_F2:
1446   case RISCVII::VLMUL::LMUL_1:
1447     return RISCV::VRRegClassID;
1448   case RISCVII::VLMUL::LMUL_2:
1449     return RISCV::VRM2RegClassID;
1450   case RISCVII::VLMUL::LMUL_4:
1451     return RISCV::VRM4RegClassID;
1452   case RISCVII::VLMUL::LMUL_8:
1453     return RISCV::VRM8RegClassID;
1454   }
1455 }
1456 
1457 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1458   RISCVII::VLMUL LMUL = getLMUL(VT);
1459   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1460       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1461       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1462       LMUL == RISCVII::VLMUL::LMUL_1) {
1463     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1464                   "Unexpected subreg numbering");
1465     return RISCV::sub_vrm1_0 + Index;
1466   }
1467   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1468     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1469                   "Unexpected subreg numbering");
1470     return RISCV::sub_vrm2_0 + Index;
1471   }
1472   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1473     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm4_0 + Index;
1476   }
1477   llvm_unreachable("Invalid vector type.");
1478 }
1479 
1480 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1481   if (VT.getVectorElementType() == MVT::i1)
1482     return RISCV::VRRegClassID;
1483   return getRegClassIDForLMUL(getLMUL(VT));
1484 }
1485 
1486 // Attempt to decompose a subvector insert/extract between VecVT and
1487 // SubVecVT via subregister indices. Returns the subregister index that
1488 // can perform the subvector insert/extract with the given element index, as
1489 // well as the index corresponding to any leftover subvectors that must be
1490 // further inserted/extracted within the register class for SubVecVT.
1491 std::pair<unsigned, unsigned>
1492 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1493     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1494     const RISCVRegisterInfo *TRI) {
1495   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1496                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1497                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1498                 "Register classes not ordered");
1499   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1500   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1501   // Try to compose a subregister index that takes us from the incoming
1502   // LMUL>1 register class down to the outgoing one. At each step we half
1503   // the LMUL:
1504   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1505   // Note that this is not guaranteed to find a subregister index, such as
1506   // when we are extracting from one VR type to another.
1507   unsigned SubRegIdx = RISCV::NoSubRegister;
1508   for (const unsigned RCID :
1509        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1510     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1511       VecVT = VecVT.getHalfNumVectorElementsVT();
1512       bool IsHi =
1513           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1514       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1515                                             getSubregIndexByMVT(VecVT, IsHi));
1516       if (IsHi)
1517         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1518     }
1519   return {SubRegIdx, InsertExtractIdx};
1520 }
1521 
1522 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1523 // stores for those types.
1524 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1525   return !Subtarget.useRVVForFixedLengthVectors() ||
1526          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1527 }
1528 
1529 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1530   if (ScalarTy->isPointerTy())
1531     return true;
1532 
1533   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1534       ScalarTy->isIntegerTy(32))
1535     return true;
1536 
1537   if (ScalarTy->isIntegerTy(64))
1538     return Subtarget.hasVInstructionsI64();
1539 
1540   if (ScalarTy->isHalfTy())
1541     return Subtarget.hasVInstructionsF16();
1542   if (ScalarTy->isFloatTy())
1543     return Subtarget.hasVInstructionsF32();
1544   if (ScalarTy->isDoubleTy())
1545     return Subtarget.hasVInstructionsF64();
1546 
1547   return false;
1548 }
1549 
1550 static SDValue getVLOperand(SDValue Op) {
1551   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1552           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1553          "Unexpected opcode");
1554   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1555   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1556   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1557       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1558   if (!II)
1559     return SDValue();
1560   return Op.getOperand(II->VLOperand + 1 + HasChain);
1561 }
1562 
1563 static bool useRVVForFixedLengthVectorVT(MVT VT,
1564                                          const RISCVSubtarget &Subtarget) {
1565   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1566   if (!Subtarget.useRVVForFixedLengthVectors())
1567     return false;
1568 
1569   // We only support a set of vector types with a consistent maximum fixed size
1570   // across all supported vector element types to avoid legalization issues.
1571   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1572   // fixed-length vector type we support is 1024 bytes.
1573   if (VT.getFixedSizeInBits() > 1024 * 8)
1574     return false;
1575 
1576   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1577 
1578   MVT EltVT = VT.getVectorElementType();
1579 
1580   // Don't use RVV for vectors we cannot scalarize if required.
1581   switch (EltVT.SimpleTy) {
1582   // i1 is supported but has different rules.
1583   default:
1584     return false;
1585   case MVT::i1:
1586     // Masks can only use a single register.
1587     if (VT.getVectorNumElements() > MinVLen)
1588       return false;
1589     MinVLen /= 8;
1590     break;
1591   case MVT::i8:
1592   case MVT::i16:
1593   case MVT::i32:
1594     break;
1595   case MVT::i64:
1596     if (!Subtarget.hasVInstructionsI64())
1597       return false;
1598     break;
1599   case MVT::f16:
1600     if (!Subtarget.hasVInstructionsF16())
1601       return false;
1602     break;
1603   case MVT::f32:
1604     if (!Subtarget.hasVInstructionsF32())
1605       return false;
1606     break;
1607   case MVT::f64:
1608     if (!Subtarget.hasVInstructionsF64())
1609       return false;
1610     break;
1611   }
1612 
1613   // Reject elements larger than ELEN.
1614   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1615     return false;
1616 
1617   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1618   // Don't use RVV for types that don't fit.
1619   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1620     return false;
1621 
1622   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1623   // the base fixed length RVV support in place.
1624   if (!VT.isPow2VectorType())
1625     return false;
1626 
1627   return true;
1628 }
1629 
1630 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1631   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1632 }
1633 
1634 // Return the largest legal scalable vector type that matches VT's element type.
1635 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1636                                             const RISCVSubtarget &Subtarget) {
1637   // This may be called before legal types are setup.
1638   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1639           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1640          "Expected legal fixed length vector!");
1641 
1642   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1643   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1644 
1645   MVT EltVT = VT.getVectorElementType();
1646   switch (EltVT.SimpleTy) {
1647   default:
1648     llvm_unreachable("unexpected element type for RVV container");
1649   case MVT::i1:
1650   case MVT::i8:
1651   case MVT::i16:
1652   case MVT::i32:
1653   case MVT::i64:
1654   case MVT::f16:
1655   case MVT::f32:
1656   case MVT::f64: {
1657     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1658     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1659     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1660     unsigned NumElts =
1661         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1662     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1663     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1664     return MVT::getScalableVectorVT(EltVT, NumElts);
1665   }
1666   }
1667 }
1668 
1669 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1670                                             const RISCVSubtarget &Subtarget) {
1671   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1672                                           Subtarget);
1673 }
1674 
1675 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1676   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1677 }
1678 
1679 // Grow V to consume an entire RVV register.
1680 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1681                                        const RISCVSubtarget &Subtarget) {
1682   assert(VT.isScalableVector() &&
1683          "Expected to convert into a scalable vector!");
1684   assert(V.getValueType().isFixedLengthVector() &&
1685          "Expected a fixed length vector operand!");
1686   SDLoc DL(V);
1687   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1688   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1689 }
1690 
1691 // Shrink V so it's just big enough to maintain a VT's worth of data.
1692 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1693                                          const RISCVSubtarget &Subtarget) {
1694   assert(VT.isFixedLengthVector() &&
1695          "Expected to convert into a fixed length vector!");
1696   assert(V.getValueType().isScalableVector() &&
1697          "Expected a scalable vector operand!");
1698   SDLoc DL(V);
1699   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1700   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1701 }
1702 
1703 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1704 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1705 // the vector type that it is contained in.
1706 static std::pair<SDValue, SDValue>
1707 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1708                 const RISCVSubtarget &Subtarget) {
1709   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1710   MVT XLenVT = Subtarget.getXLenVT();
1711   SDValue VL = VecVT.isFixedLengthVector()
1712                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1713                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1714   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1715   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1716   return {Mask, VL};
1717 }
1718 
1719 // As above but assuming the given type is a scalable vector type.
1720 static std::pair<SDValue, SDValue>
1721 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1722                         const RISCVSubtarget &Subtarget) {
1723   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1724   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1725 }
1726 
1727 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1728 // of either is (currently) supported. This can get us into an infinite loop
1729 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1730 // as a ..., etc.
1731 // Until either (or both) of these can reliably lower any node, reporting that
1732 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1733 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1734 // which is not desirable.
1735 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1736     EVT VT, unsigned DefinedValues) const {
1737   return false;
1738 }
1739 
1740 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1741   // Only splats are currently supported.
1742   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1743     return true;
1744 
1745   return false;
1746 }
1747 
1748 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1749                                   const RISCVSubtarget &Subtarget) {
1750   // RISCV FP-to-int conversions saturate to the destination register size, but
1751   // don't produce 0 for nan. We can use a conversion instruction and fix the
1752   // nan case with a compare and a select.
1753   SDValue Src = Op.getOperand(0);
1754 
1755   EVT DstVT = Op.getValueType();
1756   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1757 
1758   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1759   unsigned Opc;
1760   if (SatVT == DstVT)
1761     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1762   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1763     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1764   else
1765     return SDValue();
1766   // FIXME: Support other SatVTs by clamping before or after the conversion.
1767 
1768   SDLoc DL(Op);
1769   SDValue FpToInt = DAG.getNode(
1770       Opc, DL, DstVT, Src,
1771       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1772 
1773   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1774   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1775 }
1776 
1777 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1778 // and back. Taking care to avoid converting values that are nan or already
1779 // correct.
1780 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1781 // have FRM dependencies modeled yet.
1782 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1783   MVT VT = Op.getSimpleValueType();
1784   assert(VT.isVector() && "Unexpected type");
1785 
1786   SDLoc DL(Op);
1787 
1788   // Freeze the source since we are increasing the number of uses.
1789   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1790 
1791   // Truncate to integer and convert back to FP.
1792   MVT IntVT = VT.changeVectorElementTypeToInteger();
1793   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1794   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1795 
1796   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1797 
1798   if (Op.getOpcode() == ISD::FCEIL) {
1799     // If the truncated value is the greater than or equal to the original
1800     // value, we've computed the ceil. Otherwise, we went the wrong way and
1801     // need to increase by 1.
1802     // FIXME: This should use a masked operation. Handle here or in isel?
1803     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1804                                  DAG.getConstantFP(1.0, DL, VT));
1805     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1806     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1807   } else if (Op.getOpcode() == ISD::FFLOOR) {
1808     // If the truncated value is the less than or equal to the original value,
1809     // we've computed the floor. Otherwise, we went the wrong way and need to
1810     // decrease by 1.
1811     // FIXME: This should use a masked operation. Handle here or in isel?
1812     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1813                                  DAG.getConstantFP(1.0, DL, VT));
1814     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1815     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1816   }
1817 
1818   // Restore the original sign so that -0.0 is preserved.
1819   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1820 
1821   // Determine the largest integer that can be represented exactly. This and
1822   // values larger than it don't have any fractional bits so don't need to
1823   // be converted.
1824   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1825   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1826   APFloat MaxVal = APFloat(FltSem);
1827   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1828                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1829   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1830 
1831   // If abs(Src) was larger than MaxVal or nan, keep it.
1832   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1833   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1834   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1835 }
1836 
1837 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1838                                  const RISCVSubtarget &Subtarget) {
1839   MVT VT = Op.getSimpleValueType();
1840   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1841 
1842   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1843 
1844   SDLoc DL(Op);
1845   SDValue Mask, VL;
1846   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1847 
1848   unsigned Opc =
1849       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1850   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1851   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1852 }
1853 
1854 struct VIDSequence {
1855   int64_t StepNumerator;
1856   unsigned StepDenominator;
1857   int64_t Addend;
1858 };
1859 
1860 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1861 // to the (non-zero) step S and start value X. This can be then lowered as the
1862 // RVV sequence (VID * S) + X, for example.
1863 // The step S is represented as an integer numerator divided by a positive
1864 // denominator. Note that the implementation currently only identifies
1865 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1866 // cannot detect 2/3, for example.
1867 // Note that this method will also match potentially unappealing index
1868 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1869 // determine whether this is worth generating code for.
1870 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1871   unsigned NumElts = Op.getNumOperands();
1872   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1873   if (!Op.getValueType().isInteger())
1874     return None;
1875 
1876   Optional<unsigned> SeqStepDenom;
1877   Optional<int64_t> SeqStepNum, SeqAddend;
1878   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1879   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1880   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1881     // Assume undef elements match the sequence; we just have to be careful
1882     // when interpolating across them.
1883     if (Op.getOperand(Idx).isUndef())
1884       continue;
1885     // The BUILD_VECTOR must be all constants.
1886     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1887       return None;
1888 
1889     uint64_t Val = Op.getConstantOperandVal(Idx) &
1890                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1891 
1892     if (PrevElt) {
1893       // Calculate the step since the last non-undef element, and ensure
1894       // it's consistent across the entire sequence.
1895       unsigned IdxDiff = Idx - PrevElt->second;
1896       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1897 
1898       // A zero-value value difference means that we're somewhere in the middle
1899       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1900       // step change before evaluating the sequence.
1901       if (ValDiff != 0) {
1902         int64_t Remainder = ValDiff % IdxDiff;
1903         // Normalize the step if it's greater than 1.
1904         if (Remainder != ValDiff) {
1905           // The difference must cleanly divide the element span.
1906           if (Remainder != 0)
1907             return None;
1908           ValDiff /= IdxDiff;
1909           IdxDiff = 1;
1910         }
1911 
1912         if (!SeqStepNum)
1913           SeqStepNum = ValDiff;
1914         else if (ValDiff != SeqStepNum)
1915           return None;
1916 
1917         if (!SeqStepDenom)
1918           SeqStepDenom = IdxDiff;
1919         else if (IdxDiff != *SeqStepDenom)
1920           return None;
1921       }
1922     }
1923 
1924     // Record and/or check any addend.
1925     if (SeqStepNum && SeqStepDenom) {
1926       uint64_t ExpectedVal =
1927           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1928       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1929       if (!SeqAddend)
1930         SeqAddend = Addend;
1931       else if (SeqAddend != Addend)
1932         return None;
1933     }
1934 
1935     // Record this non-undef element for later.
1936     if (!PrevElt || PrevElt->first != Val)
1937       PrevElt = std::make_pair(Val, Idx);
1938   }
1939   // We need to have logged both a step and an addend for this to count as
1940   // a legal index sequence.
1941   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1942     return None;
1943 
1944   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1945 }
1946 
1947 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1948                                  const RISCVSubtarget &Subtarget) {
1949   MVT VT = Op.getSimpleValueType();
1950   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1951 
1952   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1953 
1954   SDLoc DL(Op);
1955   SDValue Mask, VL;
1956   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1957 
1958   MVT XLenVT = Subtarget.getXLenVT();
1959   unsigned NumElts = Op.getNumOperands();
1960 
1961   if (VT.getVectorElementType() == MVT::i1) {
1962     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1963       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1964       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1965     }
1966 
1967     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1968       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1969       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1970     }
1971 
1972     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1973     // scalar integer chunks whose bit-width depends on the number of mask
1974     // bits and XLEN.
1975     // First, determine the most appropriate scalar integer type to use. This
1976     // is at most XLenVT, but may be shrunk to a smaller vector element type
1977     // according to the size of the final vector - use i8 chunks rather than
1978     // XLenVT if we're producing a v8i1. This results in more consistent
1979     // codegen across RV32 and RV64.
1980     unsigned NumViaIntegerBits =
1981         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1982     NumViaIntegerBits = std::min(NumViaIntegerBits,
1983                                  Subtarget.getMaxELENForFixedLengthVectors());
1984     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1985       // If we have to use more than one INSERT_VECTOR_ELT then this
1986       // optimization is likely to increase code size; avoid peforming it in
1987       // such a case. We can use a load from a constant pool in this case.
1988       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1989         return SDValue();
1990       // Now we can create our integer vector type. Note that it may be larger
1991       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1992       MVT IntegerViaVecVT =
1993           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1994                            divideCeil(NumElts, NumViaIntegerBits));
1995 
1996       uint64_t Bits = 0;
1997       unsigned BitPos = 0, IntegerEltIdx = 0;
1998       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1999 
2000       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2001         // Once we accumulate enough bits to fill our scalar type, insert into
2002         // our vector and clear our accumulated data.
2003         if (I != 0 && I % NumViaIntegerBits == 0) {
2004           if (NumViaIntegerBits <= 32)
2005             Bits = SignExtend64(Bits, 32);
2006           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2007           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2008                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2009           Bits = 0;
2010           BitPos = 0;
2011           IntegerEltIdx++;
2012         }
2013         SDValue V = Op.getOperand(I);
2014         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2015         Bits |= ((uint64_t)BitValue << BitPos);
2016       }
2017 
2018       // Insert the (remaining) scalar value into position in our integer
2019       // vector type.
2020       if (NumViaIntegerBits <= 32)
2021         Bits = SignExtend64(Bits, 32);
2022       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2023       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2024                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2025 
2026       if (NumElts < NumViaIntegerBits) {
2027         // If we're producing a smaller vector than our minimum legal integer
2028         // type, bitcast to the equivalent (known-legal) mask type, and extract
2029         // our final mask.
2030         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2031         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2032         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2033                           DAG.getConstant(0, DL, XLenVT));
2034       } else {
2035         // Else we must have produced an integer type with the same size as the
2036         // mask type; bitcast for the final result.
2037         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2038         Vec = DAG.getBitcast(VT, Vec);
2039       }
2040 
2041       return Vec;
2042     }
2043 
2044     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2045     // vector type, we have a legal equivalently-sized i8 type, so we can use
2046     // that.
2047     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2048     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2049 
2050     SDValue WideVec;
2051     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2052       // For a splat, perform a scalar truncate before creating the wider
2053       // vector.
2054       assert(Splat.getValueType() == XLenVT &&
2055              "Unexpected type for i1 splat value");
2056       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2057                           DAG.getConstant(1, DL, XLenVT));
2058       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2059     } else {
2060       SmallVector<SDValue, 8> Ops(Op->op_values());
2061       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2062       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2063       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2064     }
2065 
2066     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2067   }
2068 
2069   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2070     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2071                                         : RISCVISD::VMV_V_X_VL;
2072     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2073     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2074   }
2075 
2076   // Try and match index sequences, which we can lower to the vid instruction
2077   // with optional modifications. An all-undef vector is matched by
2078   // getSplatValue, above.
2079   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2080     int64_t StepNumerator = SimpleVID->StepNumerator;
2081     unsigned StepDenominator = SimpleVID->StepDenominator;
2082     int64_t Addend = SimpleVID->Addend;
2083 
2084     assert(StepNumerator != 0 && "Invalid step");
2085     bool Negate = false;
2086     int64_t SplatStepVal = StepNumerator;
2087     unsigned StepOpcode = ISD::MUL;
2088     if (StepNumerator != 1) {
2089       if (isPowerOf2_64(std::abs(StepNumerator))) {
2090         Negate = StepNumerator < 0;
2091         StepOpcode = ISD::SHL;
2092         SplatStepVal = Log2_64(std::abs(StepNumerator));
2093       }
2094     }
2095 
2096     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2097     // threshold since it's the immediate value many RVV instructions accept.
2098     // There is no vmul.vi instruction so ensure multiply constant can fit in
2099     // a single addi instruction.
2100     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2101          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2102         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2103       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2104       // Convert right out of the scalable type so we can use standard ISD
2105       // nodes for the rest of the computation. If we used scalable types with
2106       // these, we'd lose the fixed-length vector info and generate worse
2107       // vsetvli code.
2108       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2109       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2110           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2111         SDValue SplatStep = DAG.getSplatVector(
2112             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2113         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2114       }
2115       if (StepDenominator != 1) {
2116         SDValue SplatStep = DAG.getSplatVector(
2117             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2118         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2119       }
2120       if (Addend != 0 || Negate) {
2121         SDValue SplatAddend =
2122             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2123         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2124       }
2125       return VID;
2126     }
2127   }
2128 
2129   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2130   // when re-interpreted as a vector with a larger element type. For example,
2131   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2132   // could be instead splat as
2133   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2134   // TODO: This optimization could also work on non-constant splats, but it
2135   // would require bit-manipulation instructions to construct the splat value.
2136   SmallVector<SDValue> Sequence;
2137   unsigned EltBitSize = VT.getScalarSizeInBits();
2138   const auto *BV = cast<BuildVectorSDNode>(Op);
2139   if (VT.isInteger() && EltBitSize < 64 &&
2140       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2141       BV->getRepeatedSequence(Sequence) &&
2142       (Sequence.size() * EltBitSize) <= 64) {
2143     unsigned SeqLen = Sequence.size();
2144     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2145     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2146     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2147             ViaIntVT == MVT::i64) &&
2148            "Unexpected sequence type");
2149 
2150     unsigned EltIdx = 0;
2151     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2152     uint64_t SplatValue = 0;
2153     // Construct the amalgamated value which can be splatted as this larger
2154     // vector type.
2155     for (const auto &SeqV : Sequence) {
2156       if (!SeqV.isUndef())
2157         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2158                        << (EltIdx * EltBitSize));
2159       EltIdx++;
2160     }
2161 
2162     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2163     // achieve better constant materializion.
2164     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2165       SplatValue = SignExtend64(SplatValue, 32);
2166 
2167     // Since we can't introduce illegal i64 types at this stage, we can only
2168     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2169     // way we can use RVV instructions to splat.
2170     assert((ViaIntVT.bitsLE(XLenVT) ||
2171             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2172            "Unexpected bitcast sequence");
2173     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2174       SDValue ViaVL =
2175           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2176       MVT ViaContainerVT =
2177           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2178       SDValue Splat =
2179           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2180                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2181       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2182       return DAG.getBitcast(VT, Splat);
2183     }
2184   }
2185 
2186   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2187   // which constitute a large proportion of the elements. In such cases we can
2188   // splat a vector with the dominant element and make up the shortfall with
2189   // INSERT_VECTOR_ELTs.
2190   // Note that this includes vectors of 2 elements by association. The
2191   // upper-most element is the "dominant" one, allowing us to use a splat to
2192   // "insert" the upper element, and an insert of the lower element at position
2193   // 0, which improves codegen.
2194   SDValue DominantValue;
2195   unsigned MostCommonCount = 0;
2196   DenseMap<SDValue, unsigned> ValueCounts;
2197   unsigned NumUndefElts =
2198       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2199 
2200   // Track the number of scalar loads we know we'd be inserting, estimated as
2201   // any non-zero floating-point constant. Other kinds of element are either
2202   // already in registers or are materialized on demand. The threshold at which
2203   // a vector load is more desirable than several scalar materializion and
2204   // vector-insertion instructions is not known.
2205   unsigned NumScalarLoads = 0;
2206 
2207   for (SDValue V : Op->op_values()) {
2208     if (V.isUndef())
2209       continue;
2210 
2211     ValueCounts.insert(std::make_pair(V, 0));
2212     unsigned &Count = ValueCounts[V];
2213 
2214     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2215       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2216 
2217     // Is this value dominant? In case of a tie, prefer the highest element as
2218     // it's cheaper to insert near the beginning of a vector than it is at the
2219     // end.
2220     if (++Count >= MostCommonCount) {
2221       DominantValue = V;
2222       MostCommonCount = Count;
2223     }
2224   }
2225 
2226   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2227   unsigned NumDefElts = NumElts - NumUndefElts;
2228   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2229 
2230   // Don't perform this optimization when optimizing for size, since
2231   // materializing elements and inserting them tends to cause code bloat.
2232   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2233       ((MostCommonCount > DominantValueCountThreshold) ||
2234        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2235     // Start by splatting the most common element.
2236     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2237 
2238     DenseSet<SDValue> Processed{DominantValue};
2239     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2240     for (const auto &OpIdx : enumerate(Op->ops())) {
2241       const SDValue &V = OpIdx.value();
2242       if (V.isUndef() || !Processed.insert(V).second)
2243         continue;
2244       if (ValueCounts[V] == 1) {
2245         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2246                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2247       } else {
2248         // Blend in all instances of this value using a VSELECT, using a
2249         // mask where each bit signals whether that element is the one
2250         // we're after.
2251         SmallVector<SDValue> Ops;
2252         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2253           return DAG.getConstant(V == V1, DL, XLenVT);
2254         });
2255         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2256                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2257                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2258       }
2259     }
2260 
2261     return Vec;
2262   }
2263 
2264   return SDValue();
2265 }
2266 
2267 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2268                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2269   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2270     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2271     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2272     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2273     // node in order to try and match RVV vector/scalar instructions.
2274     if ((LoC >> 31) == HiC)
2275       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2276 
2277     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2278     // vmv.v.x whose EEW = 32 to lower it.
2279     auto *Const = dyn_cast<ConstantSDNode>(VL);
2280     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2281       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2282       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2283       // access the subtarget here now.
2284       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2285       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2286     }
2287   }
2288 
2289   // Fall back to a stack store and stride x0 vector load.
2290   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2291 }
2292 
2293 // Called by type legalization to handle splat of i64 on RV32.
2294 // FIXME: We can optimize this when the type has sign or zero bits in one
2295 // of the halves.
2296 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2297                                    SDValue VL, SelectionDAG &DAG) {
2298   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2299   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2300                            DAG.getConstant(0, DL, MVT::i32));
2301   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2302                            DAG.getConstant(1, DL, MVT::i32));
2303   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2304 }
2305 
2306 // This function lowers a splat of a scalar operand Splat with the vector
2307 // length VL. It ensures the final sequence is type legal, which is useful when
2308 // lowering a splat after type legalization.
2309 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2310                                 SelectionDAG &DAG,
2311                                 const RISCVSubtarget &Subtarget) {
2312   if (VT.isFloatingPoint()) {
2313     // If VL is 1, we could use vfmv.s.f.
2314     if (isOneConstant(VL))
2315       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2316                          Scalar, VL);
2317     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2318   }
2319 
2320   MVT XLenVT = Subtarget.getXLenVT();
2321 
2322   // Simplest case is that the operand needs to be promoted to XLenVT.
2323   if (Scalar.getValueType().bitsLE(XLenVT)) {
2324     // If the operand is a constant, sign extend to increase our chances
2325     // of being able to use a .vi instruction. ANY_EXTEND would become a
2326     // a zero extend and the simm5 check in isel would fail.
2327     // FIXME: Should we ignore the upper bits in isel instead?
2328     unsigned ExtOpc =
2329         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2330     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2331     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2332     // If VL is 1 and the scalar value won't benefit from immediate, we could
2333     // use vmv.s.x.
2334     if (isOneConstant(VL) &&
2335         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2336       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2337                          VL);
2338     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2339   }
2340 
2341   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2342          "Unexpected scalar for splat lowering!");
2343 
2344   if (isOneConstant(VL) && isNullConstant(Scalar))
2345     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2346                        DAG.getConstant(0, DL, XLenVT), VL);
2347 
2348   // Otherwise use the more complicated splatting algorithm.
2349   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2350 }
2351 
2352 // Is the mask a slidedown that shifts in undefs.
2353 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2354   int Size = Mask.size();
2355 
2356   // Elements shifted in should be undef.
2357   auto CheckUndefs = [&](int Shift) {
2358     for (int i = Size - Shift; i != Size; ++i)
2359       if (Mask[i] >= 0)
2360         return false;
2361     return true;
2362   };
2363 
2364   // Elements should be shifted or undef.
2365   auto MatchShift = [&](int Shift) {
2366     for (int i = 0; i != Size - Shift; ++i)
2367        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2368          return false;
2369     return true;
2370   };
2371 
2372   // Try all possible shifts.
2373   for (int Shift = 1; Shift != Size; ++Shift)
2374     if (CheckUndefs(Shift) && MatchShift(Shift))
2375       return Shift;
2376 
2377   // No match.
2378   return -1;
2379 }
2380 
2381 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2382                                 const RISCVSubtarget &Subtarget) {
2383   // We need to be able to widen elements to the next larger integer type.
2384   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2385     return false;
2386 
2387   int Size = Mask.size();
2388   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2389 
2390   int Srcs[] = {-1, -1};
2391   for (int i = 0; i != Size; ++i) {
2392     // Ignore undef elements.
2393     if (Mask[i] < 0)
2394       continue;
2395 
2396     // Is this an even or odd element.
2397     int Pol = i % 2;
2398 
2399     // Ensure we consistently use the same source for this element polarity.
2400     int Src = Mask[i] / Size;
2401     if (Srcs[Pol] < 0)
2402       Srcs[Pol] = Src;
2403     if (Srcs[Pol] != Src)
2404       return false;
2405 
2406     // Make sure the element within the source is appropriate for this element
2407     // in the destination.
2408     int Elt = Mask[i] % Size;
2409     if (Elt != i / 2)
2410       return false;
2411   }
2412 
2413   // We need to find a source for each polarity and they can't be the same.
2414   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2415     return false;
2416 
2417   // Swap the sources if the second source was in the even polarity.
2418   SwapSources = Srcs[0] > Srcs[1];
2419 
2420   return true;
2421 }
2422 
2423 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2424                                    const RISCVSubtarget &Subtarget) {
2425   SDValue V1 = Op.getOperand(0);
2426   SDValue V2 = Op.getOperand(1);
2427   SDLoc DL(Op);
2428   MVT XLenVT = Subtarget.getXLenVT();
2429   MVT VT = Op.getSimpleValueType();
2430   unsigned NumElts = VT.getVectorNumElements();
2431   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2432 
2433   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2434 
2435   SDValue TrueMask, VL;
2436   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2437 
2438   if (SVN->isSplat()) {
2439     const int Lane = SVN->getSplatIndex();
2440     if (Lane >= 0) {
2441       MVT SVT = VT.getVectorElementType();
2442 
2443       // Turn splatted vector load into a strided load with an X0 stride.
2444       SDValue V = V1;
2445       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2446       // with undef.
2447       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2448       int Offset = Lane;
2449       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2450         int OpElements =
2451             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2452         V = V.getOperand(Offset / OpElements);
2453         Offset %= OpElements;
2454       }
2455 
2456       // We need to ensure the load isn't atomic or volatile.
2457       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2458         auto *Ld = cast<LoadSDNode>(V);
2459         Offset *= SVT.getStoreSize();
2460         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2461                                                    TypeSize::Fixed(Offset), DL);
2462 
2463         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2464         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2465           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2466           SDValue IntID =
2467               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2468           SDValue Ops[] = {Ld->getChain(),
2469                            IntID,
2470                            DAG.getUNDEF(ContainerVT),
2471                            NewAddr,
2472                            DAG.getRegister(RISCV::X0, XLenVT),
2473                            VL};
2474           SDValue NewLoad = DAG.getMemIntrinsicNode(
2475               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2476               DAG.getMachineFunction().getMachineMemOperand(
2477                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2478           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2479           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2480         }
2481 
2482         // Otherwise use a scalar load and splat. This will give the best
2483         // opportunity to fold a splat into the operation. ISel can turn it into
2484         // the x0 strided load if we aren't able to fold away the select.
2485         if (SVT.isFloatingPoint())
2486           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2487                           Ld->getPointerInfo().getWithOffset(Offset),
2488                           Ld->getOriginalAlign(),
2489                           Ld->getMemOperand()->getFlags());
2490         else
2491           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2492                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2493                              Ld->getOriginalAlign(),
2494                              Ld->getMemOperand()->getFlags());
2495         DAG.makeEquivalentMemoryOrdering(Ld, V);
2496 
2497         unsigned Opc =
2498             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2499         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2500         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2501       }
2502 
2503       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2504       assert(Lane < (int)NumElts && "Unexpected lane!");
2505       SDValue Gather =
2506           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2507                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2508       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2509     }
2510   }
2511 
2512   ArrayRef<int> Mask = SVN->getMask();
2513 
2514   // Try to match as a slidedown.
2515   int SlideAmt = matchShuffleAsSlideDown(Mask);
2516   if (SlideAmt >= 0) {
2517     // TODO: Should we reduce the VL to account for the upper undef elements?
2518     // Requires additional vsetvlis, but might be faster to execute.
2519     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2520     SDValue SlideDown =
2521         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2522                     DAG.getUNDEF(ContainerVT), V1,
2523                     DAG.getConstant(SlideAmt, DL, XLenVT),
2524                     TrueMask, VL);
2525     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2526   }
2527 
2528   // Detect an interleave shuffle and lower to
2529   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2530   bool SwapSources;
2531   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2532     // Swap sources if needed.
2533     if (SwapSources)
2534       std::swap(V1, V2);
2535 
2536     // Extract the lower half of the vectors.
2537     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2538     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2539                      DAG.getConstant(0, DL, XLenVT));
2540     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2541                      DAG.getConstant(0, DL, XLenVT));
2542 
2543     // Double the element width and halve the number of elements in an int type.
2544     unsigned EltBits = VT.getScalarSizeInBits();
2545     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2546     MVT WideIntVT =
2547         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2548     // Convert this to a scalable vector. We need to base this on the
2549     // destination size to ensure there's always a type with a smaller LMUL.
2550     MVT WideIntContainerVT =
2551         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2552 
2553     // Convert sources to scalable vectors with the same element count as the
2554     // larger type.
2555     MVT HalfContainerVT = MVT::getVectorVT(
2556         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2557     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2558     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2559 
2560     // Cast sources to integer.
2561     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2562     MVT IntHalfVT =
2563         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2564     V1 = DAG.getBitcast(IntHalfVT, V1);
2565     V2 = DAG.getBitcast(IntHalfVT, V2);
2566 
2567     // Freeze V2 since we use it twice and we need to be sure that the add and
2568     // multiply see the same value.
2569     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2570 
2571     // Recreate TrueMask using the widened type's element count.
2572     MVT MaskVT =
2573         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2574     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2575 
2576     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2577     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2578                               V2, TrueMask, VL);
2579     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2580     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2581                                      DAG.getAllOnesConstant(DL, XLenVT));
2582     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2583                                    V2, Multiplier, TrueMask, VL);
2584     // Add the new copies to our previous addition giving us 2^eltbits copies of
2585     // V2. This is equivalent to shifting V2 left by eltbits. This should
2586     // combine with the vwmulu.vv above to form vwmaccu.vv.
2587     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2588                       TrueMask, VL);
2589     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2590     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2591     // vector VT.
2592     ContainerVT =
2593         MVT::getVectorVT(VT.getVectorElementType(),
2594                          WideIntContainerVT.getVectorElementCount() * 2);
2595     Add = DAG.getBitcast(ContainerVT, Add);
2596     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2597   }
2598 
2599   // Detect shuffles which can be re-expressed as vector selects; these are
2600   // shuffles in which each element in the destination is taken from an element
2601   // at the corresponding index in either source vectors.
2602   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2603     int MaskIndex = MaskIdx.value();
2604     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2605   });
2606 
2607   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2608 
2609   SmallVector<SDValue> MaskVals;
2610   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2611   // merged with a second vrgather.
2612   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2613 
2614   // By default we preserve the original operand order, and use a mask to
2615   // select LHS as true and RHS as false. However, since RVV vector selects may
2616   // feature splats but only on the LHS, we may choose to invert our mask and
2617   // instead select between RHS and LHS.
2618   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2619   bool InvertMask = IsSelect == SwapOps;
2620 
2621   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2622   // half.
2623   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2624 
2625   // Now construct the mask that will be used by the vselect or blended
2626   // vrgather operation. For vrgathers, construct the appropriate indices into
2627   // each vector.
2628   for (int MaskIndex : Mask) {
2629     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2630     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2631     if (!IsSelect) {
2632       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2633       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2634                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2635                                      : DAG.getUNDEF(XLenVT));
2636       GatherIndicesRHS.push_back(
2637           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2638                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2639       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2640         ++LHSIndexCounts[MaskIndex];
2641       if (!IsLHSOrUndefIndex)
2642         ++RHSIndexCounts[MaskIndex - NumElts];
2643     }
2644   }
2645 
2646   if (SwapOps) {
2647     std::swap(V1, V2);
2648     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2649   }
2650 
2651   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2652   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2653   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2654 
2655   if (IsSelect)
2656     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2657 
2658   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2659     // On such a large vector we're unable to use i8 as the index type.
2660     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2661     // may involve vector splitting if we're already at LMUL=8, or our
2662     // user-supplied maximum fixed-length LMUL.
2663     return SDValue();
2664   }
2665 
2666   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2667   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2668   MVT IndexVT = VT.changeTypeToInteger();
2669   // Since we can't introduce illegal index types at this stage, use i16 and
2670   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2671   // than XLenVT.
2672   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2673     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2674     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2675   }
2676 
2677   MVT IndexContainerVT =
2678       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2679 
2680   SDValue Gather;
2681   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2682   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2683   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2684     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2685   } else {
2686     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2687     // If only one index is used, we can use a "splat" vrgather.
2688     // TODO: We can splat the most-common index and fix-up any stragglers, if
2689     // that's beneficial.
2690     if (LHSIndexCounts.size() == 1) {
2691       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2692       Gather =
2693           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2694                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2695     } else {
2696       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2697       LHSIndices =
2698           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2699 
2700       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2701                            TrueMask, VL);
2702     }
2703   }
2704 
2705   // If a second vector operand is used by this shuffle, blend it in with an
2706   // additional vrgather.
2707   if (!V2.isUndef()) {
2708     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2709     // If only one index is used, we can use a "splat" vrgather.
2710     // TODO: We can splat the most-common index and fix-up any stragglers, if
2711     // that's beneficial.
2712     if (RHSIndexCounts.size() == 1) {
2713       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2714       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2715                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2716     } else {
2717       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2718       RHSIndices =
2719           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2720       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2721                        VL);
2722     }
2723 
2724     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2725     SelectMask =
2726         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2727 
2728     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2729                          Gather, VL);
2730   }
2731 
2732   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2733 }
2734 
2735 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2736                                      SDLoc DL, SelectionDAG &DAG,
2737                                      const RISCVSubtarget &Subtarget) {
2738   if (VT.isScalableVector())
2739     return DAG.getFPExtendOrRound(Op, DL, VT);
2740   assert(VT.isFixedLengthVector() &&
2741          "Unexpected value type for RVV FP extend/round lowering");
2742   SDValue Mask, VL;
2743   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2744   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2745                         ? RISCVISD::FP_EXTEND_VL
2746                         : RISCVISD::FP_ROUND_VL;
2747   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2748 }
2749 
2750 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2751 // the exponent.
2752 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2753   MVT VT = Op.getSimpleValueType();
2754   unsigned EltSize = VT.getScalarSizeInBits();
2755   SDValue Src = Op.getOperand(0);
2756   SDLoc DL(Op);
2757 
2758   // We need a FP type that can represent the value.
2759   // TODO: Use f16 for i8 when possible?
2760   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2761   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2762 
2763   // Legal types should have been checked in the RISCVTargetLowering
2764   // constructor.
2765   // TODO: Splitting may make sense in some cases.
2766   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2767          "Expected legal float type!");
2768 
2769   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2770   // The trailing zero count is equal to log2 of this single bit value.
2771   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2772     SDValue Neg =
2773         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2774     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2775   }
2776 
2777   // We have a legal FP type, convert to it.
2778   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2779   // Bitcast to integer and shift the exponent to the LSB.
2780   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2781   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2782   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2783   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2784                               DAG.getConstant(ShiftAmt, DL, IntVT));
2785   // Truncate back to original type to allow vnsrl.
2786   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2787   // The exponent contains log2 of the value in biased form.
2788   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2789 
2790   // For trailing zeros, we just need to subtract the bias.
2791   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2792     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2793                        DAG.getConstant(ExponentBias, DL, VT));
2794 
2795   // For leading zeros, we need to remove the bias and convert from log2 to
2796   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2797   unsigned Adjust = ExponentBias + (EltSize - 1);
2798   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2799 }
2800 
2801 // While RVV has alignment restrictions, we should always be able to load as a
2802 // legal equivalently-sized byte-typed vector instead. This method is
2803 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2804 // the load is already correctly-aligned, it returns SDValue().
2805 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2806                                                     SelectionDAG &DAG) const {
2807   auto *Load = cast<LoadSDNode>(Op);
2808   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2809 
2810   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2811                                      Load->getMemoryVT(),
2812                                      *Load->getMemOperand()))
2813     return SDValue();
2814 
2815   SDLoc DL(Op);
2816   MVT VT = Op.getSimpleValueType();
2817   unsigned EltSizeBits = VT.getScalarSizeInBits();
2818   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2819          "Unexpected unaligned RVV load type");
2820   MVT NewVT =
2821       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2822   assert(NewVT.isValid() &&
2823          "Expecting equally-sized RVV vector types to be legal");
2824   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2825                           Load->getPointerInfo(), Load->getOriginalAlign(),
2826                           Load->getMemOperand()->getFlags());
2827   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2828 }
2829 
2830 // While RVV has alignment restrictions, we should always be able to store as a
2831 // legal equivalently-sized byte-typed vector instead. This method is
2832 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2833 // returns SDValue() if the store is already correctly aligned.
2834 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2835                                                      SelectionDAG &DAG) const {
2836   auto *Store = cast<StoreSDNode>(Op);
2837   assert(Store && Store->getValue().getValueType().isVector() &&
2838          "Expected vector store");
2839 
2840   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2841                                      Store->getMemoryVT(),
2842                                      *Store->getMemOperand()))
2843     return SDValue();
2844 
2845   SDLoc DL(Op);
2846   SDValue StoredVal = Store->getValue();
2847   MVT VT = StoredVal.getSimpleValueType();
2848   unsigned EltSizeBits = VT.getScalarSizeInBits();
2849   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2850          "Unexpected unaligned RVV store type");
2851   MVT NewVT =
2852       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2853   assert(NewVT.isValid() &&
2854          "Expecting equally-sized RVV vector types to be legal");
2855   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2856   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2857                       Store->getPointerInfo(), Store->getOriginalAlign(),
2858                       Store->getMemOperand()->getFlags());
2859 }
2860 
2861 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2862                                             SelectionDAG &DAG) const {
2863   switch (Op.getOpcode()) {
2864   default:
2865     report_fatal_error("unimplemented operand");
2866   case ISD::GlobalAddress:
2867     return lowerGlobalAddress(Op, DAG);
2868   case ISD::BlockAddress:
2869     return lowerBlockAddress(Op, DAG);
2870   case ISD::ConstantPool:
2871     return lowerConstantPool(Op, DAG);
2872   case ISD::JumpTable:
2873     return lowerJumpTable(Op, DAG);
2874   case ISD::GlobalTLSAddress:
2875     return lowerGlobalTLSAddress(Op, DAG);
2876   case ISD::SELECT:
2877     return lowerSELECT(Op, DAG);
2878   case ISD::BRCOND:
2879     return lowerBRCOND(Op, DAG);
2880   case ISD::VASTART:
2881     return lowerVASTART(Op, DAG);
2882   case ISD::FRAMEADDR:
2883     return lowerFRAMEADDR(Op, DAG);
2884   case ISD::RETURNADDR:
2885     return lowerRETURNADDR(Op, DAG);
2886   case ISD::SHL_PARTS:
2887     return lowerShiftLeftParts(Op, DAG);
2888   case ISD::SRA_PARTS:
2889     return lowerShiftRightParts(Op, DAG, true);
2890   case ISD::SRL_PARTS:
2891     return lowerShiftRightParts(Op, DAG, false);
2892   case ISD::BITCAST: {
2893     SDLoc DL(Op);
2894     EVT VT = Op.getValueType();
2895     SDValue Op0 = Op.getOperand(0);
2896     EVT Op0VT = Op0.getValueType();
2897     MVT XLenVT = Subtarget.getXLenVT();
2898     if (VT.isFixedLengthVector()) {
2899       // We can handle fixed length vector bitcasts with a simple replacement
2900       // in isel.
2901       if (Op0VT.isFixedLengthVector())
2902         return Op;
2903       // When bitcasting from scalar to fixed-length vector, insert the scalar
2904       // into a one-element vector of the result type, and perform a vector
2905       // bitcast.
2906       if (!Op0VT.isVector()) {
2907         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2908         if (!isTypeLegal(BVT))
2909           return SDValue();
2910         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2911                                               DAG.getUNDEF(BVT), Op0,
2912                                               DAG.getConstant(0, DL, XLenVT)));
2913       }
2914       return SDValue();
2915     }
2916     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2917     // thus: bitcast the vector to a one-element vector type whose element type
2918     // is the same as the result type, and extract the first element.
2919     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2920       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2921       if (!isTypeLegal(BVT))
2922         return SDValue();
2923       SDValue BVec = DAG.getBitcast(BVT, Op0);
2924       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2925                          DAG.getConstant(0, DL, XLenVT));
2926     }
2927     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2928       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2929       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2930       return FPConv;
2931     }
2932     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2933         Subtarget.hasStdExtF()) {
2934       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2935       SDValue FPConv =
2936           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2937       return FPConv;
2938     }
2939     return SDValue();
2940   }
2941   case ISD::INTRINSIC_WO_CHAIN:
2942     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2943   case ISD::INTRINSIC_W_CHAIN:
2944     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2945   case ISD::INTRINSIC_VOID:
2946     return LowerINTRINSIC_VOID(Op, DAG);
2947   case ISD::BSWAP:
2948   case ISD::BITREVERSE: {
2949     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2950     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2951     MVT VT = Op.getSimpleValueType();
2952     SDLoc DL(Op);
2953     // Start with the maximum immediate value which is the bitwidth - 1.
2954     unsigned Imm = VT.getSizeInBits() - 1;
2955     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2956     if (Op.getOpcode() == ISD::BSWAP)
2957       Imm &= ~0x7U;
2958     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2959                        DAG.getConstant(Imm, DL, VT));
2960   }
2961   case ISD::FSHL:
2962   case ISD::FSHR: {
2963     MVT VT = Op.getSimpleValueType();
2964     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2965     SDLoc DL(Op);
2966     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2967     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2968     // accidentally setting the extra bit.
2969     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2970     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2971                                 DAG.getConstant(ShAmtWidth, DL, VT));
2972     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2973     // instruction use different orders. fshl will return its first operand for
2974     // shift of zero, fshr will return its second operand. fsl and fsr both
2975     // return rs1 so the ISD nodes need to have different operand orders.
2976     // Shift amount is in rs2.
2977     SDValue Op0 = Op.getOperand(0);
2978     SDValue Op1 = Op.getOperand(1);
2979     unsigned Opc = RISCVISD::FSL;
2980     if (Op.getOpcode() == ISD::FSHR) {
2981       std::swap(Op0, Op1);
2982       Opc = RISCVISD::FSR;
2983     }
2984     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
2985   }
2986   case ISD::TRUNCATE: {
2987     SDLoc DL(Op);
2988     MVT VT = Op.getSimpleValueType();
2989     // Only custom-lower vector truncates
2990     if (!VT.isVector())
2991       return Op;
2992 
2993     // Truncates to mask types are handled differently
2994     if (VT.getVectorElementType() == MVT::i1)
2995       return lowerVectorMaskTrunc(Op, DAG);
2996 
2997     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2998     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2999     // truncate by one power of two at a time.
3000     MVT DstEltVT = VT.getVectorElementType();
3001 
3002     SDValue Src = Op.getOperand(0);
3003     MVT SrcVT = Src.getSimpleValueType();
3004     MVT SrcEltVT = SrcVT.getVectorElementType();
3005 
3006     assert(DstEltVT.bitsLT(SrcEltVT) &&
3007            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3008            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3009            "Unexpected vector truncate lowering");
3010 
3011     MVT ContainerVT = SrcVT;
3012     if (SrcVT.isFixedLengthVector()) {
3013       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3014       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3015     }
3016 
3017     SDValue Result = Src;
3018     SDValue Mask, VL;
3019     std::tie(Mask, VL) =
3020         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3021     LLVMContext &Context = *DAG.getContext();
3022     const ElementCount Count = ContainerVT.getVectorElementCount();
3023     do {
3024       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3025       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3026       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3027                            Mask, VL);
3028     } while (SrcEltVT != DstEltVT);
3029 
3030     if (SrcVT.isFixedLengthVector())
3031       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3032 
3033     return Result;
3034   }
3035   case ISD::ANY_EXTEND:
3036   case ISD::ZERO_EXTEND:
3037     if (Op.getOperand(0).getValueType().isVector() &&
3038         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3039       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3040     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3041   case ISD::SIGN_EXTEND:
3042     if (Op.getOperand(0).getValueType().isVector() &&
3043         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3044       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3045     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3046   case ISD::SPLAT_VECTOR_PARTS:
3047     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3048   case ISD::INSERT_VECTOR_ELT:
3049     return lowerINSERT_VECTOR_ELT(Op, DAG);
3050   case ISD::EXTRACT_VECTOR_ELT:
3051     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3052   case ISD::VSCALE: {
3053     MVT VT = Op.getSimpleValueType();
3054     SDLoc DL(Op);
3055     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3056     // We define our scalable vector types for lmul=1 to use a 64 bit known
3057     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3058     // vscale as VLENB / 8.
3059     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3060     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3061       // We assume VLENB is a multiple of 8. We manually choose the best shift
3062       // here because SimplifyDemandedBits isn't always able to simplify it.
3063       uint64_t Val = Op.getConstantOperandVal(0);
3064       if (isPowerOf2_64(Val)) {
3065         uint64_t Log2 = Log2_64(Val);
3066         if (Log2 < 3)
3067           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3068                              DAG.getConstant(3 - Log2, DL, VT));
3069         if (Log2 > 3)
3070           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3071                              DAG.getConstant(Log2 - 3, DL, VT));
3072         return VLENB;
3073       }
3074       // If the multiplier is a multiple of 8, scale it down to avoid needing
3075       // to shift the VLENB value.
3076       if ((Val % 8) == 0)
3077         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3078                            DAG.getConstant(Val / 8, DL, VT));
3079     }
3080 
3081     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3082                                  DAG.getConstant(3, DL, VT));
3083     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3084   }
3085   case ISD::FPOWI: {
3086     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3087     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3088     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3089         Op.getOperand(1).getValueType() == MVT::i32) {
3090       SDLoc DL(Op);
3091       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3092       SDValue Powi =
3093           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3094       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3095                          DAG.getIntPtrConstant(0, DL));
3096     }
3097     return SDValue();
3098   }
3099   case ISD::FP_EXTEND: {
3100     // RVV can only do fp_extend to types double the size as the source. We
3101     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3102     // via f32.
3103     SDLoc DL(Op);
3104     MVT VT = Op.getSimpleValueType();
3105     SDValue Src = Op.getOperand(0);
3106     MVT SrcVT = Src.getSimpleValueType();
3107 
3108     // Prepare any fixed-length vector operands.
3109     MVT ContainerVT = VT;
3110     if (SrcVT.isFixedLengthVector()) {
3111       ContainerVT = getContainerForFixedLengthVector(VT);
3112       MVT SrcContainerVT =
3113           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3114       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3115     }
3116 
3117     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3118         SrcVT.getVectorElementType() != MVT::f16) {
3119       // For scalable vectors, we only need to close the gap between
3120       // vXf16->vXf64.
3121       if (!VT.isFixedLengthVector())
3122         return Op;
3123       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3124       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3125       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3126     }
3127 
3128     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3129     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3130     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3131         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3132 
3133     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3134                                            DL, DAG, Subtarget);
3135     if (VT.isFixedLengthVector())
3136       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3137     return Extend;
3138   }
3139   case ISD::FP_ROUND: {
3140     // RVV can only do fp_round to types half the size as the source. We
3141     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3142     // conversion instruction.
3143     SDLoc DL(Op);
3144     MVT VT = Op.getSimpleValueType();
3145     SDValue Src = Op.getOperand(0);
3146     MVT SrcVT = Src.getSimpleValueType();
3147 
3148     // Prepare any fixed-length vector operands.
3149     MVT ContainerVT = VT;
3150     if (VT.isFixedLengthVector()) {
3151       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3152       ContainerVT =
3153           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3154       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3155     }
3156 
3157     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3158         SrcVT.getVectorElementType() != MVT::f64) {
3159       // For scalable vectors, we only need to close the gap between
3160       // vXf64<->vXf16.
3161       if (!VT.isFixedLengthVector())
3162         return Op;
3163       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3164       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3165       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3166     }
3167 
3168     SDValue Mask, VL;
3169     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3170 
3171     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3172     SDValue IntermediateRound =
3173         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3174     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3175                                           DL, DAG, Subtarget);
3176 
3177     if (VT.isFixedLengthVector())
3178       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3179     return Round;
3180   }
3181   case ISD::FP_TO_SINT:
3182   case ISD::FP_TO_UINT:
3183   case ISD::SINT_TO_FP:
3184   case ISD::UINT_TO_FP: {
3185     // RVV can only do fp<->int conversions to types half/double the size as
3186     // the source. We custom-lower any conversions that do two hops into
3187     // sequences.
3188     MVT VT = Op.getSimpleValueType();
3189     if (!VT.isVector())
3190       return Op;
3191     SDLoc DL(Op);
3192     SDValue Src = Op.getOperand(0);
3193     MVT EltVT = VT.getVectorElementType();
3194     MVT SrcVT = Src.getSimpleValueType();
3195     MVT SrcEltVT = SrcVT.getVectorElementType();
3196     unsigned EltSize = EltVT.getSizeInBits();
3197     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3198     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3199            "Unexpected vector element types");
3200 
3201     bool IsInt2FP = SrcEltVT.isInteger();
3202     // Widening conversions
3203     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3204       if (IsInt2FP) {
3205         // Do a regular integer sign/zero extension then convert to float.
3206         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3207                                       VT.getVectorElementCount());
3208         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3209                                  ? ISD::ZERO_EXTEND
3210                                  : ISD::SIGN_EXTEND;
3211         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3212         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3213       }
3214       // FP2Int
3215       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3216       // Do one doubling fp_extend then complete the operation by converting
3217       // to int.
3218       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3219       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3220       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3221     }
3222 
3223     // Narrowing conversions
3224     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3225       if (IsInt2FP) {
3226         // One narrowing int_to_fp, then an fp_round.
3227         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3228         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3229         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3230         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3231       }
3232       // FP2Int
3233       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3234       // representable by the integer, the result is poison.
3235       MVT IVecVT =
3236           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3237                            VT.getVectorElementCount());
3238       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3239       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3240     }
3241 
3242     // Scalable vectors can exit here. Patterns will handle equally-sized
3243     // conversions halving/doubling ones.
3244     if (!VT.isFixedLengthVector())
3245       return Op;
3246 
3247     // For fixed-length vectors we lower to a custom "VL" node.
3248     unsigned RVVOpc = 0;
3249     switch (Op.getOpcode()) {
3250     default:
3251       llvm_unreachable("Impossible opcode");
3252     case ISD::FP_TO_SINT:
3253       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3254       break;
3255     case ISD::FP_TO_UINT:
3256       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3257       break;
3258     case ISD::SINT_TO_FP:
3259       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3260       break;
3261     case ISD::UINT_TO_FP:
3262       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3263       break;
3264     }
3265 
3266     MVT ContainerVT, SrcContainerVT;
3267     // Derive the reference container type from the larger vector type.
3268     if (SrcEltSize > EltSize) {
3269       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3270       ContainerVT =
3271           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3272     } else {
3273       ContainerVT = getContainerForFixedLengthVector(VT);
3274       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3275     }
3276 
3277     SDValue Mask, VL;
3278     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3279 
3280     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3281     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3282     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3283   }
3284   case ISD::FP_TO_SINT_SAT:
3285   case ISD::FP_TO_UINT_SAT:
3286     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3287   case ISD::FTRUNC:
3288   case ISD::FCEIL:
3289   case ISD::FFLOOR:
3290     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3291   case ISD::VECREDUCE_ADD:
3292   case ISD::VECREDUCE_UMAX:
3293   case ISD::VECREDUCE_SMAX:
3294   case ISD::VECREDUCE_UMIN:
3295   case ISD::VECREDUCE_SMIN:
3296     return lowerVECREDUCE(Op, DAG);
3297   case ISD::VECREDUCE_AND:
3298   case ISD::VECREDUCE_OR:
3299   case ISD::VECREDUCE_XOR:
3300     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3301       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3302     return lowerVECREDUCE(Op, DAG);
3303   case ISD::VECREDUCE_FADD:
3304   case ISD::VECREDUCE_SEQ_FADD:
3305   case ISD::VECREDUCE_FMIN:
3306   case ISD::VECREDUCE_FMAX:
3307     return lowerFPVECREDUCE(Op, DAG);
3308   case ISD::VP_REDUCE_ADD:
3309   case ISD::VP_REDUCE_UMAX:
3310   case ISD::VP_REDUCE_SMAX:
3311   case ISD::VP_REDUCE_UMIN:
3312   case ISD::VP_REDUCE_SMIN:
3313   case ISD::VP_REDUCE_FADD:
3314   case ISD::VP_REDUCE_SEQ_FADD:
3315   case ISD::VP_REDUCE_FMIN:
3316   case ISD::VP_REDUCE_FMAX:
3317     return lowerVPREDUCE(Op, DAG);
3318   case ISD::VP_REDUCE_AND:
3319   case ISD::VP_REDUCE_OR:
3320   case ISD::VP_REDUCE_XOR:
3321     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3322       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3323     return lowerVPREDUCE(Op, DAG);
3324   case ISD::INSERT_SUBVECTOR:
3325     return lowerINSERT_SUBVECTOR(Op, DAG);
3326   case ISD::EXTRACT_SUBVECTOR:
3327     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3328   case ISD::STEP_VECTOR:
3329     return lowerSTEP_VECTOR(Op, DAG);
3330   case ISD::VECTOR_REVERSE:
3331     return lowerVECTOR_REVERSE(Op, DAG);
3332   case ISD::BUILD_VECTOR:
3333     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3334   case ISD::SPLAT_VECTOR:
3335     if (Op.getValueType().getVectorElementType() == MVT::i1)
3336       return lowerVectorMaskSplat(Op, DAG);
3337     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3338   case ISD::VECTOR_SHUFFLE:
3339     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3340   case ISD::CONCAT_VECTORS: {
3341     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3342     // better than going through the stack, as the default expansion does.
3343     SDLoc DL(Op);
3344     MVT VT = Op.getSimpleValueType();
3345     unsigned NumOpElts =
3346         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3347     SDValue Vec = DAG.getUNDEF(VT);
3348     for (const auto &OpIdx : enumerate(Op->ops())) {
3349       SDValue SubVec = OpIdx.value();
3350       // Don't insert undef subvectors.
3351       if (SubVec.isUndef())
3352         continue;
3353       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3354                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3355     }
3356     return Vec;
3357   }
3358   case ISD::LOAD:
3359     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3360       return V;
3361     if (Op.getValueType().isFixedLengthVector())
3362       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3363     return Op;
3364   case ISD::STORE:
3365     if (auto V = expandUnalignedRVVStore(Op, DAG))
3366       return V;
3367     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3368       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3369     return Op;
3370   case ISD::MLOAD:
3371   case ISD::VP_LOAD:
3372     return lowerMaskedLoad(Op, DAG);
3373   case ISD::MSTORE:
3374   case ISD::VP_STORE:
3375     return lowerMaskedStore(Op, DAG);
3376   case ISD::SETCC:
3377     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3378   case ISD::ADD:
3379     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3380   case ISD::SUB:
3381     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3382   case ISD::MUL:
3383     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3384   case ISD::MULHS:
3385     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3386   case ISD::MULHU:
3387     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3388   case ISD::AND:
3389     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3390                                               RISCVISD::AND_VL);
3391   case ISD::OR:
3392     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3393                                               RISCVISD::OR_VL);
3394   case ISD::XOR:
3395     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3396                                               RISCVISD::XOR_VL);
3397   case ISD::SDIV:
3398     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3399   case ISD::SREM:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3401   case ISD::UDIV:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3403   case ISD::UREM:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3405   case ISD::SHL:
3406   case ISD::SRA:
3407   case ISD::SRL:
3408     if (Op.getSimpleValueType().isFixedLengthVector())
3409       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3410     // This can be called for an i32 shift amount that needs to be promoted.
3411     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3412            "Unexpected custom legalisation");
3413     return SDValue();
3414   case ISD::SADDSAT:
3415     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3416   case ISD::UADDSAT:
3417     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3418   case ISD::SSUBSAT:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3420   case ISD::USUBSAT:
3421     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3422   case ISD::FADD:
3423     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3424   case ISD::FSUB:
3425     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3426   case ISD::FMUL:
3427     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3428   case ISD::FDIV:
3429     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3430   case ISD::FNEG:
3431     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3432   case ISD::FABS:
3433     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3434   case ISD::FSQRT:
3435     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3436   case ISD::FMA:
3437     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3438   case ISD::SMIN:
3439     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3440   case ISD::SMAX:
3441     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3442   case ISD::UMIN:
3443     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3444   case ISD::UMAX:
3445     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3446   case ISD::FMINNUM:
3447     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3448   case ISD::FMAXNUM:
3449     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3450   case ISD::ABS:
3451     return lowerABS(Op, DAG);
3452   case ISD::CTLZ_ZERO_UNDEF:
3453   case ISD::CTTZ_ZERO_UNDEF:
3454     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3455   case ISD::VSELECT:
3456     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3457   case ISD::FCOPYSIGN:
3458     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3459   case ISD::MGATHER:
3460   case ISD::VP_GATHER:
3461     return lowerMaskedGather(Op, DAG);
3462   case ISD::MSCATTER:
3463   case ISD::VP_SCATTER:
3464     return lowerMaskedScatter(Op, DAG);
3465   case ISD::FLT_ROUNDS_:
3466     return lowerGET_ROUNDING(Op, DAG);
3467   case ISD::SET_ROUNDING:
3468     return lowerSET_ROUNDING(Op, DAG);
3469   case ISD::VP_SELECT:
3470     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3471   case ISD::VP_MERGE:
3472     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3473   case ISD::VP_ADD:
3474     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3475   case ISD::VP_SUB:
3476     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3477   case ISD::VP_MUL:
3478     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3479   case ISD::VP_SDIV:
3480     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3481   case ISD::VP_UDIV:
3482     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3483   case ISD::VP_SREM:
3484     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3485   case ISD::VP_UREM:
3486     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3487   case ISD::VP_AND:
3488     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3489   case ISD::VP_OR:
3490     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3491   case ISD::VP_XOR:
3492     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3493   case ISD::VP_ASHR:
3494     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3495   case ISD::VP_LSHR:
3496     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3497   case ISD::VP_SHL:
3498     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3499   case ISD::VP_FADD:
3500     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3501   case ISD::VP_FSUB:
3502     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3503   case ISD::VP_FMUL:
3504     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3505   case ISD::VP_FDIV:
3506     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3507   }
3508 }
3509 
3510 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3511                              SelectionDAG &DAG, unsigned Flags) {
3512   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3513 }
3514 
3515 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3516                              SelectionDAG &DAG, unsigned Flags) {
3517   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3518                                    Flags);
3519 }
3520 
3521 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3522                              SelectionDAG &DAG, unsigned Flags) {
3523   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3524                                    N->getOffset(), Flags);
3525 }
3526 
3527 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3528                              SelectionDAG &DAG, unsigned Flags) {
3529   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3530 }
3531 
3532 template <class NodeTy>
3533 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3534                                      bool IsLocal) const {
3535   SDLoc DL(N);
3536   EVT Ty = getPointerTy(DAG.getDataLayout());
3537 
3538   if (isPositionIndependent()) {
3539     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3540     if (IsLocal)
3541       // Use PC-relative addressing to access the symbol. This generates the
3542       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3543       // %pcrel_lo(auipc)).
3544       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3545 
3546     // Use PC-relative addressing to access the GOT for this symbol, then load
3547     // the address from the GOT. This generates the pattern (PseudoLA sym),
3548     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3549     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3550   }
3551 
3552   switch (getTargetMachine().getCodeModel()) {
3553   default:
3554     report_fatal_error("Unsupported code model for lowering");
3555   case CodeModel::Small: {
3556     // Generate a sequence for accessing addresses within the first 2 GiB of
3557     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3558     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3559     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3560     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3561     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3562   }
3563   case CodeModel::Medium: {
3564     // Generate a sequence for accessing addresses within any 2GiB range within
3565     // the address space. This generates the pattern (PseudoLLA sym), which
3566     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3567     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3568     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3569   }
3570   }
3571 }
3572 
3573 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3574                                                 SelectionDAG &DAG) const {
3575   SDLoc DL(Op);
3576   EVT Ty = Op.getValueType();
3577   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3578   int64_t Offset = N->getOffset();
3579   MVT XLenVT = Subtarget.getXLenVT();
3580 
3581   const GlobalValue *GV = N->getGlobal();
3582   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3583   SDValue Addr = getAddr(N, DAG, IsLocal);
3584 
3585   // In order to maximise the opportunity for common subexpression elimination,
3586   // emit a separate ADD node for the global address offset instead of folding
3587   // it in the global address node. Later peephole optimisations may choose to
3588   // fold it back in when profitable.
3589   if (Offset != 0)
3590     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3591                        DAG.getConstant(Offset, DL, XLenVT));
3592   return Addr;
3593 }
3594 
3595 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3596                                                SelectionDAG &DAG) const {
3597   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3598 
3599   return getAddr(N, DAG);
3600 }
3601 
3602 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3603                                                SelectionDAG &DAG) const {
3604   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3605 
3606   return getAddr(N, DAG);
3607 }
3608 
3609 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3610                                             SelectionDAG &DAG) const {
3611   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3612 
3613   return getAddr(N, DAG);
3614 }
3615 
3616 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3617                                               SelectionDAG &DAG,
3618                                               bool UseGOT) const {
3619   SDLoc DL(N);
3620   EVT Ty = getPointerTy(DAG.getDataLayout());
3621   const GlobalValue *GV = N->getGlobal();
3622   MVT XLenVT = Subtarget.getXLenVT();
3623 
3624   if (UseGOT) {
3625     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3626     // load the address from the GOT and add the thread pointer. This generates
3627     // the pattern (PseudoLA_TLS_IE sym), which expands to
3628     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3629     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3630     SDValue Load =
3631         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3632 
3633     // Add the thread pointer.
3634     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3635     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3636   }
3637 
3638   // Generate a sequence for accessing the address relative to the thread
3639   // pointer, with the appropriate adjustment for the thread pointer offset.
3640   // This generates the pattern
3641   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3642   SDValue AddrHi =
3643       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3644   SDValue AddrAdd =
3645       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3646   SDValue AddrLo =
3647       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3648 
3649   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3650   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3651   SDValue MNAdd = SDValue(
3652       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3653       0);
3654   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3655 }
3656 
3657 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3658                                                SelectionDAG &DAG) const {
3659   SDLoc DL(N);
3660   EVT Ty = getPointerTy(DAG.getDataLayout());
3661   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3662   const GlobalValue *GV = N->getGlobal();
3663 
3664   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3665   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3666   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3667   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3668   SDValue Load =
3669       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3670 
3671   // Prepare argument list to generate call.
3672   ArgListTy Args;
3673   ArgListEntry Entry;
3674   Entry.Node = Load;
3675   Entry.Ty = CallTy;
3676   Args.push_back(Entry);
3677 
3678   // Setup call to __tls_get_addr.
3679   TargetLowering::CallLoweringInfo CLI(DAG);
3680   CLI.setDebugLoc(DL)
3681       .setChain(DAG.getEntryNode())
3682       .setLibCallee(CallingConv::C, CallTy,
3683                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3684                     std::move(Args));
3685 
3686   return LowerCallTo(CLI).first;
3687 }
3688 
3689 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3690                                                    SelectionDAG &DAG) const {
3691   SDLoc DL(Op);
3692   EVT Ty = Op.getValueType();
3693   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3694   int64_t Offset = N->getOffset();
3695   MVT XLenVT = Subtarget.getXLenVT();
3696 
3697   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3698 
3699   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3700       CallingConv::GHC)
3701     report_fatal_error("In GHC calling convention TLS is not supported");
3702 
3703   SDValue Addr;
3704   switch (Model) {
3705   case TLSModel::LocalExec:
3706     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3707     break;
3708   case TLSModel::InitialExec:
3709     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3710     break;
3711   case TLSModel::LocalDynamic:
3712   case TLSModel::GeneralDynamic:
3713     Addr = getDynamicTLSAddr(N, DAG);
3714     break;
3715   }
3716 
3717   // In order to maximise the opportunity for common subexpression elimination,
3718   // emit a separate ADD node for the global address offset instead of folding
3719   // it in the global address node. Later peephole optimisations may choose to
3720   // fold it back in when profitable.
3721   if (Offset != 0)
3722     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3723                        DAG.getConstant(Offset, DL, XLenVT));
3724   return Addr;
3725 }
3726 
3727 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3728   SDValue CondV = Op.getOperand(0);
3729   SDValue TrueV = Op.getOperand(1);
3730   SDValue FalseV = Op.getOperand(2);
3731   SDLoc DL(Op);
3732   MVT VT = Op.getSimpleValueType();
3733   MVT XLenVT = Subtarget.getXLenVT();
3734 
3735   // Lower vector SELECTs to VSELECTs by splatting the condition.
3736   if (VT.isVector()) {
3737     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3738     SDValue CondSplat = VT.isScalableVector()
3739                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3740                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3741     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3742   }
3743 
3744   // If the result type is XLenVT and CondV is the output of a SETCC node
3745   // which also operated on XLenVT inputs, then merge the SETCC node into the
3746   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3747   // compare+branch instructions. i.e.:
3748   // (select (setcc lhs, rhs, cc), truev, falsev)
3749   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3750   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3751       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3752     SDValue LHS = CondV.getOperand(0);
3753     SDValue RHS = CondV.getOperand(1);
3754     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3755     ISD::CondCode CCVal = CC->get();
3756 
3757     // Special case for a select of 2 constants that have a diffence of 1.
3758     // Normally this is done by DAGCombine, but if the select is introduced by
3759     // type legalization or op legalization, we miss it. Restricting to SETLT
3760     // case for now because that is what signed saturating add/sub need.
3761     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3762     // but we would probably want to swap the true/false values if the condition
3763     // is SETGE/SETLE to avoid an XORI.
3764     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3765         CCVal == ISD::SETLT) {
3766       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3767       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3768       if (TrueVal - 1 == FalseVal)
3769         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3770       if (TrueVal + 1 == FalseVal)
3771         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3772     }
3773 
3774     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3775 
3776     SDValue TargetCC = DAG.getCondCode(CCVal);
3777     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3778     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3779   }
3780 
3781   // Otherwise:
3782   // (select condv, truev, falsev)
3783   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3784   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3785   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3786 
3787   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3788 
3789   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3790 }
3791 
3792 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3793   SDValue CondV = Op.getOperand(1);
3794   SDLoc DL(Op);
3795   MVT XLenVT = Subtarget.getXLenVT();
3796 
3797   if (CondV.getOpcode() == ISD::SETCC &&
3798       CondV.getOperand(0).getValueType() == XLenVT) {
3799     SDValue LHS = CondV.getOperand(0);
3800     SDValue RHS = CondV.getOperand(1);
3801     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3802 
3803     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3804 
3805     SDValue TargetCC = DAG.getCondCode(CCVal);
3806     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3807                        LHS, RHS, TargetCC, Op.getOperand(2));
3808   }
3809 
3810   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3811                      CondV, DAG.getConstant(0, DL, XLenVT),
3812                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3813 }
3814 
3815 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3816   MachineFunction &MF = DAG.getMachineFunction();
3817   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3818 
3819   SDLoc DL(Op);
3820   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3821                                  getPointerTy(MF.getDataLayout()));
3822 
3823   // vastart just stores the address of the VarArgsFrameIndex slot into the
3824   // memory location argument.
3825   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3826   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3827                       MachinePointerInfo(SV));
3828 }
3829 
3830 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3831                                             SelectionDAG &DAG) const {
3832   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3833   MachineFunction &MF = DAG.getMachineFunction();
3834   MachineFrameInfo &MFI = MF.getFrameInfo();
3835   MFI.setFrameAddressIsTaken(true);
3836   Register FrameReg = RI.getFrameRegister(MF);
3837   int XLenInBytes = Subtarget.getXLen() / 8;
3838 
3839   EVT VT = Op.getValueType();
3840   SDLoc DL(Op);
3841   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3842   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3843   while (Depth--) {
3844     int Offset = -(XLenInBytes * 2);
3845     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3846                               DAG.getIntPtrConstant(Offset, DL));
3847     FrameAddr =
3848         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3849   }
3850   return FrameAddr;
3851 }
3852 
3853 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3854                                              SelectionDAG &DAG) const {
3855   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3856   MachineFunction &MF = DAG.getMachineFunction();
3857   MachineFrameInfo &MFI = MF.getFrameInfo();
3858   MFI.setReturnAddressIsTaken(true);
3859   MVT XLenVT = Subtarget.getXLenVT();
3860   int XLenInBytes = Subtarget.getXLen() / 8;
3861 
3862   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3863     return SDValue();
3864 
3865   EVT VT = Op.getValueType();
3866   SDLoc DL(Op);
3867   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3868   if (Depth) {
3869     int Off = -XLenInBytes;
3870     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3871     SDValue Offset = DAG.getConstant(Off, DL, VT);
3872     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3873                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3874                        MachinePointerInfo());
3875   }
3876 
3877   // Return the value of the return address register, marking it an implicit
3878   // live-in.
3879   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3880   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3881 }
3882 
3883 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3884                                                  SelectionDAG &DAG) const {
3885   SDLoc DL(Op);
3886   SDValue Lo = Op.getOperand(0);
3887   SDValue Hi = Op.getOperand(1);
3888   SDValue Shamt = Op.getOperand(2);
3889   EVT VT = Lo.getValueType();
3890 
3891   // if Shamt-XLEN < 0: // Shamt < XLEN
3892   //   Lo = Lo << Shamt
3893   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3894   // else:
3895   //   Lo = 0
3896   //   Hi = Lo << (Shamt-XLEN)
3897 
3898   SDValue Zero = DAG.getConstant(0, DL, VT);
3899   SDValue One = DAG.getConstant(1, DL, VT);
3900   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3901   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3902   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3903   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3904 
3905   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3906   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3907   SDValue ShiftRightLo =
3908       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3909   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3910   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3911   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3912 
3913   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3914 
3915   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3916   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3917 
3918   SDValue Parts[2] = {Lo, Hi};
3919   return DAG.getMergeValues(Parts, DL);
3920 }
3921 
3922 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3923                                                   bool IsSRA) const {
3924   SDLoc DL(Op);
3925   SDValue Lo = Op.getOperand(0);
3926   SDValue Hi = Op.getOperand(1);
3927   SDValue Shamt = Op.getOperand(2);
3928   EVT VT = Lo.getValueType();
3929 
3930   // SRA expansion:
3931   //   if Shamt-XLEN < 0: // Shamt < XLEN
3932   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3933   //     Hi = Hi >>s Shamt
3934   //   else:
3935   //     Lo = Hi >>s (Shamt-XLEN);
3936   //     Hi = Hi >>s (XLEN-1)
3937   //
3938   // SRL expansion:
3939   //   if Shamt-XLEN < 0: // Shamt < XLEN
3940   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3941   //     Hi = Hi >>u Shamt
3942   //   else:
3943   //     Lo = Hi >>u (Shamt-XLEN);
3944   //     Hi = 0;
3945 
3946   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3947 
3948   SDValue Zero = DAG.getConstant(0, DL, VT);
3949   SDValue One = DAG.getConstant(1, DL, VT);
3950   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3951   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3952   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3953   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3954 
3955   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3956   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3957   SDValue ShiftLeftHi =
3958       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3959   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3960   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3961   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3962   SDValue HiFalse =
3963       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3964 
3965   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3966 
3967   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3968   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3969 
3970   SDValue Parts[2] = {Lo, Hi};
3971   return DAG.getMergeValues(Parts, DL);
3972 }
3973 
3974 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3975 // legal equivalently-sized i8 type, so we can use that as a go-between.
3976 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3977                                                   SelectionDAG &DAG) const {
3978   SDLoc DL(Op);
3979   MVT VT = Op.getSimpleValueType();
3980   SDValue SplatVal = Op.getOperand(0);
3981   // All-zeros or all-ones splats are handled specially.
3982   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3983     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3984     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3985   }
3986   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3987     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3988     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3989   }
3990   MVT XLenVT = Subtarget.getXLenVT();
3991   assert(SplatVal.getValueType() == XLenVT &&
3992          "Unexpected type for i1 splat value");
3993   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3994   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3995                          DAG.getConstant(1, DL, XLenVT));
3996   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3997   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3998   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3999 }
4000 
4001 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4002 // illegal (currently only vXi64 RV32).
4003 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4004 // them to SPLAT_VECTOR_I64
4005 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4006                                                      SelectionDAG &DAG) const {
4007   SDLoc DL(Op);
4008   MVT VecVT = Op.getSimpleValueType();
4009   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4010          "Unexpected SPLAT_VECTOR_PARTS lowering");
4011 
4012   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4013   SDValue Lo = Op.getOperand(0);
4014   SDValue Hi = Op.getOperand(1);
4015 
4016   if (VecVT.isFixedLengthVector()) {
4017     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4018     SDLoc DL(Op);
4019     SDValue Mask, VL;
4020     std::tie(Mask, VL) =
4021         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4022 
4023     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4024     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4025   }
4026 
4027   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4028     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4029     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4030     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4031     // node in order to try and match RVV vector/scalar instructions.
4032     if ((LoC >> 31) == HiC)
4033       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4034   }
4035 
4036   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4037   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4038       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4039       Hi.getConstantOperandVal(1) == 31)
4040     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4041 
4042   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4043   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4044                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4045 }
4046 
4047 // Custom-lower extensions from mask vectors by using a vselect either with 1
4048 // for zero/any-extension or -1 for sign-extension:
4049 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4050 // Note that any-extension is lowered identically to zero-extension.
4051 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4052                                                 int64_t ExtTrueVal) const {
4053   SDLoc DL(Op);
4054   MVT VecVT = Op.getSimpleValueType();
4055   SDValue Src = Op.getOperand(0);
4056   // Only custom-lower extensions from mask types
4057   assert(Src.getValueType().isVector() &&
4058          Src.getValueType().getVectorElementType() == MVT::i1);
4059 
4060   MVT XLenVT = Subtarget.getXLenVT();
4061   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4062   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4063 
4064   if (VecVT.isScalableVector()) {
4065     // Be careful not to introduce illegal scalar types at this stage, and be
4066     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4067     // illegal and must be expanded. Since we know that the constants are
4068     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4069     bool IsRV32E64 =
4070         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4071 
4072     if (!IsRV32E64) {
4073       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4074       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4075     } else {
4076       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4077       SplatTrueVal =
4078           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4079     }
4080 
4081     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4082   }
4083 
4084   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4085   MVT I1ContainerVT =
4086       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4087 
4088   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4089 
4090   SDValue Mask, VL;
4091   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4092 
4093   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4094   SplatTrueVal =
4095       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4096   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4097                                SplatTrueVal, SplatZero, VL);
4098 
4099   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4100 }
4101 
4102 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4103     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4104   MVT ExtVT = Op.getSimpleValueType();
4105   // Only custom-lower extensions from fixed-length vector types.
4106   if (!ExtVT.isFixedLengthVector())
4107     return Op;
4108   MVT VT = Op.getOperand(0).getSimpleValueType();
4109   // Grab the canonical container type for the extended type. Infer the smaller
4110   // type from that to ensure the same number of vector elements, as we know
4111   // the LMUL will be sufficient to hold the smaller type.
4112   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4113   // Get the extended container type manually to ensure the same number of
4114   // vector elements between source and dest.
4115   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4116                                      ContainerExtVT.getVectorElementCount());
4117 
4118   SDValue Op1 =
4119       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4120 
4121   SDLoc DL(Op);
4122   SDValue Mask, VL;
4123   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4124 
4125   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4126 
4127   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4128 }
4129 
4130 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4131 // setcc operation:
4132 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4133 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4134                                                   SelectionDAG &DAG) const {
4135   SDLoc DL(Op);
4136   EVT MaskVT = Op.getValueType();
4137   // Only expect to custom-lower truncations to mask types
4138   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4139          "Unexpected type for vector mask lowering");
4140   SDValue Src = Op.getOperand(0);
4141   MVT VecVT = Src.getSimpleValueType();
4142 
4143   // If this is a fixed vector, we need to convert it to a scalable vector.
4144   MVT ContainerVT = VecVT;
4145   if (VecVT.isFixedLengthVector()) {
4146     ContainerVT = getContainerForFixedLengthVector(VecVT);
4147     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4148   }
4149 
4150   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4151   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4152 
4153   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4154   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4155 
4156   if (VecVT.isScalableVector()) {
4157     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4158     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4159   }
4160 
4161   SDValue Mask, VL;
4162   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4163 
4164   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4165   SDValue Trunc =
4166       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4167   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4168                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4169   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4170 }
4171 
4172 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4173 // first position of a vector, and that vector is slid up to the insert index.
4174 // By limiting the active vector length to index+1 and merging with the
4175 // original vector (with an undisturbed tail policy for elements >= VL), we
4176 // achieve the desired result of leaving all elements untouched except the one
4177 // at VL-1, which is replaced with the desired value.
4178 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4179                                                     SelectionDAG &DAG) const {
4180   SDLoc DL(Op);
4181   MVT VecVT = Op.getSimpleValueType();
4182   SDValue Vec = Op.getOperand(0);
4183   SDValue Val = Op.getOperand(1);
4184   SDValue Idx = Op.getOperand(2);
4185 
4186   if (VecVT.getVectorElementType() == MVT::i1) {
4187     // FIXME: For now we just promote to an i8 vector and insert into that,
4188     // but this is probably not optimal.
4189     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4190     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4191     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4192     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4193   }
4194 
4195   MVT ContainerVT = VecVT;
4196   // If the operand is a fixed-length vector, convert to a scalable one.
4197   if (VecVT.isFixedLengthVector()) {
4198     ContainerVT = getContainerForFixedLengthVector(VecVT);
4199     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4200   }
4201 
4202   MVT XLenVT = Subtarget.getXLenVT();
4203 
4204   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4205   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4206   // Even i64-element vectors on RV32 can be lowered without scalar
4207   // legalization if the most-significant 32 bits of the value are not affected
4208   // by the sign-extension of the lower 32 bits.
4209   // TODO: We could also catch sign extensions of a 32-bit value.
4210   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4211     const auto *CVal = cast<ConstantSDNode>(Val);
4212     if (isInt<32>(CVal->getSExtValue())) {
4213       IsLegalInsert = true;
4214       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4215     }
4216   }
4217 
4218   SDValue Mask, VL;
4219   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4220 
4221   SDValue ValInVec;
4222 
4223   if (IsLegalInsert) {
4224     unsigned Opc =
4225         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4226     if (isNullConstant(Idx)) {
4227       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4228       if (!VecVT.isFixedLengthVector())
4229         return Vec;
4230       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4231     }
4232     ValInVec =
4233         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4234   } else {
4235     // On RV32, i64-element vectors must be specially handled to place the
4236     // value at element 0, by using two vslide1up instructions in sequence on
4237     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4238     // this.
4239     SDValue One = DAG.getConstant(1, DL, XLenVT);
4240     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4241     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4242     MVT I32ContainerVT =
4243         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4244     SDValue I32Mask =
4245         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4246     // Limit the active VL to two.
4247     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4248     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4249     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4250     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4251                            InsertI64VL);
4252     // First slide in the hi value, then the lo in underneath it.
4253     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4254                            ValHi, I32Mask, InsertI64VL);
4255     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4256                            ValLo, I32Mask, InsertI64VL);
4257     // Bitcast back to the right container type.
4258     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4259   }
4260 
4261   // Now that the value is in a vector, slide it into position.
4262   SDValue InsertVL =
4263       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4264   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4265                                 ValInVec, Idx, Mask, InsertVL);
4266   if (!VecVT.isFixedLengthVector())
4267     return Slideup;
4268   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4269 }
4270 
4271 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4272 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4273 // types this is done using VMV_X_S to allow us to glean information about the
4274 // sign bits of the result.
4275 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4276                                                      SelectionDAG &DAG) const {
4277   SDLoc DL(Op);
4278   SDValue Idx = Op.getOperand(1);
4279   SDValue Vec = Op.getOperand(0);
4280   EVT EltVT = Op.getValueType();
4281   MVT VecVT = Vec.getSimpleValueType();
4282   MVT XLenVT = Subtarget.getXLenVT();
4283 
4284   if (VecVT.getVectorElementType() == MVT::i1) {
4285     // FIXME: For now we just promote to an i8 vector and extract from that,
4286     // but this is probably not optimal.
4287     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4288     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4289     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4290   }
4291 
4292   // If this is a fixed vector, we need to convert it to a scalable vector.
4293   MVT ContainerVT = VecVT;
4294   if (VecVT.isFixedLengthVector()) {
4295     ContainerVT = getContainerForFixedLengthVector(VecVT);
4296     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4297   }
4298 
4299   // If the index is 0, the vector is already in the right position.
4300   if (!isNullConstant(Idx)) {
4301     // Use a VL of 1 to avoid processing more elements than we need.
4302     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4303     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4304     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4305     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4306                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4307   }
4308 
4309   if (!EltVT.isInteger()) {
4310     // Floating-point extracts are handled in TableGen.
4311     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4312                        DAG.getConstant(0, DL, XLenVT));
4313   }
4314 
4315   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4316   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4317 }
4318 
4319 // Some RVV intrinsics may claim that they want an integer operand to be
4320 // promoted or expanded.
4321 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4322                                           const RISCVSubtarget &Subtarget) {
4323   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4324           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4325          "Unexpected opcode");
4326 
4327   if (!Subtarget.hasVInstructions())
4328     return SDValue();
4329 
4330   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4331   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4332   SDLoc DL(Op);
4333 
4334   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4335       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4336   if (!II || !II->hasSplatOperand())
4337     return SDValue();
4338 
4339   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4340   assert(SplatOp < Op.getNumOperands());
4341 
4342   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4343   SDValue &ScalarOp = Operands[SplatOp];
4344   MVT OpVT = ScalarOp.getSimpleValueType();
4345   MVT XLenVT = Subtarget.getXLenVT();
4346 
4347   // If this isn't a scalar, or its type is XLenVT we're done.
4348   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4349     return SDValue();
4350 
4351   // Simplest case is that the operand needs to be promoted to XLenVT.
4352   if (OpVT.bitsLT(XLenVT)) {
4353     // If the operand is a constant, sign extend to increase our chances
4354     // of being able to use a .vi instruction. ANY_EXTEND would become a
4355     // a zero extend and the simm5 check in isel would fail.
4356     // FIXME: Should we ignore the upper bits in isel instead?
4357     unsigned ExtOpc =
4358         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4359     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4360     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4361   }
4362 
4363   // Use the previous operand to get the vXi64 VT. The result might be a mask
4364   // VT for compares. Using the previous operand assumes that the previous
4365   // operand will never have a smaller element size than a scalar operand and
4366   // that a widening operation never uses SEW=64.
4367   // NOTE: If this fails the below assert, we can probably just find the
4368   // element count from any operand or result and use it to construct the VT.
4369   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4370   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4371 
4372   // The more complex case is when the scalar is larger than XLenVT.
4373   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4374          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4375 
4376   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4377   // on the instruction to sign-extend since SEW>XLEN.
4378   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4379     if (isInt<32>(CVal->getSExtValue())) {
4380       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4381       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4382     }
4383   }
4384 
4385   // We need to convert the scalar to a splat vector.
4386   // FIXME: Can we implicitly truncate the scalar if it is known to
4387   // be sign extended?
4388   SDValue VL = getVLOperand(Op);
4389   assert(VL.getValueType() == XLenVT);
4390   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4391   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4392 }
4393 
4394 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4395                                                      SelectionDAG &DAG) const {
4396   unsigned IntNo = Op.getConstantOperandVal(0);
4397   SDLoc DL(Op);
4398   MVT XLenVT = Subtarget.getXLenVT();
4399 
4400   switch (IntNo) {
4401   default:
4402     break; // Don't custom lower most intrinsics.
4403   case Intrinsic::thread_pointer: {
4404     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4405     return DAG.getRegister(RISCV::X4, PtrVT);
4406   }
4407   case Intrinsic::riscv_orc_b:
4408     // Lower to the GORCI encoding for orc.b.
4409     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4410                        DAG.getConstant(7, DL, XLenVT));
4411   case Intrinsic::riscv_grev:
4412   case Intrinsic::riscv_gorc: {
4413     unsigned Opc =
4414         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4415     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4416   }
4417   case Intrinsic::riscv_shfl:
4418   case Intrinsic::riscv_unshfl: {
4419     unsigned Opc =
4420         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4421     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4422   }
4423   case Intrinsic::riscv_bcompress:
4424   case Intrinsic::riscv_bdecompress: {
4425     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4426                                                        : RISCVISD::BDECOMPRESS;
4427     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4428   }
4429   case Intrinsic::riscv_bfp:
4430     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4431                        Op.getOperand(2));
4432   case Intrinsic::riscv_fsl:
4433     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4434                        Op.getOperand(2), Op.getOperand(3));
4435   case Intrinsic::riscv_fsr:
4436     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4437                        Op.getOperand(2), Op.getOperand(3));
4438   case Intrinsic::riscv_vmv_x_s:
4439     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4440     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4441                        Op.getOperand(1));
4442   case Intrinsic::riscv_vmv_v_x:
4443     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4444                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4445   case Intrinsic::riscv_vfmv_v_f:
4446     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4447                        Op.getOperand(1), Op.getOperand(2));
4448   case Intrinsic::riscv_vmv_s_x: {
4449     SDValue Scalar = Op.getOperand(2);
4450 
4451     if (Scalar.getValueType().bitsLE(XLenVT)) {
4452       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4453       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4454                          Op.getOperand(1), Scalar, Op.getOperand(3));
4455     }
4456 
4457     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4458 
4459     // This is an i64 value that lives in two scalar registers. We have to
4460     // insert this in a convoluted way. First we build vXi64 splat containing
4461     // the/ two values that we assemble using some bit math. Next we'll use
4462     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4463     // to merge element 0 from our splat into the source vector.
4464     // FIXME: This is probably not the best way to do this, but it is
4465     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4466     // point.
4467     //   sw lo, (a0)
4468     //   sw hi, 4(a0)
4469     //   vlse vX, (a0)
4470     //
4471     //   vid.v      vVid
4472     //   vmseq.vx   mMask, vVid, 0
4473     //   vmerge.vvm vDest, vSrc, vVal, mMask
4474     MVT VT = Op.getSimpleValueType();
4475     SDValue Vec = Op.getOperand(1);
4476     SDValue VL = getVLOperand(Op);
4477 
4478     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4479     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4480                                       DAG.getConstant(0, DL, MVT::i32), VL);
4481 
4482     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4483     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4484     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4485     SDValue SelectCond =
4486         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4487                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4488     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4489                        Vec, VL);
4490   }
4491   case Intrinsic::riscv_vslide1up:
4492   case Intrinsic::riscv_vslide1down:
4493   case Intrinsic::riscv_vslide1up_mask:
4494   case Intrinsic::riscv_vslide1down_mask: {
4495     // We need to special case these when the scalar is larger than XLen.
4496     unsigned NumOps = Op.getNumOperands();
4497     bool IsMasked = NumOps == 7;
4498     unsigned OpOffset = IsMasked ? 1 : 0;
4499     SDValue Scalar = Op.getOperand(2 + OpOffset);
4500     if (Scalar.getValueType().bitsLE(XLenVT))
4501       break;
4502 
4503     // Splatting a sign extended constant is fine.
4504     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4505       if (isInt<32>(CVal->getSExtValue()))
4506         break;
4507 
4508     MVT VT = Op.getSimpleValueType();
4509     assert(VT.getVectorElementType() == MVT::i64 &&
4510            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4511 
4512     // Convert the vector source to the equivalent nxvXi32 vector.
4513     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4514     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4515 
4516     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4517                                    DAG.getConstant(0, DL, XLenVT));
4518     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4519                                    DAG.getConstant(1, DL, XLenVT));
4520 
4521     // Double the VL since we halved SEW.
4522     SDValue VL = getVLOperand(Op);
4523     SDValue I32VL =
4524         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4525 
4526     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4527     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4528 
4529     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4530     // instructions.
4531     if (IntNo == Intrinsic::riscv_vslide1up ||
4532         IntNo == Intrinsic::riscv_vslide1up_mask) {
4533       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4534                         I32Mask, I32VL);
4535       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4536                         I32Mask, I32VL);
4537     } else {
4538       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4539                         I32Mask, I32VL);
4540       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4541                         I32Mask, I32VL);
4542     }
4543 
4544     // Convert back to nxvXi64.
4545     Vec = DAG.getBitcast(VT, Vec);
4546 
4547     if (!IsMasked)
4548       return Vec;
4549 
4550     // Apply mask after the operation.
4551     SDValue Mask = Op.getOperand(NumOps - 3);
4552     SDValue MaskedOff = Op.getOperand(1);
4553     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4554   }
4555   }
4556 
4557   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4558 }
4559 
4560 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4561                                                     SelectionDAG &DAG) const {
4562   unsigned IntNo = Op.getConstantOperandVal(1);
4563   switch (IntNo) {
4564   default:
4565     break;
4566   case Intrinsic::riscv_masked_strided_load: {
4567     SDLoc DL(Op);
4568     MVT XLenVT = Subtarget.getXLenVT();
4569 
4570     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4571     // the selection of the masked intrinsics doesn't do this for us.
4572     SDValue Mask = Op.getOperand(5);
4573     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4574 
4575     MVT VT = Op->getSimpleValueType(0);
4576     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4577 
4578     SDValue PassThru = Op.getOperand(2);
4579     if (!IsUnmasked) {
4580       MVT MaskVT =
4581           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4582       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4583       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4584     }
4585 
4586     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4587 
4588     SDValue IntID = DAG.getTargetConstant(
4589         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4590         XLenVT);
4591 
4592     auto *Load = cast<MemIntrinsicSDNode>(Op);
4593     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4594     if (IsUnmasked)
4595       Ops.push_back(DAG.getUNDEF(ContainerVT));
4596     else
4597       Ops.push_back(PassThru);
4598     Ops.push_back(Op.getOperand(3)); // Ptr
4599     Ops.push_back(Op.getOperand(4)); // Stride
4600     if (!IsUnmasked)
4601       Ops.push_back(Mask);
4602     Ops.push_back(VL);
4603     if (!IsUnmasked) {
4604       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4605       Ops.push_back(Policy);
4606     }
4607 
4608     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4609     SDValue Result =
4610         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4611                                 Load->getMemoryVT(), Load->getMemOperand());
4612     SDValue Chain = Result.getValue(1);
4613     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4614     return DAG.getMergeValues({Result, Chain}, DL);
4615   }
4616   }
4617 
4618   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4619 }
4620 
4621 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4622                                                  SelectionDAG &DAG) const {
4623   unsigned IntNo = Op.getConstantOperandVal(1);
4624   switch (IntNo) {
4625   default:
4626     break;
4627   case Intrinsic::riscv_masked_strided_store: {
4628     SDLoc DL(Op);
4629     MVT XLenVT = Subtarget.getXLenVT();
4630 
4631     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4632     // the selection of the masked intrinsics doesn't do this for us.
4633     SDValue Mask = Op.getOperand(5);
4634     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4635 
4636     SDValue Val = Op.getOperand(2);
4637     MVT VT = Val.getSimpleValueType();
4638     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4639 
4640     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4641     if (!IsUnmasked) {
4642       MVT MaskVT =
4643           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4644       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4645     }
4646 
4647     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4648 
4649     SDValue IntID = DAG.getTargetConstant(
4650         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4651         XLenVT);
4652 
4653     auto *Store = cast<MemIntrinsicSDNode>(Op);
4654     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4655     Ops.push_back(Val);
4656     Ops.push_back(Op.getOperand(3)); // Ptr
4657     Ops.push_back(Op.getOperand(4)); // Stride
4658     if (!IsUnmasked)
4659       Ops.push_back(Mask);
4660     Ops.push_back(VL);
4661 
4662     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4663                                    Ops, Store->getMemoryVT(),
4664                                    Store->getMemOperand());
4665   }
4666   }
4667 
4668   return SDValue();
4669 }
4670 
4671 static MVT getLMUL1VT(MVT VT) {
4672   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4673          "Unexpected vector MVT");
4674   return MVT::getScalableVectorVT(
4675       VT.getVectorElementType(),
4676       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4677 }
4678 
4679 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4680   switch (ISDOpcode) {
4681   default:
4682     llvm_unreachable("Unhandled reduction");
4683   case ISD::VECREDUCE_ADD:
4684     return RISCVISD::VECREDUCE_ADD_VL;
4685   case ISD::VECREDUCE_UMAX:
4686     return RISCVISD::VECREDUCE_UMAX_VL;
4687   case ISD::VECREDUCE_SMAX:
4688     return RISCVISD::VECREDUCE_SMAX_VL;
4689   case ISD::VECREDUCE_UMIN:
4690     return RISCVISD::VECREDUCE_UMIN_VL;
4691   case ISD::VECREDUCE_SMIN:
4692     return RISCVISD::VECREDUCE_SMIN_VL;
4693   case ISD::VECREDUCE_AND:
4694     return RISCVISD::VECREDUCE_AND_VL;
4695   case ISD::VECREDUCE_OR:
4696     return RISCVISD::VECREDUCE_OR_VL;
4697   case ISD::VECREDUCE_XOR:
4698     return RISCVISD::VECREDUCE_XOR_VL;
4699   }
4700 }
4701 
4702 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4703                                                          SelectionDAG &DAG,
4704                                                          bool IsVP) const {
4705   SDLoc DL(Op);
4706   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4707   MVT VecVT = Vec.getSimpleValueType();
4708   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4709           Op.getOpcode() == ISD::VECREDUCE_OR ||
4710           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4711           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4712           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4713           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4714          "Unexpected reduction lowering");
4715 
4716   MVT XLenVT = Subtarget.getXLenVT();
4717   assert(Op.getValueType() == XLenVT &&
4718          "Expected reduction output to be legalized to XLenVT");
4719 
4720   MVT ContainerVT = VecVT;
4721   if (VecVT.isFixedLengthVector()) {
4722     ContainerVT = getContainerForFixedLengthVector(VecVT);
4723     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4724   }
4725 
4726   SDValue Mask, VL;
4727   if (IsVP) {
4728     Mask = Op.getOperand(2);
4729     VL = Op.getOperand(3);
4730   } else {
4731     std::tie(Mask, VL) =
4732         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4733   }
4734 
4735   unsigned BaseOpc;
4736   ISD::CondCode CC;
4737   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4738 
4739   switch (Op.getOpcode()) {
4740   default:
4741     llvm_unreachable("Unhandled reduction");
4742   case ISD::VECREDUCE_AND:
4743   case ISD::VP_REDUCE_AND: {
4744     // vcpop ~x == 0
4745     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4746     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4747     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4748     CC = ISD::SETEQ;
4749     BaseOpc = ISD::AND;
4750     break;
4751   }
4752   case ISD::VECREDUCE_OR:
4753   case ISD::VP_REDUCE_OR:
4754     // vcpop x != 0
4755     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4756     CC = ISD::SETNE;
4757     BaseOpc = ISD::OR;
4758     break;
4759   case ISD::VECREDUCE_XOR:
4760   case ISD::VP_REDUCE_XOR: {
4761     // ((vcpop x) & 1) != 0
4762     SDValue One = DAG.getConstant(1, DL, XLenVT);
4763     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4764     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4765     CC = ISD::SETNE;
4766     BaseOpc = ISD::XOR;
4767     break;
4768   }
4769   }
4770 
4771   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4772 
4773   if (!IsVP)
4774     return SetCC;
4775 
4776   // Now include the start value in the operation.
4777   // Note that we must return the start value when no elements are operated
4778   // upon. The vcpop instructions we've emitted in each case above will return
4779   // 0 for an inactive vector, and so we've already received the neutral value:
4780   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4781   // can simply include the start value.
4782   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4783 }
4784 
4785 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4786                                             SelectionDAG &DAG) const {
4787   SDLoc DL(Op);
4788   SDValue Vec = Op.getOperand(0);
4789   EVT VecEVT = Vec.getValueType();
4790 
4791   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4792 
4793   // Due to ordering in legalize types we may have a vector type that needs to
4794   // be split. Do that manually so we can get down to a legal type.
4795   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4796          TargetLowering::TypeSplitVector) {
4797     SDValue Lo, Hi;
4798     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4799     VecEVT = Lo.getValueType();
4800     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4801   }
4802 
4803   // TODO: The type may need to be widened rather than split. Or widened before
4804   // it can be split.
4805   if (!isTypeLegal(VecEVT))
4806     return SDValue();
4807 
4808   MVT VecVT = VecEVT.getSimpleVT();
4809   MVT VecEltVT = VecVT.getVectorElementType();
4810   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4811 
4812   MVT ContainerVT = VecVT;
4813   if (VecVT.isFixedLengthVector()) {
4814     ContainerVT = getContainerForFixedLengthVector(VecVT);
4815     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4816   }
4817 
4818   MVT M1VT = getLMUL1VT(ContainerVT);
4819   MVT XLenVT = Subtarget.getXLenVT();
4820 
4821   SDValue Mask, VL;
4822   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4823 
4824   SDValue NeutralElem =
4825       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4826   SDValue IdentitySplat = lowerScalarSplat(
4827       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4828   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4829                                   IdentitySplat, Mask, VL);
4830   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4831                              DAG.getConstant(0, DL, XLenVT));
4832   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4833 }
4834 
4835 // Given a reduction op, this function returns the matching reduction opcode,
4836 // the vector SDValue and the scalar SDValue required to lower this to a
4837 // RISCVISD node.
4838 static std::tuple<unsigned, SDValue, SDValue>
4839 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4840   SDLoc DL(Op);
4841   auto Flags = Op->getFlags();
4842   unsigned Opcode = Op.getOpcode();
4843   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4844   switch (Opcode) {
4845   default:
4846     llvm_unreachable("Unhandled reduction");
4847   case ISD::VECREDUCE_FADD: {
4848     // Use positive zero if we can. It is cheaper to materialize.
4849     SDValue Zero =
4850         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4851     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4852   }
4853   case ISD::VECREDUCE_SEQ_FADD:
4854     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4855                            Op.getOperand(0));
4856   case ISD::VECREDUCE_FMIN:
4857     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4858                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4859   case ISD::VECREDUCE_FMAX:
4860     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4861                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4862   }
4863 }
4864 
4865 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4866                                               SelectionDAG &DAG) const {
4867   SDLoc DL(Op);
4868   MVT VecEltVT = Op.getSimpleValueType();
4869 
4870   unsigned RVVOpcode;
4871   SDValue VectorVal, ScalarVal;
4872   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4873       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4874   MVT VecVT = VectorVal.getSimpleValueType();
4875 
4876   MVT ContainerVT = VecVT;
4877   if (VecVT.isFixedLengthVector()) {
4878     ContainerVT = getContainerForFixedLengthVector(VecVT);
4879     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4880   }
4881 
4882   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4883   MVT XLenVT = Subtarget.getXLenVT();
4884 
4885   SDValue Mask, VL;
4886   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4887 
4888   SDValue ScalarSplat = lowerScalarSplat(
4889       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4890   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4891                                   VectorVal, ScalarSplat, Mask, VL);
4892   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4893                      DAG.getConstant(0, DL, XLenVT));
4894 }
4895 
4896 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4897   switch (ISDOpcode) {
4898   default:
4899     llvm_unreachable("Unhandled reduction");
4900   case ISD::VP_REDUCE_ADD:
4901     return RISCVISD::VECREDUCE_ADD_VL;
4902   case ISD::VP_REDUCE_UMAX:
4903     return RISCVISD::VECREDUCE_UMAX_VL;
4904   case ISD::VP_REDUCE_SMAX:
4905     return RISCVISD::VECREDUCE_SMAX_VL;
4906   case ISD::VP_REDUCE_UMIN:
4907     return RISCVISD::VECREDUCE_UMIN_VL;
4908   case ISD::VP_REDUCE_SMIN:
4909     return RISCVISD::VECREDUCE_SMIN_VL;
4910   case ISD::VP_REDUCE_AND:
4911     return RISCVISD::VECREDUCE_AND_VL;
4912   case ISD::VP_REDUCE_OR:
4913     return RISCVISD::VECREDUCE_OR_VL;
4914   case ISD::VP_REDUCE_XOR:
4915     return RISCVISD::VECREDUCE_XOR_VL;
4916   case ISD::VP_REDUCE_FADD:
4917     return RISCVISD::VECREDUCE_FADD_VL;
4918   case ISD::VP_REDUCE_SEQ_FADD:
4919     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4920   case ISD::VP_REDUCE_FMAX:
4921     return RISCVISD::VECREDUCE_FMAX_VL;
4922   case ISD::VP_REDUCE_FMIN:
4923     return RISCVISD::VECREDUCE_FMIN_VL;
4924   }
4925 }
4926 
4927 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4928                                            SelectionDAG &DAG) const {
4929   SDLoc DL(Op);
4930   SDValue Vec = Op.getOperand(1);
4931   EVT VecEVT = Vec.getValueType();
4932 
4933   // TODO: The type may need to be widened rather than split. Or widened before
4934   // it can be split.
4935   if (!isTypeLegal(VecEVT))
4936     return SDValue();
4937 
4938   MVT VecVT = VecEVT.getSimpleVT();
4939   MVT VecEltVT = VecVT.getVectorElementType();
4940   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4941 
4942   MVT ContainerVT = VecVT;
4943   if (VecVT.isFixedLengthVector()) {
4944     ContainerVT = getContainerForFixedLengthVector(VecVT);
4945     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4946   }
4947 
4948   SDValue VL = Op.getOperand(3);
4949   SDValue Mask = Op.getOperand(2);
4950 
4951   MVT M1VT = getLMUL1VT(ContainerVT);
4952   MVT XLenVT = Subtarget.getXLenVT();
4953   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4954 
4955   SDValue StartSplat =
4956       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4957                        DL, DAG, Subtarget);
4958   SDValue Reduction =
4959       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4960   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4961                              DAG.getConstant(0, DL, XLenVT));
4962   if (!VecVT.isInteger())
4963     return Elt0;
4964   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4965 }
4966 
4967 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4968                                                    SelectionDAG &DAG) const {
4969   SDValue Vec = Op.getOperand(0);
4970   SDValue SubVec = Op.getOperand(1);
4971   MVT VecVT = Vec.getSimpleValueType();
4972   MVT SubVecVT = SubVec.getSimpleValueType();
4973 
4974   SDLoc DL(Op);
4975   MVT XLenVT = Subtarget.getXLenVT();
4976   unsigned OrigIdx = Op.getConstantOperandVal(2);
4977   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4978 
4979   // We don't have the ability to slide mask vectors up indexed by their i1
4980   // elements; the smallest we can do is i8. Often we are able to bitcast to
4981   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4982   // into a scalable one, we might not necessarily have enough scalable
4983   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4984   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4985       (OrigIdx != 0 || !Vec.isUndef())) {
4986     if (VecVT.getVectorMinNumElements() >= 8 &&
4987         SubVecVT.getVectorMinNumElements() >= 8) {
4988       assert(OrigIdx % 8 == 0 && "Invalid index");
4989       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4990              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4991              "Unexpected mask vector lowering");
4992       OrigIdx /= 8;
4993       SubVecVT =
4994           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4995                            SubVecVT.isScalableVector());
4996       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4997                                VecVT.isScalableVector());
4998       Vec = DAG.getBitcast(VecVT, Vec);
4999       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5000     } else {
5001       // We can't slide this mask vector up indexed by its i1 elements.
5002       // This poses a problem when we wish to insert a scalable vector which
5003       // can't be re-expressed as a larger type. Just choose the slow path and
5004       // extend to a larger type, then truncate back down.
5005       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5006       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5007       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5008       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5009       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5010                         Op.getOperand(2));
5011       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5012       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5013     }
5014   }
5015 
5016   // If the subvector vector is a fixed-length type, we cannot use subregister
5017   // manipulation to simplify the codegen; we don't know which register of a
5018   // LMUL group contains the specific subvector as we only know the minimum
5019   // register size. Therefore we must slide the vector group up the full
5020   // amount.
5021   if (SubVecVT.isFixedLengthVector()) {
5022     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5023       return Op;
5024     MVT ContainerVT = VecVT;
5025     if (VecVT.isFixedLengthVector()) {
5026       ContainerVT = getContainerForFixedLengthVector(VecVT);
5027       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5028     }
5029     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5030                          DAG.getUNDEF(ContainerVT), SubVec,
5031                          DAG.getConstant(0, DL, XLenVT));
5032     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5033       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5034       return DAG.getBitcast(Op.getValueType(), SubVec);
5035     }
5036     SDValue Mask =
5037         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5038     // Set the vector length to only the number of elements we care about. Note
5039     // that for slideup this includes the offset.
5040     SDValue VL =
5041         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5042     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5043     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5044                                   SubVec, SlideupAmt, Mask, VL);
5045     if (VecVT.isFixedLengthVector())
5046       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5047     return DAG.getBitcast(Op.getValueType(), Slideup);
5048   }
5049 
5050   unsigned SubRegIdx, RemIdx;
5051   std::tie(SubRegIdx, RemIdx) =
5052       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5053           VecVT, SubVecVT, OrigIdx, TRI);
5054 
5055   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5056   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5057                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5058                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5059 
5060   // 1. If the Idx has been completely eliminated and this subvector's size is
5061   // a vector register or a multiple thereof, or the surrounding elements are
5062   // undef, then this is a subvector insert which naturally aligns to a vector
5063   // register. These can easily be handled using subregister manipulation.
5064   // 2. If the subvector is smaller than a vector register, then the insertion
5065   // must preserve the undisturbed elements of the register. We do this by
5066   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5067   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5068   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5069   // LMUL=1 type back into the larger vector (resolving to another subregister
5070   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5071   // to avoid allocating a large register group to hold our subvector.
5072   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5073     return Op;
5074 
5075   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5076   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5077   // (in our case undisturbed). This means we can set up a subvector insertion
5078   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5079   // size of the subvector.
5080   MVT InterSubVT = VecVT;
5081   SDValue AlignedExtract = Vec;
5082   unsigned AlignedIdx = OrigIdx - RemIdx;
5083   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5084     InterSubVT = getLMUL1VT(VecVT);
5085     // Extract a subvector equal to the nearest full vector register type. This
5086     // should resolve to a EXTRACT_SUBREG instruction.
5087     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5088                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5089   }
5090 
5091   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5092   // For scalable vectors this must be further multiplied by vscale.
5093   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5094 
5095   SDValue Mask, VL;
5096   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5097 
5098   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5099   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5100   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5101   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5102 
5103   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5104                        DAG.getUNDEF(InterSubVT), SubVec,
5105                        DAG.getConstant(0, DL, XLenVT));
5106 
5107   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5108                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5109 
5110   // If required, insert this subvector back into the correct vector register.
5111   // This should resolve to an INSERT_SUBREG instruction.
5112   if (VecVT.bitsGT(InterSubVT))
5113     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5114                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5115 
5116   // We might have bitcast from a mask type: cast back to the original type if
5117   // required.
5118   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5119 }
5120 
5121 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5122                                                     SelectionDAG &DAG) const {
5123   SDValue Vec = Op.getOperand(0);
5124   MVT SubVecVT = Op.getSimpleValueType();
5125   MVT VecVT = Vec.getSimpleValueType();
5126 
5127   SDLoc DL(Op);
5128   MVT XLenVT = Subtarget.getXLenVT();
5129   unsigned OrigIdx = Op.getConstantOperandVal(1);
5130   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5131 
5132   // We don't have the ability to slide mask vectors down indexed by their i1
5133   // elements; the smallest we can do is i8. Often we are able to bitcast to
5134   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5135   // from a scalable one, we might not necessarily have enough scalable
5136   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5137   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5138     if (VecVT.getVectorMinNumElements() >= 8 &&
5139         SubVecVT.getVectorMinNumElements() >= 8) {
5140       assert(OrigIdx % 8 == 0 && "Invalid index");
5141       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5142              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5143              "Unexpected mask vector lowering");
5144       OrigIdx /= 8;
5145       SubVecVT =
5146           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5147                            SubVecVT.isScalableVector());
5148       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5149                                VecVT.isScalableVector());
5150       Vec = DAG.getBitcast(VecVT, Vec);
5151     } else {
5152       // We can't slide this mask vector down, indexed by its i1 elements.
5153       // This poses a problem when we wish to extract a scalable vector which
5154       // can't be re-expressed as a larger type. Just choose the slow path and
5155       // extend to a larger type, then truncate back down.
5156       // TODO: We could probably improve this when extracting certain fixed
5157       // from fixed, where we can extract as i8 and shift the correct element
5158       // right to reach the desired subvector?
5159       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5160       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5161       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5162       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5163                         Op.getOperand(1));
5164       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5165       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5166     }
5167   }
5168 
5169   // If the subvector vector is a fixed-length type, we cannot use subregister
5170   // manipulation to simplify the codegen; we don't know which register of a
5171   // LMUL group contains the specific subvector as we only know the minimum
5172   // register size. Therefore we must slide the vector group down the full
5173   // amount.
5174   if (SubVecVT.isFixedLengthVector()) {
5175     // With an index of 0 this is a cast-like subvector, which can be performed
5176     // with subregister operations.
5177     if (OrigIdx == 0)
5178       return Op;
5179     MVT ContainerVT = VecVT;
5180     if (VecVT.isFixedLengthVector()) {
5181       ContainerVT = getContainerForFixedLengthVector(VecVT);
5182       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5183     }
5184     SDValue Mask =
5185         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5186     // Set the vector length to only the number of elements we care about. This
5187     // avoids sliding down elements we're going to discard straight away.
5188     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5189     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5190     SDValue Slidedown =
5191         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5192                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5193     // Now we can use a cast-like subvector extract to get the result.
5194     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5195                             DAG.getConstant(0, DL, XLenVT));
5196     return DAG.getBitcast(Op.getValueType(), Slidedown);
5197   }
5198 
5199   unsigned SubRegIdx, RemIdx;
5200   std::tie(SubRegIdx, RemIdx) =
5201       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5202           VecVT, SubVecVT, OrigIdx, TRI);
5203 
5204   // If the Idx has been completely eliminated then this is a subvector extract
5205   // which naturally aligns to a vector register. These can easily be handled
5206   // using subregister manipulation.
5207   if (RemIdx == 0)
5208     return Op;
5209 
5210   // Else we must shift our vector register directly to extract the subvector.
5211   // Do this using VSLIDEDOWN.
5212 
5213   // If the vector type is an LMUL-group type, extract a subvector equal to the
5214   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5215   // instruction.
5216   MVT InterSubVT = VecVT;
5217   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5218     InterSubVT = getLMUL1VT(VecVT);
5219     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5220                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5221   }
5222 
5223   // Slide this vector register down by the desired number of elements in order
5224   // to place the desired subvector starting at element 0.
5225   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5226   // For scalable vectors this must be further multiplied by vscale.
5227   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5228 
5229   SDValue Mask, VL;
5230   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5231   SDValue Slidedown =
5232       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5233                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5234 
5235   // Now the vector is in the right position, extract our final subvector. This
5236   // should resolve to a COPY.
5237   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5238                           DAG.getConstant(0, DL, XLenVT));
5239 
5240   // We might have bitcast from a mask type: cast back to the original type if
5241   // required.
5242   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5243 }
5244 
5245 // Lower step_vector to the vid instruction. Any non-identity step value must
5246 // be accounted for my manual expansion.
5247 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5248                                               SelectionDAG &DAG) const {
5249   SDLoc DL(Op);
5250   MVT VT = Op.getSimpleValueType();
5251   MVT XLenVT = Subtarget.getXLenVT();
5252   SDValue Mask, VL;
5253   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5254   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5255   uint64_t StepValImm = Op.getConstantOperandVal(0);
5256   if (StepValImm != 1) {
5257     if (isPowerOf2_64(StepValImm)) {
5258       SDValue StepVal =
5259           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5260                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5261       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5262     } else {
5263       SDValue StepVal = lowerScalarSplat(
5264           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5265           DL, DAG, Subtarget);
5266       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5267     }
5268   }
5269   return StepVec;
5270 }
5271 
5272 // Implement vector_reverse using vrgather.vv with indices determined by
5273 // subtracting the id of each element from (VLMAX-1). This will convert
5274 // the indices like so:
5275 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5276 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5277 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5278                                                  SelectionDAG &DAG) const {
5279   SDLoc DL(Op);
5280   MVT VecVT = Op.getSimpleValueType();
5281   unsigned EltSize = VecVT.getScalarSizeInBits();
5282   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5283 
5284   unsigned MaxVLMAX = 0;
5285   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5286   if (VectorBitsMax != 0)
5287     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5288 
5289   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5290   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5291 
5292   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5293   // to use vrgatherei16.vv.
5294   // TODO: It's also possible to use vrgatherei16.vv for other types to
5295   // decrease register width for the index calculation.
5296   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5297     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5298     // Reverse each half, then reassemble them in reverse order.
5299     // NOTE: It's also possible that after splitting that VLMAX no longer
5300     // requires vrgatherei16.vv.
5301     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5302       SDValue Lo, Hi;
5303       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5304       EVT LoVT, HiVT;
5305       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5306       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5307       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5308       // Reassemble the low and high pieces reversed.
5309       // FIXME: This is a CONCAT_VECTORS.
5310       SDValue Res =
5311           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5312                       DAG.getIntPtrConstant(0, DL));
5313       return DAG.getNode(
5314           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5315           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5316     }
5317 
5318     // Just promote the int type to i16 which will double the LMUL.
5319     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5320     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5321   }
5322 
5323   MVT XLenVT = Subtarget.getXLenVT();
5324   SDValue Mask, VL;
5325   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5326 
5327   // Calculate VLMAX-1 for the desired SEW.
5328   unsigned MinElts = VecVT.getVectorMinNumElements();
5329   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5330                               DAG.getConstant(MinElts, DL, XLenVT));
5331   SDValue VLMinus1 =
5332       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5333 
5334   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5335   bool IsRV32E64 =
5336       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5337   SDValue SplatVL;
5338   if (!IsRV32E64)
5339     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5340   else
5341     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5342 
5343   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5344   SDValue Indices =
5345       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5346 
5347   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5348 }
5349 
5350 SDValue
5351 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5352                                                      SelectionDAG &DAG) const {
5353   SDLoc DL(Op);
5354   auto *Load = cast<LoadSDNode>(Op);
5355 
5356   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5357                                         Load->getMemoryVT(),
5358                                         *Load->getMemOperand()) &&
5359          "Expecting a correctly-aligned load");
5360 
5361   MVT VT = Op.getSimpleValueType();
5362   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5363 
5364   SDValue VL =
5365       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5366 
5367   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5368   SDValue NewLoad = DAG.getMemIntrinsicNode(
5369       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5370       Load->getMemoryVT(), Load->getMemOperand());
5371 
5372   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5373   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5374 }
5375 
5376 SDValue
5377 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5378                                                       SelectionDAG &DAG) const {
5379   SDLoc DL(Op);
5380   auto *Store = cast<StoreSDNode>(Op);
5381 
5382   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5383                                         Store->getMemoryVT(),
5384                                         *Store->getMemOperand()) &&
5385          "Expecting a correctly-aligned store");
5386 
5387   SDValue StoreVal = Store->getValue();
5388   MVT VT = StoreVal.getSimpleValueType();
5389 
5390   // If the size less than a byte, we need to pad with zeros to make a byte.
5391   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5392     VT = MVT::v8i1;
5393     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5394                            DAG.getConstant(0, DL, VT), StoreVal,
5395                            DAG.getIntPtrConstant(0, DL));
5396   }
5397 
5398   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5399 
5400   SDValue VL =
5401       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5402 
5403   SDValue NewValue =
5404       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5405   return DAG.getMemIntrinsicNode(
5406       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5407       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5408       Store->getMemoryVT(), Store->getMemOperand());
5409 }
5410 
5411 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5412                                              SelectionDAG &DAG) const {
5413   SDLoc DL(Op);
5414   MVT VT = Op.getSimpleValueType();
5415 
5416   const auto *MemSD = cast<MemSDNode>(Op);
5417   EVT MemVT = MemSD->getMemoryVT();
5418   MachineMemOperand *MMO = MemSD->getMemOperand();
5419   SDValue Chain = MemSD->getChain();
5420   SDValue BasePtr = MemSD->getBasePtr();
5421 
5422   SDValue Mask, PassThru, VL;
5423   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5424     Mask = VPLoad->getMask();
5425     PassThru = DAG.getUNDEF(VT);
5426     VL = VPLoad->getVectorLength();
5427   } else {
5428     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5429     Mask = MLoad->getMask();
5430     PassThru = MLoad->getPassThru();
5431   }
5432 
5433   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5434 
5435   MVT XLenVT = Subtarget.getXLenVT();
5436 
5437   MVT ContainerVT = VT;
5438   if (VT.isFixedLengthVector()) {
5439     ContainerVT = getContainerForFixedLengthVector(VT);
5440     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5441     if (!IsUnmasked) {
5442       MVT MaskVT =
5443           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5444       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5445     }
5446   }
5447 
5448   if (!VL)
5449     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5450 
5451   unsigned IntID =
5452       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5453   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5454   if (IsUnmasked)
5455     Ops.push_back(DAG.getUNDEF(ContainerVT));
5456   else
5457     Ops.push_back(PassThru);
5458   Ops.push_back(BasePtr);
5459   if (!IsUnmasked)
5460     Ops.push_back(Mask);
5461   Ops.push_back(VL);
5462   if (!IsUnmasked)
5463     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5464 
5465   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5466 
5467   SDValue Result =
5468       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5469   Chain = Result.getValue(1);
5470 
5471   if (VT.isFixedLengthVector())
5472     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5473 
5474   return DAG.getMergeValues({Result, Chain}, DL);
5475 }
5476 
5477 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5478                                               SelectionDAG &DAG) const {
5479   SDLoc DL(Op);
5480 
5481   const auto *MemSD = cast<MemSDNode>(Op);
5482   EVT MemVT = MemSD->getMemoryVT();
5483   MachineMemOperand *MMO = MemSD->getMemOperand();
5484   SDValue Chain = MemSD->getChain();
5485   SDValue BasePtr = MemSD->getBasePtr();
5486   SDValue Val, Mask, VL;
5487 
5488   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5489     Val = VPStore->getValue();
5490     Mask = VPStore->getMask();
5491     VL = VPStore->getVectorLength();
5492   } else {
5493     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5494     Val = MStore->getValue();
5495     Mask = MStore->getMask();
5496   }
5497 
5498   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5499 
5500   MVT VT = Val.getSimpleValueType();
5501   MVT XLenVT = Subtarget.getXLenVT();
5502 
5503   MVT ContainerVT = VT;
5504   if (VT.isFixedLengthVector()) {
5505     ContainerVT = getContainerForFixedLengthVector(VT);
5506 
5507     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5508     if (!IsUnmasked) {
5509       MVT MaskVT =
5510           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5511       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5512     }
5513   }
5514 
5515   if (!VL)
5516     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5517 
5518   unsigned IntID =
5519       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5520   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5521   Ops.push_back(Val);
5522   Ops.push_back(BasePtr);
5523   if (!IsUnmasked)
5524     Ops.push_back(Mask);
5525   Ops.push_back(VL);
5526 
5527   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5528                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5529 }
5530 
5531 SDValue
5532 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5533                                                       SelectionDAG &DAG) const {
5534   MVT InVT = Op.getOperand(0).getSimpleValueType();
5535   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5536 
5537   MVT VT = Op.getSimpleValueType();
5538 
5539   SDValue Op1 =
5540       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5541   SDValue Op2 =
5542       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5543 
5544   SDLoc DL(Op);
5545   SDValue VL =
5546       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5547 
5548   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5549   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5550 
5551   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5552                             Op.getOperand(2), Mask, VL);
5553 
5554   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5555 }
5556 
5557 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5558     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5559   MVT VT = Op.getSimpleValueType();
5560 
5561   if (VT.getVectorElementType() == MVT::i1)
5562     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5563 
5564   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5565 }
5566 
5567 SDValue
5568 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5569                                                       SelectionDAG &DAG) const {
5570   unsigned Opc;
5571   switch (Op.getOpcode()) {
5572   default: llvm_unreachable("Unexpected opcode!");
5573   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5574   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5575   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5576   }
5577 
5578   return lowerToScalableOp(Op, DAG, Opc);
5579 }
5580 
5581 // Lower vector ABS to smax(X, sub(0, X)).
5582 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5583   SDLoc DL(Op);
5584   MVT VT = Op.getSimpleValueType();
5585   SDValue X = Op.getOperand(0);
5586 
5587   assert(VT.isFixedLengthVector() && "Unexpected type");
5588 
5589   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5590   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5591 
5592   SDValue Mask, VL;
5593   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5594 
5595   SDValue SplatZero =
5596       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5597                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5598   SDValue NegX =
5599       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5600   SDValue Max =
5601       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5602 
5603   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5604 }
5605 
5606 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5607     SDValue Op, SelectionDAG &DAG) const {
5608   SDLoc DL(Op);
5609   MVT VT = Op.getSimpleValueType();
5610   SDValue Mag = Op.getOperand(0);
5611   SDValue Sign = Op.getOperand(1);
5612   assert(Mag.getValueType() == Sign.getValueType() &&
5613          "Can only handle COPYSIGN with matching types.");
5614 
5615   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5616   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5617   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5618 
5619   SDValue Mask, VL;
5620   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5621 
5622   SDValue CopySign =
5623       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5624 
5625   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5626 }
5627 
5628 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5629     SDValue Op, SelectionDAG &DAG) const {
5630   MVT VT = Op.getSimpleValueType();
5631   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5632 
5633   MVT I1ContainerVT =
5634       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5635 
5636   SDValue CC =
5637       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5638   SDValue Op1 =
5639       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5640   SDValue Op2 =
5641       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5642 
5643   SDLoc DL(Op);
5644   SDValue Mask, VL;
5645   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5646 
5647   SDValue Select =
5648       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5649 
5650   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5651 }
5652 
5653 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5654                                                unsigned NewOpc,
5655                                                bool HasMask) const {
5656   MVT VT = Op.getSimpleValueType();
5657   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5658 
5659   // Create list of operands by converting existing ones to scalable types.
5660   SmallVector<SDValue, 6> Ops;
5661   for (const SDValue &V : Op->op_values()) {
5662     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5663 
5664     // Pass through non-vector operands.
5665     if (!V.getValueType().isVector()) {
5666       Ops.push_back(V);
5667       continue;
5668     }
5669 
5670     // "cast" fixed length vector to a scalable vector.
5671     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5672            "Only fixed length vectors are supported!");
5673     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5674   }
5675 
5676   SDLoc DL(Op);
5677   SDValue Mask, VL;
5678   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5679   if (HasMask)
5680     Ops.push_back(Mask);
5681   Ops.push_back(VL);
5682 
5683   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5684   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5685 }
5686 
5687 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5688 // * Operands of each node are assumed to be in the same order.
5689 // * The EVL operand is promoted from i32 to i64 on RV64.
5690 // * Fixed-length vectors are converted to their scalable-vector container
5691 //   types.
5692 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5693                                        unsigned RISCVISDOpc) const {
5694   SDLoc DL(Op);
5695   MVT VT = Op.getSimpleValueType();
5696   SmallVector<SDValue, 4> Ops;
5697 
5698   for (const auto &OpIdx : enumerate(Op->ops())) {
5699     SDValue V = OpIdx.value();
5700     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5701     // Pass through operands which aren't fixed-length vectors.
5702     if (!V.getValueType().isFixedLengthVector()) {
5703       Ops.push_back(V);
5704       continue;
5705     }
5706     // "cast" fixed length vector to a scalable vector.
5707     MVT OpVT = V.getSimpleValueType();
5708     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5709     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5710            "Only fixed length vectors are supported!");
5711     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5712   }
5713 
5714   if (!VT.isFixedLengthVector())
5715     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5716 
5717   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5718 
5719   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5720 
5721   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5722 }
5723 
5724 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5725                                             unsigned MaskOpc,
5726                                             unsigned VecOpc) const {
5727   MVT VT = Op.getSimpleValueType();
5728   if (VT.getVectorElementType() != MVT::i1)
5729     return lowerVPOp(Op, DAG, VecOpc);
5730 
5731   // It is safe to drop mask parameter as masked-off elements are undef.
5732   SDValue Op1 = Op->getOperand(0);
5733   SDValue Op2 = Op->getOperand(1);
5734   SDValue VL = Op->getOperand(3);
5735 
5736   MVT ContainerVT = VT;
5737   const bool IsFixed = VT.isFixedLengthVector();
5738   if (IsFixed) {
5739     ContainerVT = getContainerForFixedLengthVector(VT);
5740     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5741     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5742   }
5743 
5744   SDLoc DL(Op);
5745   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5746   if (!IsFixed)
5747     return Val;
5748   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5749 }
5750 
5751 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5752 // matched to a RVV indexed load. The RVV indexed load instructions only
5753 // support the "unsigned unscaled" addressing mode; indices are implicitly
5754 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5755 // signed or scaled indexing is extended to the XLEN value type and scaled
5756 // accordingly.
5757 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5758                                                SelectionDAG &DAG) const {
5759   SDLoc DL(Op);
5760   MVT VT = Op.getSimpleValueType();
5761 
5762   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5763   EVT MemVT = MemSD->getMemoryVT();
5764   MachineMemOperand *MMO = MemSD->getMemOperand();
5765   SDValue Chain = MemSD->getChain();
5766   SDValue BasePtr = MemSD->getBasePtr();
5767 
5768   ISD::LoadExtType LoadExtType;
5769   SDValue Index, Mask, PassThru, VL;
5770 
5771   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5772     Index = VPGN->getIndex();
5773     Mask = VPGN->getMask();
5774     PassThru = DAG.getUNDEF(VT);
5775     VL = VPGN->getVectorLength();
5776     // VP doesn't support extending loads.
5777     LoadExtType = ISD::NON_EXTLOAD;
5778   } else {
5779     // Else it must be a MGATHER.
5780     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5781     Index = MGN->getIndex();
5782     Mask = MGN->getMask();
5783     PassThru = MGN->getPassThru();
5784     LoadExtType = MGN->getExtensionType();
5785   }
5786 
5787   MVT IndexVT = Index.getSimpleValueType();
5788   MVT XLenVT = Subtarget.getXLenVT();
5789 
5790   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5791          "Unexpected VTs!");
5792   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5793   // Targets have to explicitly opt-in for extending vector loads.
5794   assert(LoadExtType == ISD::NON_EXTLOAD &&
5795          "Unexpected extending MGATHER/VP_GATHER");
5796   (void)LoadExtType;
5797 
5798   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5799   // the selection of the masked intrinsics doesn't do this for us.
5800   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5801 
5802   MVT ContainerVT = VT;
5803   if (VT.isFixedLengthVector()) {
5804     // We need to use the larger of the result and index type to determine the
5805     // scalable type to use so we don't increase LMUL for any operand/result.
5806     if (VT.bitsGE(IndexVT)) {
5807       ContainerVT = getContainerForFixedLengthVector(VT);
5808       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5809                                  ContainerVT.getVectorElementCount());
5810     } else {
5811       IndexVT = getContainerForFixedLengthVector(IndexVT);
5812       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5813                                      IndexVT.getVectorElementCount());
5814     }
5815 
5816     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5817 
5818     if (!IsUnmasked) {
5819       MVT MaskVT =
5820           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5821       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5822       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5823     }
5824   }
5825 
5826   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5827       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5828       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5829   }
5830 
5831   if (!VL)
5832     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5833 
5834   unsigned IntID =
5835       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5836   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5837   if (IsUnmasked)
5838     Ops.push_back(DAG.getUNDEF(ContainerVT));
5839   else
5840     Ops.push_back(PassThru);
5841   Ops.push_back(BasePtr);
5842   Ops.push_back(Index);
5843   if (!IsUnmasked)
5844     Ops.push_back(Mask);
5845   Ops.push_back(VL);
5846   if (!IsUnmasked)
5847     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5848 
5849   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5850   SDValue Result =
5851       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5852   Chain = Result.getValue(1);
5853 
5854   if (VT.isFixedLengthVector())
5855     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5856 
5857   return DAG.getMergeValues({Result, Chain}, DL);
5858 }
5859 
5860 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5861 // matched to a RVV indexed store. The RVV indexed store instructions only
5862 // support the "unsigned unscaled" addressing mode; indices are implicitly
5863 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5864 // signed or scaled indexing is extended to the XLEN value type and scaled
5865 // accordingly.
5866 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5867                                                 SelectionDAG &DAG) const {
5868   SDLoc DL(Op);
5869   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5870   EVT MemVT = MemSD->getMemoryVT();
5871   MachineMemOperand *MMO = MemSD->getMemOperand();
5872   SDValue Chain = MemSD->getChain();
5873   SDValue BasePtr = MemSD->getBasePtr();
5874 
5875   bool IsTruncatingStore = false;
5876   SDValue Index, Mask, Val, VL;
5877 
5878   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5879     Index = VPSN->getIndex();
5880     Mask = VPSN->getMask();
5881     Val = VPSN->getValue();
5882     VL = VPSN->getVectorLength();
5883     // VP doesn't support truncating stores.
5884     IsTruncatingStore = false;
5885   } else {
5886     // Else it must be a MSCATTER.
5887     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5888     Index = MSN->getIndex();
5889     Mask = MSN->getMask();
5890     Val = MSN->getValue();
5891     IsTruncatingStore = MSN->isTruncatingStore();
5892   }
5893 
5894   MVT VT = Val.getSimpleValueType();
5895   MVT IndexVT = Index.getSimpleValueType();
5896   MVT XLenVT = Subtarget.getXLenVT();
5897 
5898   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5899          "Unexpected VTs!");
5900   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5901   // Targets have to explicitly opt-in for extending vector loads and
5902   // truncating vector stores.
5903   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5904   (void)IsTruncatingStore;
5905 
5906   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5907   // the selection of the masked intrinsics doesn't do this for us.
5908   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5909 
5910   MVT ContainerVT = VT;
5911   if (VT.isFixedLengthVector()) {
5912     // We need to use the larger of the value and index type to determine the
5913     // scalable type to use so we don't increase LMUL for any operand/result.
5914     if (VT.bitsGE(IndexVT)) {
5915       ContainerVT = getContainerForFixedLengthVector(VT);
5916       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5917                                  ContainerVT.getVectorElementCount());
5918     } else {
5919       IndexVT = getContainerForFixedLengthVector(IndexVT);
5920       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5921                                      IndexVT.getVectorElementCount());
5922     }
5923 
5924     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5925     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5926 
5927     if (!IsUnmasked) {
5928       MVT MaskVT =
5929           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5930       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5931     }
5932   }
5933 
5934   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5935       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5936       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5937   }
5938 
5939   if (!VL)
5940     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5941 
5942   unsigned IntID =
5943       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5944   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5945   Ops.push_back(Val);
5946   Ops.push_back(BasePtr);
5947   Ops.push_back(Index);
5948   if (!IsUnmasked)
5949     Ops.push_back(Mask);
5950   Ops.push_back(VL);
5951 
5952   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5953                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5954 }
5955 
5956 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5957                                                SelectionDAG &DAG) const {
5958   const MVT XLenVT = Subtarget.getXLenVT();
5959   SDLoc DL(Op);
5960   SDValue Chain = Op->getOperand(0);
5961   SDValue SysRegNo = DAG.getTargetConstant(
5962       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5963   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5964   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5965 
5966   // Encoding used for rounding mode in RISCV differs from that used in
5967   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5968   // table, which consists of a sequence of 4-bit fields, each representing
5969   // corresponding FLT_ROUNDS mode.
5970   static const int Table =
5971       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5972       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5973       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5974       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5975       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5976 
5977   SDValue Shift =
5978       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5979   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5980                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5981   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5982                                DAG.getConstant(7, DL, XLenVT));
5983 
5984   return DAG.getMergeValues({Masked, Chain}, DL);
5985 }
5986 
5987 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5988                                                SelectionDAG &DAG) const {
5989   const MVT XLenVT = Subtarget.getXLenVT();
5990   SDLoc DL(Op);
5991   SDValue Chain = Op->getOperand(0);
5992   SDValue RMValue = Op->getOperand(1);
5993   SDValue SysRegNo = DAG.getTargetConstant(
5994       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5995 
5996   // Encoding used for rounding mode in RISCV differs from that used in
5997   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5998   // a table, which consists of a sequence of 4-bit fields, each representing
5999   // corresponding RISCV mode.
6000   static const unsigned Table =
6001       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6002       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6003       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6004       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6005       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6006 
6007   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6008                               DAG.getConstant(2, DL, XLenVT));
6009   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6010                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6011   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6012                         DAG.getConstant(0x7, DL, XLenVT));
6013   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6014                      RMValue);
6015 }
6016 
6017 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6018   switch (IntNo) {
6019   default:
6020     llvm_unreachable("Unexpected Intrinsic");
6021   case Intrinsic::riscv_grev:
6022     return RISCVISD::GREVW;
6023   case Intrinsic::riscv_gorc:
6024     return RISCVISD::GORCW;
6025   case Intrinsic::riscv_bcompress:
6026     return RISCVISD::BCOMPRESSW;
6027   case Intrinsic::riscv_bdecompress:
6028     return RISCVISD::BDECOMPRESSW;
6029   case Intrinsic::riscv_bfp:
6030     return RISCVISD::BFPW;
6031   case Intrinsic::riscv_fsl:
6032     return RISCVISD::FSLW;
6033   case Intrinsic::riscv_fsr:
6034     return RISCVISD::FSRW;
6035   }
6036 }
6037 
6038 // Converts the given intrinsic to a i64 operation with any extension.
6039 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6040                                          unsigned IntNo) {
6041   SDLoc DL(N);
6042   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6043   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6044   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6045   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6046   // ReplaceNodeResults requires we maintain the same type for the return value.
6047   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6048 }
6049 
6050 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6051 // form of the given Opcode.
6052 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6053   switch (Opcode) {
6054   default:
6055     llvm_unreachable("Unexpected opcode");
6056   case ISD::SHL:
6057     return RISCVISD::SLLW;
6058   case ISD::SRA:
6059     return RISCVISD::SRAW;
6060   case ISD::SRL:
6061     return RISCVISD::SRLW;
6062   case ISD::SDIV:
6063     return RISCVISD::DIVW;
6064   case ISD::UDIV:
6065     return RISCVISD::DIVUW;
6066   case ISD::UREM:
6067     return RISCVISD::REMUW;
6068   case ISD::ROTL:
6069     return RISCVISD::ROLW;
6070   case ISD::ROTR:
6071     return RISCVISD::RORW;
6072   case RISCVISD::GREV:
6073     return RISCVISD::GREVW;
6074   case RISCVISD::GORC:
6075     return RISCVISD::GORCW;
6076   }
6077 }
6078 
6079 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6080 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6081 // otherwise be promoted to i64, making it difficult to select the
6082 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6083 // type i8/i16/i32 is lost.
6084 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6085                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6086   SDLoc DL(N);
6087   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6088   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6089   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6090   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6091   // ReplaceNodeResults requires we maintain the same type for the return value.
6092   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6093 }
6094 
6095 // Converts the given 32-bit operation to a i64 operation with signed extension
6096 // semantic to reduce the signed extension instructions.
6097 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6098   SDLoc DL(N);
6099   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6100   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6101   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6102   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6103                                DAG.getValueType(MVT::i32));
6104   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6105 }
6106 
6107 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6108                                              SmallVectorImpl<SDValue> &Results,
6109                                              SelectionDAG &DAG) const {
6110   SDLoc DL(N);
6111   switch (N->getOpcode()) {
6112   default:
6113     llvm_unreachable("Don't know how to custom type legalize this operation!");
6114   case ISD::STRICT_FP_TO_SINT:
6115   case ISD::STRICT_FP_TO_UINT:
6116   case ISD::FP_TO_SINT:
6117   case ISD::FP_TO_UINT: {
6118     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6119            "Unexpected custom legalisation");
6120     bool IsStrict = N->isStrictFPOpcode();
6121     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6122                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6123     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6124     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6125         TargetLowering::TypeSoftenFloat) {
6126       if (!isTypeLegal(Op0.getValueType()))
6127         return;
6128       if (IsStrict) {
6129         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6130                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6131         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6132         SDValue Res = DAG.getNode(
6133             Opc, DL, VTs, N->getOperand(0), Op0,
6134             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6135         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6136         Results.push_back(Res.getValue(1));
6137         return;
6138       }
6139       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6140       SDValue Res =
6141           DAG.getNode(Opc, DL, MVT::i64, Op0,
6142                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6143       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6144       return;
6145     }
6146     // If the FP type needs to be softened, emit a library call using the 'si'
6147     // version. If we left it to default legalization we'd end up with 'di'. If
6148     // the FP type doesn't need to be softened just let generic type
6149     // legalization promote the result type.
6150     RTLIB::Libcall LC;
6151     if (IsSigned)
6152       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6153     else
6154       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6155     MakeLibCallOptions CallOptions;
6156     EVT OpVT = Op0.getValueType();
6157     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6158     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6159     SDValue Result;
6160     std::tie(Result, Chain) =
6161         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6162     Results.push_back(Result);
6163     if (IsStrict)
6164       Results.push_back(Chain);
6165     break;
6166   }
6167   case ISD::READCYCLECOUNTER: {
6168     assert(!Subtarget.is64Bit() &&
6169            "READCYCLECOUNTER only has custom type legalization on riscv32");
6170 
6171     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6172     SDValue RCW =
6173         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6174 
6175     Results.push_back(
6176         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6177     Results.push_back(RCW.getValue(2));
6178     break;
6179   }
6180   case ISD::MUL: {
6181     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6182     unsigned XLen = Subtarget.getXLen();
6183     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6184     if (Size > XLen) {
6185       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6186       SDValue LHS = N->getOperand(0);
6187       SDValue RHS = N->getOperand(1);
6188       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6189 
6190       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6191       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6192       // We need exactly one side to be unsigned.
6193       if (LHSIsU == RHSIsU)
6194         return;
6195 
6196       auto MakeMULPair = [&](SDValue S, SDValue U) {
6197         MVT XLenVT = Subtarget.getXLenVT();
6198         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6199         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6200         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6201         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6202         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6203       };
6204 
6205       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6206       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6207 
6208       // The other operand should be signed, but still prefer MULH when
6209       // possible.
6210       if (RHSIsU && LHSIsS && !RHSIsS)
6211         Results.push_back(MakeMULPair(LHS, RHS));
6212       else if (LHSIsU && RHSIsS && !LHSIsS)
6213         Results.push_back(MakeMULPair(RHS, LHS));
6214 
6215       return;
6216     }
6217     LLVM_FALLTHROUGH;
6218   }
6219   case ISD::ADD:
6220   case ISD::SUB:
6221     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6222            "Unexpected custom legalisation");
6223     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6224     break;
6225   case ISD::SHL:
6226   case ISD::SRA:
6227   case ISD::SRL:
6228     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6229            "Unexpected custom legalisation");
6230     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6231       Results.push_back(customLegalizeToWOp(N, DAG));
6232       break;
6233     }
6234 
6235     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6236     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6237     // shift amount.
6238     if (N->getOpcode() == ISD::SHL) {
6239       SDLoc DL(N);
6240       SDValue NewOp0 =
6241           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6242       SDValue NewOp1 =
6243           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6244       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6245       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6246                                    DAG.getValueType(MVT::i32));
6247       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6248     }
6249 
6250     break;
6251   case ISD::ROTL:
6252   case ISD::ROTR:
6253     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6254            "Unexpected custom legalisation");
6255     Results.push_back(customLegalizeToWOp(N, DAG));
6256     break;
6257   case ISD::CTTZ:
6258   case ISD::CTTZ_ZERO_UNDEF:
6259   case ISD::CTLZ:
6260   case ISD::CTLZ_ZERO_UNDEF: {
6261     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6262            "Unexpected custom legalisation");
6263 
6264     SDValue NewOp0 =
6265         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6266     bool IsCTZ =
6267         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6268     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6269     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6270     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6271     return;
6272   }
6273   case ISD::SDIV:
6274   case ISD::UDIV:
6275   case ISD::UREM: {
6276     MVT VT = N->getSimpleValueType(0);
6277     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6278            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6279            "Unexpected custom legalisation");
6280     // Don't promote division/remainder by constant since we should expand those
6281     // to multiply by magic constant.
6282     // FIXME: What if the expansion is disabled for minsize.
6283     if (N->getOperand(1).getOpcode() == ISD::Constant)
6284       return;
6285 
6286     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6287     // the upper 32 bits. For other types we need to sign or zero extend
6288     // based on the opcode.
6289     unsigned ExtOpc = ISD::ANY_EXTEND;
6290     if (VT != MVT::i32)
6291       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6292                                            : ISD::ZERO_EXTEND;
6293 
6294     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6295     break;
6296   }
6297   case ISD::UADDO:
6298   case ISD::USUBO: {
6299     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6300            "Unexpected custom legalisation");
6301     bool IsAdd = N->getOpcode() == ISD::UADDO;
6302     // Create an ADDW or SUBW.
6303     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6304     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6305     SDValue Res =
6306         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6307     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6308                       DAG.getValueType(MVT::i32));
6309 
6310     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6311     // Since the inputs are sign extended from i32, this is equivalent to
6312     // comparing the lower 32 bits.
6313     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6314     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6315                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6316 
6317     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6318     Results.push_back(Overflow);
6319     return;
6320   }
6321   case ISD::UADDSAT:
6322   case ISD::USUBSAT: {
6323     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6324            "Unexpected custom legalisation");
6325     if (Subtarget.hasStdExtZbb()) {
6326       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6327       // sign extend allows overflow of the lower 32 bits to be detected on
6328       // the promoted size.
6329       SDValue LHS =
6330           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6331       SDValue RHS =
6332           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6333       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6334       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6335       return;
6336     }
6337 
6338     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6339     // promotion for UADDO/USUBO.
6340     Results.push_back(expandAddSubSat(N, DAG));
6341     return;
6342   }
6343   case ISD::BITCAST: {
6344     EVT VT = N->getValueType(0);
6345     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6346     SDValue Op0 = N->getOperand(0);
6347     EVT Op0VT = Op0.getValueType();
6348     MVT XLenVT = Subtarget.getXLenVT();
6349     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6350       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6351       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6352     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6353                Subtarget.hasStdExtF()) {
6354       SDValue FPConv =
6355           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6356       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6357     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6358                isTypeLegal(Op0VT)) {
6359       // Custom-legalize bitcasts from fixed-length vector types to illegal
6360       // scalar types in order to improve codegen. Bitcast the vector to a
6361       // one-element vector type whose element type is the same as the result
6362       // type, and extract the first element.
6363       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6364       if (isTypeLegal(BVT)) {
6365         SDValue BVec = DAG.getBitcast(BVT, Op0);
6366         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6367                                       DAG.getConstant(0, DL, XLenVT)));
6368       }
6369     }
6370     break;
6371   }
6372   case RISCVISD::GREV:
6373   case RISCVISD::GORC: {
6374     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6375            "Unexpected custom legalisation");
6376     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6377     // This is similar to customLegalizeToWOp, except that we pass the second
6378     // operand (a TargetConstant) straight through: it is already of type
6379     // XLenVT.
6380     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6381     SDValue NewOp0 =
6382         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6383     SDValue NewOp1 =
6384         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6385     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6386     // ReplaceNodeResults requires we maintain the same type for the return
6387     // value.
6388     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6389     break;
6390   }
6391   case RISCVISD::SHFL: {
6392     // There is no SHFLIW instruction, but we can just promote the operation.
6393     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6394            "Unexpected custom legalisation");
6395     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6396     SDValue NewOp0 =
6397         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6398     SDValue NewOp1 =
6399         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6400     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6401     // ReplaceNodeResults requires we maintain the same type for the return
6402     // value.
6403     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6404     break;
6405   }
6406   case ISD::BSWAP:
6407   case ISD::BITREVERSE: {
6408     MVT VT = N->getSimpleValueType(0);
6409     MVT XLenVT = Subtarget.getXLenVT();
6410     assert((VT == MVT::i8 || VT == MVT::i16 ||
6411             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6412            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6413     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6414     unsigned Imm = VT.getSizeInBits() - 1;
6415     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6416     if (N->getOpcode() == ISD::BSWAP)
6417       Imm &= ~0x7U;
6418     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6419     SDValue GREVI =
6420         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6421     // ReplaceNodeResults requires we maintain the same type for the return
6422     // value.
6423     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6424     break;
6425   }
6426   case ISD::FSHL:
6427   case ISD::FSHR: {
6428     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6429            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6430     SDValue NewOp0 =
6431         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6432     SDValue NewOp1 =
6433         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6434     SDValue NewShAmt =
6435         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6436     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6437     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6438     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6439                            DAG.getConstant(0x1f, DL, MVT::i64));
6440     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6441     // instruction use different orders. fshl will return its first operand for
6442     // shift of zero, fshr will return its second operand. fsl and fsr both
6443     // return rs1 so the ISD nodes need to have different operand orders.
6444     // Shift amount is in rs2.
6445     unsigned Opc = RISCVISD::FSLW;
6446     if (N->getOpcode() == ISD::FSHR) {
6447       std::swap(NewOp0, NewOp1);
6448       Opc = RISCVISD::FSRW;
6449     }
6450     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6451     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6452     break;
6453   }
6454   case ISD::EXTRACT_VECTOR_ELT: {
6455     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6456     // type is illegal (currently only vXi64 RV32).
6457     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6458     // transferred to the destination register. We issue two of these from the
6459     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6460     // first element.
6461     SDValue Vec = N->getOperand(0);
6462     SDValue Idx = N->getOperand(1);
6463 
6464     // The vector type hasn't been legalized yet so we can't issue target
6465     // specific nodes if it needs legalization.
6466     // FIXME: We would manually legalize if it's important.
6467     if (!isTypeLegal(Vec.getValueType()))
6468       return;
6469 
6470     MVT VecVT = Vec.getSimpleValueType();
6471 
6472     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6473            VecVT.getVectorElementType() == MVT::i64 &&
6474            "Unexpected EXTRACT_VECTOR_ELT legalization");
6475 
6476     // If this is a fixed vector, we need to convert it to a scalable vector.
6477     MVT ContainerVT = VecVT;
6478     if (VecVT.isFixedLengthVector()) {
6479       ContainerVT = getContainerForFixedLengthVector(VecVT);
6480       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6481     }
6482 
6483     MVT XLenVT = Subtarget.getXLenVT();
6484 
6485     // Use a VL of 1 to avoid processing more elements than we need.
6486     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6487     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6488     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6489 
6490     // Unless the index is known to be 0, we must slide the vector down to get
6491     // the desired element into index 0.
6492     if (!isNullConstant(Idx)) {
6493       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6494                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6495     }
6496 
6497     // Extract the lower XLEN bits of the correct vector element.
6498     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6499 
6500     // To extract the upper XLEN bits of the vector element, shift the first
6501     // element right by 32 bits and re-extract the lower XLEN bits.
6502     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6503                                      DAG.getConstant(32, DL, XLenVT), VL);
6504     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6505                                  ThirtyTwoV, Mask, VL);
6506 
6507     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6508 
6509     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6510     break;
6511   }
6512   case ISD::INTRINSIC_WO_CHAIN: {
6513     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6514     switch (IntNo) {
6515     default:
6516       llvm_unreachable(
6517           "Don't know how to custom type legalize this intrinsic!");
6518     case Intrinsic::riscv_grev:
6519     case Intrinsic::riscv_gorc:
6520     case Intrinsic::riscv_bcompress:
6521     case Intrinsic::riscv_bdecompress:
6522     case Intrinsic::riscv_bfp: {
6523       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6524              "Unexpected custom legalisation");
6525       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6526       break;
6527     }
6528     case Intrinsic::riscv_fsl:
6529     case Intrinsic::riscv_fsr: {
6530       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6531              "Unexpected custom legalisation");
6532       SDValue NewOp1 =
6533           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6534       SDValue NewOp2 =
6535           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6536       SDValue NewOp3 =
6537           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6538       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6539       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6540       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6541       break;
6542     }
6543     case Intrinsic::riscv_orc_b: {
6544       // Lower to the GORCI encoding for orc.b with the operand extended.
6545       SDValue NewOp =
6546           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6547       // If Zbp is enabled, use GORCIW which will sign extend the result.
6548       unsigned Opc =
6549           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6550       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6551                                 DAG.getConstant(7, DL, MVT::i64));
6552       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6553       return;
6554     }
6555     case Intrinsic::riscv_shfl:
6556     case Intrinsic::riscv_unshfl: {
6557       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6558              "Unexpected custom legalisation");
6559       SDValue NewOp1 =
6560           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6561       SDValue NewOp2 =
6562           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6563       unsigned Opc =
6564           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6565       if (isa<ConstantSDNode>(N->getOperand(2))) {
6566         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6567                              DAG.getConstant(0xf, DL, MVT::i64));
6568         Opc =
6569             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6570       }
6571       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6572       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6573       break;
6574     }
6575     case Intrinsic::riscv_vmv_x_s: {
6576       EVT VT = N->getValueType(0);
6577       MVT XLenVT = Subtarget.getXLenVT();
6578       if (VT.bitsLT(XLenVT)) {
6579         // Simple case just extract using vmv.x.s and truncate.
6580         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6581                                       Subtarget.getXLenVT(), N->getOperand(1));
6582         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6583         return;
6584       }
6585 
6586       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6587              "Unexpected custom legalization");
6588 
6589       // We need to do the move in two steps.
6590       SDValue Vec = N->getOperand(1);
6591       MVT VecVT = Vec.getSimpleValueType();
6592 
6593       // First extract the lower XLEN bits of the element.
6594       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6595 
6596       // To extract the upper XLEN bits of the vector element, shift the first
6597       // element right by 32 bits and re-extract the lower XLEN bits.
6598       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6599       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6600       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6601       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6602                                        DAG.getConstant(32, DL, XLenVT), VL);
6603       SDValue LShr32 =
6604           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6605       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6606 
6607       Results.push_back(
6608           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6609       break;
6610     }
6611     }
6612     break;
6613   }
6614   case ISD::VECREDUCE_ADD:
6615   case ISD::VECREDUCE_AND:
6616   case ISD::VECREDUCE_OR:
6617   case ISD::VECREDUCE_XOR:
6618   case ISD::VECREDUCE_SMAX:
6619   case ISD::VECREDUCE_UMAX:
6620   case ISD::VECREDUCE_SMIN:
6621   case ISD::VECREDUCE_UMIN:
6622     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6623       Results.push_back(V);
6624     break;
6625   case ISD::VP_REDUCE_ADD:
6626   case ISD::VP_REDUCE_AND:
6627   case ISD::VP_REDUCE_OR:
6628   case ISD::VP_REDUCE_XOR:
6629   case ISD::VP_REDUCE_SMAX:
6630   case ISD::VP_REDUCE_UMAX:
6631   case ISD::VP_REDUCE_SMIN:
6632   case ISD::VP_REDUCE_UMIN:
6633     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6634       Results.push_back(V);
6635     break;
6636   case ISD::FLT_ROUNDS_: {
6637     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6638     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6639     Results.push_back(Res.getValue(0));
6640     Results.push_back(Res.getValue(1));
6641     break;
6642   }
6643   }
6644 }
6645 
6646 // A structure to hold one of the bit-manipulation patterns below. Together, a
6647 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6648 //   (or (and (shl x, 1), 0xAAAAAAAA),
6649 //       (and (srl x, 1), 0x55555555))
6650 struct RISCVBitmanipPat {
6651   SDValue Op;
6652   unsigned ShAmt;
6653   bool IsSHL;
6654 
6655   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6656     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6657   }
6658 };
6659 
6660 // Matches patterns of the form
6661 //   (and (shl x, C2), (C1 << C2))
6662 //   (and (srl x, C2), C1)
6663 //   (shl (and x, C1), C2)
6664 //   (srl (and x, (C1 << C2)), C2)
6665 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6666 // The expected masks for each shift amount are specified in BitmanipMasks where
6667 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6668 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6669 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6670 // XLen is 64.
6671 static Optional<RISCVBitmanipPat>
6672 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6673   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6674          "Unexpected number of masks");
6675   Optional<uint64_t> Mask;
6676   // Optionally consume a mask around the shift operation.
6677   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6678     Mask = Op.getConstantOperandVal(1);
6679     Op = Op.getOperand(0);
6680   }
6681   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6682     return None;
6683   bool IsSHL = Op.getOpcode() == ISD::SHL;
6684 
6685   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6686     return None;
6687   uint64_t ShAmt = Op.getConstantOperandVal(1);
6688 
6689   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6690   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6691     return None;
6692   // If we don't have enough masks for 64 bit, then we must be trying to
6693   // match SHFL so we're only allowed to shift 1/4 of the width.
6694   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6695     return None;
6696 
6697   SDValue Src = Op.getOperand(0);
6698 
6699   // The expected mask is shifted left when the AND is found around SHL
6700   // patterns.
6701   //   ((x >> 1) & 0x55555555)
6702   //   ((x << 1) & 0xAAAAAAAA)
6703   bool SHLExpMask = IsSHL;
6704 
6705   if (!Mask) {
6706     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6707     // the mask is all ones: consume that now.
6708     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6709       Mask = Src.getConstantOperandVal(1);
6710       Src = Src.getOperand(0);
6711       // The expected mask is now in fact shifted left for SRL, so reverse the
6712       // decision.
6713       //   ((x & 0xAAAAAAAA) >> 1)
6714       //   ((x & 0x55555555) << 1)
6715       SHLExpMask = !SHLExpMask;
6716     } else {
6717       // Use a default shifted mask of all-ones if there's no AND, truncated
6718       // down to the expected width. This simplifies the logic later on.
6719       Mask = maskTrailingOnes<uint64_t>(Width);
6720       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6721     }
6722   }
6723 
6724   unsigned MaskIdx = Log2_32(ShAmt);
6725   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6726 
6727   if (SHLExpMask)
6728     ExpMask <<= ShAmt;
6729 
6730   if (Mask != ExpMask)
6731     return None;
6732 
6733   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6734 }
6735 
6736 // Matches any of the following bit-manipulation patterns:
6737 //   (and (shl x, 1), (0x55555555 << 1))
6738 //   (and (srl x, 1), 0x55555555)
6739 //   (shl (and x, 0x55555555), 1)
6740 //   (srl (and x, (0x55555555 << 1)), 1)
6741 // where the shift amount and mask may vary thus:
6742 //   [1]  = 0x55555555 / 0xAAAAAAAA
6743 //   [2]  = 0x33333333 / 0xCCCCCCCC
6744 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6745 //   [8]  = 0x00FF00FF / 0xFF00FF00
6746 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6747 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6748 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6749   // These are the unshifted masks which we use to match bit-manipulation
6750   // patterns. They may be shifted left in certain circumstances.
6751   static const uint64_t BitmanipMasks[] = {
6752       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6753       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6754 
6755   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6756 }
6757 
6758 // Match the following pattern as a GREVI(W) operation
6759 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6760 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6761                                const RISCVSubtarget &Subtarget) {
6762   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6763   EVT VT = Op.getValueType();
6764 
6765   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6766     auto LHS = matchGREVIPat(Op.getOperand(0));
6767     auto RHS = matchGREVIPat(Op.getOperand(1));
6768     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6769       SDLoc DL(Op);
6770       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6771                          DAG.getConstant(LHS->ShAmt, DL, VT));
6772     }
6773   }
6774   return SDValue();
6775 }
6776 
6777 // Matches any the following pattern as a GORCI(W) operation
6778 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6779 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6780 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6781 // Note that with the variant of 3.,
6782 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6783 // the inner pattern will first be matched as GREVI and then the outer
6784 // pattern will be matched to GORC via the first rule above.
6785 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6786 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6787                                const RISCVSubtarget &Subtarget) {
6788   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6789   EVT VT = Op.getValueType();
6790 
6791   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6792     SDLoc DL(Op);
6793     SDValue Op0 = Op.getOperand(0);
6794     SDValue Op1 = Op.getOperand(1);
6795 
6796     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6797       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6798           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6799           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6800         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6801       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6802       if ((Reverse.getOpcode() == ISD::ROTL ||
6803            Reverse.getOpcode() == ISD::ROTR) &&
6804           Reverse.getOperand(0) == X &&
6805           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6806         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6807         if (RotAmt == (VT.getSizeInBits() / 2))
6808           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6809                              DAG.getConstant(RotAmt, DL, VT));
6810       }
6811       return SDValue();
6812     };
6813 
6814     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6815     if (SDValue V = MatchOROfReverse(Op0, Op1))
6816       return V;
6817     if (SDValue V = MatchOROfReverse(Op1, Op0))
6818       return V;
6819 
6820     // OR is commutable so canonicalize its OR operand to the left
6821     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6822       std::swap(Op0, Op1);
6823     if (Op0.getOpcode() != ISD::OR)
6824       return SDValue();
6825     SDValue OrOp0 = Op0.getOperand(0);
6826     SDValue OrOp1 = Op0.getOperand(1);
6827     auto LHS = matchGREVIPat(OrOp0);
6828     // OR is commutable so swap the operands and try again: x might have been
6829     // on the left
6830     if (!LHS) {
6831       std::swap(OrOp0, OrOp1);
6832       LHS = matchGREVIPat(OrOp0);
6833     }
6834     auto RHS = matchGREVIPat(Op1);
6835     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6836       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6837                          DAG.getConstant(LHS->ShAmt, DL, VT));
6838     }
6839   }
6840   return SDValue();
6841 }
6842 
6843 // Matches any of the following bit-manipulation patterns:
6844 //   (and (shl x, 1), (0x22222222 << 1))
6845 //   (and (srl x, 1), 0x22222222)
6846 //   (shl (and x, 0x22222222), 1)
6847 //   (srl (and x, (0x22222222 << 1)), 1)
6848 // where the shift amount and mask may vary thus:
6849 //   [1]  = 0x22222222 / 0x44444444
6850 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6851 //   [4]  = 0x00F000F0 / 0x0F000F00
6852 //   [8]  = 0x0000FF00 / 0x00FF0000
6853 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6854 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6855   // These are the unshifted masks which we use to match bit-manipulation
6856   // patterns. They may be shifted left in certain circumstances.
6857   static const uint64_t BitmanipMasks[] = {
6858       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6859       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6860 
6861   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6862 }
6863 
6864 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6865 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6866                                const RISCVSubtarget &Subtarget) {
6867   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6868   EVT VT = Op.getValueType();
6869 
6870   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6871     return SDValue();
6872 
6873   SDValue Op0 = Op.getOperand(0);
6874   SDValue Op1 = Op.getOperand(1);
6875 
6876   // Or is commutable so canonicalize the second OR to the LHS.
6877   if (Op0.getOpcode() != ISD::OR)
6878     std::swap(Op0, Op1);
6879   if (Op0.getOpcode() != ISD::OR)
6880     return SDValue();
6881 
6882   // We found an inner OR, so our operands are the operands of the inner OR
6883   // and the other operand of the outer OR.
6884   SDValue A = Op0.getOperand(0);
6885   SDValue B = Op0.getOperand(1);
6886   SDValue C = Op1;
6887 
6888   auto Match1 = matchSHFLPat(A);
6889   auto Match2 = matchSHFLPat(B);
6890 
6891   // If neither matched, we failed.
6892   if (!Match1 && !Match2)
6893     return SDValue();
6894 
6895   // We had at least one match. if one failed, try the remaining C operand.
6896   if (!Match1) {
6897     std::swap(A, C);
6898     Match1 = matchSHFLPat(A);
6899     if (!Match1)
6900       return SDValue();
6901   } else if (!Match2) {
6902     std::swap(B, C);
6903     Match2 = matchSHFLPat(B);
6904     if (!Match2)
6905       return SDValue();
6906   }
6907   assert(Match1 && Match2);
6908 
6909   // Make sure our matches pair up.
6910   if (!Match1->formsPairWith(*Match2))
6911     return SDValue();
6912 
6913   // All the remains is to make sure C is an AND with the same input, that masks
6914   // out the bits that are being shuffled.
6915   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6916       C.getOperand(0) != Match1->Op)
6917     return SDValue();
6918 
6919   uint64_t Mask = C.getConstantOperandVal(1);
6920 
6921   static const uint64_t BitmanipMasks[] = {
6922       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6923       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6924   };
6925 
6926   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6927   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6928   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6929 
6930   if (Mask != ExpMask)
6931     return SDValue();
6932 
6933   SDLoc DL(Op);
6934   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6935                      DAG.getConstant(Match1->ShAmt, DL, VT));
6936 }
6937 
6938 // Optimize (add (shl x, c0), (shl y, c1)) ->
6939 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6940 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6941                                   const RISCVSubtarget &Subtarget) {
6942   // Perform this optimization only in the zba extension.
6943   if (!Subtarget.hasStdExtZba())
6944     return SDValue();
6945 
6946   // Skip for vector types and larger types.
6947   EVT VT = N->getValueType(0);
6948   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6949     return SDValue();
6950 
6951   // The two operand nodes must be SHL and have no other use.
6952   SDValue N0 = N->getOperand(0);
6953   SDValue N1 = N->getOperand(1);
6954   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6955       !N0->hasOneUse() || !N1->hasOneUse())
6956     return SDValue();
6957 
6958   // Check c0 and c1.
6959   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6960   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6961   if (!N0C || !N1C)
6962     return SDValue();
6963   int64_t C0 = N0C->getSExtValue();
6964   int64_t C1 = N1C->getSExtValue();
6965   if (C0 <= 0 || C1 <= 0)
6966     return SDValue();
6967 
6968   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6969   int64_t Bits = std::min(C0, C1);
6970   int64_t Diff = std::abs(C0 - C1);
6971   if (Diff != 1 && Diff != 2 && Diff != 3)
6972     return SDValue();
6973 
6974   // Build nodes.
6975   SDLoc DL(N);
6976   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6977   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6978   SDValue NA0 =
6979       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6980   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6981   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6982 }
6983 
6984 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6985 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6986 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6987 // not undo itself, but they are redundant.
6988 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6989   SDValue Src = N->getOperand(0);
6990 
6991   if (Src.getOpcode() != N->getOpcode())
6992     return SDValue();
6993 
6994   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6995       !isa<ConstantSDNode>(Src.getOperand(1)))
6996     return SDValue();
6997 
6998   unsigned ShAmt1 = N->getConstantOperandVal(1);
6999   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7000   Src = Src.getOperand(0);
7001 
7002   unsigned CombinedShAmt;
7003   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7004     CombinedShAmt = ShAmt1 | ShAmt2;
7005   else
7006     CombinedShAmt = ShAmt1 ^ ShAmt2;
7007 
7008   if (CombinedShAmt == 0)
7009     return Src;
7010 
7011   SDLoc DL(N);
7012   return DAG.getNode(
7013       N->getOpcode(), DL, N->getValueType(0), Src,
7014       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7015 }
7016 
7017 // Combine a constant select operand into its use:
7018 //
7019 // (and (select cond, -1, c), x)
7020 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7021 // (or  (select cond, 0, c), x)
7022 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7023 // (xor (select cond, 0, c), x)
7024 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7025 // (add (select cond, 0, c), x)
7026 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7027 // (sub x, (select cond, 0, c))
7028 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7029 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7030                                    SelectionDAG &DAG, bool AllOnes) {
7031   EVT VT = N->getValueType(0);
7032 
7033   // Skip vectors.
7034   if (VT.isVector())
7035     return SDValue();
7036 
7037   if ((Slct.getOpcode() != ISD::SELECT &&
7038        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7039       !Slct.hasOneUse())
7040     return SDValue();
7041 
7042   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7043     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7044   };
7045 
7046   bool SwapSelectOps;
7047   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7048   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7049   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7050   SDValue NonConstantVal;
7051   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7052     SwapSelectOps = false;
7053     NonConstantVal = FalseVal;
7054   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7055     SwapSelectOps = true;
7056     NonConstantVal = TrueVal;
7057   } else
7058     return SDValue();
7059 
7060   // Slct is now know to be the desired identity constant when CC is true.
7061   TrueVal = OtherOp;
7062   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7063   // Unless SwapSelectOps says the condition should be false.
7064   if (SwapSelectOps)
7065     std::swap(TrueVal, FalseVal);
7066 
7067   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7068     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7069                        {Slct.getOperand(0), Slct.getOperand(1),
7070                         Slct.getOperand(2), TrueVal, FalseVal});
7071 
7072   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7073                      {Slct.getOperand(0), TrueVal, FalseVal});
7074 }
7075 
7076 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7077 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7078                                               bool AllOnes) {
7079   SDValue N0 = N->getOperand(0);
7080   SDValue N1 = N->getOperand(1);
7081   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7082     return Result;
7083   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7084     return Result;
7085   return SDValue();
7086 }
7087 
7088 // Transform (add (mul x, c0), c1) ->
7089 //           (add (mul (add x, c1/c0), c0), c1%c0).
7090 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7091 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7092 // to an infinite loop in DAGCombine if transformed.
7093 // Or transform (add (mul x, c0), c1) ->
7094 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7095 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7096 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7097 // lead to an infinite loop in DAGCombine if transformed.
7098 // Or transform (add (mul x, c0), c1) ->
7099 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7100 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7101 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7102 // lead to an infinite loop in DAGCombine if transformed.
7103 // Or transform (add (mul x, c0), c1) ->
7104 //              (mul (add x, c1/c0), c0).
7105 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7106 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7107                                      const RISCVSubtarget &Subtarget) {
7108   // Skip for vector types and larger types.
7109   EVT VT = N->getValueType(0);
7110   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7111     return SDValue();
7112   // The first operand node must be a MUL and has no other use.
7113   SDValue N0 = N->getOperand(0);
7114   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7115     return SDValue();
7116   // Check if c0 and c1 match above conditions.
7117   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7118   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7119   if (!N0C || !N1C)
7120     return SDValue();
7121   int64_t C0 = N0C->getSExtValue();
7122   int64_t C1 = N1C->getSExtValue();
7123   int64_t CA, CB;
7124   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7125     return SDValue();
7126   // Search for proper CA (non-zero) and CB that both are simm12.
7127   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7128       !isInt<12>(C0 * (C1 / C0))) {
7129     CA = C1 / C0;
7130     CB = C1 % C0;
7131   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7132              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7133     CA = C1 / C0 + 1;
7134     CB = C1 % C0 - C0;
7135   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7136              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7137     CA = C1 / C0 - 1;
7138     CB = C1 % C0 + C0;
7139   } else
7140     return SDValue();
7141   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7142   SDLoc DL(N);
7143   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7144                              DAG.getConstant(CA, DL, VT));
7145   SDValue New1 =
7146       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7147   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7148 }
7149 
7150 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7151                                  const RISCVSubtarget &Subtarget) {
7152   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7153     return V;
7154   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7155     return V;
7156   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7157   //      (select lhs, rhs, cc, x, (add x, y))
7158   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7159 }
7160 
7161 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7162   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7163   //      (select lhs, rhs, cc, x, (sub x, y))
7164   SDValue N0 = N->getOperand(0);
7165   SDValue N1 = N->getOperand(1);
7166   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7167 }
7168 
7169 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7170   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7171   //      (select lhs, rhs, cc, x, (and x, y))
7172   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7173 }
7174 
7175 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7176                                 const RISCVSubtarget &Subtarget) {
7177   if (Subtarget.hasStdExtZbp()) {
7178     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7179       return GREV;
7180     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7181       return GORC;
7182     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7183       return SHFL;
7184   }
7185 
7186   // fold (or (select cond, 0, y), x) ->
7187   //      (select cond, x, (or x, y))
7188   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7189 }
7190 
7191 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7192   // fold (xor (select cond, 0, y), x) ->
7193   //      (select cond, x, (xor x, y))
7194   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7195 }
7196 
7197 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7198 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7199 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7200 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7201 // ADDW/SUBW/MULW.
7202 static SDValue performANY_EXTENDCombine(SDNode *N,
7203                                         TargetLowering::DAGCombinerInfo &DCI,
7204                                         const RISCVSubtarget &Subtarget) {
7205   if (!Subtarget.is64Bit())
7206     return SDValue();
7207 
7208   SelectionDAG &DAG = DCI.DAG;
7209 
7210   SDValue Src = N->getOperand(0);
7211   EVT VT = N->getValueType(0);
7212   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7213     return SDValue();
7214 
7215   // The opcode must be one that can implicitly sign_extend.
7216   // FIXME: Additional opcodes.
7217   switch (Src.getOpcode()) {
7218   default:
7219     return SDValue();
7220   case ISD::MUL:
7221     if (!Subtarget.hasStdExtM())
7222       return SDValue();
7223     LLVM_FALLTHROUGH;
7224   case ISD::ADD:
7225   case ISD::SUB:
7226     break;
7227   }
7228 
7229   // Only handle cases where the result is used by a CopyToReg. That likely
7230   // means the value is a liveout of the basic block. This helps prevent
7231   // infinite combine loops like PR51206.
7232   if (none_of(N->uses(),
7233               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7234     return SDValue();
7235 
7236   SmallVector<SDNode *, 4> SetCCs;
7237   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7238                             UE = Src.getNode()->use_end();
7239        UI != UE; ++UI) {
7240     SDNode *User = *UI;
7241     if (User == N)
7242       continue;
7243     if (UI.getUse().getResNo() != Src.getResNo())
7244       continue;
7245     // All i32 setccs are legalized by sign extending operands.
7246     if (User->getOpcode() == ISD::SETCC) {
7247       SetCCs.push_back(User);
7248       continue;
7249     }
7250     // We don't know if we can extend this user.
7251     break;
7252   }
7253 
7254   // If we don't have any SetCCs, this isn't worthwhile.
7255   if (SetCCs.empty())
7256     return SDValue();
7257 
7258   SDLoc DL(N);
7259   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7260   DCI.CombineTo(N, SExt);
7261 
7262   // Promote all the setccs.
7263   for (SDNode *SetCC : SetCCs) {
7264     SmallVector<SDValue, 4> Ops;
7265 
7266     for (unsigned j = 0; j != 2; ++j) {
7267       SDValue SOp = SetCC->getOperand(j);
7268       if (SOp == Src)
7269         Ops.push_back(SExt);
7270       else
7271         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7272     }
7273 
7274     Ops.push_back(SetCC->getOperand(2));
7275     DCI.CombineTo(SetCC,
7276                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7277   }
7278   return SDValue(N, 0);
7279 }
7280 
7281 // Try to form VWMUL or VWMULU.
7282 // FIXME: Support VWMULSU.
7283 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7284                                        bool Commute) {
7285   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7286   SDValue Op0 = N->getOperand(0);
7287   SDValue Op1 = N->getOperand(1);
7288   if (Commute)
7289     std::swap(Op0, Op1);
7290 
7291   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7292   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7293   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7294     return SDValue();
7295 
7296   SDValue Mask = N->getOperand(2);
7297   SDValue VL = N->getOperand(3);
7298 
7299   // Make sure the mask and VL match.
7300   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7301     return SDValue();
7302 
7303   MVT VT = N->getSimpleValueType(0);
7304 
7305   // Determine the narrow size for a widening multiply.
7306   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7307   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7308                                   VT.getVectorElementCount());
7309 
7310   SDLoc DL(N);
7311 
7312   // See if the other operand is the same opcode.
7313   if (Op0.getOpcode() == Op1.getOpcode()) {
7314     if (!Op1.hasOneUse())
7315       return SDValue();
7316 
7317     // Make sure the mask and VL match.
7318     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7319       return SDValue();
7320 
7321     Op1 = Op1.getOperand(0);
7322   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7323     // The operand is a splat of a scalar.
7324 
7325     // The VL must be the same.
7326     if (Op1.getOperand(1) != VL)
7327       return SDValue();
7328 
7329     // Get the scalar value.
7330     Op1 = Op1.getOperand(0);
7331 
7332     // See if have enough sign bits or zero bits in the scalar to use a
7333     // widening multiply by splatting to smaller element size.
7334     unsigned EltBits = VT.getScalarSizeInBits();
7335     unsigned ScalarBits = Op1.getValueSizeInBits();
7336     // Make sure we're getting all element bits from the scalar register.
7337     // FIXME: Support implicit sign extension of vmv.v.x?
7338     if (ScalarBits < EltBits)
7339       return SDValue();
7340 
7341     if (IsSignExt) {
7342       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7343         return SDValue();
7344     } else {
7345       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7346       if (!DAG.MaskedValueIsZero(Op1, Mask))
7347         return SDValue();
7348     }
7349 
7350     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7351   } else
7352     return SDValue();
7353 
7354   Op0 = Op0.getOperand(0);
7355 
7356   // Re-introduce narrower extends if needed.
7357   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7358   if (Op0.getValueType() != NarrowVT)
7359     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7360   if (Op1.getValueType() != NarrowVT)
7361     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7362 
7363   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7364   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7365 }
7366 
7367 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7368   switch (Op.getOpcode()) {
7369   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7370   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7371   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7372   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7373   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7374   }
7375 
7376   return RISCVFPRndMode::Invalid;
7377 }
7378 
7379 // Fold
7380 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7381 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7382 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7383 //   (fp_to_int (fceil X))      -> fcvt X, rup
7384 //   (fp_to_int (fround X))     -> fcvt X, rmm
7385 static SDValue performFP_TO_INTCombine(SDNode *N,
7386                                        TargetLowering::DAGCombinerInfo &DCI,
7387                                        const RISCVSubtarget &Subtarget) {
7388   SelectionDAG &DAG = DCI.DAG;
7389   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7390   MVT XLenVT = Subtarget.getXLenVT();
7391 
7392   // Only handle XLen or i32 types. Other types narrower than XLen will
7393   // eventually be legalized to XLenVT.
7394   EVT VT = N->getValueType(0);
7395   if (VT != MVT::i32 && VT != XLenVT)
7396     return SDValue();
7397 
7398   SDValue Src = N->getOperand(0);
7399 
7400   // Ensure the FP type is also legal.
7401   if (!TLI.isTypeLegal(Src.getValueType()))
7402     return SDValue();
7403 
7404   // Don't do this for f16 with Zfhmin and not Zfh.
7405   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7406     return SDValue();
7407 
7408   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7409   if (FRM == RISCVFPRndMode::Invalid)
7410     return SDValue();
7411 
7412   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7413 
7414   unsigned Opc;
7415   if (VT == XLenVT)
7416     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7417   else
7418     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7419 
7420   SDLoc DL(N);
7421   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7422                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7423   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7424 }
7425 
7426 // Fold
7427 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7428 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7429 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7430 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7431 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7432 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7433                                        TargetLowering::DAGCombinerInfo &DCI,
7434                                        const RISCVSubtarget &Subtarget) {
7435   SelectionDAG &DAG = DCI.DAG;
7436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7437   MVT XLenVT = Subtarget.getXLenVT();
7438 
7439   // Only handle XLen types. Other types narrower than XLen will eventually be
7440   // legalized to XLenVT.
7441   EVT DstVT = N->getValueType(0);
7442   if (DstVT != XLenVT)
7443     return SDValue();
7444 
7445   SDValue Src = N->getOperand(0);
7446 
7447   // Ensure the FP type is also legal.
7448   if (!TLI.isTypeLegal(Src.getValueType()))
7449     return SDValue();
7450 
7451   // Don't do this for f16 with Zfhmin and not Zfh.
7452   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7453     return SDValue();
7454 
7455   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7456 
7457   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7458   if (FRM == RISCVFPRndMode::Invalid)
7459     return SDValue();
7460 
7461   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7462 
7463   unsigned Opc;
7464   if (SatVT == DstVT)
7465     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7466   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7467     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7468   else
7469     return SDValue();
7470   // FIXME: Support other SatVTs by clamping before or after the conversion.
7471 
7472   Src = Src.getOperand(0);
7473 
7474   SDLoc DL(N);
7475   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7476                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7477 
7478   // RISCV FP-to-int conversions saturate to the destination register size, but
7479   // don't produce 0 for nan.
7480   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7481   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7482 }
7483 
7484 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7485                                                DAGCombinerInfo &DCI) const {
7486   SelectionDAG &DAG = DCI.DAG;
7487 
7488   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7489   // bits are demanded. N will be added to the Worklist if it was not deleted.
7490   // Caller should return SDValue(N, 0) if this returns true.
7491   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7492     SDValue Op = N->getOperand(OpNo);
7493     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7494     if (!SimplifyDemandedBits(Op, Mask, DCI))
7495       return false;
7496 
7497     if (N->getOpcode() != ISD::DELETED_NODE)
7498       DCI.AddToWorklist(N);
7499     return true;
7500   };
7501 
7502   switch (N->getOpcode()) {
7503   default:
7504     break;
7505   case RISCVISD::SplitF64: {
7506     SDValue Op0 = N->getOperand(0);
7507     // If the input to SplitF64 is just BuildPairF64 then the operation is
7508     // redundant. Instead, use BuildPairF64's operands directly.
7509     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7510       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7511 
7512     SDLoc DL(N);
7513 
7514     // It's cheaper to materialise two 32-bit integers than to load a double
7515     // from the constant pool and transfer it to integer registers through the
7516     // stack.
7517     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7518       APInt V = C->getValueAPF().bitcastToAPInt();
7519       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7520       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7521       return DCI.CombineTo(N, Lo, Hi);
7522     }
7523 
7524     // This is a target-specific version of a DAGCombine performed in
7525     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7526     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7527     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7528     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7529         !Op0.getNode()->hasOneUse())
7530       break;
7531     SDValue NewSplitF64 =
7532         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7533                     Op0.getOperand(0));
7534     SDValue Lo = NewSplitF64.getValue(0);
7535     SDValue Hi = NewSplitF64.getValue(1);
7536     APInt SignBit = APInt::getSignMask(32);
7537     if (Op0.getOpcode() == ISD::FNEG) {
7538       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7539                                   DAG.getConstant(SignBit, DL, MVT::i32));
7540       return DCI.CombineTo(N, Lo, NewHi);
7541     }
7542     assert(Op0.getOpcode() == ISD::FABS);
7543     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7544                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7545     return DCI.CombineTo(N, Lo, NewHi);
7546   }
7547   case RISCVISD::SLLW:
7548   case RISCVISD::SRAW:
7549   case RISCVISD::SRLW:
7550   case RISCVISD::ROLW:
7551   case RISCVISD::RORW: {
7552     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7553     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7554         SimplifyDemandedLowBitsHelper(1, 5))
7555       return SDValue(N, 0);
7556     break;
7557   }
7558   case RISCVISD::CLZW:
7559   case RISCVISD::CTZW: {
7560     // Only the lower 32 bits of the first operand are read
7561     if (SimplifyDemandedLowBitsHelper(0, 32))
7562       return SDValue(N, 0);
7563     break;
7564   }
7565   case RISCVISD::GREV:
7566   case RISCVISD::GORC: {
7567     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7568     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7569     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7570     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7571       return SDValue(N, 0);
7572 
7573     return combineGREVI_GORCI(N, DAG);
7574   }
7575   case RISCVISD::GREVW:
7576   case RISCVISD::GORCW: {
7577     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7578     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7579         SimplifyDemandedLowBitsHelper(1, 5))
7580       return SDValue(N, 0);
7581 
7582     return combineGREVI_GORCI(N, DAG);
7583   }
7584   case RISCVISD::SHFL:
7585   case RISCVISD::UNSHFL: {
7586     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7587     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7588     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7589     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7590       return SDValue(N, 0);
7591 
7592     break;
7593   }
7594   case RISCVISD::SHFLW:
7595   case RISCVISD::UNSHFLW: {
7596     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7597     SDValue LHS = N->getOperand(0);
7598     SDValue RHS = N->getOperand(1);
7599     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7600     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7601     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7602         SimplifyDemandedLowBitsHelper(1, 4))
7603       return SDValue(N, 0);
7604 
7605     break;
7606   }
7607   case RISCVISD::BCOMPRESSW:
7608   case RISCVISD::BDECOMPRESSW: {
7609     // Only the lower 32 bits of LHS and RHS are read.
7610     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7611         SimplifyDemandedLowBitsHelper(1, 32))
7612       return SDValue(N, 0);
7613 
7614     break;
7615   }
7616   case RISCVISD::FMV_X_ANYEXTH:
7617   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7618     SDLoc DL(N);
7619     SDValue Op0 = N->getOperand(0);
7620     MVT VT = N->getSimpleValueType(0);
7621     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7622     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7623     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7624     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7625          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7626         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7627          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7628       assert(Op0.getOperand(0).getValueType() == VT &&
7629              "Unexpected value type!");
7630       return Op0.getOperand(0);
7631     }
7632 
7633     // This is a target-specific version of a DAGCombine performed in
7634     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7635     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7636     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7637     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7638         !Op0.getNode()->hasOneUse())
7639       break;
7640     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7641     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7642     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7643     if (Op0.getOpcode() == ISD::FNEG)
7644       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7645                          DAG.getConstant(SignBit, DL, VT));
7646 
7647     assert(Op0.getOpcode() == ISD::FABS);
7648     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7649                        DAG.getConstant(~SignBit, DL, VT));
7650   }
7651   case ISD::ADD:
7652     return performADDCombine(N, DAG, Subtarget);
7653   case ISD::SUB:
7654     return performSUBCombine(N, DAG);
7655   case ISD::AND:
7656     return performANDCombine(N, DAG);
7657   case ISD::OR:
7658     return performORCombine(N, DAG, Subtarget);
7659   case ISD::XOR:
7660     return performXORCombine(N, DAG);
7661   case ISD::ANY_EXTEND:
7662     return performANY_EXTENDCombine(N, DCI, Subtarget);
7663   case ISD::ZERO_EXTEND:
7664     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7665     // type legalization. This is safe because fp_to_uint produces poison if
7666     // it overflows.
7667     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7668       SDValue Src = N->getOperand(0);
7669       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7670           isTypeLegal(Src.getOperand(0).getValueType()))
7671         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7672                            Src.getOperand(0));
7673       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7674           isTypeLegal(Src.getOperand(1).getValueType())) {
7675         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7676         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7677                                   Src.getOperand(0), Src.getOperand(1));
7678         DCI.CombineTo(N, Res);
7679         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7680         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7681         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7682       }
7683     }
7684     return SDValue();
7685   case RISCVISD::SELECT_CC: {
7686     // Transform
7687     SDValue LHS = N->getOperand(0);
7688     SDValue RHS = N->getOperand(1);
7689     SDValue TrueV = N->getOperand(3);
7690     SDValue FalseV = N->getOperand(4);
7691 
7692     // If the True and False values are the same, we don't need a select_cc.
7693     if (TrueV == FalseV)
7694       return TrueV;
7695 
7696     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7697     if (!ISD::isIntEqualitySetCC(CCVal))
7698       break;
7699 
7700     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7701     //      (select_cc X, Y, lt, trueV, falseV)
7702     // Sometimes the setcc is introduced after select_cc has been formed.
7703     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7704         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7705       // If we're looking for eq 0 instead of ne 0, we need to invert the
7706       // condition.
7707       bool Invert = CCVal == ISD::SETEQ;
7708       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7709       if (Invert)
7710         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7711 
7712       SDLoc DL(N);
7713       RHS = LHS.getOperand(1);
7714       LHS = LHS.getOperand(0);
7715       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7716 
7717       SDValue TargetCC = DAG.getCondCode(CCVal);
7718       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7719                          {LHS, RHS, TargetCC, TrueV, FalseV});
7720     }
7721 
7722     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7723     //      (select_cc X, Y, eq/ne, trueV, falseV)
7724     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7725       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7726                          {LHS.getOperand(0), LHS.getOperand(1),
7727                           N->getOperand(2), TrueV, FalseV});
7728     // (select_cc X, 1, setne, trueV, falseV) ->
7729     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7730     // This can occur when legalizing some floating point comparisons.
7731     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7732     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7733       SDLoc DL(N);
7734       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7735       SDValue TargetCC = DAG.getCondCode(CCVal);
7736       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7737       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7738                          {LHS, RHS, TargetCC, TrueV, FalseV});
7739     }
7740 
7741     break;
7742   }
7743   case RISCVISD::BR_CC: {
7744     SDValue LHS = N->getOperand(1);
7745     SDValue RHS = N->getOperand(2);
7746     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7747     if (!ISD::isIntEqualitySetCC(CCVal))
7748       break;
7749 
7750     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7751     //      (br_cc X, Y, lt, dest)
7752     // Sometimes the setcc is introduced after br_cc has been formed.
7753     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7754         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7755       // If we're looking for eq 0 instead of ne 0, we need to invert the
7756       // condition.
7757       bool Invert = CCVal == ISD::SETEQ;
7758       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7759       if (Invert)
7760         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7761 
7762       SDLoc DL(N);
7763       RHS = LHS.getOperand(1);
7764       LHS = LHS.getOperand(0);
7765       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7766 
7767       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7768                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7769                          N->getOperand(4));
7770     }
7771 
7772     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7773     //      (br_cc X, Y, eq/ne, trueV, falseV)
7774     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7775       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7776                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7777                          N->getOperand(3), N->getOperand(4));
7778 
7779     // (br_cc X, 1, setne, br_cc) ->
7780     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7781     // This can occur when legalizing some floating point comparisons.
7782     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7783     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7784       SDLoc DL(N);
7785       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7786       SDValue TargetCC = DAG.getCondCode(CCVal);
7787       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7788       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7789                          N->getOperand(0), LHS, RHS, TargetCC,
7790                          N->getOperand(4));
7791     }
7792     break;
7793   }
7794   case ISD::FP_TO_SINT:
7795   case ISD::FP_TO_UINT:
7796     return performFP_TO_INTCombine(N, DCI, Subtarget);
7797   case ISD::FP_TO_SINT_SAT:
7798   case ISD::FP_TO_UINT_SAT:
7799     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7800   case ISD::FCOPYSIGN: {
7801     EVT VT = N->getValueType(0);
7802     if (!VT.isVector())
7803       break;
7804     // There is a form of VFSGNJ which injects the negated sign of its second
7805     // operand. Try and bubble any FNEG up after the extend/round to produce
7806     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7807     // TRUNC=1.
7808     SDValue In2 = N->getOperand(1);
7809     // Avoid cases where the extend/round has multiple uses, as duplicating
7810     // those is typically more expensive than removing a fneg.
7811     if (!In2.hasOneUse())
7812       break;
7813     if (In2.getOpcode() != ISD::FP_EXTEND &&
7814         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7815       break;
7816     In2 = In2.getOperand(0);
7817     if (In2.getOpcode() != ISD::FNEG)
7818       break;
7819     SDLoc DL(N);
7820     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7821     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7822                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7823   }
7824   case ISD::MGATHER:
7825   case ISD::MSCATTER:
7826   case ISD::VP_GATHER:
7827   case ISD::VP_SCATTER: {
7828     if (!DCI.isBeforeLegalize())
7829       break;
7830     SDValue Index, ScaleOp;
7831     bool IsIndexScaled = false;
7832     bool IsIndexSigned = false;
7833     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7834       Index = VPGSN->getIndex();
7835       ScaleOp = VPGSN->getScale();
7836       IsIndexScaled = VPGSN->isIndexScaled();
7837       IsIndexSigned = VPGSN->isIndexSigned();
7838     } else {
7839       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7840       Index = MGSN->getIndex();
7841       ScaleOp = MGSN->getScale();
7842       IsIndexScaled = MGSN->isIndexScaled();
7843       IsIndexSigned = MGSN->isIndexSigned();
7844     }
7845     EVT IndexVT = Index.getValueType();
7846     MVT XLenVT = Subtarget.getXLenVT();
7847     // RISCV indexed loads only support the "unsigned unscaled" addressing
7848     // mode, so anything else must be manually legalized.
7849     bool NeedsIdxLegalization =
7850         IsIndexScaled ||
7851         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7852     if (!NeedsIdxLegalization)
7853       break;
7854 
7855     SDLoc DL(N);
7856 
7857     // Any index legalization should first promote to XLenVT, so we don't lose
7858     // bits when scaling. This may create an illegal index type so we let
7859     // LLVM's legalization take care of the splitting.
7860     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7861     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7862       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7863       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7864                           DL, IndexVT, Index);
7865     }
7866 
7867     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7868     if (IsIndexScaled && Scale != 1) {
7869       // Manually scale the indices by the element size.
7870       // TODO: Sanitize the scale operand here?
7871       // TODO: For VP nodes, should we use VP_SHL here?
7872       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7873       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7874       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7875     }
7876 
7877     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7878     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7879       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7880                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7881                               VPGN->getScale(), VPGN->getMask(),
7882                               VPGN->getVectorLength()},
7883                              VPGN->getMemOperand(), NewIndexTy);
7884     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7885       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7886                               {VPSN->getChain(), VPSN->getValue(),
7887                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7888                                VPSN->getMask(), VPSN->getVectorLength()},
7889                               VPSN->getMemOperand(), NewIndexTy);
7890     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7891       return DAG.getMaskedGather(
7892           N->getVTList(), MGN->getMemoryVT(), DL,
7893           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7894            MGN->getBasePtr(), Index, MGN->getScale()},
7895           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7896     const auto *MSN = cast<MaskedScatterSDNode>(N);
7897     return DAG.getMaskedScatter(
7898         N->getVTList(), MSN->getMemoryVT(), DL,
7899         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7900          Index, MSN->getScale()},
7901         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7902   }
7903   case RISCVISD::SRA_VL:
7904   case RISCVISD::SRL_VL:
7905   case RISCVISD::SHL_VL: {
7906     SDValue ShAmt = N->getOperand(1);
7907     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7908       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7909       SDLoc DL(N);
7910       SDValue VL = N->getOperand(3);
7911       EVT VT = N->getValueType(0);
7912       ShAmt =
7913           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7914       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7915                          N->getOperand(2), N->getOperand(3));
7916     }
7917     break;
7918   }
7919   case ISD::SRA:
7920   case ISD::SRL:
7921   case ISD::SHL: {
7922     SDValue ShAmt = N->getOperand(1);
7923     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7924       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7925       SDLoc DL(N);
7926       EVT VT = N->getValueType(0);
7927       ShAmt =
7928           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7929       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7930     }
7931     break;
7932   }
7933   case RISCVISD::MUL_VL:
7934     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
7935       return V;
7936     // Mul is commutative.
7937     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
7938   case ISD::STORE: {
7939     auto *Store = cast<StoreSDNode>(N);
7940     SDValue Val = Store->getValue();
7941     // Combine store of vmv.x.s to vse with VL of 1.
7942     // FIXME: Support FP.
7943     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7944       SDValue Src = Val.getOperand(0);
7945       EVT VecVT = Src.getValueType();
7946       EVT MemVT = Store->getMemoryVT();
7947       // The memory VT and the element type must match.
7948       if (VecVT.getVectorElementType() == MemVT) {
7949         SDLoc DL(N);
7950         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7951         return DAG.getStoreVP(
7952             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
7953             DAG.getConstant(1, DL, MaskVT),
7954             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
7955             Store->getMemOperand(), Store->getAddressingMode(),
7956             Store->isTruncatingStore(), /*IsCompress*/ false);
7957       }
7958     }
7959 
7960     break;
7961   }
7962   }
7963 
7964   return SDValue();
7965 }
7966 
7967 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7968     const SDNode *N, CombineLevel Level) const {
7969   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7970   // materialised in fewer instructions than `(OP _, c1)`:
7971   //
7972   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7973   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7974   SDValue N0 = N->getOperand(0);
7975   EVT Ty = N0.getValueType();
7976   if (Ty.isScalarInteger() &&
7977       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7978     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7979     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7980     if (C1 && C2) {
7981       const APInt &C1Int = C1->getAPIntValue();
7982       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7983 
7984       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7985       // and the combine should happen, to potentially allow further combines
7986       // later.
7987       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7988           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7989         return true;
7990 
7991       // We can materialise `c1` in an add immediate, so it's "free", and the
7992       // combine should be prevented.
7993       if (C1Int.getMinSignedBits() <= 64 &&
7994           isLegalAddImmediate(C1Int.getSExtValue()))
7995         return false;
7996 
7997       // Neither constant will fit into an immediate, so find materialisation
7998       // costs.
7999       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8000                                               Subtarget.getFeatureBits(),
8001                                               /*CompressionCost*/true);
8002       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8003           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8004           /*CompressionCost*/true);
8005 
8006       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8007       // combine should be prevented.
8008       if (C1Cost < ShiftedC1Cost)
8009         return false;
8010     }
8011   }
8012   return true;
8013 }
8014 
8015 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8016     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8017     TargetLoweringOpt &TLO) const {
8018   // Delay this optimization as late as possible.
8019   if (!TLO.LegalOps)
8020     return false;
8021 
8022   EVT VT = Op.getValueType();
8023   if (VT.isVector())
8024     return false;
8025 
8026   // Only handle AND for now.
8027   if (Op.getOpcode() != ISD::AND)
8028     return false;
8029 
8030   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8031   if (!C)
8032     return false;
8033 
8034   const APInt &Mask = C->getAPIntValue();
8035 
8036   // Clear all non-demanded bits initially.
8037   APInt ShrunkMask = Mask & DemandedBits;
8038 
8039   // Try to make a smaller immediate by setting undemanded bits.
8040 
8041   APInt ExpandedMask = Mask | ~DemandedBits;
8042 
8043   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8044     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8045   };
8046   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8047     if (NewMask == Mask)
8048       return true;
8049     SDLoc DL(Op);
8050     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8051     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8052     return TLO.CombineTo(Op, NewOp);
8053   };
8054 
8055   // If the shrunk mask fits in sign extended 12 bits, let the target
8056   // independent code apply it.
8057   if (ShrunkMask.isSignedIntN(12))
8058     return false;
8059 
8060   // Preserve (and X, 0xffff) when zext.h is supported.
8061   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8062     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8063     if (IsLegalMask(NewMask))
8064       return UseMask(NewMask);
8065   }
8066 
8067   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8068   if (VT == MVT::i64) {
8069     APInt NewMask = APInt(64, 0xffffffff);
8070     if (IsLegalMask(NewMask))
8071       return UseMask(NewMask);
8072   }
8073 
8074   // For the remaining optimizations, we need to be able to make a negative
8075   // number through a combination of mask and undemanded bits.
8076   if (!ExpandedMask.isNegative())
8077     return false;
8078 
8079   // What is the fewest number of bits we need to represent the negative number.
8080   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8081 
8082   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8083   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8084   APInt NewMask = ShrunkMask;
8085   if (MinSignedBits <= 12)
8086     NewMask.setBitsFrom(11);
8087   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8088     NewMask.setBitsFrom(31);
8089   else
8090     return false;
8091 
8092   // Check that our new mask is a subset of the demanded mask.
8093   assert(IsLegalMask(NewMask));
8094   return UseMask(NewMask);
8095 }
8096 
8097 static void computeGREV(APInt &Src, unsigned ShAmt) {
8098   ShAmt &= Src.getBitWidth() - 1;
8099   uint64_t x = Src.getZExtValue();
8100   if (ShAmt & 1)
8101     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8102   if (ShAmt & 2)
8103     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8104   if (ShAmt & 4)
8105     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8106   if (ShAmt & 8)
8107     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8108   if (ShAmt & 16)
8109     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8110   if (ShAmt & 32)
8111     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8112   Src = x;
8113 }
8114 
8115 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8116                                                         KnownBits &Known,
8117                                                         const APInt &DemandedElts,
8118                                                         const SelectionDAG &DAG,
8119                                                         unsigned Depth) const {
8120   unsigned BitWidth = Known.getBitWidth();
8121   unsigned Opc = Op.getOpcode();
8122   assert((Opc >= ISD::BUILTIN_OP_END ||
8123           Opc == ISD::INTRINSIC_WO_CHAIN ||
8124           Opc == ISD::INTRINSIC_W_CHAIN ||
8125           Opc == ISD::INTRINSIC_VOID) &&
8126          "Should use MaskedValueIsZero if you don't know whether Op"
8127          " is a target node!");
8128 
8129   Known.resetAll();
8130   switch (Opc) {
8131   default: break;
8132   case RISCVISD::SELECT_CC: {
8133     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8134     // If we don't know any bits, early out.
8135     if (Known.isUnknown())
8136       break;
8137     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8138 
8139     // Only known if known in both the LHS and RHS.
8140     Known = KnownBits::commonBits(Known, Known2);
8141     break;
8142   }
8143   case RISCVISD::REMUW: {
8144     KnownBits Known2;
8145     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8146     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8147     // We only care about the lower 32 bits.
8148     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8149     // Restore the original width by sign extending.
8150     Known = Known.sext(BitWidth);
8151     break;
8152   }
8153   case RISCVISD::DIVUW: {
8154     KnownBits Known2;
8155     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8156     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8157     // We only care about the lower 32 bits.
8158     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8159     // Restore the original width by sign extending.
8160     Known = Known.sext(BitWidth);
8161     break;
8162   }
8163   case RISCVISD::CTZW: {
8164     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8165     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8166     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8167     Known.Zero.setBitsFrom(LowBits);
8168     break;
8169   }
8170   case RISCVISD::CLZW: {
8171     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8172     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8173     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8174     Known.Zero.setBitsFrom(LowBits);
8175     break;
8176   }
8177   case RISCVISD::GREV:
8178   case RISCVISD::GREVW: {
8179     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8180       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8181       if (Opc == RISCVISD::GREVW)
8182         Known = Known.trunc(32);
8183       unsigned ShAmt = C->getZExtValue();
8184       computeGREV(Known.Zero, ShAmt);
8185       computeGREV(Known.One, ShAmt);
8186       if (Opc == RISCVISD::GREVW)
8187         Known = Known.sext(BitWidth);
8188     }
8189     break;
8190   }
8191   case RISCVISD::READ_VLENB:
8192     // We assume VLENB is at least 16 bytes.
8193     Known.Zero.setLowBits(4);
8194     // We assume VLENB is no more than 65536 / 8 bytes.
8195     Known.Zero.setBitsFrom(14);
8196     break;
8197   case ISD::INTRINSIC_W_CHAIN:
8198   case ISD::INTRINSIC_WO_CHAIN: {
8199     unsigned IntNo =
8200         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8201     switch (IntNo) {
8202     default:
8203       // We can't do anything for most intrinsics.
8204       break;
8205     case Intrinsic::riscv_vsetvli:
8206     case Intrinsic::riscv_vsetvlimax:
8207     case Intrinsic::riscv_vsetvli_opt:
8208     case Intrinsic::riscv_vsetvlimax_opt:
8209       // Assume that VL output is positive and would fit in an int32_t.
8210       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8211       if (BitWidth >= 32)
8212         Known.Zero.setBitsFrom(31);
8213       break;
8214     }
8215     break;
8216   }
8217   }
8218 }
8219 
8220 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8221     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8222     unsigned Depth) const {
8223   switch (Op.getOpcode()) {
8224   default:
8225     break;
8226   case RISCVISD::SELECT_CC: {
8227     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8228     if (Tmp == 1) return 1;  // Early out.
8229     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8230     return std::min(Tmp, Tmp2);
8231   }
8232   case RISCVISD::SLLW:
8233   case RISCVISD::SRAW:
8234   case RISCVISD::SRLW:
8235   case RISCVISD::DIVW:
8236   case RISCVISD::DIVUW:
8237   case RISCVISD::REMUW:
8238   case RISCVISD::ROLW:
8239   case RISCVISD::RORW:
8240   case RISCVISD::GREVW:
8241   case RISCVISD::GORCW:
8242   case RISCVISD::FSLW:
8243   case RISCVISD::FSRW:
8244   case RISCVISD::SHFLW:
8245   case RISCVISD::UNSHFLW:
8246   case RISCVISD::BCOMPRESSW:
8247   case RISCVISD::BDECOMPRESSW:
8248   case RISCVISD::BFPW:
8249   case RISCVISD::FCVT_W_RV64:
8250   case RISCVISD::FCVT_WU_RV64:
8251   case RISCVISD::STRICT_FCVT_W_RV64:
8252   case RISCVISD::STRICT_FCVT_WU_RV64:
8253     // TODO: As the result is sign-extended, this is conservatively correct. A
8254     // more precise answer could be calculated for SRAW depending on known
8255     // bits in the shift amount.
8256     return 33;
8257   case RISCVISD::SHFL:
8258   case RISCVISD::UNSHFL: {
8259     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8260     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8261     // will stay within the upper 32 bits. If there were more than 32 sign bits
8262     // before there will be at least 33 sign bits after.
8263     if (Op.getValueType() == MVT::i64 &&
8264         isa<ConstantSDNode>(Op.getOperand(1)) &&
8265         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8266       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8267       if (Tmp > 32)
8268         return 33;
8269     }
8270     break;
8271   }
8272   case RISCVISD::VMV_X_S:
8273     // The number of sign bits of the scalar result is computed by obtaining the
8274     // element type of the input vector operand, subtracting its width from the
8275     // XLEN, and then adding one (sign bit within the element type). If the
8276     // element type is wider than XLen, the least-significant XLEN bits are
8277     // taken.
8278     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
8279       return 1;
8280     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
8281   }
8282 
8283   return 1;
8284 }
8285 
8286 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8287                                                   MachineBasicBlock *BB) {
8288   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8289 
8290   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8291   // Should the count have wrapped while it was being read, we need to try
8292   // again.
8293   // ...
8294   // read:
8295   // rdcycleh x3 # load high word of cycle
8296   // rdcycle  x2 # load low word of cycle
8297   // rdcycleh x4 # load high word of cycle
8298   // bne x3, x4, read # check if high word reads match, otherwise try again
8299   // ...
8300 
8301   MachineFunction &MF = *BB->getParent();
8302   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8303   MachineFunction::iterator It = ++BB->getIterator();
8304 
8305   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8306   MF.insert(It, LoopMBB);
8307 
8308   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8309   MF.insert(It, DoneMBB);
8310 
8311   // Transfer the remainder of BB and its successor edges to DoneMBB.
8312   DoneMBB->splice(DoneMBB->begin(), BB,
8313                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8314   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8315 
8316   BB->addSuccessor(LoopMBB);
8317 
8318   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8319   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8320   Register LoReg = MI.getOperand(0).getReg();
8321   Register HiReg = MI.getOperand(1).getReg();
8322   DebugLoc DL = MI.getDebugLoc();
8323 
8324   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8325   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8326       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8327       .addReg(RISCV::X0);
8328   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8329       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8330       .addReg(RISCV::X0);
8331   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8332       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8333       .addReg(RISCV::X0);
8334 
8335   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8336       .addReg(HiReg)
8337       .addReg(ReadAgainReg)
8338       .addMBB(LoopMBB);
8339 
8340   LoopMBB->addSuccessor(LoopMBB);
8341   LoopMBB->addSuccessor(DoneMBB);
8342 
8343   MI.eraseFromParent();
8344 
8345   return DoneMBB;
8346 }
8347 
8348 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8349                                              MachineBasicBlock *BB) {
8350   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8351 
8352   MachineFunction &MF = *BB->getParent();
8353   DebugLoc DL = MI.getDebugLoc();
8354   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8355   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8356   Register LoReg = MI.getOperand(0).getReg();
8357   Register HiReg = MI.getOperand(1).getReg();
8358   Register SrcReg = MI.getOperand(2).getReg();
8359   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8360   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8361 
8362   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8363                           RI);
8364   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8365   MachineMemOperand *MMOLo =
8366       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8367   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8368       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8369   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8370       .addFrameIndex(FI)
8371       .addImm(0)
8372       .addMemOperand(MMOLo);
8373   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8374       .addFrameIndex(FI)
8375       .addImm(4)
8376       .addMemOperand(MMOHi);
8377   MI.eraseFromParent(); // The pseudo instruction is gone now.
8378   return BB;
8379 }
8380 
8381 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8382                                                  MachineBasicBlock *BB) {
8383   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8384          "Unexpected instruction");
8385 
8386   MachineFunction &MF = *BB->getParent();
8387   DebugLoc DL = MI.getDebugLoc();
8388   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8389   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8390   Register DstReg = MI.getOperand(0).getReg();
8391   Register LoReg = MI.getOperand(1).getReg();
8392   Register HiReg = MI.getOperand(2).getReg();
8393   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8394   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8395 
8396   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8397   MachineMemOperand *MMOLo =
8398       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8399   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8400       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8401   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8402       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8403       .addFrameIndex(FI)
8404       .addImm(0)
8405       .addMemOperand(MMOLo);
8406   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8407       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8408       .addFrameIndex(FI)
8409       .addImm(4)
8410       .addMemOperand(MMOHi);
8411   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8412   MI.eraseFromParent(); // The pseudo instruction is gone now.
8413   return BB;
8414 }
8415 
8416 static bool isSelectPseudo(MachineInstr &MI) {
8417   switch (MI.getOpcode()) {
8418   default:
8419     return false;
8420   case RISCV::Select_GPR_Using_CC_GPR:
8421   case RISCV::Select_FPR16_Using_CC_GPR:
8422   case RISCV::Select_FPR32_Using_CC_GPR:
8423   case RISCV::Select_FPR64_Using_CC_GPR:
8424     return true;
8425   }
8426 }
8427 
8428 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8429                                         unsigned RelOpcode, unsigned EqOpcode,
8430                                         const RISCVSubtarget &Subtarget) {
8431   DebugLoc DL = MI.getDebugLoc();
8432   Register DstReg = MI.getOperand(0).getReg();
8433   Register Src1Reg = MI.getOperand(1).getReg();
8434   Register Src2Reg = MI.getOperand(2).getReg();
8435   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8436   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8437   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8438 
8439   // Save the current FFLAGS.
8440   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8441 
8442   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8443                  .addReg(Src1Reg)
8444                  .addReg(Src2Reg);
8445   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8446     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8447 
8448   // Restore the FFLAGS.
8449   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8450       .addReg(SavedFFlags, RegState::Kill);
8451 
8452   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8453   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8454                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8455                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8456   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8457     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8458 
8459   // Erase the pseudoinstruction.
8460   MI.eraseFromParent();
8461   return BB;
8462 }
8463 
8464 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8465                                            MachineBasicBlock *BB,
8466                                            const RISCVSubtarget &Subtarget) {
8467   // To "insert" Select_* instructions, we actually have to insert the triangle
8468   // control-flow pattern.  The incoming instructions know the destination vreg
8469   // to set, the condition code register to branch on, the true/false values to
8470   // select between, and the condcode to use to select the appropriate branch.
8471   //
8472   // We produce the following control flow:
8473   //     HeadMBB
8474   //     |  \
8475   //     |  IfFalseMBB
8476   //     | /
8477   //    TailMBB
8478   //
8479   // When we find a sequence of selects we attempt to optimize their emission
8480   // by sharing the control flow. Currently we only handle cases where we have
8481   // multiple selects with the exact same condition (same LHS, RHS and CC).
8482   // The selects may be interleaved with other instructions if the other
8483   // instructions meet some requirements we deem safe:
8484   // - They are debug instructions. Otherwise,
8485   // - They do not have side-effects, do not access memory and their inputs do
8486   //   not depend on the results of the select pseudo-instructions.
8487   // The TrueV/FalseV operands of the selects cannot depend on the result of
8488   // previous selects in the sequence.
8489   // These conditions could be further relaxed. See the X86 target for a
8490   // related approach and more information.
8491   Register LHS = MI.getOperand(1).getReg();
8492   Register RHS = MI.getOperand(2).getReg();
8493   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8494 
8495   SmallVector<MachineInstr *, 4> SelectDebugValues;
8496   SmallSet<Register, 4> SelectDests;
8497   SelectDests.insert(MI.getOperand(0).getReg());
8498 
8499   MachineInstr *LastSelectPseudo = &MI;
8500 
8501   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8502        SequenceMBBI != E; ++SequenceMBBI) {
8503     if (SequenceMBBI->isDebugInstr())
8504       continue;
8505     else if (isSelectPseudo(*SequenceMBBI)) {
8506       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8507           SequenceMBBI->getOperand(2).getReg() != RHS ||
8508           SequenceMBBI->getOperand(3).getImm() != CC ||
8509           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8510           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8511         break;
8512       LastSelectPseudo = &*SequenceMBBI;
8513       SequenceMBBI->collectDebugValues(SelectDebugValues);
8514       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8515     } else {
8516       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8517           SequenceMBBI->mayLoadOrStore())
8518         break;
8519       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8520             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8521           }))
8522         break;
8523     }
8524   }
8525 
8526   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8527   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8528   DebugLoc DL = MI.getDebugLoc();
8529   MachineFunction::iterator I = ++BB->getIterator();
8530 
8531   MachineBasicBlock *HeadMBB = BB;
8532   MachineFunction *F = BB->getParent();
8533   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8534   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8535 
8536   F->insert(I, IfFalseMBB);
8537   F->insert(I, TailMBB);
8538 
8539   // Transfer debug instructions associated with the selects to TailMBB.
8540   for (MachineInstr *DebugInstr : SelectDebugValues) {
8541     TailMBB->push_back(DebugInstr->removeFromParent());
8542   }
8543 
8544   // Move all instructions after the sequence to TailMBB.
8545   TailMBB->splice(TailMBB->end(), HeadMBB,
8546                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8547   // Update machine-CFG edges by transferring all successors of the current
8548   // block to the new block which will contain the Phi nodes for the selects.
8549   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8550   // Set the successors for HeadMBB.
8551   HeadMBB->addSuccessor(IfFalseMBB);
8552   HeadMBB->addSuccessor(TailMBB);
8553 
8554   // Insert appropriate branch.
8555   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8556     .addReg(LHS)
8557     .addReg(RHS)
8558     .addMBB(TailMBB);
8559 
8560   // IfFalseMBB just falls through to TailMBB.
8561   IfFalseMBB->addSuccessor(TailMBB);
8562 
8563   // Create PHIs for all of the select pseudo-instructions.
8564   auto SelectMBBI = MI.getIterator();
8565   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8566   auto InsertionPoint = TailMBB->begin();
8567   while (SelectMBBI != SelectEnd) {
8568     auto Next = std::next(SelectMBBI);
8569     if (isSelectPseudo(*SelectMBBI)) {
8570       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8571       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8572               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8573           .addReg(SelectMBBI->getOperand(4).getReg())
8574           .addMBB(HeadMBB)
8575           .addReg(SelectMBBI->getOperand(5).getReg())
8576           .addMBB(IfFalseMBB);
8577       SelectMBBI->eraseFromParent();
8578     }
8579     SelectMBBI = Next;
8580   }
8581 
8582   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8583   return TailMBB;
8584 }
8585 
8586 MachineBasicBlock *
8587 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8588                                                  MachineBasicBlock *BB) const {
8589   switch (MI.getOpcode()) {
8590   default:
8591     llvm_unreachable("Unexpected instr type to insert");
8592   case RISCV::ReadCycleWide:
8593     assert(!Subtarget.is64Bit() &&
8594            "ReadCycleWrite is only to be used on riscv32");
8595     return emitReadCycleWidePseudo(MI, BB);
8596   case RISCV::Select_GPR_Using_CC_GPR:
8597   case RISCV::Select_FPR16_Using_CC_GPR:
8598   case RISCV::Select_FPR32_Using_CC_GPR:
8599   case RISCV::Select_FPR64_Using_CC_GPR:
8600     return emitSelectPseudo(MI, BB, Subtarget);
8601   case RISCV::BuildPairF64Pseudo:
8602     return emitBuildPairF64Pseudo(MI, BB);
8603   case RISCV::SplitF64Pseudo:
8604     return emitSplitF64Pseudo(MI, BB);
8605   case RISCV::PseudoQuietFLE_H:
8606     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8607   case RISCV::PseudoQuietFLT_H:
8608     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8609   case RISCV::PseudoQuietFLE_S:
8610     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8611   case RISCV::PseudoQuietFLT_S:
8612     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8613   case RISCV::PseudoQuietFLE_D:
8614     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8615   case RISCV::PseudoQuietFLT_D:
8616     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8617   }
8618 }
8619 
8620 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8621                                                         SDNode *Node) const {
8622   // Add FRM dependency to any instructions with dynamic rounding mode.
8623   unsigned Opc = MI.getOpcode();
8624   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8625   if (Idx < 0)
8626     return;
8627   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8628     return;
8629   // If the instruction already reads FRM, don't add another read.
8630   if (MI.readsRegister(RISCV::FRM))
8631     return;
8632   MI.addOperand(
8633       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8634 }
8635 
8636 // Calling Convention Implementation.
8637 // The expectations for frontend ABI lowering vary from target to target.
8638 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8639 // details, but this is a longer term goal. For now, we simply try to keep the
8640 // role of the frontend as simple and well-defined as possible. The rules can
8641 // be summarised as:
8642 // * Never split up large scalar arguments. We handle them here.
8643 // * If a hardfloat calling convention is being used, and the struct may be
8644 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8645 // available, then pass as two separate arguments. If either the GPRs or FPRs
8646 // are exhausted, then pass according to the rule below.
8647 // * If a struct could never be passed in registers or directly in a stack
8648 // slot (as it is larger than 2*XLEN and the floating point rules don't
8649 // apply), then pass it using a pointer with the byval attribute.
8650 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8651 // word-sized array or a 2*XLEN scalar (depending on alignment).
8652 // * The frontend can determine whether a struct is returned by reference or
8653 // not based on its size and fields. If it will be returned by reference, the
8654 // frontend must modify the prototype so a pointer with the sret annotation is
8655 // passed as the first argument. This is not necessary for large scalar
8656 // returns.
8657 // * Struct return values and varargs should be coerced to structs containing
8658 // register-size fields in the same situations they would be for fixed
8659 // arguments.
8660 
8661 static const MCPhysReg ArgGPRs[] = {
8662   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8663   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8664 };
8665 static const MCPhysReg ArgFPR16s[] = {
8666   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8667   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8668 };
8669 static const MCPhysReg ArgFPR32s[] = {
8670   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8671   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8672 };
8673 static const MCPhysReg ArgFPR64s[] = {
8674   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8675   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8676 };
8677 // This is an interim calling convention and it may be changed in the future.
8678 static const MCPhysReg ArgVRs[] = {
8679     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8680     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8681     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8682 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8683                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8684                                      RISCV::V20M2, RISCV::V22M2};
8685 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8686                                      RISCV::V20M4};
8687 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8688 
8689 // Pass a 2*XLEN argument that has been split into two XLEN values through
8690 // registers or the stack as necessary.
8691 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8692                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8693                                 MVT ValVT2, MVT LocVT2,
8694                                 ISD::ArgFlagsTy ArgFlags2) {
8695   unsigned XLenInBytes = XLen / 8;
8696   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8697     // At least one half can be passed via register.
8698     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8699                                      VA1.getLocVT(), CCValAssign::Full));
8700   } else {
8701     // Both halves must be passed on the stack, with proper alignment.
8702     Align StackAlign =
8703         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8704     State.addLoc(
8705         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8706                             State.AllocateStack(XLenInBytes, StackAlign),
8707                             VA1.getLocVT(), CCValAssign::Full));
8708     State.addLoc(CCValAssign::getMem(
8709         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8710         LocVT2, CCValAssign::Full));
8711     return false;
8712   }
8713 
8714   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8715     // The second half can also be passed via register.
8716     State.addLoc(
8717         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8718   } else {
8719     // The second half is passed via the stack, without additional alignment.
8720     State.addLoc(CCValAssign::getMem(
8721         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8722         LocVT2, CCValAssign::Full));
8723   }
8724 
8725   return false;
8726 }
8727 
8728 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8729                                Optional<unsigned> FirstMaskArgument,
8730                                CCState &State, const RISCVTargetLowering &TLI) {
8731   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8732   if (RC == &RISCV::VRRegClass) {
8733     // Assign the first mask argument to V0.
8734     // This is an interim calling convention and it may be changed in the
8735     // future.
8736     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8737       return State.AllocateReg(RISCV::V0);
8738     return State.AllocateReg(ArgVRs);
8739   }
8740   if (RC == &RISCV::VRM2RegClass)
8741     return State.AllocateReg(ArgVRM2s);
8742   if (RC == &RISCV::VRM4RegClass)
8743     return State.AllocateReg(ArgVRM4s);
8744   if (RC == &RISCV::VRM8RegClass)
8745     return State.AllocateReg(ArgVRM8s);
8746   llvm_unreachable("Unhandled register class for ValueType");
8747 }
8748 
8749 // Implements the RISC-V calling convention. Returns true upon failure.
8750 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8751                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8752                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8753                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8754                      Optional<unsigned> FirstMaskArgument) {
8755   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8756   assert(XLen == 32 || XLen == 64);
8757   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8758 
8759   // Any return value split in to more than two values can't be returned
8760   // directly. Vectors are returned via the available vector registers.
8761   if (!LocVT.isVector() && IsRet && ValNo > 1)
8762     return true;
8763 
8764   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8765   // variadic argument, or if no F16/F32 argument registers are available.
8766   bool UseGPRForF16_F32 = true;
8767   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8768   // variadic argument, or if no F64 argument registers are available.
8769   bool UseGPRForF64 = true;
8770 
8771   switch (ABI) {
8772   default:
8773     llvm_unreachable("Unexpected ABI");
8774   case RISCVABI::ABI_ILP32:
8775   case RISCVABI::ABI_LP64:
8776     break;
8777   case RISCVABI::ABI_ILP32F:
8778   case RISCVABI::ABI_LP64F:
8779     UseGPRForF16_F32 = !IsFixed;
8780     break;
8781   case RISCVABI::ABI_ILP32D:
8782   case RISCVABI::ABI_LP64D:
8783     UseGPRForF16_F32 = !IsFixed;
8784     UseGPRForF64 = !IsFixed;
8785     break;
8786   }
8787 
8788   // FPR16, FPR32, and FPR64 alias each other.
8789   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8790     UseGPRForF16_F32 = true;
8791     UseGPRForF64 = true;
8792   }
8793 
8794   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8795   // similar local variables rather than directly checking against the target
8796   // ABI.
8797 
8798   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8799     LocVT = XLenVT;
8800     LocInfo = CCValAssign::BCvt;
8801   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8802     LocVT = MVT::i64;
8803     LocInfo = CCValAssign::BCvt;
8804   }
8805 
8806   // If this is a variadic argument, the RISC-V calling convention requires
8807   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8808   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8809   // be used regardless of whether the original argument was split during
8810   // legalisation or not. The argument will not be passed by registers if the
8811   // original type is larger than 2*XLEN, so the register alignment rule does
8812   // not apply.
8813   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8814   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8815       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8816     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8817     // Skip 'odd' register if necessary.
8818     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8819       State.AllocateReg(ArgGPRs);
8820   }
8821 
8822   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8823   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8824       State.getPendingArgFlags();
8825 
8826   assert(PendingLocs.size() == PendingArgFlags.size() &&
8827          "PendingLocs and PendingArgFlags out of sync");
8828 
8829   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8830   // registers are exhausted.
8831   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8832     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8833            "Can't lower f64 if it is split");
8834     // Depending on available argument GPRS, f64 may be passed in a pair of
8835     // GPRs, split between a GPR and the stack, or passed completely on the
8836     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8837     // cases.
8838     Register Reg = State.AllocateReg(ArgGPRs);
8839     LocVT = MVT::i32;
8840     if (!Reg) {
8841       unsigned StackOffset = State.AllocateStack(8, Align(8));
8842       State.addLoc(
8843           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8844       return false;
8845     }
8846     if (!State.AllocateReg(ArgGPRs))
8847       State.AllocateStack(4, Align(4));
8848     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8849     return false;
8850   }
8851 
8852   // Fixed-length vectors are located in the corresponding scalable-vector
8853   // container types.
8854   if (ValVT.isFixedLengthVector())
8855     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8856 
8857   // Split arguments might be passed indirectly, so keep track of the pending
8858   // values. Split vectors are passed via a mix of registers and indirectly, so
8859   // treat them as we would any other argument.
8860   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8861     LocVT = XLenVT;
8862     LocInfo = CCValAssign::Indirect;
8863     PendingLocs.push_back(
8864         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8865     PendingArgFlags.push_back(ArgFlags);
8866     if (!ArgFlags.isSplitEnd()) {
8867       return false;
8868     }
8869   }
8870 
8871   // If the split argument only had two elements, it should be passed directly
8872   // in registers or on the stack.
8873   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8874       PendingLocs.size() <= 2) {
8875     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8876     // Apply the normal calling convention rules to the first half of the
8877     // split argument.
8878     CCValAssign VA = PendingLocs[0];
8879     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8880     PendingLocs.clear();
8881     PendingArgFlags.clear();
8882     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8883                                ArgFlags);
8884   }
8885 
8886   // Allocate to a register if possible, or else a stack slot.
8887   Register Reg;
8888   unsigned StoreSizeBytes = XLen / 8;
8889   Align StackAlign = Align(XLen / 8);
8890 
8891   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8892     Reg = State.AllocateReg(ArgFPR16s);
8893   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8894     Reg = State.AllocateReg(ArgFPR32s);
8895   else if (ValVT == MVT::f64 && !UseGPRForF64)
8896     Reg = State.AllocateReg(ArgFPR64s);
8897   else if (ValVT.isVector()) {
8898     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8899     if (!Reg) {
8900       // For return values, the vector must be passed fully via registers or
8901       // via the stack.
8902       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8903       // but we're using all of them.
8904       if (IsRet)
8905         return true;
8906       // Try using a GPR to pass the address
8907       if ((Reg = State.AllocateReg(ArgGPRs))) {
8908         LocVT = XLenVT;
8909         LocInfo = CCValAssign::Indirect;
8910       } else if (ValVT.isScalableVector()) {
8911         LocVT = XLenVT;
8912         LocInfo = CCValAssign::Indirect;
8913       } else {
8914         // Pass fixed-length vectors on the stack.
8915         LocVT = ValVT;
8916         StoreSizeBytes = ValVT.getStoreSize();
8917         // Align vectors to their element sizes, being careful for vXi1
8918         // vectors.
8919         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8920       }
8921     }
8922   } else {
8923     Reg = State.AllocateReg(ArgGPRs);
8924   }
8925 
8926   unsigned StackOffset =
8927       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8928 
8929   // If we reach this point and PendingLocs is non-empty, we must be at the
8930   // end of a split argument that must be passed indirectly.
8931   if (!PendingLocs.empty()) {
8932     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8933     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8934 
8935     for (auto &It : PendingLocs) {
8936       if (Reg)
8937         It.convertToReg(Reg);
8938       else
8939         It.convertToMem(StackOffset);
8940       State.addLoc(It);
8941     }
8942     PendingLocs.clear();
8943     PendingArgFlags.clear();
8944     return false;
8945   }
8946 
8947   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8948           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8949          "Expected an XLenVT or vector types at this stage");
8950 
8951   if (Reg) {
8952     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8953     return false;
8954   }
8955 
8956   // When a floating-point value is passed on the stack, no bit-conversion is
8957   // needed.
8958   if (ValVT.isFloatingPoint()) {
8959     LocVT = ValVT;
8960     LocInfo = CCValAssign::Full;
8961   }
8962   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8963   return false;
8964 }
8965 
8966 template <typename ArgTy>
8967 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8968   for (const auto &ArgIdx : enumerate(Args)) {
8969     MVT ArgVT = ArgIdx.value().VT;
8970     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8971       return ArgIdx.index();
8972   }
8973   return None;
8974 }
8975 
8976 void RISCVTargetLowering::analyzeInputArgs(
8977     MachineFunction &MF, CCState &CCInfo,
8978     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8979     RISCVCCAssignFn Fn) const {
8980   unsigned NumArgs = Ins.size();
8981   FunctionType *FType = MF.getFunction().getFunctionType();
8982 
8983   Optional<unsigned> FirstMaskArgument;
8984   if (Subtarget.hasVInstructions())
8985     FirstMaskArgument = preAssignMask(Ins);
8986 
8987   for (unsigned i = 0; i != NumArgs; ++i) {
8988     MVT ArgVT = Ins[i].VT;
8989     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8990 
8991     Type *ArgTy = nullptr;
8992     if (IsRet)
8993       ArgTy = FType->getReturnType();
8994     else if (Ins[i].isOrigArg())
8995       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8996 
8997     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8998     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8999            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9000            FirstMaskArgument)) {
9001       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9002                         << EVT(ArgVT).getEVTString() << '\n');
9003       llvm_unreachable(nullptr);
9004     }
9005   }
9006 }
9007 
9008 void RISCVTargetLowering::analyzeOutputArgs(
9009     MachineFunction &MF, CCState &CCInfo,
9010     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9011     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9012   unsigned NumArgs = Outs.size();
9013 
9014   Optional<unsigned> FirstMaskArgument;
9015   if (Subtarget.hasVInstructions())
9016     FirstMaskArgument = preAssignMask(Outs);
9017 
9018   for (unsigned i = 0; i != NumArgs; i++) {
9019     MVT ArgVT = Outs[i].VT;
9020     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9021     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9022 
9023     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9024     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9025            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9026            FirstMaskArgument)) {
9027       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9028                         << EVT(ArgVT).getEVTString() << "\n");
9029       llvm_unreachable(nullptr);
9030     }
9031   }
9032 }
9033 
9034 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9035 // values.
9036 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9037                                    const CCValAssign &VA, const SDLoc &DL,
9038                                    const RISCVSubtarget &Subtarget) {
9039   switch (VA.getLocInfo()) {
9040   default:
9041     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9042   case CCValAssign::Full:
9043     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9044       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9045     break;
9046   case CCValAssign::BCvt:
9047     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9048       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9049     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9050       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9051     else
9052       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9053     break;
9054   }
9055   return Val;
9056 }
9057 
9058 // The caller is responsible for loading the full value if the argument is
9059 // passed with CCValAssign::Indirect.
9060 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9061                                 const CCValAssign &VA, const SDLoc &DL,
9062                                 const RISCVTargetLowering &TLI) {
9063   MachineFunction &MF = DAG.getMachineFunction();
9064   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9065   EVT LocVT = VA.getLocVT();
9066   SDValue Val;
9067   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9068   Register VReg = RegInfo.createVirtualRegister(RC);
9069   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9070   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9071 
9072   if (VA.getLocInfo() == CCValAssign::Indirect)
9073     return Val;
9074 
9075   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9076 }
9077 
9078 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9079                                    const CCValAssign &VA, const SDLoc &DL,
9080                                    const RISCVSubtarget &Subtarget) {
9081   EVT LocVT = VA.getLocVT();
9082 
9083   switch (VA.getLocInfo()) {
9084   default:
9085     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9086   case CCValAssign::Full:
9087     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9088       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9089     break;
9090   case CCValAssign::BCvt:
9091     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9092       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9093     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9094       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9095     else
9096       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9097     break;
9098   }
9099   return Val;
9100 }
9101 
9102 // The caller is responsible for loading the full value if the argument is
9103 // passed with CCValAssign::Indirect.
9104 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9105                                 const CCValAssign &VA, const SDLoc &DL) {
9106   MachineFunction &MF = DAG.getMachineFunction();
9107   MachineFrameInfo &MFI = MF.getFrameInfo();
9108   EVT LocVT = VA.getLocVT();
9109   EVT ValVT = VA.getValVT();
9110   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9111   if (ValVT.isScalableVector()) {
9112     // When the value is a scalable vector, we save the pointer which points to
9113     // the scalable vector value in the stack. The ValVT will be the pointer
9114     // type, instead of the scalable vector type.
9115     ValVT = LocVT;
9116   }
9117   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9118                                  /*IsImmutable=*/true);
9119   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9120   SDValue Val;
9121 
9122   ISD::LoadExtType ExtType;
9123   switch (VA.getLocInfo()) {
9124   default:
9125     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9126   case CCValAssign::Full:
9127   case CCValAssign::Indirect:
9128   case CCValAssign::BCvt:
9129     ExtType = ISD::NON_EXTLOAD;
9130     break;
9131   }
9132   Val = DAG.getExtLoad(
9133       ExtType, DL, LocVT, Chain, FIN,
9134       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9135   return Val;
9136 }
9137 
9138 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9139                                        const CCValAssign &VA, const SDLoc &DL) {
9140   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9141          "Unexpected VA");
9142   MachineFunction &MF = DAG.getMachineFunction();
9143   MachineFrameInfo &MFI = MF.getFrameInfo();
9144   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9145 
9146   if (VA.isMemLoc()) {
9147     // f64 is passed on the stack.
9148     int FI =
9149         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9150     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9151     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9152                        MachinePointerInfo::getFixedStack(MF, FI));
9153   }
9154 
9155   assert(VA.isRegLoc() && "Expected register VA assignment");
9156 
9157   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9158   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9159   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9160   SDValue Hi;
9161   if (VA.getLocReg() == RISCV::X17) {
9162     // Second half of f64 is passed on the stack.
9163     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9164     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9165     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9166                      MachinePointerInfo::getFixedStack(MF, FI));
9167   } else {
9168     // Second half of f64 is passed in another GPR.
9169     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9170     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9171     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9172   }
9173   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9174 }
9175 
9176 // FastCC has less than 1% performance improvement for some particular
9177 // benchmark. But theoretically, it may has benenfit for some cases.
9178 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9179                             unsigned ValNo, MVT ValVT, MVT LocVT,
9180                             CCValAssign::LocInfo LocInfo,
9181                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9182                             bool IsFixed, bool IsRet, Type *OrigTy,
9183                             const RISCVTargetLowering &TLI,
9184                             Optional<unsigned> FirstMaskArgument) {
9185 
9186   // X5 and X6 might be used for save-restore libcall.
9187   static const MCPhysReg GPRList[] = {
9188       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9189       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9190       RISCV::X29, RISCV::X30, RISCV::X31};
9191 
9192   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9193     if (unsigned Reg = State.AllocateReg(GPRList)) {
9194       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9195       return false;
9196     }
9197   }
9198 
9199   if (LocVT == MVT::f16) {
9200     static const MCPhysReg FPR16List[] = {
9201         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9202         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9203         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9204         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9205     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9206       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9207       return false;
9208     }
9209   }
9210 
9211   if (LocVT == MVT::f32) {
9212     static const MCPhysReg FPR32List[] = {
9213         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9214         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9215         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9216         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9217     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9218       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9219       return false;
9220     }
9221   }
9222 
9223   if (LocVT == MVT::f64) {
9224     static const MCPhysReg FPR64List[] = {
9225         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9226         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9227         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9228         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9229     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9230       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9231       return false;
9232     }
9233   }
9234 
9235   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9236     unsigned Offset4 = State.AllocateStack(4, Align(4));
9237     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9238     return false;
9239   }
9240 
9241   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9242     unsigned Offset5 = State.AllocateStack(8, Align(8));
9243     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9244     return false;
9245   }
9246 
9247   if (LocVT.isVector()) {
9248     if (unsigned Reg =
9249             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9250       // Fixed-length vectors are located in the corresponding scalable-vector
9251       // container types.
9252       if (ValVT.isFixedLengthVector())
9253         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9254       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9255     } else {
9256       // Try and pass the address via a "fast" GPR.
9257       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9258         LocInfo = CCValAssign::Indirect;
9259         LocVT = TLI.getSubtarget().getXLenVT();
9260         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9261       } else if (ValVT.isFixedLengthVector()) {
9262         auto StackAlign =
9263             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9264         unsigned StackOffset =
9265             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9266         State.addLoc(
9267             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9268       } else {
9269         // Can't pass scalable vectors on the stack.
9270         return true;
9271       }
9272     }
9273 
9274     return false;
9275   }
9276 
9277   return true; // CC didn't match.
9278 }
9279 
9280 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9281                          CCValAssign::LocInfo LocInfo,
9282                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9283 
9284   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9285     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9286     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9287     static const MCPhysReg GPRList[] = {
9288         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9289         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9290     if (unsigned Reg = State.AllocateReg(GPRList)) {
9291       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9292       return false;
9293     }
9294   }
9295 
9296   if (LocVT == MVT::f32) {
9297     // Pass in STG registers: F1, ..., F6
9298     //                        fs0 ... fs5
9299     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9300                                           RISCV::F18_F, RISCV::F19_F,
9301                                           RISCV::F20_F, RISCV::F21_F};
9302     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9303       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9304       return false;
9305     }
9306   }
9307 
9308   if (LocVT == MVT::f64) {
9309     // Pass in STG registers: D1, ..., D6
9310     //                        fs6 ... fs11
9311     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9312                                           RISCV::F24_D, RISCV::F25_D,
9313                                           RISCV::F26_D, RISCV::F27_D};
9314     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9315       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9316       return false;
9317     }
9318   }
9319 
9320   report_fatal_error("No registers left in GHC calling convention");
9321   return true;
9322 }
9323 
9324 // Transform physical registers into virtual registers.
9325 SDValue RISCVTargetLowering::LowerFormalArguments(
9326     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9327     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9328     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9329 
9330   MachineFunction &MF = DAG.getMachineFunction();
9331 
9332   switch (CallConv) {
9333   default:
9334     report_fatal_error("Unsupported calling convention");
9335   case CallingConv::C:
9336   case CallingConv::Fast:
9337     break;
9338   case CallingConv::GHC:
9339     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9340         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9341       report_fatal_error(
9342         "GHC calling convention requires the F and D instruction set extensions");
9343   }
9344 
9345   const Function &Func = MF.getFunction();
9346   if (Func.hasFnAttribute("interrupt")) {
9347     if (!Func.arg_empty())
9348       report_fatal_error(
9349         "Functions with the interrupt attribute cannot have arguments!");
9350 
9351     StringRef Kind =
9352       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9353 
9354     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9355       report_fatal_error(
9356         "Function interrupt attribute argument not supported!");
9357   }
9358 
9359   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9360   MVT XLenVT = Subtarget.getXLenVT();
9361   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9362   // Used with vargs to acumulate store chains.
9363   std::vector<SDValue> OutChains;
9364 
9365   // Assign locations to all of the incoming arguments.
9366   SmallVector<CCValAssign, 16> ArgLocs;
9367   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9368 
9369   if (CallConv == CallingConv::GHC)
9370     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9371   else
9372     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9373                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9374                                                    : CC_RISCV);
9375 
9376   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9377     CCValAssign &VA = ArgLocs[i];
9378     SDValue ArgValue;
9379     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9380     // case.
9381     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9382       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9383     else if (VA.isRegLoc())
9384       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9385     else
9386       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9387 
9388     if (VA.getLocInfo() == CCValAssign::Indirect) {
9389       // If the original argument was split and passed by reference (e.g. i128
9390       // on RV32), we need to load all parts of it here (using the same
9391       // address). Vectors may be partly split to registers and partly to the
9392       // stack, in which case the base address is partly offset and subsequent
9393       // stores are relative to that.
9394       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9395                                    MachinePointerInfo()));
9396       unsigned ArgIndex = Ins[i].OrigArgIndex;
9397       unsigned ArgPartOffset = Ins[i].PartOffset;
9398       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9399       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9400         CCValAssign &PartVA = ArgLocs[i + 1];
9401         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9402         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9403         if (PartVA.getValVT().isScalableVector())
9404           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9405         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9406         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9407                                      MachinePointerInfo()));
9408         ++i;
9409       }
9410       continue;
9411     }
9412     InVals.push_back(ArgValue);
9413   }
9414 
9415   if (IsVarArg) {
9416     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9417     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9418     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9419     MachineFrameInfo &MFI = MF.getFrameInfo();
9420     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9421     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9422 
9423     // Offset of the first variable argument from stack pointer, and size of
9424     // the vararg save area. For now, the varargs save area is either zero or
9425     // large enough to hold a0-a7.
9426     int VaArgOffset, VarArgsSaveSize;
9427 
9428     // If all registers are allocated, then all varargs must be passed on the
9429     // stack and we don't need to save any argregs.
9430     if (ArgRegs.size() == Idx) {
9431       VaArgOffset = CCInfo.getNextStackOffset();
9432       VarArgsSaveSize = 0;
9433     } else {
9434       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9435       VaArgOffset = -VarArgsSaveSize;
9436     }
9437 
9438     // Record the frame index of the first variable argument
9439     // which is a value necessary to VASTART.
9440     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9441     RVFI->setVarArgsFrameIndex(FI);
9442 
9443     // If saving an odd number of registers then create an extra stack slot to
9444     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9445     // offsets to even-numbered registered remain 2*XLEN-aligned.
9446     if (Idx % 2) {
9447       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9448       VarArgsSaveSize += XLenInBytes;
9449     }
9450 
9451     // Copy the integer registers that may have been used for passing varargs
9452     // to the vararg save area.
9453     for (unsigned I = Idx; I < ArgRegs.size();
9454          ++I, VaArgOffset += XLenInBytes) {
9455       const Register Reg = RegInfo.createVirtualRegister(RC);
9456       RegInfo.addLiveIn(ArgRegs[I], Reg);
9457       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9458       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9459       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9460       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9461                                    MachinePointerInfo::getFixedStack(MF, FI));
9462       cast<StoreSDNode>(Store.getNode())
9463           ->getMemOperand()
9464           ->setValue((Value *)nullptr);
9465       OutChains.push_back(Store);
9466     }
9467     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9468   }
9469 
9470   // All stores are grouped in one node to allow the matching between
9471   // the size of Ins and InVals. This only happens for vararg functions.
9472   if (!OutChains.empty()) {
9473     OutChains.push_back(Chain);
9474     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9475   }
9476 
9477   return Chain;
9478 }
9479 
9480 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9481 /// for tail call optimization.
9482 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9483 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9484     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9485     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9486 
9487   auto &Callee = CLI.Callee;
9488   auto CalleeCC = CLI.CallConv;
9489   auto &Outs = CLI.Outs;
9490   auto &Caller = MF.getFunction();
9491   auto CallerCC = Caller.getCallingConv();
9492 
9493   // Exception-handling functions need a special set of instructions to
9494   // indicate a return to the hardware. Tail-calling another function would
9495   // probably break this.
9496   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9497   // should be expanded as new function attributes are introduced.
9498   if (Caller.hasFnAttribute("interrupt"))
9499     return false;
9500 
9501   // Do not tail call opt if the stack is used to pass parameters.
9502   if (CCInfo.getNextStackOffset() != 0)
9503     return false;
9504 
9505   // Do not tail call opt if any parameters need to be passed indirectly.
9506   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9507   // passed indirectly. So the address of the value will be passed in a
9508   // register, or if not available, then the address is put on the stack. In
9509   // order to pass indirectly, space on the stack often needs to be allocated
9510   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9511   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9512   // are passed CCValAssign::Indirect.
9513   for (auto &VA : ArgLocs)
9514     if (VA.getLocInfo() == CCValAssign::Indirect)
9515       return false;
9516 
9517   // Do not tail call opt if either caller or callee uses struct return
9518   // semantics.
9519   auto IsCallerStructRet = Caller.hasStructRetAttr();
9520   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9521   if (IsCallerStructRet || IsCalleeStructRet)
9522     return false;
9523 
9524   // Externally-defined functions with weak linkage should not be
9525   // tail-called. The behaviour of branch instructions in this situation (as
9526   // used for tail calls) is implementation-defined, so we cannot rely on the
9527   // linker replacing the tail call with a return.
9528   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9529     const GlobalValue *GV = G->getGlobal();
9530     if (GV->hasExternalWeakLinkage())
9531       return false;
9532   }
9533 
9534   // The callee has to preserve all registers the caller needs to preserve.
9535   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9536   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9537   if (CalleeCC != CallerCC) {
9538     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9539     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9540       return false;
9541   }
9542 
9543   // Byval parameters hand the function a pointer directly into the stack area
9544   // we want to reuse during a tail call. Working around this *is* possible
9545   // but less efficient and uglier in LowerCall.
9546   for (auto &Arg : Outs)
9547     if (Arg.Flags.isByVal())
9548       return false;
9549 
9550   return true;
9551 }
9552 
9553 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9554   return DAG.getDataLayout().getPrefTypeAlign(
9555       VT.getTypeForEVT(*DAG.getContext()));
9556 }
9557 
9558 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9559 // and output parameter nodes.
9560 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9561                                        SmallVectorImpl<SDValue> &InVals) const {
9562   SelectionDAG &DAG = CLI.DAG;
9563   SDLoc &DL = CLI.DL;
9564   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9565   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9566   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9567   SDValue Chain = CLI.Chain;
9568   SDValue Callee = CLI.Callee;
9569   bool &IsTailCall = CLI.IsTailCall;
9570   CallingConv::ID CallConv = CLI.CallConv;
9571   bool IsVarArg = CLI.IsVarArg;
9572   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9573   MVT XLenVT = Subtarget.getXLenVT();
9574 
9575   MachineFunction &MF = DAG.getMachineFunction();
9576 
9577   // Analyze the operands of the call, assigning locations to each operand.
9578   SmallVector<CCValAssign, 16> ArgLocs;
9579   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9580 
9581   if (CallConv == CallingConv::GHC)
9582     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9583   else
9584     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9585                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9586                                                     : CC_RISCV);
9587 
9588   // Check if it's really possible to do a tail call.
9589   if (IsTailCall)
9590     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9591 
9592   if (IsTailCall)
9593     ++NumTailCalls;
9594   else if (CLI.CB && CLI.CB->isMustTailCall())
9595     report_fatal_error("failed to perform tail call elimination on a call "
9596                        "site marked musttail");
9597 
9598   // Get a count of how many bytes are to be pushed on the stack.
9599   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9600 
9601   // Create local copies for byval args
9602   SmallVector<SDValue, 8> ByValArgs;
9603   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9604     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9605     if (!Flags.isByVal())
9606       continue;
9607 
9608     SDValue Arg = OutVals[i];
9609     unsigned Size = Flags.getByValSize();
9610     Align Alignment = Flags.getNonZeroByValAlign();
9611 
9612     int FI =
9613         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9614     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9615     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9616 
9617     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9618                           /*IsVolatile=*/false,
9619                           /*AlwaysInline=*/false, IsTailCall,
9620                           MachinePointerInfo(), MachinePointerInfo());
9621     ByValArgs.push_back(FIPtr);
9622   }
9623 
9624   if (!IsTailCall)
9625     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9626 
9627   // Copy argument values to their designated locations.
9628   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9629   SmallVector<SDValue, 8> MemOpChains;
9630   SDValue StackPtr;
9631   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9632     CCValAssign &VA = ArgLocs[i];
9633     SDValue ArgValue = OutVals[i];
9634     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9635 
9636     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9637     bool IsF64OnRV32DSoftABI =
9638         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9639     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9640       SDValue SplitF64 = DAG.getNode(
9641           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9642       SDValue Lo = SplitF64.getValue(0);
9643       SDValue Hi = SplitF64.getValue(1);
9644 
9645       Register RegLo = VA.getLocReg();
9646       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9647 
9648       if (RegLo == RISCV::X17) {
9649         // Second half of f64 is passed on the stack.
9650         // Work out the address of the stack slot.
9651         if (!StackPtr.getNode())
9652           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9653         // Emit the store.
9654         MemOpChains.push_back(
9655             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9656       } else {
9657         // Second half of f64 is passed in another GPR.
9658         assert(RegLo < RISCV::X31 && "Invalid register pair");
9659         Register RegHigh = RegLo + 1;
9660         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9661       }
9662       continue;
9663     }
9664 
9665     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9666     // as any other MemLoc.
9667 
9668     // Promote the value if needed.
9669     // For now, only handle fully promoted and indirect arguments.
9670     if (VA.getLocInfo() == CCValAssign::Indirect) {
9671       // Store the argument in a stack slot and pass its address.
9672       Align StackAlign =
9673           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9674                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9675       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9676       // If the original argument was split (e.g. i128), we need
9677       // to store the required parts of it here (and pass just one address).
9678       // Vectors may be partly split to registers and partly to the stack, in
9679       // which case the base address is partly offset and subsequent stores are
9680       // relative to that.
9681       unsigned ArgIndex = Outs[i].OrigArgIndex;
9682       unsigned ArgPartOffset = Outs[i].PartOffset;
9683       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9684       // Calculate the total size to store. We don't have access to what we're
9685       // actually storing other than performing the loop and collecting the
9686       // info.
9687       SmallVector<std::pair<SDValue, SDValue>> Parts;
9688       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9689         SDValue PartValue = OutVals[i + 1];
9690         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9691         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9692         EVT PartVT = PartValue.getValueType();
9693         if (PartVT.isScalableVector())
9694           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9695         StoredSize += PartVT.getStoreSize();
9696         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9697         Parts.push_back(std::make_pair(PartValue, Offset));
9698         ++i;
9699       }
9700       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9701       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9702       MemOpChains.push_back(
9703           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9704                        MachinePointerInfo::getFixedStack(MF, FI)));
9705       for (const auto &Part : Parts) {
9706         SDValue PartValue = Part.first;
9707         SDValue PartOffset = Part.second;
9708         SDValue Address =
9709             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9710         MemOpChains.push_back(
9711             DAG.getStore(Chain, DL, PartValue, Address,
9712                          MachinePointerInfo::getFixedStack(MF, FI)));
9713       }
9714       ArgValue = SpillSlot;
9715     } else {
9716       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9717     }
9718 
9719     // Use local copy if it is a byval arg.
9720     if (Flags.isByVal())
9721       ArgValue = ByValArgs[j++];
9722 
9723     if (VA.isRegLoc()) {
9724       // Queue up the argument copies and emit them at the end.
9725       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9726     } else {
9727       assert(VA.isMemLoc() && "Argument not register or memory");
9728       assert(!IsTailCall && "Tail call not allowed if stack is used "
9729                             "for passing parameters");
9730 
9731       // Work out the address of the stack slot.
9732       if (!StackPtr.getNode())
9733         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9734       SDValue Address =
9735           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9736                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9737 
9738       // Emit the store.
9739       MemOpChains.push_back(
9740           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9741     }
9742   }
9743 
9744   // Join the stores, which are independent of one another.
9745   if (!MemOpChains.empty())
9746     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9747 
9748   SDValue Glue;
9749 
9750   // Build a sequence of copy-to-reg nodes, chained and glued together.
9751   for (auto &Reg : RegsToPass) {
9752     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9753     Glue = Chain.getValue(1);
9754   }
9755 
9756   // Validate that none of the argument registers have been marked as
9757   // reserved, if so report an error. Do the same for the return address if this
9758   // is not a tailcall.
9759   validateCCReservedRegs(RegsToPass, MF);
9760   if (!IsTailCall &&
9761       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9762     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9763         MF.getFunction(),
9764         "Return address register required, but has been reserved."});
9765 
9766   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9767   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9768   // split it and then direct call can be matched by PseudoCALL.
9769   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9770     const GlobalValue *GV = S->getGlobal();
9771 
9772     unsigned OpFlags = RISCVII::MO_CALL;
9773     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9774       OpFlags = RISCVII::MO_PLT;
9775 
9776     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9777   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9778     unsigned OpFlags = RISCVII::MO_CALL;
9779 
9780     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9781                                                  nullptr))
9782       OpFlags = RISCVII::MO_PLT;
9783 
9784     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9785   }
9786 
9787   // The first call operand is the chain and the second is the target address.
9788   SmallVector<SDValue, 8> Ops;
9789   Ops.push_back(Chain);
9790   Ops.push_back(Callee);
9791 
9792   // Add argument registers to the end of the list so that they are
9793   // known live into the call.
9794   for (auto &Reg : RegsToPass)
9795     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9796 
9797   if (!IsTailCall) {
9798     // Add a register mask operand representing the call-preserved registers.
9799     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9800     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9801     assert(Mask && "Missing call preserved mask for calling convention");
9802     Ops.push_back(DAG.getRegisterMask(Mask));
9803   }
9804 
9805   // Glue the call to the argument copies, if any.
9806   if (Glue.getNode())
9807     Ops.push_back(Glue);
9808 
9809   // Emit the call.
9810   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9811 
9812   if (IsTailCall) {
9813     MF.getFrameInfo().setHasTailCall();
9814     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9815   }
9816 
9817   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9818   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9819   Glue = Chain.getValue(1);
9820 
9821   // Mark the end of the call, which is glued to the call itself.
9822   Chain = DAG.getCALLSEQ_END(Chain,
9823                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9824                              DAG.getConstant(0, DL, PtrVT, true),
9825                              Glue, DL);
9826   Glue = Chain.getValue(1);
9827 
9828   // Assign locations to each value returned by this call.
9829   SmallVector<CCValAssign, 16> RVLocs;
9830   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9831   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9832 
9833   // Copy all of the result registers out of their specified physreg.
9834   for (auto &VA : RVLocs) {
9835     // Copy the value out
9836     SDValue RetValue =
9837         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9838     // Glue the RetValue to the end of the call sequence
9839     Chain = RetValue.getValue(1);
9840     Glue = RetValue.getValue(2);
9841 
9842     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9843       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9844       SDValue RetValue2 =
9845           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9846       Chain = RetValue2.getValue(1);
9847       Glue = RetValue2.getValue(2);
9848       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9849                              RetValue2);
9850     }
9851 
9852     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9853 
9854     InVals.push_back(RetValue);
9855   }
9856 
9857   return Chain;
9858 }
9859 
9860 bool RISCVTargetLowering::CanLowerReturn(
9861     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9862     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9863   SmallVector<CCValAssign, 16> RVLocs;
9864   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9865 
9866   Optional<unsigned> FirstMaskArgument;
9867   if (Subtarget.hasVInstructions())
9868     FirstMaskArgument = preAssignMask(Outs);
9869 
9870   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9871     MVT VT = Outs[i].VT;
9872     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9873     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9874     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9875                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9876                  *this, FirstMaskArgument))
9877       return false;
9878   }
9879   return true;
9880 }
9881 
9882 SDValue
9883 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9884                                  bool IsVarArg,
9885                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9886                                  const SmallVectorImpl<SDValue> &OutVals,
9887                                  const SDLoc &DL, SelectionDAG &DAG) const {
9888   const MachineFunction &MF = DAG.getMachineFunction();
9889   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9890 
9891   // Stores the assignment of the return value to a location.
9892   SmallVector<CCValAssign, 16> RVLocs;
9893 
9894   // Info about the registers and stack slot.
9895   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9896                  *DAG.getContext());
9897 
9898   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9899                     nullptr, CC_RISCV);
9900 
9901   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9902     report_fatal_error("GHC functions return void only");
9903 
9904   SDValue Glue;
9905   SmallVector<SDValue, 4> RetOps(1, Chain);
9906 
9907   // Copy the result values into the output registers.
9908   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9909     SDValue Val = OutVals[i];
9910     CCValAssign &VA = RVLocs[i];
9911     assert(VA.isRegLoc() && "Can only return in registers!");
9912 
9913     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9914       // Handle returning f64 on RV32D with a soft float ABI.
9915       assert(VA.isRegLoc() && "Expected return via registers");
9916       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9917                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9918       SDValue Lo = SplitF64.getValue(0);
9919       SDValue Hi = SplitF64.getValue(1);
9920       Register RegLo = VA.getLocReg();
9921       assert(RegLo < RISCV::X31 && "Invalid register pair");
9922       Register RegHi = RegLo + 1;
9923 
9924       if (STI.isRegisterReservedByUser(RegLo) ||
9925           STI.isRegisterReservedByUser(RegHi))
9926         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9927             MF.getFunction(),
9928             "Return value register required, but has been reserved."});
9929 
9930       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9931       Glue = Chain.getValue(1);
9932       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9933       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9934       Glue = Chain.getValue(1);
9935       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9936     } else {
9937       // Handle a 'normal' return.
9938       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9939       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9940 
9941       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9942         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9943             MF.getFunction(),
9944             "Return value register required, but has been reserved."});
9945 
9946       // Guarantee that all emitted copies are stuck together.
9947       Glue = Chain.getValue(1);
9948       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9949     }
9950   }
9951 
9952   RetOps[0] = Chain; // Update chain.
9953 
9954   // Add the glue node if we have it.
9955   if (Glue.getNode()) {
9956     RetOps.push_back(Glue);
9957   }
9958 
9959   unsigned RetOpc = RISCVISD::RET_FLAG;
9960   // Interrupt service routines use different return instructions.
9961   const Function &Func = DAG.getMachineFunction().getFunction();
9962   if (Func.hasFnAttribute("interrupt")) {
9963     if (!Func.getReturnType()->isVoidTy())
9964       report_fatal_error(
9965           "Functions with the interrupt attribute must have void return type!");
9966 
9967     MachineFunction &MF = DAG.getMachineFunction();
9968     StringRef Kind =
9969       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9970 
9971     if (Kind == "user")
9972       RetOpc = RISCVISD::URET_FLAG;
9973     else if (Kind == "supervisor")
9974       RetOpc = RISCVISD::SRET_FLAG;
9975     else
9976       RetOpc = RISCVISD::MRET_FLAG;
9977   }
9978 
9979   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9980 }
9981 
9982 void RISCVTargetLowering::validateCCReservedRegs(
9983     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9984     MachineFunction &MF) const {
9985   const Function &F = MF.getFunction();
9986   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9987 
9988   if (llvm::any_of(Regs, [&STI](auto Reg) {
9989         return STI.isRegisterReservedByUser(Reg.first);
9990       }))
9991     F.getContext().diagnose(DiagnosticInfoUnsupported{
9992         F, "Argument register required, but has been reserved."});
9993 }
9994 
9995 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9996   return CI->isTailCall();
9997 }
9998 
9999 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10000 #define NODE_NAME_CASE(NODE)                                                   \
10001   case RISCVISD::NODE:                                                         \
10002     return "RISCVISD::" #NODE;
10003   // clang-format off
10004   switch ((RISCVISD::NodeType)Opcode) {
10005   case RISCVISD::FIRST_NUMBER:
10006     break;
10007   NODE_NAME_CASE(RET_FLAG)
10008   NODE_NAME_CASE(URET_FLAG)
10009   NODE_NAME_CASE(SRET_FLAG)
10010   NODE_NAME_CASE(MRET_FLAG)
10011   NODE_NAME_CASE(CALL)
10012   NODE_NAME_CASE(SELECT_CC)
10013   NODE_NAME_CASE(BR_CC)
10014   NODE_NAME_CASE(BuildPairF64)
10015   NODE_NAME_CASE(SplitF64)
10016   NODE_NAME_CASE(TAIL)
10017   NODE_NAME_CASE(MULHSU)
10018   NODE_NAME_CASE(SLLW)
10019   NODE_NAME_CASE(SRAW)
10020   NODE_NAME_CASE(SRLW)
10021   NODE_NAME_CASE(DIVW)
10022   NODE_NAME_CASE(DIVUW)
10023   NODE_NAME_CASE(REMUW)
10024   NODE_NAME_CASE(ROLW)
10025   NODE_NAME_CASE(RORW)
10026   NODE_NAME_CASE(CLZW)
10027   NODE_NAME_CASE(CTZW)
10028   NODE_NAME_CASE(FSLW)
10029   NODE_NAME_CASE(FSRW)
10030   NODE_NAME_CASE(FSL)
10031   NODE_NAME_CASE(FSR)
10032   NODE_NAME_CASE(FMV_H_X)
10033   NODE_NAME_CASE(FMV_X_ANYEXTH)
10034   NODE_NAME_CASE(FMV_W_X_RV64)
10035   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10036   NODE_NAME_CASE(FCVT_X)
10037   NODE_NAME_CASE(FCVT_XU)
10038   NODE_NAME_CASE(FCVT_W_RV64)
10039   NODE_NAME_CASE(FCVT_WU_RV64)
10040   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10041   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10042   NODE_NAME_CASE(READ_CYCLE_WIDE)
10043   NODE_NAME_CASE(GREV)
10044   NODE_NAME_CASE(GREVW)
10045   NODE_NAME_CASE(GORC)
10046   NODE_NAME_CASE(GORCW)
10047   NODE_NAME_CASE(SHFL)
10048   NODE_NAME_CASE(SHFLW)
10049   NODE_NAME_CASE(UNSHFL)
10050   NODE_NAME_CASE(UNSHFLW)
10051   NODE_NAME_CASE(BFP)
10052   NODE_NAME_CASE(BFPW)
10053   NODE_NAME_CASE(BCOMPRESS)
10054   NODE_NAME_CASE(BCOMPRESSW)
10055   NODE_NAME_CASE(BDECOMPRESS)
10056   NODE_NAME_CASE(BDECOMPRESSW)
10057   NODE_NAME_CASE(VMV_V_X_VL)
10058   NODE_NAME_CASE(VFMV_V_F_VL)
10059   NODE_NAME_CASE(VMV_X_S)
10060   NODE_NAME_CASE(VMV_S_X_VL)
10061   NODE_NAME_CASE(VFMV_S_F_VL)
10062   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10063   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10064   NODE_NAME_CASE(READ_VLENB)
10065   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10066   NODE_NAME_CASE(VSLIDEUP_VL)
10067   NODE_NAME_CASE(VSLIDE1UP_VL)
10068   NODE_NAME_CASE(VSLIDEDOWN_VL)
10069   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10070   NODE_NAME_CASE(VID_VL)
10071   NODE_NAME_CASE(VFNCVT_ROD_VL)
10072   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10073   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10074   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10075   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10076   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10077   NODE_NAME_CASE(VECREDUCE_AND_VL)
10078   NODE_NAME_CASE(VECREDUCE_OR_VL)
10079   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10080   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10081   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10082   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10083   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10084   NODE_NAME_CASE(ADD_VL)
10085   NODE_NAME_CASE(AND_VL)
10086   NODE_NAME_CASE(MUL_VL)
10087   NODE_NAME_CASE(OR_VL)
10088   NODE_NAME_CASE(SDIV_VL)
10089   NODE_NAME_CASE(SHL_VL)
10090   NODE_NAME_CASE(SREM_VL)
10091   NODE_NAME_CASE(SRA_VL)
10092   NODE_NAME_CASE(SRL_VL)
10093   NODE_NAME_CASE(SUB_VL)
10094   NODE_NAME_CASE(UDIV_VL)
10095   NODE_NAME_CASE(UREM_VL)
10096   NODE_NAME_CASE(XOR_VL)
10097   NODE_NAME_CASE(SADDSAT_VL)
10098   NODE_NAME_CASE(UADDSAT_VL)
10099   NODE_NAME_CASE(SSUBSAT_VL)
10100   NODE_NAME_CASE(USUBSAT_VL)
10101   NODE_NAME_CASE(FADD_VL)
10102   NODE_NAME_CASE(FSUB_VL)
10103   NODE_NAME_CASE(FMUL_VL)
10104   NODE_NAME_CASE(FDIV_VL)
10105   NODE_NAME_CASE(FNEG_VL)
10106   NODE_NAME_CASE(FABS_VL)
10107   NODE_NAME_CASE(FSQRT_VL)
10108   NODE_NAME_CASE(FMA_VL)
10109   NODE_NAME_CASE(FCOPYSIGN_VL)
10110   NODE_NAME_CASE(SMIN_VL)
10111   NODE_NAME_CASE(SMAX_VL)
10112   NODE_NAME_CASE(UMIN_VL)
10113   NODE_NAME_CASE(UMAX_VL)
10114   NODE_NAME_CASE(FMINNUM_VL)
10115   NODE_NAME_CASE(FMAXNUM_VL)
10116   NODE_NAME_CASE(MULHS_VL)
10117   NODE_NAME_CASE(MULHU_VL)
10118   NODE_NAME_CASE(FP_TO_SINT_VL)
10119   NODE_NAME_CASE(FP_TO_UINT_VL)
10120   NODE_NAME_CASE(SINT_TO_FP_VL)
10121   NODE_NAME_CASE(UINT_TO_FP_VL)
10122   NODE_NAME_CASE(FP_EXTEND_VL)
10123   NODE_NAME_CASE(FP_ROUND_VL)
10124   NODE_NAME_CASE(VWMUL_VL)
10125   NODE_NAME_CASE(VWMULU_VL)
10126   NODE_NAME_CASE(VWADDU_VL)
10127   NODE_NAME_CASE(SETCC_VL)
10128   NODE_NAME_CASE(VSELECT_VL)
10129   NODE_NAME_CASE(VP_MERGE_VL)
10130   NODE_NAME_CASE(VMAND_VL)
10131   NODE_NAME_CASE(VMOR_VL)
10132   NODE_NAME_CASE(VMXOR_VL)
10133   NODE_NAME_CASE(VMCLR_VL)
10134   NODE_NAME_CASE(VMSET_VL)
10135   NODE_NAME_CASE(VRGATHER_VX_VL)
10136   NODE_NAME_CASE(VRGATHER_VV_VL)
10137   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10138   NODE_NAME_CASE(VSEXT_VL)
10139   NODE_NAME_CASE(VZEXT_VL)
10140   NODE_NAME_CASE(VCPOP_VL)
10141   NODE_NAME_CASE(VLE_VL)
10142   NODE_NAME_CASE(VSE_VL)
10143   NODE_NAME_CASE(READ_CSR)
10144   NODE_NAME_CASE(WRITE_CSR)
10145   NODE_NAME_CASE(SWAP_CSR)
10146   }
10147   // clang-format on
10148   return nullptr;
10149 #undef NODE_NAME_CASE
10150 }
10151 
10152 /// getConstraintType - Given a constraint letter, return the type of
10153 /// constraint it is for this target.
10154 RISCVTargetLowering::ConstraintType
10155 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10156   if (Constraint.size() == 1) {
10157     switch (Constraint[0]) {
10158     default:
10159       break;
10160     case 'f':
10161       return C_RegisterClass;
10162     case 'I':
10163     case 'J':
10164     case 'K':
10165       return C_Immediate;
10166     case 'A':
10167       return C_Memory;
10168     case 'S': // A symbolic address
10169       return C_Other;
10170     }
10171   } else {
10172     if (Constraint == "vr" || Constraint == "vm")
10173       return C_RegisterClass;
10174   }
10175   return TargetLowering::getConstraintType(Constraint);
10176 }
10177 
10178 std::pair<unsigned, const TargetRegisterClass *>
10179 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10180                                                   StringRef Constraint,
10181                                                   MVT VT) const {
10182   // First, see if this is a constraint that directly corresponds to a
10183   // RISCV register class.
10184   if (Constraint.size() == 1) {
10185     switch (Constraint[0]) {
10186     case 'r':
10187       // TODO: Support fixed vectors up to XLen for P extension?
10188       if (VT.isVector())
10189         break;
10190       return std::make_pair(0U, &RISCV::GPRRegClass);
10191     case 'f':
10192       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10193         return std::make_pair(0U, &RISCV::FPR16RegClass);
10194       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10195         return std::make_pair(0U, &RISCV::FPR32RegClass);
10196       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10197         return std::make_pair(0U, &RISCV::FPR64RegClass);
10198       break;
10199     default:
10200       break;
10201     }
10202   } else if (Constraint == "vr") {
10203     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10204                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10205       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10206         return std::make_pair(0U, RC);
10207     }
10208   } else if (Constraint == "vm") {
10209     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10210       return std::make_pair(0U, &RISCV::VMV0RegClass);
10211   }
10212 
10213   // Clang will correctly decode the usage of register name aliases into their
10214   // official names. However, other frontends like `rustc` do not. This allows
10215   // users of these frontends to use the ABI names for registers in LLVM-style
10216   // register constraints.
10217   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10218                                .Case("{zero}", RISCV::X0)
10219                                .Case("{ra}", RISCV::X1)
10220                                .Case("{sp}", RISCV::X2)
10221                                .Case("{gp}", RISCV::X3)
10222                                .Case("{tp}", RISCV::X4)
10223                                .Case("{t0}", RISCV::X5)
10224                                .Case("{t1}", RISCV::X6)
10225                                .Case("{t2}", RISCV::X7)
10226                                .Cases("{s0}", "{fp}", RISCV::X8)
10227                                .Case("{s1}", RISCV::X9)
10228                                .Case("{a0}", RISCV::X10)
10229                                .Case("{a1}", RISCV::X11)
10230                                .Case("{a2}", RISCV::X12)
10231                                .Case("{a3}", RISCV::X13)
10232                                .Case("{a4}", RISCV::X14)
10233                                .Case("{a5}", RISCV::X15)
10234                                .Case("{a6}", RISCV::X16)
10235                                .Case("{a7}", RISCV::X17)
10236                                .Case("{s2}", RISCV::X18)
10237                                .Case("{s3}", RISCV::X19)
10238                                .Case("{s4}", RISCV::X20)
10239                                .Case("{s5}", RISCV::X21)
10240                                .Case("{s6}", RISCV::X22)
10241                                .Case("{s7}", RISCV::X23)
10242                                .Case("{s8}", RISCV::X24)
10243                                .Case("{s9}", RISCV::X25)
10244                                .Case("{s10}", RISCV::X26)
10245                                .Case("{s11}", RISCV::X27)
10246                                .Case("{t3}", RISCV::X28)
10247                                .Case("{t4}", RISCV::X29)
10248                                .Case("{t5}", RISCV::X30)
10249                                .Case("{t6}", RISCV::X31)
10250                                .Default(RISCV::NoRegister);
10251   if (XRegFromAlias != RISCV::NoRegister)
10252     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10253 
10254   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10255   // TableGen record rather than the AsmName to choose registers for InlineAsm
10256   // constraints, plus we want to match those names to the widest floating point
10257   // register type available, manually select floating point registers here.
10258   //
10259   // The second case is the ABI name of the register, so that frontends can also
10260   // use the ABI names in register constraint lists.
10261   if (Subtarget.hasStdExtF()) {
10262     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10263                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10264                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10265                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10266                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10267                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10268                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10269                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10270                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10271                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10272                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10273                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10274                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10275                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10276                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10277                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10278                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10279                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10280                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10281                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10282                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10283                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10284                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10285                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10286                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10287                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10288                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10289                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10290                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10291                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10292                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10293                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10294                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10295                         .Default(RISCV::NoRegister);
10296     if (FReg != RISCV::NoRegister) {
10297       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10298       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10299         unsigned RegNo = FReg - RISCV::F0_F;
10300         unsigned DReg = RISCV::F0_D + RegNo;
10301         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10302       }
10303       if (VT == MVT::f32 || VT == MVT::Other)
10304         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10305       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10306         unsigned RegNo = FReg - RISCV::F0_F;
10307         unsigned HReg = RISCV::F0_H + RegNo;
10308         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10309       }
10310     }
10311   }
10312 
10313   if (Subtarget.hasVInstructions()) {
10314     Register VReg = StringSwitch<Register>(Constraint.lower())
10315                         .Case("{v0}", RISCV::V0)
10316                         .Case("{v1}", RISCV::V1)
10317                         .Case("{v2}", RISCV::V2)
10318                         .Case("{v3}", RISCV::V3)
10319                         .Case("{v4}", RISCV::V4)
10320                         .Case("{v5}", RISCV::V5)
10321                         .Case("{v6}", RISCV::V6)
10322                         .Case("{v7}", RISCV::V7)
10323                         .Case("{v8}", RISCV::V8)
10324                         .Case("{v9}", RISCV::V9)
10325                         .Case("{v10}", RISCV::V10)
10326                         .Case("{v11}", RISCV::V11)
10327                         .Case("{v12}", RISCV::V12)
10328                         .Case("{v13}", RISCV::V13)
10329                         .Case("{v14}", RISCV::V14)
10330                         .Case("{v15}", RISCV::V15)
10331                         .Case("{v16}", RISCV::V16)
10332                         .Case("{v17}", RISCV::V17)
10333                         .Case("{v18}", RISCV::V18)
10334                         .Case("{v19}", RISCV::V19)
10335                         .Case("{v20}", RISCV::V20)
10336                         .Case("{v21}", RISCV::V21)
10337                         .Case("{v22}", RISCV::V22)
10338                         .Case("{v23}", RISCV::V23)
10339                         .Case("{v24}", RISCV::V24)
10340                         .Case("{v25}", RISCV::V25)
10341                         .Case("{v26}", RISCV::V26)
10342                         .Case("{v27}", RISCV::V27)
10343                         .Case("{v28}", RISCV::V28)
10344                         .Case("{v29}", RISCV::V29)
10345                         .Case("{v30}", RISCV::V30)
10346                         .Case("{v31}", RISCV::V31)
10347                         .Default(RISCV::NoRegister);
10348     if (VReg != RISCV::NoRegister) {
10349       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10350         return std::make_pair(VReg, &RISCV::VMRegClass);
10351       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10352         return std::make_pair(VReg, &RISCV::VRRegClass);
10353       for (const auto *RC :
10354            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10355         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10356           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10357           return std::make_pair(VReg, RC);
10358         }
10359       }
10360     }
10361   }
10362 
10363   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10364 }
10365 
10366 unsigned
10367 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10368   // Currently only support length 1 constraints.
10369   if (ConstraintCode.size() == 1) {
10370     switch (ConstraintCode[0]) {
10371     case 'A':
10372       return InlineAsm::Constraint_A;
10373     default:
10374       break;
10375     }
10376   }
10377 
10378   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10379 }
10380 
10381 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10382     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10383     SelectionDAG &DAG) const {
10384   // Currently only support length 1 constraints.
10385   if (Constraint.length() == 1) {
10386     switch (Constraint[0]) {
10387     case 'I':
10388       // Validate & create a 12-bit signed immediate operand.
10389       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10390         uint64_t CVal = C->getSExtValue();
10391         if (isInt<12>(CVal))
10392           Ops.push_back(
10393               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10394       }
10395       return;
10396     case 'J':
10397       // Validate & create an integer zero operand.
10398       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10399         if (C->getZExtValue() == 0)
10400           Ops.push_back(
10401               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10402       return;
10403     case 'K':
10404       // Validate & create a 5-bit unsigned immediate operand.
10405       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10406         uint64_t CVal = C->getZExtValue();
10407         if (isUInt<5>(CVal))
10408           Ops.push_back(
10409               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10410       }
10411       return;
10412     case 'S':
10413       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10414         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10415                                                  GA->getValueType(0)));
10416       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10417         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10418                                                 BA->getValueType(0)));
10419       }
10420       return;
10421     default:
10422       break;
10423     }
10424   }
10425   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10426 }
10427 
10428 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10429                                                    Instruction *Inst,
10430                                                    AtomicOrdering Ord) const {
10431   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10432     return Builder.CreateFence(Ord);
10433   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10434     return Builder.CreateFence(AtomicOrdering::Release);
10435   return nullptr;
10436 }
10437 
10438 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10439                                                     Instruction *Inst,
10440                                                     AtomicOrdering Ord) const {
10441   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10442     return Builder.CreateFence(AtomicOrdering::Acquire);
10443   return nullptr;
10444 }
10445 
10446 TargetLowering::AtomicExpansionKind
10447 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10448   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10449   // point operations can't be used in an lr/sc sequence without breaking the
10450   // forward-progress guarantee.
10451   if (AI->isFloatingPointOperation())
10452     return AtomicExpansionKind::CmpXChg;
10453 
10454   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10455   if (Size == 8 || Size == 16)
10456     return AtomicExpansionKind::MaskedIntrinsic;
10457   return AtomicExpansionKind::None;
10458 }
10459 
10460 static Intrinsic::ID
10461 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10462   if (XLen == 32) {
10463     switch (BinOp) {
10464     default:
10465       llvm_unreachable("Unexpected AtomicRMW BinOp");
10466     case AtomicRMWInst::Xchg:
10467       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10468     case AtomicRMWInst::Add:
10469       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10470     case AtomicRMWInst::Sub:
10471       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10472     case AtomicRMWInst::Nand:
10473       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10474     case AtomicRMWInst::Max:
10475       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10476     case AtomicRMWInst::Min:
10477       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10478     case AtomicRMWInst::UMax:
10479       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10480     case AtomicRMWInst::UMin:
10481       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10482     }
10483   }
10484 
10485   if (XLen == 64) {
10486     switch (BinOp) {
10487     default:
10488       llvm_unreachable("Unexpected AtomicRMW BinOp");
10489     case AtomicRMWInst::Xchg:
10490       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10491     case AtomicRMWInst::Add:
10492       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10493     case AtomicRMWInst::Sub:
10494       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10495     case AtomicRMWInst::Nand:
10496       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10497     case AtomicRMWInst::Max:
10498       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10499     case AtomicRMWInst::Min:
10500       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10501     case AtomicRMWInst::UMax:
10502       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10503     case AtomicRMWInst::UMin:
10504       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10505     }
10506   }
10507 
10508   llvm_unreachable("Unexpected XLen\n");
10509 }
10510 
10511 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10512     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10513     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10514   unsigned XLen = Subtarget.getXLen();
10515   Value *Ordering =
10516       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10517   Type *Tys[] = {AlignedAddr->getType()};
10518   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10519       AI->getModule(),
10520       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10521 
10522   if (XLen == 64) {
10523     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10524     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10525     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10526   }
10527 
10528   Value *Result;
10529 
10530   // Must pass the shift amount needed to sign extend the loaded value prior
10531   // to performing a signed comparison for min/max. ShiftAmt is the number of
10532   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10533   // is the number of bits to left+right shift the value in order to
10534   // sign-extend.
10535   if (AI->getOperation() == AtomicRMWInst::Min ||
10536       AI->getOperation() == AtomicRMWInst::Max) {
10537     const DataLayout &DL = AI->getModule()->getDataLayout();
10538     unsigned ValWidth =
10539         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10540     Value *SextShamt =
10541         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10542     Result = Builder.CreateCall(LrwOpScwLoop,
10543                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10544   } else {
10545     Result =
10546         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10547   }
10548 
10549   if (XLen == 64)
10550     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10551   return Result;
10552 }
10553 
10554 TargetLowering::AtomicExpansionKind
10555 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10556     AtomicCmpXchgInst *CI) const {
10557   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10558   if (Size == 8 || Size == 16)
10559     return AtomicExpansionKind::MaskedIntrinsic;
10560   return AtomicExpansionKind::None;
10561 }
10562 
10563 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10564     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10565     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10566   unsigned XLen = Subtarget.getXLen();
10567   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10568   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10569   if (XLen == 64) {
10570     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10571     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10572     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10573     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10574   }
10575   Type *Tys[] = {AlignedAddr->getType()};
10576   Function *MaskedCmpXchg =
10577       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10578   Value *Result = Builder.CreateCall(
10579       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10580   if (XLen == 64)
10581     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10582   return Result;
10583 }
10584 
10585 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10586   return false;
10587 }
10588 
10589 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10590                                                EVT VT) const {
10591   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10592     return false;
10593 
10594   switch (FPVT.getSimpleVT().SimpleTy) {
10595   case MVT::f16:
10596     return Subtarget.hasStdExtZfh();
10597   case MVT::f32:
10598     return Subtarget.hasStdExtF();
10599   case MVT::f64:
10600     return Subtarget.hasStdExtD();
10601   default:
10602     return false;
10603   }
10604 }
10605 
10606 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10607   // If we are using the small code model, we can reduce size of jump table
10608   // entry to 4 bytes.
10609   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10610       getTargetMachine().getCodeModel() == CodeModel::Small) {
10611     return MachineJumpTableInfo::EK_Custom32;
10612   }
10613   return TargetLowering::getJumpTableEncoding();
10614 }
10615 
10616 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10617     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10618     unsigned uid, MCContext &Ctx) const {
10619   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10620          getTargetMachine().getCodeModel() == CodeModel::Small);
10621   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10622 }
10623 
10624 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10625                                                      EVT VT) const {
10626   VT = VT.getScalarType();
10627 
10628   if (!VT.isSimple())
10629     return false;
10630 
10631   switch (VT.getSimpleVT().SimpleTy) {
10632   case MVT::f16:
10633     return Subtarget.hasStdExtZfh();
10634   case MVT::f32:
10635     return Subtarget.hasStdExtF();
10636   case MVT::f64:
10637     return Subtarget.hasStdExtD();
10638   default:
10639     break;
10640   }
10641 
10642   return false;
10643 }
10644 
10645 Register RISCVTargetLowering::getExceptionPointerRegister(
10646     const Constant *PersonalityFn) const {
10647   return RISCV::X10;
10648 }
10649 
10650 Register RISCVTargetLowering::getExceptionSelectorRegister(
10651     const Constant *PersonalityFn) const {
10652   return RISCV::X11;
10653 }
10654 
10655 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10656   // Return false to suppress the unnecessary extensions if the LibCall
10657   // arguments or return value is f32 type for LP64 ABI.
10658   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10659   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10660     return false;
10661 
10662   return true;
10663 }
10664 
10665 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10666   if (Subtarget.is64Bit() && Type == MVT::i32)
10667     return true;
10668 
10669   return IsSigned;
10670 }
10671 
10672 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10673                                                  SDValue C) const {
10674   // Check integral scalar types.
10675   if (VT.isScalarInteger()) {
10676     // Omit the optimization if the sub target has the M extension and the data
10677     // size exceeds XLen.
10678     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10679       return false;
10680     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10681       // Break the MUL to a SLLI and an ADD/SUB.
10682       const APInt &Imm = ConstNode->getAPIntValue();
10683       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10684           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10685         return true;
10686       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10687       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10688           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10689            (Imm - 8).isPowerOf2()))
10690         return true;
10691       // Omit the following optimization if the sub target has the M extension
10692       // and the data size >= XLen.
10693       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10694         return false;
10695       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10696       // a pair of LUI/ADDI.
10697       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10698         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10699         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10700             (1 - ImmS).isPowerOf2())
10701         return true;
10702       }
10703     }
10704   }
10705 
10706   return false;
10707 }
10708 
10709 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10710     const SDValue &AddNode, const SDValue &ConstNode) const {
10711   // Let the DAGCombiner decide for vectors.
10712   EVT VT = AddNode.getValueType();
10713   if (VT.isVector())
10714     return true;
10715 
10716   // Let the DAGCombiner decide for larger types.
10717   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10718     return true;
10719 
10720   // It is worse if c1 is simm12 while c1*c2 is not.
10721   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10722   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10723   const APInt &C1 = C1Node->getAPIntValue();
10724   const APInt &C2 = C2Node->getAPIntValue();
10725   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10726     return false;
10727 
10728   // Default to true and let the DAGCombiner decide.
10729   return true;
10730 }
10731 
10732 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10733     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10734     bool *Fast) const {
10735   if (!VT.isVector())
10736     return false;
10737 
10738   EVT ElemVT = VT.getVectorElementType();
10739   if (Alignment >= ElemVT.getStoreSize()) {
10740     if (Fast)
10741       *Fast = true;
10742     return true;
10743   }
10744 
10745   return false;
10746 }
10747 
10748 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10749     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10750     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10751   bool IsABIRegCopy = CC.hasValue();
10752   EVT ValueVT = Val.getValueType();
10753   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10754     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10755     // and cast to f32.
10756     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10757     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10758     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10759                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10760     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10761     Parts[0] = Val;
10762     return true;
10763   }
10764 
10765   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10766     LLVMContext &Context = *DAG.getContext();
10767     EVT ValueEltVT = ValueVT.getVectorElementType();
10768     EVT PartEltVT = PartVT.getVectorElementType();
10769     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10770     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10771     if (PartVTBitSize % ValueVTBitSize == 0) {
10772       assert(PartVTBitSize >= ValueVTBitSize);
10773       // If the element types are different, bitcast to the same element type of
10774       // PartVT first.
10775       // Give an example here, we want copy a <vscale x 1 x i8> value to
10776       // <vscale x 4 x i16>.
10777       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10778       // subvector, then we can bitcast to <vscale x 4 x i16>.
10779       if (ValueEltVT != PartEltVT) {
10780         if (PartVTBitSize > ValueVTBitSize) {
10781           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10782           assert(Count != 0 && "The number of element should not be zero.");
10783           EVT SameEltTypeVT =
10784               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10785           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10786                             DAG.getUNDEF(SameEltTypeVT), Val,
10787                             DAG.getVectorIdxConstant(0, DL));
10788         }
10789         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10790       } else {
10791         Val =
10792             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10793                         Val, DAG.getVectorIdxConstant(0, DL));
10794       }
10795       Parts[0] = Val;
10796       return true;
10797     }
10798   }
10799   return false;
10800 }
10801 
10802 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10803     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10804     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10805   bool IsABIRegCopy = CC.hasValue();
10806   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10807     SDValue Val = Parts[0];
10808 
10809     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10810     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10811     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10812     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10813     return Val;
10814   }
10815 
10816   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10817     LLVMContext &Context = *DAG.getContext();
10818     SDValue Val = Parts[0];
10819     EVT ValueEltVT = ValueVT.getVectorElementType();
10820     EVT PartEltVT = PartVT.getVectorElementType();
10821     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10822     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10823     if (PartVTBitSize % ValueVTBitSize == 0) {
10824       assert(PartVTBitSize >= ValueVTBitSize);
10825       EVT SameEltTypeVT = ValueVT;
10826       // If the element types are different, convert it to the same element type
10827       // of PartVT.
10828       // Give an example here, we want copy a <vscale x 1 x i8> value from
10829       // <vscale x 4 x i16>.
10830       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10831       // then we can extract <vscale x 1 x i8>.
10832       if (ValueEltVT != PartEltVT) {
10833         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10834         assert(Count != 0 && "The number of element should not be zero.");
10835         SameEltTypeVT =
10836             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10837         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10838       }
10839       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10840                         DAG.getVectorIdxConstant(0, DL));
10841       return Val;
10842     }
10843   }
10844   return SDValue();
10845 }
10846 
10847 SDValue
10848 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10849                                    SelectionDAG &DAG,
10850                                    SmallVectorImpl<SDNode *> &Created) const {
10851   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10852   if (isIntDivCheap(N->getValueType(0), Attr))
10853     return SDValue(N, 0); // Lower SDIV as SDIV
10854 
10855   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10856          "Unexpected divisor!");
10857 
10858   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10859   if (!Subtarget.hasStdExtZbt())
10860     return SDValue();
10861 
10862   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10863   // Besides, more critical path instructions will be generated when dividing
10864   // by 2. So we keep using the original DAGs for these cases.
10865   unsigned Lg2 = Divisor.countTrailingZeros();
10866   if (Lg2 == 1 || Lg2 >= 12)
10867     return SDValue();
10868 
10869   // fold (sdiv X, pow2)
10870   EVT VT = N->getValueType(0);
10871   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10872     return SDValue();
10873 
10874   SDLoc DL(N);
10875   SDValue N0 = N->getOperand(0);
10876   SDValue Zero = DAG.getConstant(0, DL, VT);
10877   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10878 
10879   // Add (N0 < 0) ? Pow2 - 1 : 0;
10880   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10881   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10882   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10883 
10884   Created.push_back(Cmp.getNode());
10885   Created.push_back(Add.getNode());
10886   Created.push_back(Sel.getNode());
10887 
10888   // Divide by pow2.
10889   SDValue SRA =
10890       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10891 
10892   // If we're dividing by a positive value, we're done.  Otherwise, we must
10893   // negate the result.
10894   if (Divisor.isNonNegative())
10895     return SRA;
10896 
10897   Created.push_back(SRA.getNode());
10898   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10899 }
10900 
10901 #define GET_REGISTER_MATCHER
10902 #include "RISCVGenAsmMatcher.inc"
10903 
10904 Register
10905 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10906                                        const MachineFunction &MF) const {
10907   Register Reg = MatchRegisterAltName(RegName);
10908   if (Reg == RISCV::NoRegister)
10909     Reg = MatchRegisterName(RegName);
10910   if (Reg == RISCV::NoRegister)
10911     report_fatal_error(
10912         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10913   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10914   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10915     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10916                              StringRef(RegName) + "\"."));
10917   return Reg;
10918 }
10919 
10920 namespace llvm {
10921 namespace RISCVVIntrinsicsTable {
10922 
10923 #define GET_RISCVVIntrinsicsTable_IMPL
10924 #include "RISCVGenSearchableTables.inc"
10925 
10926 } // namespace RISCVVIntrinsicsTable
10927 
10928 } // namespace llvm
10929