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 bool useRVVForFixedLengthVectorVT(MVT VT,
1551                                          const RISCVSubtarget &Subtarget) {
1552   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1553   if (!Subtarget.useRVVForFixedLengthVectors())
1554     return false;
1555 
1556   // We only support a set of vector types with a consistent maximum fixed size
1557   // across all supported vector element types to avoid legalization issues.
1558   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1559   // fixed-length vector type we support is 1024 bytes.
1560   if (VT.getFixedSizeInBits() > 1024 * 8)
1561     return false;
1562 
1563   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1564 
1565   MVT EltVT = VT.getVectorElementType();
1566 
1567   // Don't use RVV for vectors we cannot scalarize if required.
1568   switch (EltVT.SimpleTy) {
1569   // i1 is supported but has different rules.
1570   default:
1571     return false;
1572   case MVT::i1:
1573     // Masks can only use a single register.
1574     if (VT.getVectorNumElements() > MinVLen)
1575       return false;
1576     MinVLen /= 8;
1577     break;
1578   case MVT::i8:
1579   case MVT::i16:
1580   case MVT::i32:
1581     break;
1582   case MVT::i64:
1583     if (!Subtarget.hasVInstructionsI64())
1584       return false;
1585     break;
1586   case MVT::f16:
1587     if (!Subtarget.hasVInstructionsF16())
1588       return false;
1589     break;
1590   case MVT::f32:
1591     if (!Subtarget.hasVInstructionsF32())
1592       return false;
1593     break;
1594   case MVT::f64:
1595     if (!Subtarget.hasVInstructionsF64())
1596       return false;
1597     break;
1598   }
1599 
1600   // Reject elements larger than ELEN.
1601   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1602     return false;
1603 
1604   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1605   // Don't use RVV for types that don't fit.
1606   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1607     return false;
1608 
1609   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1610   // the base fixed length RVV support in place.
1611   if (!VT.isPow2VectorType())
1612     return false;
1613 
1614   return true;
1615 }
1616 
1617 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1618   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1619 }
1620 
1621 // Return the largest legal scalable vector type that matches VT's element type.
1622 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1623                                             const RISCVSubtarget &Subtarget) {
1624   // This may be called before legal types are setup.
1625   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1626           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1627          "Expected legal fixed length vector!");
1628 
1629   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1630   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1631 
1632   MVT EltVT = VT.getVectorElementType();
1633   switch (EltVT.SimpleTy) {
1634   default:
1635     llvm_unreachable("unexpected element type for RVV container");
1636   case MVT::i1:
1637   case MVT::i8:
1638   case MVT::i16:
1639   case MVT::i32:
1640   case MVT::i64:
1641   case MVT::f16:
1642   case MVT::f32:
1643   case MVT::f64: {
1644     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1645     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1646     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1647     unsigned NumElts =
1648         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1649     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1650     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1651     return MVT::getScalableVectorVT(EltVT, NumElts);
1652   }
1653   }
1654 }
1655 
1656 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1657                                             const RISCVSubtarget &Subtarget) {
1658   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1659                                           Subtarget);
1660 }
1661 
1662 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1663   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1664 }
1665 
1666 // Grow V to consume an entire RVV register.
1667 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1668                                        const RISCVSubtarget &Subtarget) {
1669   assert(VT.isScalableVector() &&
1670          "Expected to convert into a scalable vector!");
1671   assert(V.getValueType().isFixedLengthVector() &&
1672          "Expected a fixed length vector operand!");
1673   SDLoc DL(V);
1674   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1675   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1676 }
1677 
1678 // Shrink V so it's just big enough to maintain a VT's worth of data.
1679 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1680                                          const RISCVSubtarget &Subtarget) {
1681   assert(VT.isFixedLengthVector() &&
1682          "Expected to convert into a fixed length vector!");
1683   assert(V.getValueType().isScalableVector() &&
1684          "Expected a scalable vector operand!");
1685   SDLoc DL(V);
1686   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1687   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1688 }
1689 
1690 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1691 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1692 // the vector type that it is contained in.
1693 static std::pair<SDValue, SDValue>
1694 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1695                 const RISCVSubtarget &Subtarget) {
1696   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1697   MVT XLenVT = Subtarget.getXLenVT();
1698   SDValue VL = VecVT.isFixedLengthVector()
1699                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1700                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1701   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1702   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1703   return {Mask, VL};
1704 }
1705 
1706 // As above but assuming the given type is a scalable vector type.
1707 static std::pair<SDValue, SDValue>
1708 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1709                         const RISCVSubtarget &Subtarget) {
1710   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1711   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1712 }
1713 
1714 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1715 // of either is (currently) supported. This can get us into an infinite loop
1716 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1717 // as a ..., etc.
1718 // Until either (or both) of these can reliably lower any node, reporting that
1719 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1720 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1721 // which is not desirable.
1722 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1723     EVT VT, unsigned DefinedValues) const {
1724   return false;
1725 }
1726 
1727 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1728   // Only splats are currently supported.
1729   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1730     return true;
1731 
1732   return false;
1733 }
1734 
1735 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1736                                   const RISCVSubtarget &Subtarget) {
1737   // RISCV FP-to-int conversions saturate to the destination register size, but
1738   // don't produce 0 for nan. We can use a conversion instruction and fix the
1739   // nan case with a compare and a select.
1740   SDValue Src = Op.getOperand(0);
1741 
1742   EVT DstVT = Op.getValueType();
1743   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1744 
1745   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1746   unsigned Opc;
1747   if (SatVT == DstVT)
1748     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1749   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1750     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1751   else
1752     return SDValue();
1753   // FIXME: Support other SatVTs by clamping before or after the conversion.
1754 
1755   SDLoc DL(Op);
1756   SDValue FpToInt = DAG.getNode(
1757       Opc, DL, DstVT, Src,
1758       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1759 
1760   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1761   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1762 }
1763 
1764 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1765 // and back. Taking care to avoid converting values that are nan or already
1766 // correct.
1767 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1768 // have FRM dependencies modeled yet.
1769 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1770   MVT VT = Op.getSimpleValueType();
1771   assert(VT.isVector() && "Unexpected type");
1772 
1773   SDLoc DL(Op);
1774 
1775   // Freeze the source since we are increasing the number of uses.
1776   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1777 
1778   // Truncate to integer and convert back to FP.
1779   MVT IntVT = VT.changeVectorElementTypeToInteger();
1780   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1781   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1782 
1783   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1784 
1785   if (Op.getOpcode() == ISD::FCEIL) {
1786     // If the truncated value is the greater than or equal to the original
1787     // value, we've computed the ceil. Otherwise, we went the wrong way and
1788     // need to increase by 1.
1789     // FIXME: This should use a masked operation. Handle here or in isel?
1790     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1791                                  DAG.getConstantFP(1.0, DL, VT));
1792     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1793     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1794   } else if (Op.getOpcode() == ISD::FFLOOR) {
1795     // If the truncated value is the less than or equal to the original value,
1796     // we've computed the floor. Otherwise, we went the wrong way and need to
1797     // decrease by 1.
1798     // FIXME: This should use a masked operation. Handle here or in isel?
1799     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1800                                  DAG.getConstantFP(1.0, DL, VT));
1801     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1802     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1803   }
1804 
1805   // Restore the original sign so that -0.0 is preserved.
1806   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1807 
1808   // Determine the largest integer that can be represented exactly. This and
1809   // values larger than it don't have any fractional bits so don't need to
1810   // be converted.
1811   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1812   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1813   APFloat MaxVal = APFloat(FltSem);
1814   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1815                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1816   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1817 
1818   // If abs(Src) was larger than MaxVal or nan, keep it.
1819   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1820   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1821   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1822 }
1823 
1824 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1825                                  const RISCVSubtarget &Subtarget) {
1826   MVT VT = Op.getSimpleValueType();
1827   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1828 
1829   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1830 
1831   SDLoc DL(Op);
1832   SDValue Mask, VL;
1833   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1834 
1835   unsigned Opc =
1836       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1837   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1838   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1839 }
1840 
1841 struct VIDSequence {
1842   int64_t StepNumerator;
1843   unsigned StepDenominator;
1844   int64_t Addend;
1845 };
1846 
1847 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1848 // to the (non-zero) step S and start value X. This can be then lowered as the
1849 // RVV sequence (VID * S) + X, for example.
1850 // The step S is represented as an integer numerator divided by a positive
1851 // denominator. Note that the implementation currently only identifies
1852 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1853 // cannot detect 2/3, for example.
1854 // Note that this method will also match potentially unappealing index
1855 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1856 // determine whether this is worth generating code for.
1857 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1858   unsigned NumElts = Op.getNumOperands();
1859   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1860   if (!Op.getValueType().isInteger())
1861     return None;
1862 
1863   Optional<unsigned> SeqStepDenom;
1864   Optional<int64_t> SeqStepNum, SeqAddend;
1865   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1866   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1867   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1868     // Assume undef elements match the sequence; we just have to be careful
1869     // when interpolating across them.
1870     if (Op.getOperand(Idx).isUndef())
1871       continue;
1872     // The BUILD_VECTOR must be all constants.
1873     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1874       return None;
1875 
1876     uint64_t Val = Op.getConstantOperandVal(Idx) &
1877                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1878 
1879     if (PrevElt) {
1880       // Calculate the step since the last non-undef element, and ensure
1881       // it's consistent across the entire sequence.
1882       unsigned IdxDiff = Idx - PrevElt->second;
1883       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1884 
1885       // A zero-value value difference means that we're somewhere in the middle
1886       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1887       // step change before evaluating the sequence.
1888       if (ValDiff != 0) {
1889         int64_t Remainder = ValDiff % IdxDiff;
1890         // Normalize the step if it's greater than 1.
1891         if (Remainder != ValDiff) {
1892           // The difference must cleanly divide the element span.
1893           if (Remainder != 0)
1894             return None;
1895           ValDiff /= IdxDiff;
1896           IdxDiff = 1;
1897         }
1898 
1899         if (!SeqStepNum)
1900           SeqStepNum = ValDiff;
1901         else if (ValDiff != SeqStepNum)
1902           return None;
1903 
1904         if (!SeqStepDenom)
1905           SeqStepDenom = IdxDiff;
1906         else if (IdxDiff != *SeqStepDenom)
1907           return None;
1908       }
1909     }
1910 
1911     // Record and/or check any addend.
1912     if (SeqStepNum && SeqStepDenom) {
1913       uint64_t ExpectedVal =
1914           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1915       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1916       if (!SeqAddend)
1917         SeqAddend = Addend;
1918       else if (SeqAddend != Addend)
1919         return None;
1920     }
1921 
1922     // Record this non-undef element for later.
1923     if (!PrevElt || PrevElt->first != Val)
1924       PrevElt = std::make_pair(Val, Idx);
1925   }
1926   // We need to have logged both a step and an addend for this to count as
1927   // a legal index sequence.
1928   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1929     return None;
1930 
1931   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1932 }
1933 
1934 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1935                                  const RISCVSubtarget &Subtarget) {
1936   MVT VT = Op.getSimpleValueType();
1937   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1938 
1939   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1940 
1941   SDLoc DL(Op);
1942   SDValue Mask, VL;
1943   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1944 
1945   MVT XLenVT = Subtarget.getXLenVT();
1946   unsigned NumElts = Op.getNumOperands();
1947 
1948   if (VT.getVectorElementType() == MVT::i1) {
1949     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1950       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1951       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1952     }
1953 
1954     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1955       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1956       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1957     }
1958 
1959     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1960     // scalar integer chunks whose bit-width depends on the number of mask
1961     // bits and XLEN.
1962     // First, determine the most appropriate scalar integer type to use. This
1963     // is at most XLenVT, but may be shrunk to a smaller vector element type
1964     // according to the size of the final vector - use i8 chunks rather than
1965     // XLenVT if we're producing a v8i1. This results in more consistent
1966     // codegen across RV32 and RV64.
1967     unsigned NumViaIntegerBits =
1968         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1969     NumViaIntegerBits = std::min(NumViaIntegerBits,
1970                                  Subtarget.getMaxELENForFixedLengthVectors());
1971     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1972       // If we have to use more than one INSERT_VECTOR_ELT then this
1973       // optimization is likely to increase code size; avoid peforming it in
1974       // such a case. We can use a load from a constant pool in this case.
1975       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1976         return SDValue();
1977       // Now we can create our integer vector type. Note that it may be larger
1978       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1979       MVT IntegerViaVecVT =
1980           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1981                            divideCeil(NumElts, NumViaIntegerBits));
1982 
1983       uint64_t Bits = 0;
1984       unsigned BitPos = 0, IntegerEltIdx = 0;
1985       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1986 
1987       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1988         // Once we accumulate enough bits to fill our scalar type, insert into
1989         // our vector and clear our accumulated data.
1990         if (I != 0 && I % NumViaIntegerBits == 0) {
1991           if (NumViaIntegerBits <= 32)
1992             Bits = SignExtend64(Bits, 32);
1993           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1994           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1995                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1996           Bits = 0;
1997           BitPos = 0;
1998           IntegerEltIdx++;
1999         }
2000         SDValue V = Op.getOperand(I);
2001         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2002         Bits |= ((uint64_t)BitValue << BitPos);
2003       }
2004 
2005       // Insert the (remaining) scalar value into position in our integer
2006       // vector type.
2007       if (NumViaIntegerBits <= 32)
2008         Bits = SignExtend64(Bits, 32);
2009       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2010       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2011                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2012 
2013       if (NumElts < NumViaIntegerBits) {
2014         // If we're producing a smaller vector than our minimum legal integer
2015         // type, bitcast to the equivalent (known-legal) mask type, and extract
2016         // our final mask.
2017         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2018         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2019         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2020                           DAG.getConstant(0, DL, XLenVT));
2021       } else {
2022         // Else we must have produced an integer type with the same size as the
2023         // mask type; bitcast for the final result.
2024         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2025         Vec = DAG.getBitcast(VT, Vec);
2026       }
2027 
2028       return Vec;
2029     }
2030 
2031     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2032     // vector type, we have a legal equivalently-sized i8 type, so we can use
2033     // that.
2034     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2035     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2036 
2037     SDValue WideVec;
2038     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2039       // For a splat, perform a scalar truncate before creating the wider
2040       // vector.
2041       assert(Splat.getValueType() == XLenVT &&
2042              "Unexpected type for i1 splat value");
2043       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2044                           DAG.getConstant(1, DL, XLenVT));
2045       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2046     } else {
2047       SmallVector<SDValue, 8> Ops(Op->op_values());
2048       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2049       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2050       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2051     }
2052 
2053     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2054   }
2055 
2056   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2057     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2058                                         : RISCVISD::VMV_V_X_VL;
2059     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2060     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2061   }
2062 
2063   // Try and match index sequences, which we can lower to the vid instruction
2064   // with optional modifications. An all-undef vector is matched by
2065   // getSplatValue, above.
2066   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2067     int64_t StepNumerator = SimpleVID->StepNumerator;
2068     unsigned StepDenominator = SimpleVID->StepDenominator;
2069     int64_t Addend = SimpleVID->Addend;
2070 
2071     assert(StepNumerator != 0 && "Invalid step");
2072     bool Negate = false;
2073     int64_t SplatStepVal = StepNumerator;
2074     unsigned StepOpcode = ISD::MUL;
2075     if (StepNumerator != 1) {
2076       if (isPowerOf2_64(std::abs(StepNumerator))) {
2077         Negate = StepNumerator < 0;
2078         StepOpcode = ISD::SHL;
2079         SplatStepVal = Log2_64(std::abs(StepNumerator));
2080       }
2081     }
2082 
2083     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2084     // threshold since it's the immediate value many RVV instructions accept.
2085     // There is no vmul.vi instruction so ensure multiply constant can fit in
2086     // a single addi instruction.
2087     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2088          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2089         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2090       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2091       // Convert right out of the scalable type so we can use standard ISD
2092       // nodes for the rest of the computation. If we used scalable types with
2093       // these, we'd lose the fixed-length vector info and generate worse
2094       // vsetvli code.
2095       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2096       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2097           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2098         SDValue SplatStep = DAG.getSplatVector(
2099             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2100         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2101       }
2102       if (StepDenominator != 1) {
2103         SDValue SplatStep = DAG.getSplatVector(
2104             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2105         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2106       }
2107       if (Addend != 0 || Negate) {
2108         SDValue SplatAddend =
2109             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2110         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2111       }
2112       return VID;
2113     }
2114   }
2115 
2116   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2117   // when re-interpreted as a vector with a larger element type. For example,
2118   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2119   // could be instead splat as
2120   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2121   // TODO: This optimization could also work on non-constant splats, but it
2122   // would require bit-manipulation instructions to construct the splat value.
2123   SmallVector<SDValue> Sequence;
2124   unsigned EltBitSize = VT.getScalarSizeInBits();
2125   const auto *BV = cast<BuildVectorSDNode>(Op);
2126   if (VT.isInteger() && EltBitSize < 64 &&
2127       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2128       BV->getRepeatedSequence(Sequence) &&
2129       (Sequence.size() * EltBitSize) <= 64) {
2130     unsigned SeqLen = Sequence.size();
2131     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2132     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2133     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2134             ViaIntVT == MVT::i64) &&
2135            "Unexpected sequence type");
2136 
2137     unsigned EltIdx = 0;
2138     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2139     uint64_t SplatValue = 0;
2140     // Construct the amalgamated value which can be splatted as this larger
2141     // vector type.
2142     for (const auto &SeqV : Sequence) {
2143       if (!SeqV.isUndef())
2144         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2145                        << (EltIdx * EltBitSize));
2146       EltIdx++;
2147     }
2148 
2149     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2150     // achieve better constant materializion.
2151     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2152       SplatValue = SignExtend64(SplatValue, 32);
2153 
2154     // Since we can't introduce illegal i64 types at this stage, we can only
2155     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2156     // way we can use RVV instructions to splat.
2157     assert((ViaIntVT.bitsLE(XLenVT) ||
2158             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2159            "Unexpected bitcast sequence");
2160     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2161       SDValue ViaVL =
2162           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2163       MVT ViaContainerVT =
2164           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2165       SDValue Splat =
2166           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2167                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2168       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2169       return DAG.getBitcast(VT, Splat);
2170     }
2171   }
2172 
2173   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2174   // which constitute a large proportion of the elements. In such cases we can
2175   // splat a vector with the dominant element and make up the shortfall with
2176   // INSERT_VECTOR_ELTs.
2177   // Note that this includes vectors of 2 elements by association. The
2178   // upper-most element is the "dominant" one, allowing us to use a splat to
2179   // "insert" the upper element, and an insert of the lower element at position
2180   // 0, which improves codegen.
2181   SDValue DominantValue;
2182   unsigned MostCommonCount = 0;
2183   DenseMap<SDValue, unsigned> ValueCounts;
2184   unsigned NumUndefElts =
2185       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2186 
2187   // Track the number of scalar loads we know we'd be inserting, estimated as
2188   // any non-zero floating-point constant. Other kinds of element are either
2189   // already in registers or are materialized on demand. The threshold at which
2190   // a vector load is more desirable than several scalar materializion and
2191   // vector-insertion instructions is not known.
2192   unsigned NumScalarLoads = 0;
2193 
2194   for (SDValue V : Op->op_values()) {
2195     if (V.isUndef())
2196       continue;
2197 
2198     ValueCounts.insert(std::make_pair(V, 0));
2199     unsigned &Count = ValueCounts[V];
2200 
2201     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2202       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2203 
2204     // Is this value dominant? In case of a tie, prefer the highest element as
2205     // it's cheaper to insert near the beginning of a vector than it is at the
2206     // end.
2207     if (++Count >= MostCommonCount) {
2208       DominantValue = V;
2209       MostCommonCount = Count;
2210     }
2211   }
2212 
2213   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2214   unsigned NumDefElts = NumElts - NumUndefElts;
2215   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2216 
2217   // Don't perform this optimization when optimizing for size, since
2218   // materializing elements and inserting them tends to cause code bloat.
2219   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2220       ((MostCommonCount > DominantValueCountThreshold) ||
2221        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2222     // Start by splatting the most common element.
2223     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2224 
2225     DenseSet<SDValue> Processed{DominantValue};
2226     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2227     for (const auto &OpIdx : enumerate(Op->ops())) {
2228       const SDValue &V = OpIdx.value();
2229       if (V.isUndef() || !Processed.insert(V).second)
2230         continue;
2231       if (ValueCounts[V] == 1) {
2232         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2233                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2234       } else {
2235         // Blend in all instances of this value using a VSELECT, using a
2236         // mask where each bit signals whether that element is the one
2237         // we're after.
2238         SmallVector<SDValue> Ops;
2239         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2240           return DAG.getConstant(V == V1, DL, XLenVT);
2241         });
2242         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2243                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2244                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2245       }
2246     }
2247 
2248     return Vec;
2249   }
2250 
2251   return SDValue();
2252 }
2253 
2254 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2255                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2256   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2257     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2258     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2259     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2260     // node in order to try and match RVV vector/scalar instructions.
2261     if ((LoC >> 31) == HiC)
2262       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2263 
2264     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2265     // vmv.v.x whose EEW = 32 to lower it.
2266     auto *Const = dyn_cast<ConstantSDNode>(VL);
2267     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2268       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2269       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2270       // access the subtarget here now.
2271       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2272       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2273     }
2274   }
2275 
2276   // Fall back to a stack store and stride x0 vector load.
2277   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2278 }
2279 
2280 // Called by type legalization to handle splat of i64 on RV32.
2281 // FIXME: We can optimize this when the type has sign or zero bits in one
2282 // of the halves.
2283 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2284                                    SDValue VL, SelectionDAG &DAG) {
2285   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2286   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2287                            DAG.getConstant(0, DL, MVT::i32));
2288   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2289                            DAG.getConstant(1, DL, MVT::i32));
2290   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2291 }
2292 
2293 // This function lowers a splat of a scalar operand Splat with the vector
2294 // length VL. It ensures the final sequence is type legal, which is useful when
2295 // lowering a splat after type legalization.
2296 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2297                                 SelectionDAG &DAG,
2298                                 const RISCVSubtarget &Subtarget) {
2299   if (VT.isFloatingPoint()) {
2300     // If VL is 1, we could use vfmv.s.f.
2301     if (isOneConstant(VL))
2302       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2303                          Scalar, VL);
2304     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2305   }
2306 
2307   MVT XLenVT = Subtarget.getXLenVT();
2308 
2309   // Simplest case is that the operand needs to be promoted to XLenVT.
2310   if (Scalar.getValueType().bitsLE(XLenVT)) {
2311     // If the operand is a constant, sign extend to increase our chances
2312     // of being able to use a .vi instruction. ANY_EXTEND would become a
2313     // a zero extend and the simm5 check in isel would fail.
2314     // FIXME: Should we ignore the upper bits in isel instead?
2315     unsigned ExtOpc =
2316         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2317     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2318     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2319     // If VL is 1 and the scalar value won't benefit from immediate, we could
2320     // use vmv.s.x.
2321     if (isOneConstant(VL) &&
2322         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2323       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2324                          VL);
2325     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2326   }
2327 
2328   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2329          "Unexpected scalar for splat lowering!");
2330 
2331   if (isOneConstant(VL) && isNullConstant(Scalar))
2332     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2333                        DAG.getConstant(0, DL, XLenVT), VL);
2334 
2335   // Otherwise use the more complicated splatting algorithm.
2336   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2337 }
2338 
2339 // Is the mask a slidedown that shifts in undefs.
2340 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2341   int Size = Mask.size();
2342 
2343   // Elements shifted in should be undef.
2344   auto CheckUndefs = [&](int Shift) {
2345     for (int i = Size - Shift; i != Size; ++i)
2346       if (Mask[i] >= 0)
2347         return false;
2348     return true;
2349   };
2350 
2351   // Elements should be shifted or undef.
2352   auto MatchShift = [&](int Shift) {
2353     for (int i = 0; i != Size - Shift; ++i)
2354        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2355          return false;
2356     return true;
2357   };
2358 
2359   // Try all possible shifts.
2360   for (int Shift = 1; Shift != Size; ++Shift)
2361     if (CheckUndefs(Shift) && MatchShift(Shift))
2362       return Shift;
2363 
2364   // No match.
2365   return -1;
2366 }
2367 
2368 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2369                                 const RISCVSubtarget &Subtarget) {
2370   // We need to be able to widen elements to the next larger integer type.
2371   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2372     return false;
2373 
2374   int Size = Mask.size();
2375   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2376 
2377   int Srcs[] = {-1, -1};
2378   for (int i = 0; i != Size; ++i) {
2379     // Ignore undef elements.
2380     if (Mask[i] < 0)
2381       continue;
2382 
2383     // Is this an even or odd element.
2384     int Pol = i % 2;
2385 
2386     // Ensure we consistently use the same source for this element polarity.
2387     int Src = Mask[i] / Size;
2388     if (Srcs[Pol] < 0)
2389       Srcs[Pol] = Src;
2390     if (Srcs[Pol] != Src)
2391       return false;
2392 
2393     // Make sure the element within the source is appropriate for this element
2394     // in the destination.
2395     int Elt = Mask[i] % Size;
2396     if (Elt != i / 2)
2397       return false;
2398   }
2399 
2400   // We need to find a source for each polarity and they can't be the same.
2401   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2402     return false;
2403 
2404   // Swap the sources if the second source was in the even polarity.
2405   SwapSources = Srcs[0] > Srcs[1];
2406 
2407   return true;
2408 }
2409 
2410 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2411                                    const RISCVSubtarget &Subtarget) {
2412   SDValue V1 = Op.getOperand(0);
2413   SDValue V2 = Op.getOperand(1);
2414   SDLoc DL(Op);
2415   MVT XLenVT = Subtarget.getXLenVT();
2416   MVT VT = Op.getSimpleValueType();
2417   unsigned NumElts = VT.getVectorNumElements();
2418   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2419 
2420   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2421 
2422   SDValue TrueMask, VL;
2423   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2424 
2425   if (SVN->isSplat()) {
2426     const int Lane = SVN->getSplatIndex();
2427     if (Lane >= 0) {
2428       MVT SVT = VT.getVectorElementType();
2429 
2430       // Turn splatted vector load into a strided load with an X0 stride.
2431       SDValue V = V1;
2432       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2433       // with undef.
2434       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2435       int Offset = Lane;
2436       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2437         int OpElements =
2438             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2439         V = V.getOperand(Offset / OpElements);
2440         Offset %= OpElements;
2441       }
2442 
2443       // We need to ensure the load isn't atomic or volatile.
2444       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2445         auto *Ld = cast<LoadSDNode>(V);
2446         Offset *= SVT.getStoreSize();
2447         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2448                                                    TypeSize::Fixed(Offset), DL);
2449 
2450         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2451         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2452           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2453           SDValue IntID =
2454               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2455           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2456                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2457           SDValue NewLoad = DAG.getMemIntrinsicNode(
2458               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2459               DAG.getMachineFunction().getMachineMemOperand(
2460                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2461           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2462           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2463         }
2464 
2465         // Otherwise use a scalar load and splat. This will give the best
2466         // opportunity to fold a splat into the operation. ISel can turn it into
2467         // the x0 strided load if we aren't able to fold away the select.
2468         if (SVT.isFloatingPoint())
2469           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2470                           Ld->getPointerInfo().getWithOffset(Offset),
2471                           Ld->getOriginalAlign(),
2472                           Ld->getMemOperand()->getFlags());
2473         else
2474           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2475                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2476                              Ld->getOriginalAlign(),
2477                              Ld->getMemOperand()->getFlags());
2478         DAG.makeEquivalentMemoryOrdering(Ld, V);
2479 
2480         unsigned Opc =
2481             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2482         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2483         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2484       }
2485 
2486       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2487       assert(Lane < (int)NumElts && "Unexpected lane!");
2488       SDValue Gather =
2489           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2490                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2491       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2492     }
2493   }
2494 
2495   ArrayRef<int> Mask = SVN->getMask();
2496 
2497   // Try to match as a slidedown.
2498   int SlideAmt = matchShuffleAsSlideDown(Mask);
2499   if (SlideAmt >= 0) {
2500     // TODO: Should we reduce the VL to account for the upper undef elements?
2501     // Requires additional vsetvlis, but might be faster to execute.
2502     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2503     SDValue SlideDown =
2504         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2505                     DAG.getUNDEF(ContainerVT), V1,
2506                     DAG.getConstant(SlideAmt, DL, XLenVT),
2507                     TrueMask, VL);
2508     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2509   }
2510 
2511   // Detect an interleave shuffle and lower to
2512   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2513   bool SwapSources;
2514   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2515     // Swap sources if needed.
2516     if (SwapSources)
2517       std::swap(V1, V2);
2518 
2519     // Extract the lower half of the vectors.
2520     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2521     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2522                      DAG.getConstant(0, DL, XLenVT));
2523     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2524                      DAG.getConstant(0, DL, XLenVT));
2525 
2526     // Double the element width and halve the number of elements in an int type.
2527     unsigned EltBits = VT.getScalarSizeInBits();
2528     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2529     MVT WideIntVT =
2530         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2531     // Convert this to a scalable vector. We need to base this on the
2532     // destination size to ensure there's always a type with a smaller LMUL.
2533     MVT WideIntContainerVT =
2534         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2535 
2536     // Convert sources to scalable vectors with the same element count as the
2537     // larger type.
2538     MVT HalfContainerVT = MVT::getVectorVT(
2539         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2540     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2541     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2542 
2543     // Cast sources to integer.
2544     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2545     MVT IntHalfVT =
2546         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2547     V1 = DAG.getBitcast(IntHalfVT, V1);
2548     V2 = DAG.getBitcast(IntHalfVT, V2);
2549 
2550     // Freeze V2 since we use it twice and we need to be sure that the add and
2551     // multiply see the same value.
2552     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2553 
2554     // Recreate TrueMask using the widened type's element count.
2555     MVT MaskVT =
2556         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2557     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2558 
2559     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2560     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2561                               V2, TrueMask, VL);
2562     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2563     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2564                                      DAG.getAllOnesConstant(DL, XLenVT));
2565     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2566                                    V2, Multiplier, TrueMask, VL);
2567     // Add the new copies to our previous addition giving us 2^eltbits copies of
2568     // V2. This is equivalent to shifting V2 left by eltbits. This should
2569     // combine with the vwmulu.vv above to form vwmaccu.vv.
2570     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2571                       TrueMask, VL);
2572     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2573     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2574     // vector VT.
2575     ContainerVT =
2576         MVT::getVectorVT(VT.getVectorElementType(),
2577                          WideIntContainerVT.getVectorElementCount() * 2);
2578     Add = DAG.getBitcast(ContainerVT, Add);
2579     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2580   }
2581 
2582   // Detect shuffles which can be re-expressed as vector selects; these are
2583   // shuffles in which each element in the destination is taken from an element
2584   // at the corresponding index in either source vectors.
2585   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2586     int MaskIndex = MaskIdx.value();
2587     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2588   });
2589 
2590   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2591 
2592   SmallVector<SDValue> MaskVals;
2593   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2594   // merged with a second vrgather.
2595   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2596 
2597   // By default we preserve the original operand order, and use a mask to
2598   // select LHS as true and RHS as false. However, since RVV vector selects may
2599   // feature splats but only on the LHS, we may choose to invert our mask and
2600   // instead select between RHS and LHS.
2601   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2602   bool InvertMask = IsSelect == SwapOps;
2603 
2604   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2605   // half.
2606   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2607 
2608   // Now construct the mask that will be used by the vselect or blended
2609   // vrgather operation. For vrgathers, construct the appropriate indices into
2610   // each vector.
2611   for (int MaskIndex : Mask) {
2612     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2613     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2614     if (!IsSelect) {
2615       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2616       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2617                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2618                                      : DAG.getUNDEF(XLenVT));
2619       GatherIndicesRHS.push_back(
2620           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2621                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2622       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2623         ++LHSIndexCounts[MaskIndex];
2624       if (!IsLHSOrUndefIndex)
2625         ++RHSIndexCounts[MaskIndex - NumElts];
2626     }
2627   }
2628 
2629   if (SwapOps) {
2630     std::swap(V1, V2);
2631     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2632   }
2633 
2634   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2635   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2636   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2637 
2638   if (IsSelect)
2639     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2640 
2641   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2642     // On such a large vector we're unable to use i8 as the index type.
2643     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2644     // may involve vector splitting if we're already at LMUL=8, or our
2645     // user-supplied maximum fixed-length LMUL.
2646     return SDValue();
2647   }
2648 
2649   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2650   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2651   MVT IndexVT = VT.changeTypeToInteger();
2652   // Since we can't introduce illegal index types at this stage, use i16 and
2653   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2654   // than XLenVT.
2655   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2656     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2657     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2658   }
2659 
2660   MVT IndexContainerVT =
2661       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2662 
2663   SDValue Gather;
2664   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2665   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2666   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2667     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2668   } else {
2669     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2670     // If only one index is used, we can use a "splat" vrgather.
2671     // TODO: We can splat the most-common index and fix-up any stragglers, if
2672     // that's beneficial.
2673     if (LHSIndexCounts.size() == 1) {
2674       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2675       Gather =
2676           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2677                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2678     } else {
2679       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2680       LHSIndices =
2681           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2682 
2683       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2684                            TrueMask, VL);
2685     }
2686   }
2687 
2688   // If a second vector operand is used by this shuffle, blend it in with an
2689   // additional vrgather.
2690   if (!V2.isUndef()) {
2691     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2692     // If only one index is used, we can use a "splat" vrgather.
2693     // TODO: We can splat the most-common index and fix-up any stragglers, if
2694     // that's beneficial.
2695     if (RHSIndexCounts.size() == 1) {
2696       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2697       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2698                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2699     } else {
2700       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2701       RHSIndices =
2702           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2703       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2704                        VL);
2705     }
2706 
2707     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2708     SelectMask =
2709         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2710 
2711     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2712                          Gather, VL);
2713   }
2714 
2715   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2716 }
2717 
2718 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2719                                      SDLoc DL, SelectionDAG &DAG,
2720                                      const RISCVSubtarget &Subtarget) {
2721   if (VT.isScalableVector())
2722     return DAG.getFPExtendOrRound(Op, DL, VT);
2723   assert(VT.isFixedLengthVector() &&
2724          "Unexpected value type for RVV FP extend/round lowering");
2725   SDValue Mask, VL;
2726   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2727   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2728                         ? RISCVISD::FP_EXTEND_VL
2729                         : RISCVISD::FP_ROUND_VL;
2730   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2731 }
2732 
2733 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2734 // the exponent.
2735 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2736   MVT VT = Op.getSimpleValueType();
2737   unsigned EltSize = VT.getScalarSizeInBits();
2738   SDValue Src = Op.getOperand(0);
2739   SDLoc DL(Op);
2740 
2741   // We need a FP type that can represent the value.
2742   // TODO: Use f16 for i8 when possible?
2743   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2744   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2745 
2746   // Legal types should have been checked in the RISCVTargetLowering
2747   // constructor.
2748   // TODO: Splitting may make sense in some cases.
2749   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2750          "Expected legal float type!");
2751 
2752   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2753   // The trailing zero count is equal to log2 of this single bit value.
2754   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2755     SDValue Neg =
2756         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2757     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2758   }
2759 
2760   // We have a legal FP type, convert to it.
2761   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2762   // Bitcast to integer and shift the exponent to the LSB.
2763   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2764   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2765   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2766   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2767                               DAG.getConstant(ShiftAmt, DL, IntVT));
2768   // Truncate back to original type to allow vnsrl.
2769   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2770   // The exponent contains log2 of the value in biased form.
2771   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2772 
2773   // For trailing zeros, we just need to subtract the bias.
2774   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2775     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2776                        DAG.getConstant(ExponentBias, DL, VT));
2777 
2778   // For leading zeros, we need to remove the bias and convert from log2 to
2779   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2780   unsigned Adjust = ExponentBias + (EltSize - 1);
2781   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2782 }
2783 
2784 // While RVV has alignment restrictions, we should always be able to load as a
2785 // legal equivalently-sized byte-typed vector instead. This method is
2786 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2787 // the load is already correctly-aligned, it returns SDValue().
2788 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2789                                                     SelectionDAG &DAG) const {
2790   auto *Load = cast<LoadSDNode>(Op);
2791   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2792 
2793   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2794                                      Load->getMemoryVT(),
2795                                      *Load->getMemOperand()))
2796     return SDValue();
2797 
2798   SDLoc DL(Op);
2799   MVT VT = Op.getSimpleValueType();
2800   unsigned EltSizeBits = VT.getScalarSizeInBits();
2801   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2802          "Unexpected unaligned RVV load type");
2803   MVT NewVT =
2804       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2805   assert(NewVT.isValid() &&
2806          "Expecting equally-sized RVV vector types to be legal");
2807   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2808                           Load->getPointerInfo(), Load->getOriginalAlign(),
2809                           Load->getMemOperand()->getFlags());
2810   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2811 }
2812 
2813 // While RVV has alignment restrictions, we should always be able to store as a
2814 // legal equivalently-sized byte-typed vector instead. This method is
2815 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2816 // returns SDValue() if the store is already correctly aligned.
2817 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2818                                                      SelectionDAG &DAG) const {
2819   auto *Store = cast<StoreSDNode>(Op);
2820   assert(Store && Store->getValue().getValueType().isVector() &&
2821          "Expected vector store");
2822 
2823   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2824                                      Store->getMemoryVT(),
2825                                      *Store->getMemOperand()))
2826     return SDValue();
2827 
2828   SDLoc DL(Op);
2829   SDValue StoredVal = Store->getValue();
2830   MVT VT = StoredVal.getSimpleValueType();
2831   unsigned EltSizeBits = VT.getScalarSizeInBits();
2832   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2833          "Unexpected unaligned RVV store type");
2834   MVT NewVT =
2835       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2836   assert(NewVT.isValid() &&
2837          "Expecting equally-sized RVV vector types to be legal");
2838   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2839   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2840                       Store->getPointerInfo(), Store->getOriginalAlign(),
2841                       Store->getMemOperand()->getFlags());
2842 }
2843 
2844 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2845                                             SelectionDAG &DAG) const {
2846   switch (Op.getOpcode()) {
2847   default:
2848     report_fatal_error("unimplemented operand");
2849   case ISD::GlobalAddress:
2850     return lowerGlobalAddress(Op, DAG);
2851   case ISD::BlockAddress:
2852     return lowerBlockAddress(Op, DAG);
2853   case ISD::ConstantPool:
2854     return lowerConstantPool(Op, DAG);
2855   case ISD::JumpTable:
2856     return lowerJumpTable(Op, DAG);
2857   case ISD::GlobalTLSAddress:
2858     return lowerGlobalTLSAddress(Op, DAG);
2859   case ISD::SELECT:
2860     return lowerSELECT(Op, DAG);
2861   case ISD::BRCOND:
2862     return lowerBRCOND(Op, DAG);
2863   case ISD::VASTART:
2864     return lowerVASTART(Op, DAG);
2865   case ISD::FRAMEADDR:
2866     return lowerFRAMEADDR(Op, DAG);
2867   case ISD::RETURNADDR:
2868     return lowerRETURNADDR(Op, DAG);
2869   case ISD::SHL_PARTS:
2870     return lowerShiftLeftParts(Op, DAG);
2871   case ISD::SRA_PARTS:
2872     return lowerShiftRightParts(Op, DAG, true);
2873   case ISD::SRL_PARTS:
2874     return lowerShiftRightParts(Op, DAG, false);
2875   case ISD::BITCAST: {
2876     SDLoc DL(Op);
2877     EVT VT = Op.getValueType();
2878     SDValue Op0 = Op.getOperand(0);
2879     EVT Op0VT = Op0.getValueType();
2880     MVT XLenVT = Subtarget.getXLenVT();
2881     if (VT.isFixedLengthVector()) {
2882       // We can handle fixed length vector bitcasts with a simple replacement
2883       // in isel.
2884       if (Op0VT.isFixedLengthVector())
2885         return Op;
2886       // When bitcasting from scalar to fixed-length vector, insert the scalar
2887       // into a one-element vector of the result type, and perform a vector
2888       // bitcast.
2889       if (!Op0VT.isVector()) {
2890         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2891         if (!isTypeLegal(BVT))
2892           return SDValue();
2893         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2894                                               DAG.getUNDEF(BVT), Op0,
2895                                               DAG.getConstant(0, DL, XLenVT)));
2896       }
2897       return SDValue();
2898     }
2899     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2900     // thus: bitcast the vector to a one-element vector type whose element type
2901     // is the same as the result type, and extract the first element.
2902     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2903       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2904       if (!isTypeLegal(BVT))
2905         return SDValue();
2906       SDValue BVec = DAG.getBitcast(BVT, Op0);
2907       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2908                          DAG.getConstant(0, DL, XLenVT));
2909     }
2910     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2911       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2912       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2913       return FPConv;
2914     }
2915     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2916         Subtarget.hasStdExtF()) {
2917       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2918       SDValue FPConv =
2919           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2920       return FPConv;
2921     }
2922     return SDValue();
2923   }
2924   case ISD::INTRINSIC_WO_CHAIN:
2925     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2926   case ISD::INTRINSIC_W_CHAIN:
2927     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2928   case ISD::INTRINSIC_VOID:
2929     return LowerINTRINSIC_VOID(Op, DAG);
2930   case ISD::BSWAP:
2931   case ISD::BITREVERSE: {
2932     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2933     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2934     MVT VT = Op.getSimpleValueType();
2935     SDLoc DL(Op);
2936     // Start with the maximum immediate value which is the bitwidth - 1.
2937     unsigned Imm = VT.getSizeInBits() - 1;
2938     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2939     if (Op.getOpcode() == ISD::BSWAP)
2940       Imm &= ~0x7U;
2941     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2942                        DAG.getConstant(Imm, DL, VT));
2943   }
2944   case ISD::FSHL:
2945   case ISD::FSHR: {
2946     MVT VT = Op.getSimpleValueType();
2947     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2948     SDLoc DL(Op);
2949     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2950     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2951     // accidentally setting the extra bit.
2952     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2953     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2954                                 DAG.getConstant(ShAmtWidth, DL, VT));
2955     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2956     // instruction use different orders. fshl will return its first operand for
2957     // shift of zero, fshr will return its second operand. fsl and fsr both
2958     // return rs1 so the ISD nodes need to have different operand orders.
2959     // Shift amount is in rs2.
2960     SDValue Op0 = Op.getOperand(0);
2961     SDValue Op1 = Op.getOperand(1);
2962     unsigned Opc = RISCVISD::FSL;
2963     if (Op.getOpcode() == ISD::FSHR) {
2964       std::swap(Op0, Op1);
2965       Opc = RISCVISD::FSR;
2966     }
2967     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
2968   }
2969   case ISD::TRUNCATE: {
2970     SDLoc DL(Op);
2971     MVT VT = Op.getSimpleValueType();
2972     // Only custom-lower vector truncates
2973     if (!VT.isVector())
2974       return Op;
2975 
2976     // Truncates to mask types are handled differently
2977     if (VT.getVectorElementType() == MVT::i1)
2978       return lowerVectorMaskTrunc(Op, DAG);
2979 
2980     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2981     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2982     // truncate by one power of two at a time.
2983     MVT DstEltVT = VT.getVectorElementType();
2984 
2985     SDValue Src = Op.getOperand(0);
2986     MVT SrcVT = Src.getSimpleValueType();
2987     MVT SrcEltVT = SrcVT.getVectorElementType();
2988 
2989     assert(DstEltVT.bitsLT(SrcEltVT) &&
2990            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2991            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2992            "Unexpected vector truncate lowering");
2993 
2994     MVT ContainerVT = SrcVT;
2995     if (SrcVT.isFixedLengthVector()) {
2996       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2997       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2998     }
2999 
3000     SDValue Result = Src;
3001     SDValue Mask, VL;
3002     std::tie(Mask, VL) =
3003         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3004     LLVMContext &Context = *DAG.getContext();
3005     const ElementCount Count = ContainerVT.getVectorElementCount();
3006     do {
3007       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3008       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3009       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3010                            Mask, VL);
3011     } while (SrcEltVT != DstEltVT);
3012 
3013     if (SrcVT.isFixedLengthVector())
3014       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3015 
3016     return Result;
3017   }
3018   case ISD::ANY_EXTEND:
3019   case ISD::ZERO_EXTEND:
3020     if (Op.getOperand(0).getValueType().isVector() &&
3021         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3022       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3023     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3024   case ISD::SIGN_EXTEND:
3025     if (Op.getOperand(0).getValueType().isVector() &&
3026         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3027       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3028     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3029   case ISD::SPLAT_VECTOR_PARTS:
3030     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3031   case ISD::INSERT_VECTOR_ELT:
3032     return lowerINSERT_VECTOR_ELT(Op, DAG);
3033   case ISD::EXTRACT_VECTOR_ELT:
3034     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3035   case ISD::VSCALE: {
3036     MVT VT = Op.getSimpleValueType();
3037     SDLoc DL(Op);
3038     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3039     // We define our scalable vector types for lmul=1 to use a 64 bit known
3040     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3041     // vscale as VLENB / 8.
3042     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3043     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3044       // We assume VLENB is a multiple of 8. We manually choose the best shift
3045       // here because SimplifyDemandedBits isn't always able to simplify it.
3046       uint64_t Val = Op.getConstantOperandVal(0);
3047       if (isPowerOf2_64(Val)) {
3048         uint64_t Log2 = Log2_64(Val);
3049         if (Log2 < 3)
3050           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3051                              DAG.getConstant(3 - Log2, DL, VT));
3052         if (Log2 > 3)
3053           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3054                              DAG.getConstant(Log2 - 3, DL, VT));
3055         return VLENB;
3056       }
3057       // If the multiplier is a multiple of 8, scale it down to avoid needing
3058       // to shift the VLENB value.
3059       if ((Val % 8) == 0)
3060         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3061                            DAG.getConstant(Val / 8, DL, VT));
3062     }
3063 
3064     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3065                                  DAG.getConstant(3, DL, VT));
3066     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3067   }
3068   case ISD::FPOWI: {
3069     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3070     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3071     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3072         Op.getOperand(1).getValueType() == MVT::i32) {
3073       SDLoc DL(Op);
3074       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3075       SDValue Powi =
3076           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3077       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3078                          DAG.getIntPtrConstant(0, DL));
3079     }
3080     return SDValue();
3081   }
3082   case ISD::FP_EXTEND: {
3083     // RVV can only do fp_extend to types double the size as the source. We
3084     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3085     // via f32.
3086     SDLoc DL(Op);
3087     MVT VT = Op.getSimpleValueType();
3088     SDValue Src = Op.getOperand(0);
3089     MVT SrcVT = Src.getSimpleValueType();
3090 
3091     // Prepare any fixed-length vector operands.
3092     MVT ContainerVT = VT;
3093     if (SrcVT.isFixedLengthVector()) {
3094       ContainerVT = getContainerForFixedLengthVector(VT);
3095       MVT SrcContainerVT =
3096           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3097       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3098     }
3099 
3100     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3101         SrcVT.getVectorElementType() != MVT::f16) {
3102       // For scalable vectors, we only need to close the gap between
3103       // vXf16->vXf64.
3104       if (!VT.isFixedLengthVector())
3105         return Op;
3106       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3107       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3108       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3109     }
3110 
3111     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3112     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3113     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3114         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3115 
3116     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3117                                            DL, DAG, Subtarget);
3118     if (VT.isFixedLengthVector())
3119       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3120     return Extend;
3121   }
3122   case ISD::FP_ROUND: {
3123     // RVV can only do fp_round to types half the size as the source. We
3124     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3125     // conversion instruction.
3126     SDLoc DL(Op);
3127     MVT VT = Op.getSimpleValueType();
3128     SDValue Src = Op.getOperand(0);
3129     MVT SrcVT = Src.getSimpleValueType();
3130 
3131     // Prepare any fixed-length vector operands.
3132     MVT ContainerVT = VT;
3133     if (VT.isFixedLengthVector()) {
3134       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3135       ContainerVT =
3136           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3137       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3138     }
3139 
3140     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3141         SrcVT.getVectorElementType() != MVT::f64) {
3142       // For scalable vectors, we only need to close the gap between
3143       // vXf64<->vXf16.
3144       if (!VT.isFixedLengthVector())
3145         return Op;
3146       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3147       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3148       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3149     }
3150 
3151     SDValue Mask, VL;
3152     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3153 
3154     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3155     SDValue IntermediateRound =
3156         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3157     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3158                                           DL, DAG, Subtarget);
3159 
3160     if (VT.isFixedLengthVector())
3161       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3162     return Round;
3163   }
3164   case ISD::FP_TO_SINT:
3165   case ISD::FP_TO_UINT:
3166   case ISD::SINT_TO_FP:
3167   case ISD::UINT_TO_FP: {
3168     // RVV can only do fp<->int conversions to types half/double the size as
3169     // the source. We custom-lower any conversions that do two hops into
3170     // sequences.
3171     MVT VT = Op.getSimpleValueType();
3172     if (!VT.isVector())
3173       return Op;
3174     SDLoc DL(Op);
3175     SDValue Src = Op.getOperand(0);
3176     MVT EltVT = VT.getVectorElementType();
3177     MVT SrcVT = Src.getSimpleValueType();
3178     MVT SrcEltVT = SrcVT.getVectorElementType();
3179     unsigned EltSize = EltVT.getSizeInBits();
3180     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3181     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3182            "Unexpected vector element types");
3183 
3184     bool IsInt2FP = SrcEltVT.isInteger();
3185     // Widening conversions
3186     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3187       if (IsInt2FP) {
3188         // Do a regular integer sign/zero extension then convert to float.
3189         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3190                                       VT.getVectorElementCount());
3191         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3192                                  ? ISD::ZERO_EXTEND
3193                                  : ISD::SIGN_EXTEND;
3194         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3195         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3196       }
3197       // FP2Int
3198       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3199       // Do one doubling fp_extend then complete the operation by converting
3200       // to int.
3201       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3202       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3203       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3204     }
3205 
3206     // Narrowing conversions
3207     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3208       if (IsInt2FP) {
3209         // One narrowing int_to_fp, then an fp_round.
3210         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3211         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3212         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3213         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3214       }
3215       // FP2Int
3216       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3217       // representable by the integer, the result is poison.
3218       MVT IVecVT =
3219           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3220                            VT.getVectorElementCount());
3221       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3222       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3223     }
3224 
3225     // Scalable vectors can exit here. Patterns will handle equally-sized
3226     // conversions halving/doubling ones.
3227     if (!VT.isFixedLengthVector())
3228       return Op;
3229 
3230     // For fixed-length vectors we lower to a custom "VL" node.
3231     unsigned RVVOpc = 0;
3232     switch (Op.getOpcode()) {
3233     default:
3234       llvm_unreachable("Impossible opcode");
3235     case ISD::FP_TO_SINT:
3236       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3237       break;
3238     case ISD::FP_TO_UINT:
3239       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3240       break;
3241     case ISD::SINT_TO_FP:
3242       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3243       break;
3244     case ISD::UINT_TO_FP:
3245       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3246       break;
3247     }
3248 
3249     MVT ContainerVT, SrcContainerVT;
3250     // Derive the reference container type from the larger vector type.
3251     if (SrcEltSize > EltSize) {
3252       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3253       ContainerVT =
3254           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3255     } else {
3256       ContainerVT = getContainerForFixedLengthVector(VT);
3257       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3258     }
3259 
3260     SDValue Mask, VL;
3261     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3262 
3263     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3264     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3265     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3266   }
3267   case ISD::FP_TO_SINT_SAT:
3268   case ISD::FP_TO_UINT_SAT:
3269     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3270   case ISD::FTRUNC:
3271   case ISD::FCEIL:
3272   case ISD::FFLOOR:
3273     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3274   case ISD::VECREDUCE_ADD:
3275   case ISD::VECREDUCE_UMAX:
3276   case ISD::VECREDUCE_SMAX:
3277   case ISD::VECREDUCE_UMIN:
3278   case ISD::VECREDUCE_SMIN:
3279     return lowerVECREDUCE(Op, DAG);
3280   case ISD::VECREDUCE_AND:
3281   case ISD::VECREDUCE_OR:
3282   case ISD::VECREDUCE_XOR:
3283     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3284       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3285     return lowerVECREDUCE(Op, DAG);
3286   case ISD::VECREDUCE_FADD:
3287   case ISD::VECREDUCE_SEQ_FADD:
3288   case ISD::VECREDUCE_FMIN:
3289   case ISD::VECREDUCE_FMAX:
3290     return lowerFPVECREDUCE(Op, DAG);
3291   case ISD::VP_REDUCE_ADD:
3292   case ISD::VP_REDUCE_UMAX:
3293   case ISD::VP_REDUCE_SMAX:
3294   case ISD::VP_REDUCE_UMIN:
3295   case ISD::VP_REDUCE_SMIN:
3296   case ISD::VP_REDUCE_FADD:
3297   case ISD::VP_REDUCE_SEQ_FADD:
3298   case ISD::VP_REDUCE_FMIN:
3299   case ISD::VP_REDUCE_FMAX:
3300     return lowerVPREDUCE(Op, DAG);
3301   case ISD::VP_REDUCE_AND:
3302   case ISD::VP_REDUCE_OR:
3303   case ISD::VP_REDUCE_XOR:
3304     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3305       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3306     return lowerVPREDUCE(Op, DAG);
3307   case ISD::INSERT_SUBVECTOR:
3308     return lowerINSERT_SUBVECTOR(Op, DAG);
3309   case ISD::EXTRACT_SUBVECTOR:
3310     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3311   case ISD::STEP_VECTOR:
3312     return lowerSTEP_VECTOR(Op, DAG);
3313   case ISD::VECTOR_REVERSE:
3314     return lowerVECTOR_REVERSE(Op, DAG);
3315   case ISD::BUILD_VECTOR:
3316     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3317   case ISD::SPLAT_VECTOR:
3318     if (Op.getValueType().getVectorElementType() == MVT::i1)
3319       return lowerVectorMaskSplat(Op, DAG);
3320     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3321   case ISD::VECTOR_SHUFFLE:
3322     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3323   case ISD::CONCAT_VECTORS: {
3324     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3325     // better than going through the stack, as the default expansion does.
3326     SDLoc DL(Op);
3327     MVT VT = Op.getSimpleValueType();
3328     unsigned NumOpElts =
3329         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3330     SDValue Vec = DAG.getUNDEF(VT);
3331     for (const auto &OpIdx : enumerate(Op->ops())) {
3332       SDValue SubVec = OpIdx.value();
3333       // Don't insert undef subvectors.
3334       if (SubVec.isUndef())
3335         continue;
3336       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3337                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3338     }
3339     return Vec;
3340   }
3341   case ISD::LOAD:
3342     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3343       return V;
3344     if (Op.getValueType().isFixedLengthVector())
3345       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3346     return Op;
3347   case ISD::STORE:
3348     if (auto V = expandUnalignedRVVStore(Op, DAG))
3349       return V;
3350     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3351       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3352     return Op;
3353   case ISD::MLOAD:
3354   case ISD::VP_LOAD:
3355     return lowerMaskedLoad(Op, DAG);
3356   case ISD::MSTORE:
3357   case ISD::VP_STORE:
3358     return lowerMaskedStore(Op, DAG);
3359   case ISD::SETCC:
3360     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3361   case ISD::ADD:
3362     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3363   case ISD::SUB:
3364     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3365   case ISD::MUL:
3366     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3367   case ISD::MULHS:
3368     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3369   case ISD::MULHU:
3370     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3371   case ISD::AND:
3372     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3373                                               RISCVISD::AND_VL);
3374   case ISD::OR:
3375     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3376                                               RISCVISD::OR_VL);
3377   case ISD::XOR:
3378     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3379                                               RISCVISD::XOR_VL);
3380   case ISD::SDIV:
3381     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3382   case ISD::SREM:
3383     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3384   case ISD::UDIV:
3385     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3386   case ISD::UREM:
3387     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3388   case ISD::SHL:
3389   case ISD::SRA:
3390   case ISD::SRL:
3391     if (Op.getSimpleValueType().isFixedLengthVector())
3392       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3393     // This can be called for an i32 shift amount that needs to be promoted.
3394     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3395            "Unexpected custom legalisation");
3396     return SDValue();
3397   case ISD::SADDSAT:
3398     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3399   case ISD::UADDSAT:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3401   case ISD::SSUBSAT:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3403   case ISD::USUBSAT:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3405   case ISD::FADD:
3406     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3407   case ISD::FSUB:
3408     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3409   case ISD::FMUL:
3410     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3411   case ISD::FDIV:
3412     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3413   case ISD::FNEG:
3414     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3415   case ISD::FABS:
3416     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3417   case ISD::FSQRT:
3418     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3419   case ISD::FMA:
3420     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3421   case ISD::SMIN:
3422     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3423   case ISD::SMAX:
3424     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3425   case ISD::UMIN:
3426     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3427   case ISD::UMAX:
3428     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3429   case ISD::FMINNUM:
3430     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3431   case ISD::FMAXNUM:
3432     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3433   case ISD::ABS:
3434     return lowerABS(Op, DAG);
3435   case ISD::CTLZ_ZERO_UNDEF:
3436   case ISD::CTTZ_ZERO_UNDEF:
3437     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3438   case ISD::VSELECT:
3439     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3440   case ISD::FCOPYSIGN:
3441     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3442   case ISD::MGATHER:
3443   case ISD::VP_GATHER:
3444     return lowerMaskedGather(Op, DAG);
3445   case ISD::MSCATTER:
3446   case ISD::VP_SCATTER:
3447     return lowerMaskedScatter(Op, DAG);
3448   case ISD::FLT_ROUNDS_:
3449     return lowerGET_ROUNDING(Op, DAG);
3450   case ISD::SET_ROUNDING:
3451     return lowerSET_ROUNDING(Op, DAG);
3452   case ISD::VP_SELECT:
3453     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3454   case ISD::VP_MERGE:
3455     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3456   case ISD::VP_ADD:
3457     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3458   case ISD::VP_SUB:
3459     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3460   case ISD::VP_MUL:
3461     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3462   case ISD::VP_SDIV:
3463     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3464   case ISD::VP_UDIV:
3465     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3466   case ISD::VP_SREM:
3467     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3468   case ISD::VP_UREM:
3469     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3470   case ISD::VP_AND:
3471     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3472   case ISD::VP_OR:
3473     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3474   case ISD::VP_XOR:
3475     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3476   case ISD::VP_ASHR:
3477     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3478   case ISD::VP_LSHR:
3479     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3480   case ISD::VP_SHL:
3481     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3482   case ISD::VP_FADD:
3483     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3484   case ISD::VP_FSUB:
3485     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3486   case ISD::VP_FMUL:
3487     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3488   case ISD::VP_FDIV:
3489     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3490   }
3491 }
3492 
3493 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3494                              SelectionDAG &DAG, unsigned Flags) {
3495   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3496 }
3497 
3498 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3499                              SelectionDAG &DAG, unsigned Flags) {
3500   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3501                                    Flags);
3502 }
3503 
3504 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3505                              SelectionDAG &DAG, unsigned Flags) {
3506   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3507                                    N->getOffset(), Flags);
3508 }
3509 
3510 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3511                              SelectionDAG &DAG, unsigned Flags) {
3512   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3513 }
3514 
3515 template <class NodeTy>
3516 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3517                                      bool IsLocal) const {
3518   SDLoc DL(N);
3519   EVT Ty = getPointerTy(DAG.getDataLayout());
3520 
3521   if (isPositionIndependent()) {
3522     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3523     if (IsLocal)
3524       // Use PC-relative addressing to access the symbol. This generates the
3525       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3526       // %pcrel_lo(auipc)).
3527       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3528 
3529     // Use PC-relative addressing to access the GOT for this symbol, then load
3530     // the address from the GOT. This generates the pattern (PseudoLA sym),
3531     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3532     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3533   }
3534 
3535   switch (getTargetMachine().getCodeModel()) {
3536   default:
3537     report_fatal_error("Unsupported code model for lowering");
3538   case CodeModel::Small: {
3539     // Generate a sequence for accessing addresses within the first 2 GiB of
3540     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3541     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3542     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3543     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3544     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3545   }
3546   case CodeModel::Medium: {
3547     // Generate a sequence for accessing addresses within any 2GiB range within
3548     // the address space. This generates the pattern (PseudoLLA sym), which
3549     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3550     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3551     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3552   }
3553   }
3554 }
3555 
3556 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3557                                                 SelectionDAG &DAG) const {
3558   SDLoc DL(Op);
3559   EVT Ty = Op.getValueType();
3560   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3561   int64_t Offset = N->getOffset();
3562   MVT XLenVT = Subtarget.getXLenVT();
3563 
3564   const GlobalValue *GV = N->getGlobal();
3565   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3566   SDValue Addr = getAddr(N, DAG, IsLocal);
3567 
3568   // In order to maximise the opportunity for common subexpression elimination,
3569   // emit a separate ADD node for the global address offset instead of folding
3570   // it in the global address node. Later peephole optimisations may choose to
3571   // fold it back in when profitable.
3572   if (Offset != 0)
3573     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3574                        DAG.getConstant(Offset, DL, XLenVT));
3575   return Addr;
3576 }
3577 
3578 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3579                                                SelectionDAG &DAG) const {
3580   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3581 
3582   return getAddr(N, DAG);
3583 }
3584 
3585 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3586                                                SelectionDAG &DAG) const {
3587   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3588 
3589   return getAddr(N, DAG);
3590 }
3591 
3592 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3593                                             SelectionDAG &DAG) const {
3594   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3595 
3596   return getAddr(N, DAG);
3597 }
3598 
3599 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3600                                               SelectionDAG &DAG,
3601                                               bool UseGOT) const {
3602   SDLoc DL(N);
3603   EVT Ty = getPointerTy(DAG.getDataLayout());
3604   const GlobalValue *GV = N->getGlobal();
3605   MVT XLenVT = Subtarget.getXLenVT();
3606 
3607   if (UseGOT) {
3608     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3609     // load the address from the GOT and add the thread pointer. This generates
3610     // the pattern (PseudoLA_TLS_IE sym), which expands to
3611     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3612     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3613     SDValue Load =
3614         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3615 
3616     // Add the thread pointer.
3617     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3618     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3619   }
3620 
3621   // Generate a sequence for accessing the address relative to the thread
3622   // pointer, with the appropriate adjustment for the thread pointer offset.
3623   // This generates the pattern
3624   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3625   SDValue AddrHi =
3626       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3627   SDValue AddrAdd =
3628       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3629   SDValue AddrLo =
3630       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3631 
3632   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3633   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3634   SDValue MNAdd = SDValue(
3635       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3636       0);
3637   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3638 }
3639 
3640 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3641                                                SelectionDAG &DAG) const {
3642   SDLoc DL(N);
3643   EVT Ty = getPointerTy(DAG.getDataLayout());
3644   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3645   const GlobalValue *GV = N->getGlobal();
3646 
3647   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3648   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3649   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3650   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3651   SDValue Load =
3652       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3653 
3654   // Prepare argument list to generate call.
3655   ArgListTy Args;
3656   ArgListEntry Entry;
3657   Entry.Node = Load;
3658   Entry.Ty = CallTy;
3659   Args.push_back(Entry);
3660 
3661   // Setup call to __tls_get_addr.
3662   TargetLowering::CallLoweringInfo CLI(DAG);
3663   CLI.setDebugLoc(DL)
3664       .setChain(DAG.getEntryNode())
3665       .setLibCallee(CallingConv::C, CallTy,
3666                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3667                     std::move(Args));
3668 
3669   return LowerCallTo(CLI).first;
3670 }
3671 
3672 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3673                                                    SelectionDAG &DAG) const {
3674   SDLoc DL(Op);
3675   EVT Ty = Op.getValueType();
3676   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3677   int64_t Offset = N->getOffset();
3678   MVT XLenVT = Subtarget.getXLenVT();
3679 
3680   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3681 
3682   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3683       CallingConv::GHC)
3684     report_fatal_error("In GHC calling convention TLS is not supported");
3685 
3686   SDValue Addr;
3687   switch (Model) {
3688   case TLSModel::LocalExec:
3689     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3690     break;
3691   case TLSModel::InitialExec:
3692     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3693     break;
3694   case TLSModel::LocalDynamic:
3695   case TLSModel::GeneralDynamic:
3696     Addr = getDynamicTLSAddr(N, DAG);
3697     break;
3698   }
3699 
3700   // In order to maximise the opportunity for common subexpression elimination,
3701   // emit a separate ADD node for the global address offset instead of folding
3702   // it in the global address node. Later peephole optimisations may choose to
3703   // fold it back in when profitable.
3704   if (Offset != 0)
3705     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3706                        DAG.getConstant(Offset, DL, XLenVT));
3707   return Addr;
3708 }
3709 
3710 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3711   SDValue CondV = Op.getOperand(0);
3712   SDValue TrueV = Op.getOperand(1);
3713   SDValue FalseV = Op.getOperand(2);
3714   SDLoc DL(Op);
3715   MVT VT = Op.getSimpleValueType();
3716   MVT XLenVT = Subtarget.getXLenVT();
3717 
3718   // Lower vector SELECTs to VSELECTs by splatting the condition.
3719   if (VT.isVector()) {
3720     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3721     SDValue CondSplat = VT.isScalableVector()
3722                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3723                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3724     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3725   }
3726 
3727   // If the result type is XLenVT and CondV is the output of a SETCC node
3728   // which also operated on XLenVT inputs, then merge the SETCC node into the
3729   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3730   // compare+branch instructions. i.e.:
3731   // (select (setcc lhs, rhs, cc), truev, falsev)
3732   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3733   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3734       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3735     SDValue LHS = CondV.getOperand(0);
3736     SDValue RHS = CondV.getOperand(1);
3737     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3738     ISD::CondCode CCVal = CC->get();
3739 
3740     // Special case for a select of 2 constants that have a diffence of 1.
3741     // Normally this is done by DAGCombine, but if the select is introduced by
3742     // type legalization or op legalization, we miss it. Restricting to SETLT
3743     // case for now because that is what signed saturating add/sub need.
3744     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3745     // but we would probably want to swap the true/false values if the condition
3746     // is SETGE/SETLE to avoid an XORI.
3747     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3748         CCVal == ISD::SETLT) {
3749       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3750       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3751       if (TrueVal - 1 == FalseVal)
3752         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3753       if (TrueVal + 1 == FalseVal)
3754         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3755     }
3756 
3757     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3758 
3759     SDValue TargetCC = DAG.getCondCode(CCVal);
3760     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3761     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3762   }
3763 
3764   // Otherwise:
3765   // (select condv, truev, falsev)
3766   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3767   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3768   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3769 
3770   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3771 
3772   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3773 }
3774 
3775 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3776   SDValue CondV = Op.getOperand(1);
3777   SDLoc DL(Op);
3778   MVT XLenVT = Subtarget.getXLenVT();
3779 
3780   if (CondV.getOpcode() == ISD::SETCC &&
3781       CondV.getOperand(0).getValueType() == XLenVT) {
3782     SDValue LHS = CondV.getOperand(0);
3783     SDValue RHS = CondV.getOperand(1);
3784     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3785 
3786     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3787 
3788     SDValue TargetCC = DAG.getCondCode(CCVal);
3789     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3790                        LHS, RHS, TargetCC, Op.getOperand(2));
3791   }
3792 
3793   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3794                      CondV, DAG.getConstant(0, DL, XLenVT),
3795                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3796 }
3797 
3798 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3799   MachineFunction &MF = DAG.getMachineFunction();
3800   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3801 
3802   SDLoc DL(Op);
3803   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3804                                  getPointerTy(MF.getDataLayout()));
3805 
3806   // vastart just stores the address of the VarArgsFrameIndex slot into the
3807   // memory location argument.
3808   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3809   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3810                       MachinePointerInfo(SV));
3811 }
3812 
3813 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3814                                             SelectionDAG &DAG) const {
3815   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3816   MachineFunction &MF = DAG.getMachineFunction();
3817   MachineFrameInfo &MFI = MF.getFrameInfo();
3818   MFI.setFrameAddressIsTaken(true);
3819   Register FrameReg = RI.getFrameRegister(MF);
3820   int XLenInBytes = Subtarget.getXLen() / 8;
3821 
3822   EVT VT = Op.getValueType();
3823   SDLoc DL(Op);
3824   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3825   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3826   while (Depth--) {
3827     int Offset = -(XLenInBytes * 2);
3828     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3829                               DAG.getIntPtrConstant(Offset, DL));
3830     FrameAddr =
3831         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3832   }
3833   return FrameAddr;
3834 }
3835 
3836 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3837                                              SelectionDAG &DAG) const {
3838   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3839   MachineFunction &MF = DAG.getMachineFunction();
3840   MachineFrameInfo &MFI = MF.getFrameInfo();
3841   MFI.setReturnAddressIsTaken(true);
3842   MVT XLenVT = Subtarget.getXLenVT();
3843   int XLenInBytes = Subtarget.getXLen() / 8;
3844 
3845   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3846     return SDValue();
3847 
3848   EVT VT = Op.getValueType();
3849   SDLoc DL(Op);
3850   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3851   if (Depth) {
3852     int Off = -XLenInBytes;
3853     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3854     SDValue Offset = DAG.getConstant(Off, DL, VT);
3855     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3856                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3857                        MachinePointerInfo());
3858   }
3859 
3860   // Return the value of the return address register, marking it an implicit
3861   // live-in.
3862   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3863   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3864 }
3865 
3866 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3867                                                  SelectionDAG &DAG) const {
3868   SDLoc DL(Op);
3869   SDValue Lo = Op.getOperand(0);
3870   SDValue Hi = Op.getOperand(1);
3871   SDValue Shamt = Op.getOperand(2);
3872   EVT VT = Lo.getValueType();
3873 
3874   // if Shamt-XLEN < 0: // Shamt < XLEN
3875   //   Lo = Lo << Shamt
3876   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3877   // else:
3878   //   Lo = 0
3879   //   Hi = Lo << (Shamt-XLEN)
3880 
3881   SDValue Zero = DAG.getConstant(0, DL, VT);
3882   SDValue One = DAG.getConstant(1, DL, VT);
3883   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3884   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3885   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3886   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3887 
3888   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3889   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3890   SDValue ShiftRightLo =
3891       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3892   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3893   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3894   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3895 
3896   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3897 
3898   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3899   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3900 
3901   SDValue Parts[2] = {Lo, Hi};
3902   return DAG.getMergeValues(Parts, DL);
3903 }
3904 
3905 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3906                                                   bool IsSRA) const {
3907   SDLoc DL(Op);
3908   SDValue Lo = Op.getOperand(0);
3909   SDValue Hi = Op.getOperand(1);
3910   SDValue Shamt = Op.getOperand(2);
3911   EVT VT = Lo.getValueType();
3912 
3913   // SRA expansion:
3914   //   if Shamt-XLEN < 0: // Shamt < XLEN
3915   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3916   //     Hi = Hi >>s Shamt
3917   //   else:
3918   //     Lo = Hi >>s (Shamt-XLEN);
3919   //     Hi = Hi >>s (XLEN-1)
3920   //
3921   // SRL expansion:
3922   //   if Shamt-XLEN < 0: // Shamt < XLEN
3923   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3924   //     Hi = Hi >>u Shamt
3925   //   else:
3926   //     Lo = Hi >>u (Shamt-XLEN);
3927   //     Hi = 0;
3928 
3929   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3930 
3931   SDValue Zero = DAG.getConstant(0, DL, VT);
3932   SDValue One = DAG.getConstant(1, DL, VT);
3933   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3934   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3935   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3936   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3937 
3938   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3939   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3940   SDValue ShiftLeftHi =
3941       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3942   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3943   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3944   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3945   SDValue HiFalse =
3946       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3947 
3948   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3949 
3950   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3951   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3952 
3953   SDValue Parts[2] = {Lo, Hi};
3954   return DAG.getMergeValues(Parts, DL);
3955 }
3956 
3957 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3958 // legal equivalently-sized i8 type, so we can use that as a go-between.
3959 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3960                                                   SelectionDAG &DAG) const {
3961   SDLoc DL(Op);
3962   MVT VT = Op.getSimpleValueType();
3963   SDValue SplatVal = Op.getOperand(0);
3964   // All-zeros or all-ones splats are handled specially.
3965   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3966     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3967     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3968   }
3969   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3970     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3971     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3972   }
3973   MVT XLenVT = Subtarget.getXLenVT();
3974   assert(SplatVal.getValueType() == XLenVT &&
3975          "Unexpected type for i1 splat value");
3976   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3977   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3978                          DAG.getConstant(1, DL, XLenVT));
3979   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3980   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3981   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3982 }
3983 
3984 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3985 // illegal (currently only vXi64 RV32).
3986 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3987 // them to SPLAT_VECTOR_I64
3988 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3989                                                      SelectionDAG &DAG) const {
3990   SDLoc DL(Op);
3991   MVT VecVT = Op.getSimpleValueType();
3992   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3993          "Unexpected SPLAT_VECTOR_PARTS lowering");
3994 
3995   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3996   SDValue Lo = Op.getOperand(0);
3997   SDValue Hi = Op.getOperand(1);
3998 
3999   if (VecVT.isFixedLengthVector()) {
4000     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4001     SDLoc DL(Op);
4002     SDValue Mask, VL;
4003     std::tie(Mask, VL) =
4004         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4005 
4006     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4007     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4008   }
4009 
4010   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4011     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4012     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4013     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4014     // node in order to try and match RVV vector/scalar instructions.
4015     if ((LoC >> 31) == HiC)
4016       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4017   }
4018 
4019   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4020   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4021       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4022       Hi.getConstantOperandVal(1) == 31)
4023     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4024 
4025   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4026   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4027                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4028 }
4029 
4030 // Custom-lower extensions from mask vectors by using a vselect either with 1
4031 // for zero/any-extension or -1 for sign-extension:
4032 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4033 // Note that any-extension is lowered identically to zero-extension.
4034 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4035                                                 int64_t ExtTrueVal) const {
4036   SDLoc DL(Op);
4037   MVT VecVT = Op.getSimpleValueType();
4038   SDValue Src = Op.getOperand(0);
4039   // Only custom-lower extensions from mask types
4040   assert(Src.getValueType().isVector() &&
4041          Src.getValueType().getVectorElementType() == MVT::i1);
4042 
4043   MVT XLenVT = Subtarget.getXLenVT();
4044   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4045   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4046 
4047   if (VecVT.isScalableVector()) {
4048     // Be careful not to introduce illegal scalar types at this stage, and be
4049     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4050     // illegal and must be expanded. Since we know that the constants are
4051     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4052     bool IsRV32E64 =
4053         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4054 
4055     if (!IsRV32E64) {
4056       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4057       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4058     } else {
4059       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4060       SplatTrueVal =
4061           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4062     }
4063 
4064     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4065   }
4066 
4067   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4068   MVT I1ContainerVT =
4069       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4070 
4071   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4072 
4073   SDValue Mask, VL;
4074   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4075 
4076   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4077   SplatTrueVal =
4078       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4079   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4080                                SplatTrueVal, SplatZero, VL);
4081 
4082   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4083 }
4084 
4085 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4086     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4087   MVT ExtVT = Op.getSimpleValueType();
4088   // Only custom-lower extensions from fixed-length vector types.
4089   if (!ExtVT.isFixedLengthVector())
4090     return Op;
4091   MVT VT = Op.getOperand(0).getSimpleValueType();
4092   // Grab the canonical container type for the extended type. Infer the smaller
4093   // type from that to ensure the same number of vector elements, as we know
4094   // the LMUL will be sufficient to hold the smaller type.
4095   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4096   // Get the extended container type manually to ensure the same number of
4097   // vector elements between source and dest.
4098   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4099                                      ContainerExtVT.getVectorElementCount());
4100 
4101   SDValue Op1 =
4102       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4103 
4104   SDLoc DL(Op);
4105   SDValue Mask, VL;
4106   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4107 
4108   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4109 
4110   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4111 }
4112 
4113 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4114 // setcc operation:
4115 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4116 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4117                                                   SelectionDAG &DAG) const {
4118   SDLoc DL(Op);
4119   EVT MaskVT = Op.getValueType();
4120   // Only expect to custom-lower truncations to mask types
4121   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4122          "Unexpected type for vector mask lowering");
4123   SDValue Src = Op.getOperand(0);
4124   MVT VecVT = Src.getSimpleValueType();
4125 
4126   // If this is a fixed vector, we need to convert it to a scalable vector.
4127   MVT ContainerVT = VecVT;
4128   if (VecVT.isFixedLengthVector()) {
4129     ContainerVT = getContainerForFixedLengthVector(VecVT);
4130     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4131   }
4132 
4133   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4134   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4135 
4136   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4137   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4138 
4139   if (VecVT.isScalableVector()) {
4140     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4141     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4142   }
4143 
4144   SDValue Mask, VL;
4145   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4146 
4147   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4148   SDValue Trunc =
4149       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4150   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4151                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4152   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4153 }
4154 
4155 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4156 // first position of a vector, and that vector is slid up to the insert index.
4157 // By limiting the active vector length to index+1 and merging with the
4158 // original vector (with an undisturbed tail policy for elements >= VL), we
4159 // achieve the desired result of leaving all elements untouched except the one
4160 // at VL-1, which is replaced with the desired value.
4161 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4162                                                     SelectionDAG &DAG) const {
4163   SDLoc DL(Op);
4164   MVT VecVT = Op.getSimpleValueType();
4165   SDValue Vec = Op.getOperand(0);
4166   SDValue Val = Op.getOperand(1);
4167   SDValue Idx = Op.getOperand(2);
4168 
4169   if (VecVT.getVectorElementType() == MVT::i1) {
4170     // FIXME: For now we just promote to an i8 vector and insert into that,
4171     // but this is probably not optimal.
4172     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4173     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4174     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4175     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4176   }
4177 
4178   MVT ContainerVT = VecVT;
4179   // If the operand is a fixed-length vector, convert to a scalable one.
4180   if (VecVT.isFixedLengthVector()) {
4181     ContainerVT = getContainerForFixedLengthVector(VecVT);
4182     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4183   }
4184 
4185   MVT XLenVT = Subtarget.getXLenVT();
4186 
4187   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4188   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4189   // Even i64-element vectors on RV32 can be lowered without scalar
4190   // legalization if the most-significant 32 bits of the value are not affected
4191   // by the sign-extension of the lower 32 bits.
4192   // TODO: We could also catch sign extensions of a 32-bit value.
4193   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4194     const auto *CVal = cast<ConstantSDNode>(Val);
4195     if (isInt<32>(CVal->getSExtValue())) {
4196       IsLegalInsert = true;
4197       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4198     }
4199   }
4200 
4201   SDValue Mask, VL;
4202   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4203 
4204   SDValue ValInVec;
4205 
4206   if (IsLegalInsert) {
4207     unsigned Opc =
4208         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4209     if (isNullConstant(Idx)) {
4210       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4211       if (!VecVT.isFixedLengthVector())
4212         return Vec;
4213       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4214     }
4215     ValInVec =
4216         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4217   } else {
4218     // On RV32, i64-element vectors must be specially handled to place the
4219     // value at element 0, by using two vslide1up instructions in sequence on
4220     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4221     // this.
4222     SDValue One = DAG.getConstant(1, DL, XLenVT);
4223     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4224     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4225     MVT I32ContainerVT =
4226         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4227     SDValue I32Mask =
4228         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4229     // Limit the active VL to two.
4230     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4231     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4232     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4233     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4234                            InsertI64VL);
4235     // First slide in the hi value, then the lo in underneath it.
4236     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4237                            ValHi, I32Mask, InsertI64VL);
4238     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4239                            ValLo, I32Mask, InsertI64VL);
4240     // Bitcast back to the right container type.
4241     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4242   }
4243 
4244   // Now that the value is in a vector, slide it into position.
4245   SDValue InsertVL =
4246       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4247   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4248                                 ValInVec, Idx, Mask, InsertVL);
4249   if (!VecVT.isFixedLengthVector())
4250     return Slideup;
4251   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4252 }
4253 
4254 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4255 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4256 // types this is done using VMV_X_S to allow us to glean information about the
4257 // sign bits of the result.
4258 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4259                                                      SelectionDAG &DAG) const {
4260   SDLoc DL(Op);
4261   SDValue Idx = Op.getOperand(1);
4262   SDValue Vec = Op.getOperand(0);
4263   EVT EltVT = Op.getValueType();
4264   MVT VecVT = Vec.getSimpleValueType();
4265   MVT XLenVT = Subtarget.getXLenVT();
4266 
4267   if (VecVT.getVectorElementType() == MVT::i1) {
4268     // FIXME: For now we just promote to an i8 vector and extract from that,
4269     // but this is probably not optimal.
4270     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4271     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4272     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4273   }
4274 
4275   // If this is a fixed vector, we need to convert it to a scalable vector.
4276   MVT ContainerVT = VecVT;
4277   if (VecVT.isFixedLengthVector()) {
4278     ContainerVT = getContainerForFixedLengthVector(VecVT);
4279     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4280   }
4281 
4282   // If the index is 0, the vector is already in the right position.
4283   if (!isNullConstant(Idx)) {
4284     // Use a VL of 1 to avoid processing more elements than we need.
4285     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4286     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4287     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4288     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4289                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4290   }
4291 
4292   if (!EltVT.isInteger()) {
4293     // Floating-point extracts are handled in TableGen.
4294     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4295                        DAG.getConstant(0, DL, XLenVT));
4296   }
4297 
4298   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4299   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4300 }
4301 
4302 // Some RVV intrinsics may claim that they want an integer operand to be
4303 // promoted or expanded.
4304 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4305                                           const RISCVSubtarget &Subtarget) {
4306   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4307           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4308          "Unexpected opcode");
4309 
4310   if (!Subtarget.hasVInstructions())
4311     return SDValue();
4312 
4313   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4314   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4315   SDLoc DL(Op);
4316 
4317   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4318       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4319   if (!II || !II->hasSplatOperand())
4320     return SDValue();
4321 
4322   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4323   assert(SplatOp < Op.getNumOperands());
4324 
4325   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4326   SDValue &ScalarOp = Operands[SplatOp];
4327   MVT OpVT = ScalarOp.getSimpleValueType();
4328   MVT XLenVT = Subtarget.getXLenVT();
4329 
4330   // If this isn't a scalar, or its type is XLenVT we're done.
4331   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4332     return SDValue();
4333 
4334   // Simplest case is that the operand needs to be promoted to XLenVT.
4335   if (OpVT.bitsLT(XLenVT)) {
4336     // If the operand is a constant, sign extend to increase our chances
4337     // of being able to use a .vi instruction. ANY_EXTEND would become a
4338     // a zero extend and the simm5 check in isel would fail.
4339     // FIXME: Should we ignore the upper bits in isel instead?
4340     unsigned ExtOpc =
4341         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4342     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4343     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4344   }
4345 
4346   // Use the previous operand to get the vXi64 VT. The result might be a mask
4347   // VT for compares. Using the previous operand assumes that the previous
4348   // operand will never have a smaller element size than a scalar operand and
4349   // that a widening operation never uses SEW=64.
4350   // NOTE: If this fails the below assert, we can probably just find the
4351   // element count from any operand or result and use it to construct the VT.
4352   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4353   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4354 
4355   // The more complex case is when the scalar is larger than XLenVT.
4356   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4357          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4358 
4359   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4360   // on the instruction to sign-extend since SEW>XLEN.
4361   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4362     if (isInt<32>(CVal->getSExtValue())) {
4363       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4364       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4365     }
4366   }
4367 
4368   // We need to convert the scalar to a splat vector.
4369   // FIXME: Can we implicitly truncate the scalar if it is known to
4370   // be sign extended?
4371   SDValue VL = Op.getOperand(II->VLOperand + 1 + HasChain);
4372   assert(VL.getValueType() == XLenVT);
4373   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4374   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4375 }
4376 
4377 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4378                                                      SelectionDAG &DAG) const {
4379   unsigned IntNo = Op.getConstantOperandVal(0);
4380   SDLoc DL(Op);
4381   MVT XLenVT = Subtarget.getXLenVT();
4382 
4383   switch (IntNo) {
4384   default:
4385     break; // Don't custom lower most intrinsics.
4386   case Intrinsic::thread_pointer: {
4387     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4388     return DAG.getRegister(RISCV::X4, PtrVT);
4389   }
4390   case Intrinsic::riscv_orc_b:
4391     // Lower to the GORCI encoding for orc.b.
4392     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4393                        DAG.getConstant(7, DL, XLenVT));
4394   case Intrinsic::riscv_grev:
4395   case Intrinsic::riscv_gorc: {
4396     unsigned Opc =
4397         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4398     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4399   }
4400   case Intrinsic::riscv_shfl:
4401   case Intrinsic::riscv_unshfl: {
4402     unsigned Opc =
4403         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4404     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4405   }
4406   case Intrinsic::riscv_bcompress:
4407   case Intrinsic::riscv_bdecompress: {
4408     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4409                                                        : RISCVISD::BDECOMPRESS;
4410     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4411   }
4412   case Intrinsic::riscv_bfp:
4413     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4414                        Op.getOperand(2));
4415   case Intrinsic::riscv_fsl:
4416     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4417                        Op.getOperand(2), Op.getOperand(3));
4418   case Intrinsic::riscv_fsr:
4419     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4420                        Op.getOperand(2), Op.getOperand(3));
4421   case Intrinsic::riscv_vmv_x_s:
4422     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4423     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4424                        Op.getOperand(1));
4425   case Intrinsic::riscv_vmv_v_x:
4426     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4427                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4428   case Intrinsic::riscv_vfmv_v_f:
4429     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4430                        Op.getOperand(1), Op.getOperand(2));
4431   case Intrinsic::riscv_vmv_s_x: {
4432     SDValue Scalar = Op.getOperand(2);
4433 
4434     if (Scalar.getValueType().bitsLE(XLenVT)) {
4435       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4436       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4437                          Op.getOperand(1), Scalar, Op.getOperand(3));
4438     }
4439 
4440     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4441 
4442     // This is an i64 value that lives in two scalar registers. We have to
4443     // insert this in a convoluted way. First we build vXi64 splat containing
4444     // the/ two values that we assemble using some bit math. Next we'll use
4445     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4446     // to merge element 0 from our splat into the source vector.
4447     // FIXME: This is probably not the best way to do this, but it is
4448     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4449     // point.
4450     //   sw lo, (a0)
4451     //   sw hi, 4(a0)
4452     //   vlse vX, (a0)
4453     //
4454     //   vid.v      vVid
4455     //   vmseq.vx   mMask, vVid, 0
4456     //   vmerge.vvm vDest, vSrc, vVal, mMask
4457     MVT VT = Op.getSimpleValueType();
4458     SDValue Vec = Op.getOperand(1);
4459     SDValue VL = Op.getOperand(3);
4460 
4461     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4462     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4463                                       DAG.getConstant(0, DL, MVT::i32), VL);
4464 
4465     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4466     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4467     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4468     SDValue SelectCond =
4469         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4470                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4471     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4472                        Vec, VL);
4473   }
4474   case Intrinsic::riscv_vslide1up:
4475   case Intrinsic::riscv_vslide1down:
4476   case Intrinsic::riscv_vslide1up_mask:
4477   case Intrinsic::riscv_vslide1down_mask: {
4478     // We need to special case these when the scalar is larger than XLen.
4479     unsigned NumOps = Op.getNumOperands();
4480     bool IsMasked = NumOps == 7;
4481     unsigned OpOffset = IsMasked ? 1 : 0;
4482     SDValue Scalar = Op.getOperand(2 + OpOffset);
4483     if (Scalar.getValueType().bitsLE(XLenVT))
4484       break;
4485 
4486     // Splatting a sign extended constant is fine.
4487     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4488       if (isInt<32>(CVal->getSExtValue()))
4489         break;
4490 
4491     MVT VT = Op.getSimpleValueType();
4492     assert(VT.getVectorElementType() == MVT::i64 &&
4493            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4494 
4495     // Convert the vector source to the equivalent nxvXi32 vector.
4496     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4497     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4498 
4499     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4500                                    DAG.getConstant(0, DL, XLenVT));
4501     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4502                                    DAG.getConstant(1, DL, XLenVT));
4503 
4504     // Double the VL since we halved SEW.
4505     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4506     SDValue I32VL =
4507         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4508 
4509     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4510     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4511 
4512     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4513     // instructions.
4514     if (IntNo == Intrinsic::riscv_vslide1up ||
4515         IntNo == Intrinsic::riscv_vslide1up_mask) {
4516       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4517                         I32Mask, I32VL);
4518       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4519                         I32Mask, I32VL);
4520     } else {
4521       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4522                         I32Mask, I32VL);
4523       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4524                         I32Mask, I32VL);
4525     }
4526 
4527     // Convert back to nxvXi64.
4528     Vec = DAG.getBitcast(VT, Vec);
4529 
4530     if (!IsMasked)
4531       return Vec;
4532 
4533     // Apply mask after the operation.
4534     SDValue Mask = Op.getOperand(NumOps - 3);
4535     SDValue MaskedOff = Op.getOperand(1);
4536     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4537   }
4538   }
4539 
4540   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4541 }
4542 
4543 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4544                                                     SelectionDAG &DAG) const {
4545   unsigned IntNo = Op.getConstantOperandVal(1);
4546   switch (IntNo) {
4547   default:
4548     break;
4549   case Intrinsic::riscv_masked_strided_load: {
4550     SDLoc DL(Op);
4551     MVT XLenVT = Subtarget.getXLenVT();
4552 
4553     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4554     // the selection of the masked intrinsics doesn't do this for us.
4555     SDValue Mask = Op.getOperand(5);
4556     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4557 
4558     MVT VT = Op->getSimpleValueType(0);
4559     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4560 
4561     SDValue PassThru = Op.getOperand(2);
4562     if (!IsUnmasked) {
4563       MVT MaskVT =
4564           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4565       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4566       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4567     }
4568 
4569     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4570 
4571     SDValue IntID = DAG.getTargetConstant(
4572         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4573         XLenVT);
4574 
4575     auto *Load = cast<MemIntrinsicSDNode>(Op);
4576     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4577     if (!IsUnmasked)
4578       Ops.push_back(PassThru);
4579     Ops.push_back(Op.getOperand(3)); // Ptr
4580     Ops.push_back(Op.getOperand(4)); // Stride
4581     if (!IsUnmasked)
4582       Ops.push_back(Mask);
4583     Ops.push_back(VL);
4584     if (!IsUnmasked) {
4585       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4586       Ops.push_back(Policy);
4587     }
4588 
4589     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4590     SDValue Result =
4591         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4592                                 Load->getMemoryVT(), Load->getMemOperand());
4593     SDValue Chain = Result.getValue(1);
4594     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4595     return DAG.getMergeValues({Result, Chain}, DL);
4596   }
4597   }
4598 
4599   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4600 }
4601 
4602 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4603                                                  SelectionDAG &DAG) const {
4604   unsigned IntNo = Op.getConstantOperandVal(1);
4605   switch (IntNo) {
4606   default:
4607     break;
4608   case Intrinsic::riscv_masked_strided_store: {
4609     SDLoc DL(Op);
4610     MVT XLenVT = Subtarget.getXLenVT();
4611 
4612     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4613     // the selection of the masked intrinsics doesn't do this for us.
4614     SDValue Mask = Op.getOperand(5);
4615     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4616 
4617     SDValue Val = Op.getOperand(2);
4618     MVT VT = Val.getSimpleValueType();
4619     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4620 
4621     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4622     if (!IsUnmasked) {
4623       MVT MaskVT =
4624           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4625       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4626     }
4627 
4628     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4629 
4630     SDValue IntID = DAG.getTargetConstant(
4631         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4632         XLenVT);
4633 
4634     auto *Store = cast<MemIntrinsicSDNode>(Op);
4635     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4636     Ops.push_back(Val);
4637     Ops.push_back(Op.getOperand(3)); // Ptr
4638     Ops.push_back(Op.getOperand(4)); // Stride
4639     if (!IsUnmasked)
4640       Ops.push_back(Mask);
4641     Ops.push_back(VL);
4642 
4643     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4644                                    Ops, Store->getMemoryVT(),
4645                                    Store->getMemOperand());
4646   }
4647   }
4648 
4649   return SDValue();
4650 }
4651 
4652 static MVT getLMUL1VT(MVT VT) {
4653   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4654          "Unexpected vector MVT");
4655   return MVT::getScalableVectorVT(
4656       VT.getVectorElementType(),
4657       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4658 }
4659 
4660 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4661   switch (ISDOpcode) {
4662   default:
4663     llvm_unreachable("Unhandled reduction");
4664   case ISD::VECREDUCE_ADD:
4665     return RISCVISD::VECREDUCE_ADD_VL;
4666   case ISD::VECREDUCE_UMAX:
4667     return RISCVISD::VECREDUCE_UMAX_VL;
4668   case ISD::VECREDUCE_SMAX:
4669     return RISCVISD::VECREDUCE_SMAX_VL;
4670   case ISD::VECREDUCE_UMIN:
4671     return RISCVISD::VECREDUCE_UMIN_VL;
4672   case ISD::VECREDUCE_SMIN:
4673     return RISCVISD::VECREDUCE_SMIN_VL;
4674   case ISD::VECREDUCE_AND:
4675     return RISCVISD::VECREDUCE_AND_VL;
4676   case ISD::VECREDUCE_OR:
4677     return RISCVISD::VECREDUCE_OR_VL;
4678   case ISD::VECREDUCE_XOR:
4679     return RISCVISD::VECREDUCE_XOR_VL;
4680   }
4681 }
4682 
4683 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4684                                                          SelectionDAG &DAG,
4685                                                          bool IsVP) const {
4686   SDLoc DL(Op);
4687   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4688   MVT VecVT = Vec.getSimpleValueType();
4689   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4690           Op.getOpcode() == ISD::VECREDUCE_OR ||
4691           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4692           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4693           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4694           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4695          "Unexpected reduction lowering");
4696 
4697   MVT XLenVT = Subtarget.getXLenVT();
4698   assert(Op.getValueType() == XLenVT &&
4699          "Expected reduction output to be legalized to XLenVT");
4700 
4701   MVT ContainerVT = VecVT;
4702   if (VecVT.isFixedLengthVector()) {
4703     ContainerVT = getContainerForFixedLengthVector(VecVT);
4704     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4705   }
4706 
4707   SDValue Mask, VL;
4708   if (IsVP) {
4709     Mask = Op.getOperand(2);
4710     VL = Op.getOperand(3);
4711   } else {
4712     std::tie(Mask, VL) =
4713         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4714   }
4715 
4716   unsigned BaseOpc;
4717   ISD::CondCode CC;
4718   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4719 
4720   switch (Op.getOpcode()) {
4721   default:
4722     llvm_unreachable("Unhandled reduction");
4723   case ISD::VECREDUCE_AND:
4724   case ISD::VP_REDUCE_AND: {
4725     // vcpop ~x == 0
4726     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4727     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4728     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4729     CC = ISD::SETEQ;
4730     BaseOpc = ISD::AND;
4731     break;
4732   }
4733   case ISD::VECREDUCE_OR:
4734   case ISD::VP_REDUCE_OR:
4735     // vcpop x != 0
4736     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4737     CC = ISD::SETNE;
4738     BaseOpc = ISD::OR;
4739     break;
4740   case ISD::VECREDUCE_XOR:
4741   case ISD::VP_REDUCE_XOR: {
4742     // ((vcpop x) & 1) != 0
4743     SDValue One = DAG.getConstant(1, DL, XLenVT);
4744     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4745     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4746     CC = ISD::SETNE;
4747     BaseOpc = ISD::XOR;
4748     break;
4749   }
4750   }
4751 
4752   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4753 
4754   if (!IsVP)
4755     return SetCC;
4756 
4757   // Now include the start value in the operation.
4758   // Note that we must return the start value when no elements are operated
4759   // upon. The vcpop instructions we've emitted in each case above will return
4760   // 0 for an inactive vector, and so we've already received the neutral value:
4761   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4762   // can simply include the start value.
4763   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4764 }
4765 
4766 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4767                                             SelectionDAG &DAG) const {
4768   SDLoc DL(Op);
4769   SDValue Vec = Op.getOperand(0);
4770   EVT VecEVT = Vec.getValueType();
4771 
4772   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4773 
4774   // Due to ordering in legalize types we may have a vector type that needs to
4775   // be split. Do that manually so we can get down to a legal type.
4776   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4777          TargetLowering::TypeSplitVector) {
4778     SDValue Lo, Hi;
4779     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4780     VecEVT = Lo.getValueType();
4781     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4782   }
4783 
4784   // TODO: The type may need to be widened rather than split. Or widened before
4785   // it can be split.
4786   if (!isTypeLegal(VecEVT))
4787     return SDValue();
4788 
4789   MVT VecVT = VecEVT.getSimpleVT();
4790   MVT VecEltVT = VecVT.getVectorElementType();
4791   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4792 
4793   MVT ContainerVT = VecVT;
4794   if (VecVT.isFixedLengthVector()) {
4795     ContainerVT = getContainerForFixedLengthVector(VecVT);
4796     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4797   }
4798 
4799   MVT M1VT = getLMUL1VT(ContainerVT);
4800   MVT XLenVT = Subtarget.getXLenVT();
4801 
4802   SDValue Mask, VL;
4803   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4804 
4805   SDValue NeutralElem =
4806       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4807   SDValue IdentitySplat = lowerScalarSplat(
4808       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4809   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4810                                   IdentitySplat, Mask, VL);
4811   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4812                              DAG.getConstant(0, DL, XLenVT));
4813   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4814 }
4815 
4816 // Given a reduction op, this function returns the matching reduction opcode,
4817 // the vector SDValue and the scalar SDValue required to lower this to a
4818 // RISCVISD node.
4819 static std::tuple<unsigned, SDValue, SDValue>
4820 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4821   SDLoc DL(Op);
4822   auto Flags = Op->getFlags();
4823   unsigned Opcode = Op.getOpcode();
4824   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4825   switch (Opcode) {
4826   default:
4827     llvm_unreachable("Unhandled reduction");
4828   case ISD::VECREDUCE_FADD: {
4829     // Use positive zero if we can. It is cheaper to materialize.
4830     SDValue Zero =
4831         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4832     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4833   }
4834   case ISD::VECREDUCE_SEQ_FADD:
4835     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4836                            Op.getOperand(0));
4837   case ISD::VECREDUCE_FMIN:
4838     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4839                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4840   case ISD::VECREDUCE_FMAX:
4841     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4842                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4843   }
4844 }
4845 
4846 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4847                                               SelectionDAG &DAG) const {
4848   SDLoc DL(Op);
4849   MVT VecEltVT = Op.getSimpleValueType();
4850 
4851   unsigned RVVOpcode;
4852   SDValue VectorVal, ScalarVal;
4853   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4854       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4855   MVT VecVT = VectorVal.getSimpleValueType();
4856 
4857   MVT ContainerVT = VecVT;
4858   if (VecVT.isFixedLengthVector()) {
4859     ContainerVT = getContainerForFixedLengthVector(VecVT);
4860     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4861   }
4862 
4863   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4864   MVT XLenVT = Subtarget.getXLenVT();
4865 
4866   SDValue Mask, VL;
4867   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4868 
4869   SDValue ScalarSplat = lowerScalarSplat(
4870       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4871   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4872                                   VectorVal, ScalarSplat, Mask, VL);
4873   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4874                      DAG.getConstant(0, DL, XLenVT));
4875 }
4876 
4877 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4878   switch (ISDOpcode) {
4879   default:
4880     llvm_unreachable("Unhandled reduction");
4881   case ISD::VP_REDUCE_ADD:
4882     return RISCVISD::VECREDUCE_ADD_VL;
4883   case ISD::VP_REDUCE_UMAX:
4884     return RISCVISD::VECREDUCE_UMAX_VL;
4885   case ISD::VP_REDUCE_SMAX:
4886     return RISCVISD::VECREDUCE_SMAX_VL;
4887   case ISD::VP_REDUCE_UMIN:
4888     return RISCVISD::VECREDUCE_UMIN_VL;
4889   case ISD::VP_REDUCE_SMIN:
4890     return RISCVISD::VECREDUCE_SMIN_VL;
4891   case ISD::VP_REDUCE_AND:
4892     return RISCVISD::VECREDUCE_AND_VL;
4893   case ISD::VP_REDUCE_OR:
4894     return RISCVISD::VECREDUCE_OR_VL;
4895   case ISD::VP_REDUCE_XOR:
4896     return RISCVISD::VECREDUCE_XOR_VL;
4897   case ISD::VP_REDUCE_FADD:
4898     return RISCVISD::VECREDUCE_FADD_VL;
4899   case ISD::VP_REDUCE_SEQ_FADD:
4900     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4901   case ISD::VP_REDUCE_FMAX:
4902     return RISCVISD::VECREDUCE_FMAX_VL;
4903   case ISD::VP_REDUCE_FMIN:
4904     return RISCVISD::VECREDUCE_FMIN_VL;
4905   }
4906 }
4907 
4908 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4909                                            SelectionDAG &DAG) const {
4910   SDLoc DL(Op);
4911   SDValue Vec = Op.getOperand(1);
4912   EVT VecEVT = Vec.getValueType();
4913 
4914   // TODO: The type may need to be widened rather than split. Or widened before
4915   // it can be split.
4916   if (!isTypeLegal(VecEVT))
4917     return SDValue();
4918 
4919   MVT VecVT = VecEVT.getSimpleVT();
4920   MVT VecEltVT = VecVT.getVectorElementType();
4921   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4922 
4923   MVT ContainerVT = VecVT;
4924   if (VecVT.isFixedLengthVector()) {
4925     ContainerVT = getContainerForFixedLengthVector(VecVT);
4926     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4927   }
4928 
4929   SDValue VL = Op.getOperand(3);
4930   SDValue Mask = Op.getOperand(2);
4931 
4932   MVT M1VT = getLMUL1VT(ContainerVT);
4933   MVT XLenVT = Subtarget.getXLenVT();
4934   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4935 
4936   SDValue StartSplat =
4937       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4938                        DL, DAG, Subtarget);
4939   SDValue Reduction =
4940       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4941   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4942                              DAG.getConstant(0, DL, XLenVT));
4943   if (!VecVT.isInteger())
4944     return Elt0;
4945   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4946 }
4947 
4948 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4949                                                    SelectionDAG &DAG) const {
4950   SDValue Vec = Op.getOperand(0);
4951   SDValue SubVec = Op.getOperand(1);
4952   MVT VecVT = Vec.getSimpleValueType();
4953   MVT SubVecVT = SubVec.getSimpleValueType();
4954 
4955   SDLoc DL(Op);
4956   MVT XLenVT = Subtarget.getXLenVT();
4957   unsigned OrigIdx = Op.getConstantOperandVal(2);
4958   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4959 
4960   // We don't have the ability to slide mask vectors up indexed by their i1
4961   // elements; the smallest we can do is i8. Often we are able to bitcast to
4962   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4963   // into a scalable one, we might not necessarily have enough scalable
4964   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4965   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4966       (OrigIdx != 0 || !Vec.isUndef())) {
4967     if (VecVT.getVectorMinNumElements() >= 8 &&
4968         SubVecVT.getVectorMinNumElements() >= 8) {
4969       assert(OrigIdx % 8 == 0 && "Invalid index");
4970       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4971              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4972              "Unexpected mask vector lowering");
4973       OrigIdx /= 8;
4974       SubVecVT =
4975           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4976                            SubVecVT.isScalableVector());
4977       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4978                                VecVT.isScalableVector());
4979       Vec = DAG.getBitcast(VecVT, Vec);
4980       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4981     } else {
4982       // We can't slide this mask vector up indexed by its i1 elements.
4983       // This poses a problem when we wish to insert a scalable vector which
4984       // can't be re-expressed as a larger type. Just choose the slow path and
4985       // extend to a larger type, then truncate back down.
4986       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4987       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4988       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4989       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4990       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4991                         Op.getOperand(2));
4992       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4993       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4994     }
4995   }
4996 
4997   // If the subvector vector is a fixed-length type, we cannot use subregister
4998   // manipulation to simplify the codegen; we don't know which register of a
4999   // LMUL group contains the specific subvector as we only know the minimum
5000   // register size. Therefore we must slide the vector group up the full
5001   // amount.
5002   if (SubVecVT.isFixedLengthVector()) {
5003     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5004       return Op;
5005     MVT ContainerVT = VecVT;
5006     if (VecVT.isFixedLengthVector()) {
5007       ContainerVT = getContainerForFixedLengthVector(VecVT);
5008       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5009     }
5010     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5011                          DAG.getUNDEF(ContainerVT), SubVec,
5012                          DAG.getConstant(0, DL, XLenVT));
5013     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5014       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5015       return DAG.getBitcast(Op.getValueType(), SubVec);
5016     }
5017     SDValue Mask =
5018         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5019     // Set the vector length to only the number of elements we care about. Note
5020     // that for slideup this includes the offset.
5021     SDValue VL =
5022         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5023     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5024     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5025                                   SubVec, SlideupAmt, Mask, VL);
5026     if (VecVT.isFixedLengthVector())
5027       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5028     return DAG.getBitcast(Op.getValueType(), Slideup);
5029   }
5030 
5031   unsigned SubRegIdx, RemIdx;
5032   std::tie(SubRegIdx, RemIdx) =
5033       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5034           VecVT, SubVecVT, OrigIdx, TRI);
5035 
5036   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5037   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5038                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5039                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5040 
5041   // 1. If the Idx has been completely eliminated and this subvector's size is
5042   // a vector register or a multiple thereof, or the surrounding elements are
5043   // undef, then this is a subvector insert which naturally aligns to a vector
5044   // register. These can easily be handled using subregister manipulation.
5045   // 2. If the subvector is smaller than a vector register, then the insertion
5046   // must preserve the undisturbed elements of the register. We do this by
5047   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5048   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5049   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5050   // LMUL=1 type back into the larger vector (resolving to another subregister
5051   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5052   // to avoid allocating a large register group to hold our subvector.
5053   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5054     return Op;
5055 
5056   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5057   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5058   // (in our case undisturbed). This means we can set up a subvector insertion
5059   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5060   // size of the subvector.
5061   MVT InterSubVT = VecVT;
5062   SDValue AlignedExtract = Vec;
5063   unsigned AlignedIdx = OrigIdx - RemIdx;
5064   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5065     InterSubVT = getLMUL1VT(VecVT);
5066     // Extract a subvector equal to the nearest full vector register type. This
5067     // should resolve to a EXTRACT_SUBREG instruction.
5068     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5069                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5070   }
5071 
5072   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5073   // For scalable vectors this must be further multiplied by vscale.
5074   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5075 
5076   SDValue Mask, VL;
5077   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5078 
5079   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5080   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5081   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5082   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5083 
5084   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5085                        DAG.getUNDEF(InterSubVT), SubVec,
5086                        DAG.getConstant(0, DL, XLenVT));
5087 
5088   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5089                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5090 
5091   // If required, insert this subvector back into the correct vector register.
5092   // This should resolve to an INSERT_SUBREG instruction.
5093   if (VecVT.bitsGT(InterSubVT))
5094     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5095                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5096 
5097   // We might have bitcast from a mask type: cast back to the original type if
5098   // required.
5099   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5100 }
5101 
5102 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5103                                                     SelectionDAG &DAG) const {
5104   SDValue Vec = Op.getOperand(0);
5105   MVT SubVecVT = Op.getSimpleValueType();
5106   MVT VecVT = Vec.getSimpleValueType();
5107 
5108   SDLoc DL(Op);
5109   MVT XLenVT = Subtarget.getXLenVT();
5110   unsigned OrigIdx = Op.getConstantOperandVal(1);
5111   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5112 
5113   // We don't have the ability to slide mask vectors down indexed by their i1
5114   // elements; the smallest we can do is i8. Often we are able to bitcast to
5115   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5116   // from a scalable one, we might not necessarily have enough scalable
5117   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5118   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5119     if (VecVT.getVectorMinNumElements() >= 8 &&
5120         SubVecVT.getVectorMinNumElements() >= 8) {
5121       assert(OrigIdx % 8 == 0 && "Invalid index");
5122       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5123              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5124              "Unexpected mask vector lowering");
5125       OrigIdx /= 8;
5126       SubVecVT =
5127           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5128                            SubVecVT.isScalableVector());
5129       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5130                                VecVT.isScalableVector());
5131       Vec = DAG.getBitcast(VecVT, Vec);
5132     } else {
5133       // We can't slide this mask vector down, indexed by its i1 elements.
5134       // This poses a problem when we wish to extract a scalable vector which
5135       // can't be re-expressed as a larger type. Just choose the slow path and
5136       // extend to a larger type, then truncate back down.
5137       // TODO: We could probably improve this when extracting certain fixed
5138       // from fixed, where we can extract as i8 and shift the correct element
5139       // right to reach the desired subvector?
5140       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5141       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5142       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5143       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5144                         Op.getOperand(1));
5145       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5146       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5147     }
5148   }
5149 
5150   // If the subvector vector is a fixed-length type, we cannot use subregister
5151   // manipulation to simplify the codegen; we don't know which register of a
5152   // LMUL group contains the specific subvector as we only know the minimum
5153   // register size. Therefore we must slide the vector group down the full
5154   // amount.
5155   if (SubVecVT.isFixedLengthVector()) {
5156     // With an index of 0 this is a cast-like subvector, which can be performed
5157     // with subregister operations.
5158     if (OrigIdx == 0)
5159       return Op;
5160     MVT ContainerVT = VecVT;
5161     if (VecVT.isFixedLengthVector()) {
5162       ContainerVT = getContainerForFixedLengthVector(VecVT);
5163       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5164     }
5165     SDValue Mask =
5166         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5167     // Set the vector length to only the number of elements we care about. This
5168     // avoids sliding down elements we're going to discard straight away.
5169     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5170     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5171     SDValue Slidedown =
5172         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5173                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5174     // Now we can use a cast-like subvector extract to get the result.
5175     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5176                             DAG.getConstant(0, DL, XLenVT));
5177     return DAG.getBitcast(Op.getValueType(), Slidedown);
5178   }
5179 
5180   unsigned SubRegIdx, RemIdx;
5181   std::tie(SubRegIdx, RemIdx) =
5182       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5183           VecVT, SubVecVT, OrigIdx, TRI);
5184 
5185   // If the Idx has been completely eliminated then this is a subvector extract
5186   // which naturally aligns to a vector register. These can easily be handled
5187   // using subregister manipulation.
5188   if (RemIdx == 0)
5189     return Op;
5190 
5191   // Else we must shift our vector register directly to extract the subvector.
5192   // Do this using VSLIDEDOWN.
5193 
5194   // If the vector type is an LMUL-group type, extract a subvector equal to the
5195   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5196   // instruction.
5197   MVT InterSubVT = VecVT;
5198   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5199     InterSubVT = getLMUL1VT(VecVT);
5200     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5201                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5202   }
5203 
5204   // Slide this vector register down by the desired number of elements in order
5205   // to place the desired subvector starting at element 0.
5206   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5207   // For scalable vectors this must be further multiplied by vscale.
5208   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5209 
5210   SDValue Mask, VL;
5211   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5212   SDValue Slidedown =
5213       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5214                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5215 
5216   // Now the vector is in the right position, extract our final subvector. This
5217   // should resolve to a COPY.
5218   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5219                           DAG.getConstant(0, DL, XLenVT));
5220 
5221   // We might have bitcast from a mask type: cast back to the original type if
5222   // required.
5223   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5224 }
5225 
5226 // Lower step_vector to the vid instruction. Any non-identity step value must
5227 // be accounted for my manual expansion.
5228 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5229                                               SelectionDAG &DAG) const {
5230   SDLoc DL(Op);
5231   MVT VT = Op.getSimpleValueType();
5232   MVT XLenVT = Subtarget.getXLenVT();
5233   SDValue Mask, VL;
5234   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5235   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5236   uint64_t StepValImm = Op.getConstantOperandVal(0);
5237   if (StepValImm != 1) {
5238     if (isPowerOf2_64(StepValImm)) {
5239       SDValue StepVal =
5240           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5241                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5242       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5243     } else {
5244       SDValue StepVal = lowerScalarSplat(
5245           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5246           DL, DAG, Subtarget);
5247       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5248     }
5249   }
5250   return StepVec;
5251 }
5252 
5253 // Implement vector_reverse using vrgather.vv with indices determined by
5254 // subtracting the id of each element from (VLMAX-1). This will convert
5255 // the indices like so:
5256 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5257 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5258 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5259                                                  SelectionDAG &DAG) const {
5260   SDLoc DL(Op);
5261   MVT VecVT = Op.getSimpleValueType();
5262   unsigned EltSize = VecVT.getScalarSizeInBits();
5263   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5264 
5265   unsigned MaxVLMAX = 0;
5266   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5267   if (VectorBitsMax != 0)
5268     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5269 
5270   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5271   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5272 
5273   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5274   // to use vrgatherei16.vv.
5275   // TODO: It's also possible to use vrgatherei16.vv for other types to
5276   // decrease register width for the index calculation.
5277   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5278     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5279     // Reverse each half, then reassemble them in reverse order.
5280     // NOTE: It's also possible that after splitting that VLMAX no longer
5281     // requires vrgatherei16.vv.
5282     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5283       SDValue Lo, Hi;
5284       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5285       EVT LoVT, HiVT;
5286       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5287       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5288       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5289       // Reassemble the low and high pieces reversed.
5290       // FIXME: This is a CONCAT_VECTORS.
5291       SDValue Res =
5292           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5293                       DAG.getIntPtrConstant(0, DL));
5294       return DAG.getNode(
5295           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5296           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5297     }
5298 
5299     // Just promote the int type to i16 which will double the LMUL.
5300     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5301     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5302   }
5303 
5304   MVT XLenVT = Subtarget.getXLenVT();
5305   SDValue Mask, VL;
5306   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5307 
5308   // Calculate VLMAX-1 for the desired SEW.
5309   unsigned MinElts = VecVT.getVectorMinNumElements();
5310   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5311                               DAG.getConstant(MinElts, DL, XLenVT));
5312   SDValue VLMinus1 =
5313       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5314 
5315   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5316   bool IsRV32E64 =
5317       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5318   SDValue SplatVL;
5319   if (!IsRV32E64)
5320     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5321   else
5322     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5323 
5324   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5325   SDValue Indices =
5326       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5327 
5328   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5329 }
5330 
5331 SDValue
5332 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5333                                                      SelectionDAG &DAG) const {
5334   SDLoc DL(Op);
5335   auto *Load = cast<LoadSDNode>(Op);
5336 
5337   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5338                                         Load->getMemoryVT(),
5339                                         *Load->getMemOperand()) &&
5340          "Expecting a correctly-aligned load");
5341 
5342   MVT VT = Op.getSimpleValueType();
5343   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5344 
5345   SDValue VL =
5346       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5347 
5348   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5349   SDValue NewLoad = DAG.getMemIntrinsicNode(
5350       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5351       Load->getMemoryVT(), Load->getMemOperand());
5352 
5353   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5354   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5355 }
5356 
5357 SDValue
5358 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5359                                                       SelectionDAG &DAG) const {
5360   SDLoc DL(Op);
5361   auto *Store = cast<StoreSDNode>(Op);
5362 
5363   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5364                                         Store->getMemoryVT(),
5365                                         *Store->getMemOperand()) &&
5366          "Expecting a correctly-aligned store");
5367 
5368   SDValue StoreVal = Store->getValue();
5369   MVT VT = StoreVal.getSimpleValueType();
5370 
5371   // If the size less than a byte, we need to pad with zeros to make a byte.
5372   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5373     VT = MVT::v8i1;
5374     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5375                            DAG.getConstant(0, DL, VT), StoreVal,
5376                            DAG.getIntPtrConstant(0, DL));
5377   }
5378 
5379   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5380 
5381   SDValue VL =
5382       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5383 
5384   SDValue NewValue =
5385       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5386   return DAG.getMemIntrinsicNode(
5387       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5388       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5389       Store->getMemoryVT(), Store->getMemOperand());
5390 }
5391 
5392 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5393                                              SelectionDAG &DAG) const {
5394   SDLoc DL(Op);
5395   MVT VT = Op.getSimpleValueType();
5396 
5397   const auto *MemSD = cast<MemSDNode>(Op);
5398   EVT MemVT = MemSD->getMemoryVT();
5399   MachineMemOperand *MMO = MemSD->getMemOperand();
5400   SDValue Chain = MemSD->getChain();
5401   SDValue BasePtr = MemSD->getBasePtr();
5402 
5403   SDValue Mask, PassThru, VL;
5404   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5405     Mask = VPLoad->getMask();
5406     PassThru = DAG.getUNDEF(VT);
5407     VL = VPLoad->getVectorLength();
5408   } else {
5409     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5410     Mask = MLoad->getMask();
5411     PassThru = MLoad->getPassThru();
5412   }
5413 
5414   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5415 
5416   MVT XLenVT = Subtarget.getXLenVT();
5417 
5418   MVT ContainerVT = VT;
5419   if (VT.isFixedLengthVector()) {
5420     ContainerVT = getContainerForFixedLengthVector(VT);
5421     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5422     if (!IsUnmasked) {
5423       MVT MaskVT =
5424           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5425       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5426     }
5427   }
5428 
5429   if (!VL)
5430     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5431 
5432   unsigned IntID =
5433       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5434   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5435   if (!IsUnmasked)
5436     Ops.push_back(PassThru);
5437   Ops.push_back(BasePtr);
5438   if (!IsUnmasked)
5439     Ops.push_back(Mask);
5440   Ops.push_back(VL);
5441   if (!IsUnmasked)
5442     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5443 
5444   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5445 
5446   SDValue Result =
5447       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5448   Chain = Result.getValue(1);
5449 
5450   if (VT.isFixedLengthVector())
5451     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5452 
5453   return DAG.getMergeValues({Result, Chain}, DL);
5454 }
5455 
5456 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5457                                               SelectionDAG &DAG) const {
5458   SDLoc DL(Op);
5459 
5460   const auto *MemSD = cast<MemSDNode>(Op);
5461   EVT MemVT = MemSD->getMemoryVT();
5462   MachineMemOperand *MMO = MemSD->getMemOperand();
5463   SDValue Chain = MemSD->getChain();
5464   SDValue BasePtr = MemSD->getBasePtr();
5465   SDValue Val, Mask, VL;
5466 
5467   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5468     Val = VPStore->getValue();
5469     Mask = VPStore->getMask();
5470     VL = VPStore->getVectorLength();
5471   } else {
5472     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5473     Val = MStore->getValue();
5474     Mask = MStore->getMask();
5475   }
5476 
5477   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5478 
5479   MVT VT = Val.getSimpleValueType();
5480   MVT XLenVT = Subtarget.getXLenVT();
5481 
5482   MVT ContainerVT = VT;
5483   if (VT.isFixedLengthVector()) {
5484     ContainerVT = getContainerForFixedLengthVector(VT);
5485 
5486     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5487     if (!IsUnmasked) {
5488       MVT MaskVT =
5489           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5490       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5491     }
5492   }
5493 
5494   if (!VL)
5495     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5496 
5497   unsigned IntID =
5498       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5499   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5500   Ops.push_back(Val);
5501   Ops.push_back(BasePtr);
5502   if (!IsUnmasked)
5503     Ops.push_back(Mask);
5504   Ops.push_back(VL);
5505 
5506   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5507                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5508 }
5509 
5510 SDValue
5511 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5512                                                       SelectionDAG &DAG) const {
5513   MVT InVT = Op.getOperand(0).getSimpleValueType();
5514   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5515 
5516   MVT VT = Op.getSimpleValueType();
5517 
5518   SDValue Op1 =
5519       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5520   SDValue Op2 =
5521       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5522 
5523   SDLoc DL(Op);
5524   SDValue VL =
5525       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5526 
5527   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5528   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5529 
5530   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5531                             Op.getOperand(2), Mask, VL);
5532 
5533   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5534 }
5535 
5536 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5537     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5538   MVT VT = Op.getSimpleValueType();
5539 
5540   if (VT.getVectorElementType() == MVT::i1)
5541     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5542 
5543   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5544 }
5545 
5546 SDValue
5547 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5548                                                       SelectionDAG &DAG) const {
5549   unsigned Opc;
5550   switch (Op.getOpcode()) {
5551   default: llvm_unreachable("Unexpected opcode!");
5552   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5553   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5554   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5555   }
5556 
5557   return lowerToScalableOp(Op, DAG, Opc);
5558 }
5559 
5560 // Lower vector ABS to smax(X, sub(0, X)).
5561 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5562   SDLoc DL(Op);
5563   MVT VT = Op.getSimpleValueType();
5564   SDValue X = Op.getOperand(0);
5565 
5566   assert(VT.isFixedLengthVector() && "Unexpected type");
5567 
5568   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5569   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5570 
5571   SDValue Mask, VL;
5572   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5573 
5574   SDValue SplatZero =
5575       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5576                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5577   SDValue NegX =
5578       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5579   SDValue Max =
5580       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5581 
5582   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5583 }
5584 
5585 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5586     SDValue Op, SelectionDAG &DAG) const {
5587   SDLoc DL(Op);
5588   MVT VT = Op.getSimpleValueType();
5589   SDValue Mag = Op.getOperand(0);
5590   SDValue Sign = Op.getOperand(1);
5591   assert(Mag.getValueType() == Sign.getValueType() &&
5592          "Can only handle COPYSIGN with matching types.");
5593 
5594   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5595   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5596   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5597 
5598   SDValue Mask, VL;
5599   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5600 
5601   SDValue CopySign =
5602       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5603 
5604   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5605 }
5606 
5607 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5608     SDValue Op, SelectionDAG &DAG) const {
5609   MVT VT = Op.getSimpleValueType();
5610   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5611 
5612   MVT I1ContainerVT =
5613       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5614 
5615   SDValue CC =
5616       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5617   SDValue Op1 =
5618       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5619   SDValue Op2 =
5620       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5621 
5622   SDLoc DL(Op);
5623   SDValue Mask, VL;
5624   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5625 
5626   SDValue Select =
5627       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5628 
5629   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5630 }
5631 
5632 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5633                                                unsigned NewOpc,
5634                                                bool HasMask) const {
5635   MVT VT = Op.getSimpleValueType();
5636   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5637 
5638   // Create list of operands by converting existing ones to scalable types.
5639   SmallVector<SDValue, 6> Ops;
5640   for (const SDValue &V : Op->op_values()) {
5641     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5642 
5643     // Pass through non-vector operands.
5644     if (!V.getValueType().isVector()) {
5645       Ops.push_back(V);
5646       continue;
5647     }
5648 
5649     // "cast" fixed length vector to a scalable vector.
5650     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5651            "Only fixed length vectors are supported!");
5652     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5653   }
5654 
5655   SDLoc DL(Op);
5656   SDValue Mask, VL;
5657   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5658   if (HasMask)
5659     Ops.push_back(Mask);
5660   Ops.push_back(VL);
5661 
5662   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5663   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5664 }
5665 
5666 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5667 // * Operands of each node are assumed to be in the same order.
5668 // * The EVL operand is promoted from i32 to i64 on RV64.
5669 // * Fixed-length vectors are converted to their scalable-vector container
5670 //   types.
5671 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5672                                        unsigned RISCVISDOpc) const {
5673   SDLoc DL(Op);
5674   MVT VT = Op.getSimpleValueType();
5675   SmallVector<SDValue, 4> Ops;
5676 
5677   for (const auto &OpIdx : enumerate(Op->ops())) {
5678     SDValue V = OpIdx.value();
5679     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5680     // Pass through operands which aren't fixed-length vectors.
5681     if (!V.getValueType().isFixedLengthVector()) {
5682       Ops.push_back(V);
5683       continue;
5684     }
5685     // "cast" fixed length vector to a scalable vector.
5686     MVT OpVT = V.getSimpleValueType();
5687     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5688     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5689            "Only fixed length vectors are supported!");
5690     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5691   }
5692 
5693   if (!VT.isFixedLengthVector())
5694     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5695 
5696   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5697 
5698   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5699 
5700   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5701 }
5702 
5703 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5704                                             unsigned MaskOpc,
5705                                             unsigned VecOpc) const {
5706   MVT VT = Op.getSimpleValueType();
5707   if (VT.getVectorElementType() != MVT::i1)
5708     return lowerVPOp(Op, DAG, VecOpc);
5709 
5710   // It is safe to drop mask parameter as masked-off elements are undef.
5711   SDValue Op1 = Op->getOperand(0);
5712   SDValue Op2 = Op->getOperand(1);
5713   SDValue VL = Op->getOperand(3);
5714 
5715   MVT ContainerVT = VT;
5716   const bool IsFixed = VT.isFixedLengthVector();
5717   if (IsFixed) {
5718     ContainerVT = getContainerForFixedLengthVector(VT);
5719     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5720     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5721   }
5722 
5723   SDLoc DL(Op);
5724   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5725   if (!IsFixed)
5726     return Val;
5727   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5728 }
5729 
5730 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5731 // matched to a RVV indexed load. The RVV indexed load instructions only
5732 // support the "unsigned unscaled" addressing mode; indices are implicitly
5733 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5734 // signed or scaled indexing is extended to the XLEN value type and scaled
5735 // accordingly.
5736 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5737                                                SelectionDAG &DAG) const {
5738   SDLoc DL(Op);
5739   MVT VT = Op.getSimpleValueType();
5740 
5741   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5742   EVT MemVT = MemSD->getMemoryVT();
5743   MachineMemOperand *MMO = MemSD->getMemOperand();
5744   SDValue Chain = MemSD->getChain();
5745   SDValue BasePtr = MemSD->getBasePtr();
5746 
5747   ISD::LoadExtType LoadExtType;
5748   SDValue Index, Mask, PassThru, VL;
5749 
5750   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5751     Index = VPGN->getIndex();
5752     Mask = VPGN->getMask();
5753     PassThru = DAG.getUNDEF(VT);
5754     VL = VPGN->getVectorLength();
5755     // VP doesn't support extending loads.
5756     LoadExtType = ISD::NON_EXTLOAD;
5757   } else {
5758     // Else it must be a MGATHER.
5759     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5760     Index = MGN->getIndex();
5761     Mask = MGN->getMask();
5762     PassThru = MGN->getPassThru();
5763     LoadExtType = MGN->getExtensionType();
5764   }
5765 
5766   MVT IndexVT = Index.getSimpleValueType();
5767   MVT XLenVT = Subtarget.getXLenVT();
5768 
5769   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5770          "Unexpected VTs!");
5771   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5772   // Targets have to explicitly opt-in for extending vector loads.
5773   assert(LoadExtType == ISD::NON_EXTLOAD &&
5774          "Unexpected extending MGATHER/VP_GATHER");
5775   (void)LoadExtType;
5776 
5777   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5778   // the selection of the masked intrinsics doesn't do this for us.
5779   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5780 
5781   MVT ContainerVT = VT;
5782   if (VT.isFixedLengthVector()) {
5783     // We need to use the larger of the result and index type to determine the
5784     // scalable type to use so we don't increase LMUL for any operand/result.
5785     if (VT.bitsGE(IndexVT)) {
5786       ContainerVT = getContainerForFixedLengthVector(VT);
5787       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5788                                  ContainerVT.getVectorElementCount());
5789     } else {
5790       IndexVT = getContainerForFixedLengthVector(IndexVT);
5791       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5792                                      IndexVT.getVectorElementCount());
5793     }
5794 
5795     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5796 
5797     if (!IsUnmasked) {
5798       MVT MaskVT =
5799           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5800       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5801       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5802     }
5803   }
5804 
5805   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5806       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5807       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5808   }
5809 
5810   if (!VL)
5811     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5812 
5813   unsigned IntID =
5814       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5815   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5816   if (!IsUnmasked)
5817     Ops.push_back(PassThru);
5818   Ops.push_back(BasePtr);
5819   Ops.push_back(Index);
5820   if (!IsUnmasked)
5821     Ops.push_back(Mask);
5822   Ops.push_back(VL);
5823   if (!IsUnmasked)
5824     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5825 
5826   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5827   SDValue Result =
5828       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5829   Chain = Result.getValue(1);
5830 
5831   if (VT.isFixedLengthVector())
5832     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5833 
5834   return DAG.getMergeValues({Result, Chain}, DL);
5835 }
5836 
5837 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5838 // matched to a RVV indexed store. The RVV indexed store instructions only
5839 // support the "unsigned unscaled" addressing mode; indices are implicitly
5840 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5841 // signed or scaled indexing is extended to the XLEN value type and scaled
5842 // accordingly.
5843 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5844                                                 SelectionDAG &DAG) const {
5845   SDLoc DL(Op);
5846   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5847   EVT MemVT = MemSD->getMemoryVT();
5848   MachineMemOperand *MMO = MemSD->getMemOperand();
5849   SDValue Chain = MemSD->getChain();
5850   SDValue BasePtr = MemSD->getBasePtr();
5851 
5852   bool IsTruncatingStore = false;
5853   SDValue Index, Mask, Val, VL;
5854 
5855   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5856     Index = VPSN->getIndex();
5857     Mask = VPSN->getMask();
5858     Val = VPSN->getValue();
5859     VL = VPSN->getVectorLength();
5860     // VP doesn't support truncating stores.
5861     IsTruncatingStore = false;
5862   } else {
5863     // Else it must be a MSCATTER.
5864     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5865     Index = MSN->getIndex();
5866     Mask = MSN->getMask();
5867     Val = MSN->getValue();
5868     IsTruncatingStore = MSN->isTruncatingStore();
5869   }
5870 
5871   MVT VT = Val.getSimpleValueType();
5872   MVT IndexVT = Index.getSimpleValueType();
5873   MVT XLenVT = Subtarget.getXLenVT();
5874 
5875   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5876          "Unexpected VTs!");
5877   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5878   // Targets have to explicitly opt-in for extending vector loads and
5879   // truncating vector stores.
5880   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5881   (void)IsTruncatingStore;
5882 
5883   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5884   // the selection of the masked intrinsics doesn't do this for us.
5885   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5886 
5887   MVT ContainerVT = VT;
5888   if (VT.isFixedLengthVector()) {
5889     // We need to use the larger of the value and index type to determine the
5890     // scalable type to use so we don't increase LMUL for any operand/result.
5891     if (VT.bitsGE(IndexVT)) {
5892       ContainerVT = getContainerForFixedLengthVector(VT);
5893       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5894                                  ContainerVT.getVectorElementCount());
5895     } else {
5896       IndexVT = getContainerForFixedLengthVector(IndexVT);
5897       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5898                                      IndexVT.getVectorElementCount());
5899     }
5900 
5901     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5902     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5903 
5904     if (!IsUnmasked) {
5905       MVT MaskVT =
5906           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5907       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5908     }
5909   }
5910 
5911   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5912       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5913       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5914   }
5915 
5916   if (!VL)
5917     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5918 
5919   unsigned IntID =
5920       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5921   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5922   Ops.push_back(Val);
5923   Ops.push_back(BasePtr);
5924   Ops.push_back(Index);
5925   if (!IsUnmasked)
5926     Ops.push_back(Mask);
5927   Ops.push_back(VL);
5928 
5929   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5930                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5931 }
5932 
5933 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5934                                                SelectionDAG &DAG) const {
5935   const MVT XLenVT = Subtarget.getXLenVT();
5936   SDLoc DL(Op);
5937   SDValue Chain = Op->getOperand(0);
5938   SDValue SysRegNo = DAG.getTargetConstant(
5939       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5940   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5941   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5942 
5943   // Encoding used for rounding mode in RISCV differs from that used in
5944   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5945   // table, which consists of a sequence of 4-bit fields, each representing
5946   // corresponding FLT_ROUNDS mode.
5947   static const int Table =
5948       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5949       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5950       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5951       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5952       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5953 
5954   SDValue Shift =
5955       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5956   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5957                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5958   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5959                                DAG.getConstant(7, DL, XLenVT));
5960 
5961   return DAG.getMergeValues({Masked, Chain}, DL);
5962 }
5963 
5964 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5965                                                SelectionDAG &DAG) const {
5966   const MVT XLenVT = Subtarget.getXLenVT();
5967   SDLoc DL(Op);
5968   SDValue Chain = Op->getOperand(0);
5969   SDValue RMValue = Op->getOperand(1);
5970   SDValue SysRegNo = DAG.getTargetConstant(
5971       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5972 
5973   // Encoding used for rounding mode in RISCV differs from that used in
5974   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5975   // a table, which consists of a sequence of 4-bit fields, each representing
5976   // corresponding RISCV mode.
5977   static const unsigned Table =
5978       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5979       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5980       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5981       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5982       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5983 
5984   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5985                               DAG.getConstant(2, DL, XLenVT));
5986   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5987                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5988   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5989                         DAG.getConstant(0x7, DL, XLenVT));
5990   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5991                      RMValue);
5992 }
5993 
5994 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
5995   switch (IntNo) {
5996   default:
5997     llvm_unreachable("Unexpected Intrinsic");
5998   case Intrinsic::riscv_grev:
5999     return RISCVISD::GREVW;
6000   case Intrinsic::riscv_gorc:
6001     return RISCVISD::GORCW;
6002   case Intrinsic::riscv_bcompress:
6003     return RISCVISD::BCOMPRESSW;
6004   case Intrinsic::riscv_bdecompress:
6005     return RISCVISD::BDECOMPRESSW;
6006   case Intrinsic::riscv_bfp:
6007     return RISCVISD::BFPW;
6008   case Intrinsic::riscv_fsl:
6009     return RISCVISD::FSLW;
6010   case Intrinsic::riscv_fsr:
6011     return RISCVISD::FSRW;
6012   }
6013 }
6014 
6015 // Converts the given intrinsic to a i64 operation with any extension.
6016 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6017                                          unsigned IntNo) {
6018   SDLoc DL(N);
6019   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6020   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6021   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6022   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6023   // ReplaceNodeResults requires we maintain the same type for the return value.
6024   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6025 }
6026 
6027 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6028 // form of the given Opcode.
6029 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6030   switch (Opcode) {
6031   default:
6032     llvm_unreachable("Unexpected opcode");
6033   case ISD::SHL:
6034     return RISCVISD::SLLW;
6035   case ISD::SRA:
6036     return RISCVISD::SRAW;
6037   case ISD::SRL:
6038     return RISCVISD::SRLW;
6039   case ISD::SDIV:
6040     return RISCVISD::DIVW;
6041   case ISD::UDIV:
6042     return RISCVISD::DIVUW;
6043   case ISD::UREM:
6044     return RISCVISD::REMUW;
6045   case ISD::ROTL:
6046     return RISCVISD::ROLW;
6047   case ISD::ROTR:
6048     return RISCVISD::RORW;
6049   case RISCVISD::GREV:
6050     return RISCVISD::GREVW;
6051   case RISCVISD::GORC:
6052     return RISCVISD::GORCW;
6053   }
6054 }
6055 
6056 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6057 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6058 // otherwise be promoted to i64, making it difficult to select the
6059 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6060 // type i8/i16/i32 is lost.
6061 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6062                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6063   SDLoc DL(N);
6064   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6065   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6066   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6067   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6068   // ReplaceNodeResults requires we maintain the same type for the return value.
6069   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6070 }
6071 
6072 // Converts the given 32-bit operation to a i64 operation with signed extension
6073 // semantic to reduce the signed extension instructions.
6074 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6075   SDLoc DL(N);
6076   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6077   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6078   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6079   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6080                                DAG.getValueType(MVT::i32));
6081   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6082 }
6083 
6084 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6085                                              SmallVectorImpl<SDValue> &Results,
6086                                              SelectionDAG &DAG) const {
6087   SDLoc DL(N);
6088   switch (N->getOpcode()) {
6089   default:
6090     llvm_unreachable("Don't know how to custom type legalize this operation!");
6091   case ISD::STRICT_FP_TO_SINT:
6092   case ISD::STRICT_FP_TO_UINT:
6093   case ISD::FP_TO_SINT:
6094   case ISD::FP_TO_UINT: {
6095     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6096            "Unexpected custom legalisation");
6097     bool IsStrict = N->isStrictFPOpcode();
6098     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6099                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6100     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6101     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6102         TargetLowering::TypeSoftenFloat) {
6103       if (!isTypeLegal(Op0.getValueType()))
6104         return;
6105       if (IsStrict) {
6106         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6107                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6108         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6109         SDValue Res = DAG.getNode(
6110             Opc, DL, VTs, N->getOperand(0), Op0,
6111             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6112         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6113         Results.push_back(Res.getValue(1));
6114         return;
6115       }
6116       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6117       SDValue Res =
6118           DAG.getNode(Opc, DL, MVT::i64, Op0,
6119                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6120       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6121       return;
6122     }
6123     // If the FP type needs to be softened, emit a library call using the 'si'
6124     // version. If we left it to default legalization we'd end up with 'di'. If
6125     // the FP type doesn't need to be softened just let generic type
6126     // legalization promote the result type.
6127     RTLIB::Libcall LC;
6128     if (IsSigned)
6129       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6130     else
6131       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6132     MakeLibCallOptions CallOptions;
6133     EVT OpVT = Op0.getValueType();
6134     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6135     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6136     SDValue Result;
6137     std::tie(Result, Chain) =
6138         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6139     Results.push_back(Result);
6140     if (IsStrict)
6141       Results.push_back(Chain);
6142     break;
6143   }
6144   case ISD::READCYCLECOUNTER: {
6145     assert(!Subtarget.is64Bit() &&
6146            "READCYCLECOUNTER only has custom type legalization on riscv32");
6147 
6148     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6149     SDValue RCW =
6150         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6151 
6152     Results.push_back(
6153         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6154     Results.push_back(RCW.getValue(2));
6155     break;
6156   }
6157   case ISD::MUL: {
6158     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6159     unsigned XLen = Subtarget.getXLen();
6160     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6161     if (Size > XLen) {
6162       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6163       SDValue LHS = N->getOperand(0);
6164       SDValue RHS = N->getOperand(1);
6165       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6166 
6167       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6168       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6169       // We need exactly one side to be unsigned.
6170       if (LHSIsU == RHSIsU)
6171         return;
6172 
6173       auto MakeMULPair = [&](SDValue S, SDValue U) {
6174         MVT XLenVT = Subtarget.getXLenVT();
6175         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6176         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6177         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6178         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6179         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6180       };
6181 
6182       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6183       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6184 
6185       // The other operand should be signed, but still prefer MULH when
6186       // possible.
6187       if (RHSIsU && LHSIsS && !RHSIsS)
6188         Results.push_back(MakeMULPair(LHS, RHS));
6189       else if (LHSIsU && RHSIsS && !LHSIsS)
6190         Results.push_back(MakeMULPair(RHS, LHS));
6191 
6192       return;
6193     }
6194     LLVM_FALLTHROUGH;
6195   }
6196   case ISD::ADD:
6197   case ISD::SUB:
6198     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6199            "Unexpected custom legalisation");
6200     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6201     break;
6202   case ISD::SHL:
6203   case ISD::SRA:
6204   case ISD::SRL:
6205     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6206            "Unexpected custom legalisation");
6207     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6208       Results.push_back(customLegalizeToWOp(N, DAG));
6209       break;
6210     }
6211 
6212     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6213     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6214     // shift amount.
6215     if (N->getOpcode() == ISD::SHL) {
6216       SDLoc DL(N);
6217       SDValue NewOp0 =
6218           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6219       SDValue NewOp1 =
6220           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6221       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6222       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6223                                    DAG.getValueType(MVT::i32));
6224       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6225     }
6226 
6227     break;
6228   case ISD::ROTL:
6229   case ISD::ROTR:
6230     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6231            "Unexpected custom legalisation");
6232     Results.push_back(customLegalizeToWOp(N, DAG));
6233     break;
6234   case ISD::CTTZ:
6235   case ISD::CTTZ_ZERO_UNDEF:
6236   case ISD::CTLZ:
6237   case ISD::CTLZ_ZERO_UNDEF: {
6238     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6239            "Unexpected custom legalisation");
6240 
6241     SDValue NewOp0 =
6242         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6243     bool IsCTZ =
6244         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6245     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6246     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6247     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6248     return;
6249   }
6250   case ISD::SDIV:
6251   case ISD::UDIV:
6252   case ISD::UREM: {
6253     MVT VT = N->getSimpleValueType(0);
6254     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6255            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6256            "Unexpected custom legalisation");
6257     // Don't promote division/remainder by constant since we should expand those
6258     // to multiply by magic constant.
6259     // FIXME: What if the expansion is disabled for minsize.
6260     if (N->getOperand(1).getOpcode() == ISD::Constant)
6261       return;
6262 
6263     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6264     // the upper 32 bits. For other types we need to sign or zero extend
6265     // based on the opcode.
6266     unsigned ExtOpc = ISD::ANY_EXTEND;
6267     if (VT != MVT::i32)
6268       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6269                                            : ISD::ZERO_EXTEND;
6270 
6271     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6272     break;
6273   }
6274   case ISD::UADDO:
6275   case ISD::USUBO: {
6276     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6277            "Unexpected custom legalisation");
6278     bool IsAdd = N->getOpcode() == ISD::UADDO;
6279     // Create an ADDW or SUBW.
6280     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6281     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6282     SDValue Res =
6283         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6284     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6285                       DAG.getValueType(MVT::i32));
6286 
6287     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6288     // Since the inputs are sign extended from i32, this is equivalent to
6289     // comparing the lower 32 bits.
6290     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6291     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6292                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6293 
6294     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6295     Results.push_back(Overflow);
6296     return;
6297   }
6298   case ISD::UADDSAT:
6299   case ISD::USUBSAT: {
6300     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6301            "Unexpected custom legalisation");
6302     if (Subtarget.hasStdExtZbb()) {
6303       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6304       // sign extend allows overflow of the lower 32 bits to be detected on
6305       // the promoted size.
6306       SDValue LHS =
6307           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6308       SDValue RHS =
6309           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6310       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6311       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6312       return;
6313     }
6314 
6315     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6316     // promotion for UADDO/USUBO.
6317     Results.push_back(expandAddSubSat(N, DAG));
6318     return;
6319   }
6320   case ISD::BITCAST: {
6321     EVT VT = N->getValueType(0);
6322     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6323     SDValue Op0 = N->getOperand(0);
6324     EVT Op0VT = Op0.getValueType();
6325     MVT XLenVT = Subtarget.getXLenVT();
6326     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6327       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6328       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6329     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6330                Subtarget.hasStdExtF()) {
6331       SDValue FPConv =
6332           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6333       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6334     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6335                isTypeLegal(Op0VT)) {
6336       // Custom-legalize bitcasts from fixed-length vector types to illegal
6337       // scalar types in order to improve codegen. Bitcast the vector to a
6338       // one-element vector type whose element type is the same as the result
6339       // type, and extract the first element.
6340       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6341       if (isTypeLegal(BVT)) {
6342         SDValue BVec = DAG.getBitcast(BVT, Op0);
6343         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6344                                       DAG.getConstant(0, DL, XLenVT)));
6345       }
6346     }
6347     break;
6348   }
6349   case RISCVISD::GREV:
6350   case RISCVISD::GORC: {
6351     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6352            "Unexpected custom legalisation");
6353     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6354     // This is similar to customLegalizeToWOp, except that we pass the second
6355     // operand (a TargetConstant) straight through: it is already of type
6356     // XLenVT.
6357     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6358     SDValue NewOp0 =
6359         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6360     SDValue NewOp1 =
6361         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6362     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6363     // ReplaceNodeResults requires we maintain the same type for the return
6364     // value.
6365     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6366     break;
6367   }
6368   case RISCVISD::SHFL: {
6369     // There is no SHFLIW instruction, but we can just promote the operation.
6370     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6371            "Unexpected custom legalisation");
6372     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6373     SDValue NewOp0 =
6374         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6375     SDValue NewOp1 =
6376         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6377     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6378     // ReplaceNodeResults requires we maintain the same type for the return
6379     // value.
6380     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6381     break;
6382   }
6383   case ISD::BSWAP:
6384   case ISD::BITREVERSE: {
6385     MVT VT = N->getSimpleValueType(0);
6386     MVT XLenVT = Subtarget.getXLenVT();
6387     assert((VT == MVT::i8 || VT == MVT::i16 ||
6388             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6389            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6390     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6391     unsigned Imm = VT.getSizeInBits() - 1;
6392     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6393     if (N->getOpcode() == ISD::BSWAP)
6394       Imm &= ~0x7U;
6395     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6396     SDValue GREVI =
6397         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6398     // ReplaceNodeResults requires we maintain the same type for the return
6399     // value.
6400     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6401     break;
6402   }
6403   case ISD::FSHL:
6404   case ISD::FSHR: {
6405     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6406            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6407     SDValue NewOp0 =
6408         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6409     SDValue NewOp1 =
6410         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6411     SDValue NewShAmt =
6412         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6413     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6414     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6415     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6416                            DAG.getConstant(0x1f, DL, MVT::i64));
6417     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6418     // instruction use different orders. fshl will return its first operand for
6419     // shift of zero, fshr will return its second operand. fsl and fsr both
6420     // return rs1 so the ISD nodes need to have different operand orders.
6421     // Shift amount is in rs2.
6422     unsigned Opc = RISCVISD::FSLW;
6423     if (N->getOpcode() == ISD::FSHR) {
6424       std::swap(NewOp0, NewOp1);
6425       Opc = RISCVISD::FSRW;
6426     }
6427     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6428     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6429     break;
6430   }
6431   case ISD::EXTRACT_VECTOR_ELT: {
6432     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6433     // type is illegal (currently only vXi64 RV32).
6434     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6435     // transferred to the destination register. We issue two of these from the
6436     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6437     // first element.
6438     SDValue Vec = N->getOperand(0);
6439     SDValue Idx = N->getOperand(1);
6440 
6441     // The vector type hasn't been legalized yet so we can't issue target
6442     // specific nodes if it needs legalization.
6443     // FIXME: We would manually legalize if it's important.
6444     if (!isTypeLegal(Vec.getValueType()))
6445       return;
6446 
6447     MVT VecVT = Vec.getSimpleValueType();
6448 
6449     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6450            VecVT.getVectorElementType() == MVT::i64 &&
6451            "Unexpected EXTRACT_VECTOR_ELT legalization");
6452 
6453     // If this is a fixed vector, we need to convert it to a scalable vector.
6454     MVT ContainerVT = VecVT;
6455     if (VecVT.isFixedLengthVector()) {
6456       ContainerVT = getContainerForFixedLengthVector(VecVT);
6457       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6458     }
6459 
6460     MVT XLenVT = Subtarget.getXLenVT();
6461 
6462     // Use a VL of 1 to avoid processing more elements than we need.
6463     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6464     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6465     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6466 
6467     // Unless the index is known to be 0, we must slide the vector down to get
6468     // the desired element into index 0.
6469     if (!isNullConstant(Idx)) {
6470       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6471                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6472     }
6473 
6474     // Extract the lower XLEN bits of the correct vector element.
6475     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6476 
6477     // To extract the upper XLEN bits of the vector element, shift the first
6478     // element right by 32 bits and re-extract the lower XLEN bits.
6479     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6480                                      DAG.getConstant(32, DL, XLenVT), VL);
6481     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6482                                  ThirtyTwoV, Mask, VL);
6483 
6484     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6485 
6486     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6487     break;
6488   }
6489   case ISD::INTRINSIC_WO_CHAIN: {
6490     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6491     switch (IntNo) {
6492     default:
6493       llvm_unreachable(
6494           "Don't know how to custom type legalize this intrinsic!");
6495     case Intrinsic::riscv_grev:
6496     case Intrinsic::riscv_gorc:
6497     case Intrinsic::riscv_bcompress:
6498     case Intrinsic::riscv_bdecompress:
6499     case Intrinsic::riscv_bfp: {
6500       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6501              "Unexpected custom legalisation");
6502       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6503       break;
6504     }
6505     case Intrinsic::riscv_fsl:
6506     case Intrinsic::riscv_fsr: {
6507       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6508              "Unexpected custom legalisation");
6509       SDValue NewOp1 =
6510           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6511       SDValue NewOp2 =
6512           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6513       SDValue NewOp3 =
6514           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6515       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6516       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6517       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6518       break;
6519     }
6520     case Intrinsic::riscv_orc_b: {
6521       // Lower to the GORCI encoding for orc.b with the operand extended.
6522       SDValue NewOp =
6523           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6524       // If Zbp is enabled, use GORCIW which will sign extend the result.
6525       unsigned Opc =
6526           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6527       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6528                                 DAG.getConstant(7, DL, MVT::i64));
6529       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6530       return;
6531     }
6532     case Intrinsic::riscv_shfl:
6533     case Intrinsic::riscv_unshfl: {
6534       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6535              "Unexpected custom legalisation");
6536       SDValue NewOp1 =
6537           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6538       SDValue NewOp2 =
6539           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6540       unsigned Opc =
6541           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6542       if (isa<ConstantSDNode>(N->getOperand(2))) {
6543         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6544                              DAG.getConstant(0xf, DL, MVT::i64));
6545         Opc =
6546             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6547       }
6548       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6549       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6550       break;
6551     }
6552     case Intrinsic::riscv_vmv_x_s: {
6553       EVT VT = N->getValueType(0);
6554       MVT XLenVT = Subtarget.getXLenVT();
6555       if (VT.bitsLT(XLenVT)) {
6556         // Simple case just extract using vmv.x.s and truncate.
6557         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6558                                       Subtarget.getXLenVT(), N->getOperand(1));
6559         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6560         return;
6561       }
6562 
6563       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6564              "Unexpected custom legalization");
6565 
6566       // We need to do the move in two steps.
6567       SDValue Vec = N->getOperand(1);
6568       MVT VecVT = Vec.getSimpleValueType();
6569 
6570       // First extract the lower XLEN bits of the element.
6571       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6572 
6573       // To extract the upper XLEN bits of the vector element, shift the first
6574       // element right by 32 bits and re-extract the lower XLEN bits.
6575       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6576       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6577       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6578       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6579                                        DAG.getConstant(32, DL, XLenVT), VL);
6580       SDValue LShr32 =
6581           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6582       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6583 
6584       Results.push_back(
6585           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6586       break;
6587     }
6588     }
6589     break;
6590   }
6591   case ISD::VECREDUCE_ADD:
6592   case ISD::VECREDUCE_AND:
6593   case ISD::VECREDUCE_OR:
6594   case ISD::VECREDUCE_XOR:
6595   case ISD::VECREDUCE_SMAX:
6596   case ISD::VECREDUCE_UMAX:
6597   case ISD::VECREDUCE_SMIN:
6598   case ISD::VECREDUCE_UMIN:
6599     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6600       Results.push_back(V);
6601     break;
6602   case ISD::VP_REDUCE_ADD:
6603   case ISD::VP_REDUCE_AND:
6604   case ISD::VP_REDUCE_OR:
6605   case ISD::VP_REDUCE_XOR:
6606   case ISD::VP_REDUCE_SMAX:
6607   case ISD::VP_REDUCE_UMAX:
6608   case ISD::VP_REDUCE_SMIN:
6609   case ISD::VP_REDUCE_UMIN:
6610     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6611       Results.push_back(V);
6612     break;
6613   case ISD::FLT_ROUNDS_: {
6614     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6615     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6616     Results.push_back(Res.getValue(0));
6617     Results.push_back(Res.getValue(1));
6618     break;
6619   }
6620   }
6621 }
6622 
6623 // A structure to hold one of the bit-manipulation patterns below. Together, a
6624 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6625 //   (or (and (shl x, 1), 0xAAAAAAAA),
6626 //       (and (srl x, 1), 0x55555555))
6627 struct RISCVBitmanipPat {
6628   SDValue Op;
6629   unsigned ShAmt;
6630   bool IsSHL;
6631 
6632   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6633     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6634   }
6635 };
6636 
6637 // Matches patterns of the form
6638 //   (and (shl x, C2), (C1 << C2))
6639 //   (and (srl x, C2), C1)
6640 //   (shl (and x, C1), C2)
6641 //   (srl (and x, (C1 << C2)), C2)
6642 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6643 // The expected masks for each shift amount are specified in BitmanipMasks where
6644 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6645 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6646 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6647 // XLen is 64.
6648 static Optional<RISCVBitmanipPat>
6649 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6650   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6651          "Unexpected number of masks");
6652   Optional<uint64_t> Mask;
6653   // Optionally consume a mask around the shift operation.
6654   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6655     Mask = Op.getConstantOperandVal(1);
6656     Op = Op.getOperand(0);
6657   }
6658   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6659     return None;
6660   bool IsSHL = Op.getOpcode() == ISD::SHL;
6661 
6662   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6663     return None;
6664   uint64_t ShAmt = Op.getConstantOperandVal(1);
6665 
6666   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6667   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6668     return None;
6669   // If we don't have enough masks for 64 bit, then we must be trying to
6670   // match SHFL so we're only allowed to shift 1/4 of the width.
6671   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6672     return None;
6673 
6674   SDValue Src = Op.getOperand(0);
6675 
6676   // The expected mask is shifted left when the AND is found around SHL
6677   // patterns.
6678   //   ((x >> 1) & 0x55555555)
6679   //   ((x << 1) & 0xAAAAAAAA)
6680   bool SHLExpMask = IsSHL;
6681 
6682   if (!Mask) {
6683     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6684     // the mask is all ones: consume that now.
6685     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6686       Mask = Src.getConstantOperandVal(1);
6687       Src = Src.getOperand(0);
6688       // The expected mask is now in fact shifted left for SRL, so reverse the
6689       // decision.
6690       //   ((x & 0xAAAAAAAA) >> 1)
6691       //   ((x & 0x55555555) << 1)
6692       SHLExpMask = !SHLExpMask;
6693     } else {
6694       // Use a default shifted mask of all-ones if there's no AND, truncated
6695       // down to the expected width. This simplifies the logic later on.
6696       Mask = maskTrailingOnes<uint64_t>(Width);
6697       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6698     }
6699   }
6700 
6701   unsigned MaskIdx = Log2_32(ShAmt);
6702   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6703 
6704   if (SHLExpMask)
6705     ExpMask <<= ShAmt;
6706 
6707   if (Mask != ExpMask)
6708     return None;
6709 
6710   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6711 }
6712 
6713 // Matches any of the following bit-manipulation patterns:
6714 //   (and (shl x, 1), (0x55555555 << 1))
6715 //   (and (srl x, 1), 0x55555555)
6716 //   (shl (and x, 0x55555555), 1)
6717 //   (srl (and x, (0x55555555 << 1)), 1)
6718 // where the shift amount and mask may vary thus:
6719 //   [1]  = 0x55555555 / 0xAAAAAAAA
6720 //   [2]  = 0x33333333 / 0xCCCCCCCC
6721 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6722 //   [8]  = 0x00FF00FF / 0xFF00FF00
6723 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6724 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6725 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6726   // These are the unshifted masks which we use to match bit-manipulation
6727   // patterns. They may be shifted left in certain circumstances.
6728   static const uint64_t BitmanipMasks[] = {
6729       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6730       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6731 
6732   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6733 }
6734 
6735 // Match the following pattern as a GREVI(W) operation
6736 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6737 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6738                                const RISCVSubtarget &Subtarget) {
6739   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6740   EVT VT = Op.getValueType();
6741 
6742   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6743     auto LHS = matchGREVIPat(Op.getOperand(0));
6744     auto RHS = matchGREVIPat(Op.getOperand(1));
6745     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6746       SDLoc DL(Op);
6747       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6748                          DAG.getConstant(LHS->ShAmt, DL, VT));
6749     }
6750   }
6751   return SDValue();
6752 }
6753 
6754 // Matches any the following pattern as a GORCI(W) operation
6755 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6756 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6757 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6758 // Note that with the variant of 3.,
6759 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6760 // the inner pattern will first be matched as GREVI and then the outer
6761 // pattern will be matched to GORC via the first rule above.
6762 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6763 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6764                                const RISCVSubtarget &Subtarget) {
6765   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6766   EVT VT = Op.getValueType();
6767 
6768   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6769     SDLoc DL(Op);
6770     SDValue Op0 = Op.getOperand(0);
6771     SDValue Op1 = Op.getOperand(1);
6772 
6773     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6774       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6775           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6776           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6777         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6778       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6779       if ((Reverse.getOpcode() == ISD::ROTL ||
6780            Reverse.getOpcode() == ISD::ROTR) &&
6781           Reverse.getOperand(0) == X &&
6782           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6783         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6784         if (RotAmt == (VT.getSizeInBits() / 2))
6785           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6786                              DAG.getConstant(RotAmt, DL, VT));
6787       }
6788       return SDValue();
6789     };
6790 
6791     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6792     if (SDValue V = MatchOROfReverse(Op0, Op1))
6793       return V;
6794     if (SDValue V = MatchOROfReverse(Op1, Op0))
6795       return V;
6796 
6797     // OR is commutable so canonicalize its OR operand to the left
6798     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6799       std::swap(Op0, Op1);
6800     if (Op0.getOpcode() != ISD::OR)
6801       return SDValue();
6802     SDValue OrOp0 = Op0.getOperand(0);
6803     SDValue OrOp1 = Op0.getOperand(1);
6804     auto LHS = matchGREVIPat(OrOp0);
6805     // OR is commutable so swap the operands and try again: x might have been
6806     // on the left
6807     if (!LHS) {
6808       std::swap(OrOp0, OrOp1);
6809       LHS = matchGREVIPat(OrOp0);
6810     }
6811     auto RHS = matchGREVIPat(Op1);
6812     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6813       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6814                          DAG.getConstant(LHS->ShAmt, DL, VT));
6815     }
6816   }
6817   return SDValue();
6818 }
6819 
6820 // Matches any of the following bit-manipulation patterns:
6821 //   (and (shl x, 1), (0x22222222 << 1))
6822 //   (and (srl x, 1), 0x22222222)
6823 //   (shl (and x, 0x22222222), 1)
6824 //   (srl (and x, (0x22222222 << 1)), 1)
6825 // where the shift amount and mask may vary thus:
6826 //   [1]  = 0x22222222 / 0x44444444
6827 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6828 //   [4]  = 0x00F000F0 / 0x0F000F00
6829 //   [8]  = 0x0000FF00 / 0x00FF0000
6830 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6831 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6832   // These are the unshifted masks which we use to match bit-manipulation
6833   // patterns. They may be shifted left in certain circumstances.
6834   static const uint64_t BitmanipMasks[] = {
6835       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6836       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6837 
6838   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6839 }
6840 
6841 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6842 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6843                                const RISCVSubtarget &Subtarget) {
6844   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6845   EVT VT = Op.getValueType();
6846 
6847   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6848     return SDValue();
6849 
6850   SDValue Op0 = Op.getOperand(0);
6851   SDValue Op1 = Op.getOperand(1);
6852 
6853   // Or is commutable so canonicalize the second OR to the LHS.
6854   if (Op0.getOpcode() != ISD::OR)
6855     std::swap(Op0, Op1);
6856   if (Op0.getOpcode() != ISD::OR)
6857     return SDValue();
6858 
6859   // We found an inner OR, so our operands are the operands of the inner OR
6860   // and the other operand of the outer OR.
6861   SDValue A = Op0.getOperand(0);
6862   SDValue B = Op0.getOperand(1);
6863   SDValue C = Op1;
6864 
6865   auto Match1 = matchSHFLPat(A);
6866   auto Match2 = matchSHFLPat(B);
6867 
6868   // If neither matched, we failed.
6869   if (!Match1 && !Match2)
6870     return SDValue();
6871 
6872   // We had at least one match. if one failed, try the remaining C operand.
6873   if (!Match1) {
6874     std::swap(A, C);
6875     Match1 = matchSHFLPat(A);
6876     if (!Match1)
6877       return SDValue();
6878   } else if (!Match2) {
6879     std::swap(B, C);
6880     Match2 = matchSHFLPat(B);
6881     if (!Match2)
6882       return SDValue();
6883   }
6884   assert(Match1 && Match2);
6885 
6886   // Make sure our matches pair up.
6887   if (!Match1->formsPairWith(*Match2))
6888     return SDValue();
6889 
6890   // All the remains is to make sure C is an AND with the same input, that masks
6891   // out the bits that are being shuffled.
6892   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6893       C.getOperand(0) != Match1->Op)
6894     return SDValue();
6895 
6896   uint64_t Mask = C.getConstantOperandVal(1);
6897 
6898   static const uint64_t BitmanipMasks[] = {
6899       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6900       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6901   };
6902 
6903   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6904   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6905   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6906 
6907   if (Mask != ExpMask)
6908     return SDValue();
6909 
6910   SDLoc DL(Op);
6911   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6912                      DAG.getConstant(Match1->ShAmt, DL, VT));
6913 }
6914 
6915 // Optimize (add (shl x, c0), (shl y, c1)) ->
6916 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6917 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6918                                   const RISCVSubtarget &Subtarget) {
6919   // Perform this optimization only in the zba extension.
6920   if (!Subtarget.hasStdExtZba())
6921     return SDValue();
6922 
6923   // Skip for vector types and larger types.
6924   EVT VT = N->getValueType(0);
6925   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6926     return SDValue();
6927 
6928   // The two operand nodes must be SHL and have no other use.
6929   SDValue N0 = N->getOperand(0);
6930   SDValue N1 = N->getOperand(1);
6931   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6932       !N0->hasOneUse() || !N1->hasOneUse())
6933     return SDValue();
6934 
6935   // Check c0 and c1.
6936   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6937   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6938   if (!N0C || !N1C)
6939     return SDValue();
6940   int64_t C0 = N0C->getSExtValue();
6941   int64_t C1 = N1C->getSExtValue();
6942   if (C0 <= 0 || C1 <= 0)
6943     return SDValue();
6944 
6945   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6946   int64_t Bits = std::min(C0, C1);
6947   int64_t Diff = std::abs(C0 - C1);
6948   if (Diff != 1 && Diff != 2 && Diff != 3)
6949     return SDValue();
6950 
6951   // Build nodes.
6952   SDLoc DL(N);
6953   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6954   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6955   SDValue NA0 =
6956       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6957   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6958   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6959 }
6960 
6961 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6962 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6963 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6964 // not undo itself, but they are redundant.
6965 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6966   SDValue Src = N->getOperand(0);
6967 
6968   if (Src.getOpcode() != N->getOpcode())
6969     return SDValue();
6970 
6971   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6972       !isa<ConstantSDNode>(Src.getOperand(1)))
6973     return SDValue();
6974 
6975   unsigned ShAmt1 = N->getConstantOperandVal(1);
6976   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6977   Src = Src.getOperand(0);
6978 
6979   unsigned CombinedShAmt;
6980   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6981     CombinedShAmt = ShAmt1 | ShAmt2;
6982   else
6983     CombinedShAmt = ShAmt1 ^ ShAmt2;
6984 
6985   if (CombinedShAmt == 0)
6986     return Src;
6987 
6988   SDLoc DL(N);
6989   return DAG.getNode(
6990       N->getOpcode(), DL, N->getValueType(0), Src,
6991       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6992 }
6993 
6994 // Combine a constant select operand into its use:
6995 //
6996 // (and (select cond, -1, c), x)
6997 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6998 // (or  (select cond, 0, c), x)
6999 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7000 // (xor (select cond, 0, c), x)
7001 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7002 // (add (select cond, 0, c), x)
7003 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7004 // (sub x, (select cond, 0, c))
7005 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7006 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7007                                    SelectionDAG &DAG, bool AllOnes) {
7008   EVT VT = N->getValueType(0);
7009 
7010   // Skip vectors.
7011   if (VT.isVector())
7012     return SDValue();
7013 
7014   if ((Slct.getOpcode() != ISD::SELECT &&
7015        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7016       !Slct.hasOneUse())
7017     return SDValue();
7018 
7019   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7020     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7021   };
7022 
7023   bool SwapSelectOps;
7024   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7025   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7026   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7027   SDValue NonConstantVal;
7028   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7029     SwapSelectOps = false;
7030     NonConstantVal = FalseVal;
7031   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7032     SwapSelectOps = true;
7033     NonConstantVal = TrueVal;
7034   } else
7035     return SDValue();
7036 
7037   // Slct is now know to be the desired identity constant when CC is true.
7038   TrueVal = OtherOp;
7039   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7040   // Unless SwapSelectOps says the condition should be false.
7041   if (SwapSelectOps)
7042     std::swap(TrueVal, FalseVal);
7043 
7044   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7045     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7046                        {Slct.getOperand(0), Slct.getOperand(1),
7047                         Slct.getOperand(2), TrueVal, FalseVal});
7048 
7049   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7050                      {Slct.getOperand(0), TrueVal, FalseVal});
7051 }
7052 
7053 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7054 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7055                                               bool AllOnes) {
7056   SDValue N0 = N->getOperand(0);
7057   SDValue N1 = N->getOperand(1);
7058   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7059     return Result;
7060   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7061     return Result;
7062   return SDValue();
7063 }
7064 
7065 // Transform (add (mul x, c0), c1) ->
7066 //           (add (mul (add x, c1/c0), c0), c1%c0).
7067 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7068 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7069 // to an infinite loop in DAGCombine if transformed.
7070 // Or transform (add (mul x, c0), c1) ->
7071 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7072 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7073 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7074 // lead to an infinite loop in DAGCombine if transformed.
7075 // Or transform (add (mul x, c0), c1) ->
7076 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7077 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7078 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7079 // lead to an infinite loop in DAGCombine if transformed.
7080 // Or transform (add (mul x, c0), c1) ->
7081 //              (mul (add x, c1/c0), c0).
7082 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7083 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7084                                      const RISCVSubtarget &Subtarget) {
7085   // Skip for vector types and larger types.
7086   EVT VT = N->getValueType(0);
7087   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7088     return SDValue();
7089   // The first operand node must be a MUL and has no other use.
7090   SDValue N0 = N->getOperand(0);
7091   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7092     return SDValue();
7093   // Check if c0 and c1 match above conditions.
7094   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7095   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7096   if (!N0C || !N1C)
7097     return SDValue();
7098   int64_t C0 = N0C->getSExtValue();
7099   int64_t C1 = N1C->getSExtValue();
7100   int64_t CA, CB;
7101   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7102     return SDValue();
7103   // Search for proper CA (non-zero) and CB that both are simm12.
7104   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7105       !isInt<12>(C0 * (C1 / C0))) {
7106     CA = C1 / C0;
7107     CB = C1 % C0;
7108   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7109              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7110     CA = C1 / C0 + 1;
7111     CB = C1 % C0 - C0;
7112   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7113              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7114     CA = C1 / C0 - 1;
7115     CB = C1 % C0 + C0;
7116   } else
7117     return SDValue();
7118   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7119   SDLoc DL(N);
7120   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7121                              DAG.getConstant(CA, DL, VT));
7122   SDValue New1 =
7123       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7124   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7125 }
7126 
7127 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7128                                  const RISCVSubtarget &Subtarget) {
7129   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7130     return V;
7131   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7132     return V;
7133   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7134   //      (select lhs, rhs, cc, x, (add x, y))
7135   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7136 }
7137 
7138 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7139   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7140   //      (select lhs, rhs, cc, x, (sub x, y))
7141   SDValue N0 = N->getOperand(0);
7142   SDValue N1 = N->getOperand(1);
7143   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7144 }
7145 
7146 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7147   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7148   //      (select lhs, rhs, cc, x, (and x, y))
7149   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7150 }
7151 
7152 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7153                                 const RISCVSubtarget &Subtarget) {
7154   if (Subtarget.hasStdExtZbp()) {
7155     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7156       return GREV;
7157     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7158       return GORC;
7159     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7160       return SHFL;
7161   }
7162 
7163   // fold (or (select cond, 0, y), x) ->
7164   //      (select cond, x, (or x, y))
7165   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7166 }
7167 
7168 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7169   // fold (xor (select cond, 0, y), x) ->
7170   //      (select cond, x, (xor x, y))
7171   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7172 }
7173 
7174 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7175 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7176 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7177 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7178 // ADDW/SUBW/MULW.
7179 static SDValue performANY_EXTENDCombine(SDNode *N,
7180                                         TargetLowering::DAGCombinerInfo &DCI,
7181                                         const RISCVSubtarget &Subtarget) {
7182   if (!Subtarget.is64Bit())
7183     return SDValue();
7184 
7185   SelectionDAG &DAG = DCI.DAG;
7186 
7187   SDValue Src = N->getOperand(0);
7188   EVT VT = N->getValueType(0);
7189   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7190     return SDValue();
7191 
7192   // The opcode must be one that can implicitly sign_extend.
7193   // FIXME: Additional opcodes.
7194   switch (Src.getOpcode()) {
7195   default:
7196     return SDValue();
7197   case ISD::MUL:
7198     if (!Subtarget.hasStdExtM())
7199       return SDValue();
7200     LLVM_FALLTHROUGH;
7201   case ISD::ADD:
7202   case ISD::SUB:
7203     break;
7204   }
7205 
7206   // Only handle cases where the result is used by a CopyToReg. That likely
7207   // means the value is a liveout of the basic block. This helps prevent
7208   // infinite combine loops like PR51206.
7209   if (none_of(N->uses(),
7210               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7211     return SDValue();
7212 
7213   SmallVector<SDNode *, 4> SetCCs;
7214   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7215                             UE = Src.getNode()->use_end();
7216        UI != UE; ++UI) {
7217     SDNode *User = *UI;
7218     if (User == N)
7219       continue;
7220     if (UI.getUse().getResNo() != Src.getResNo())
7221       continue;
7222     // All i32 setccs are legalized by sign extending operands.
7223     if (User->getOpcode() == ISD::SETCC) {
7224       SetCCs.push_back(User);
7225       continue;
7226     }
7227     // We don't know if we can extend this user.
7228     break;
7229   }
7230 
7231   // If we don't have any SetCCs, this isn't worthwhile.
7232   if (SetCCs.empty())
7233     return SDValue();
7234 
7235   SDLoc DL(N);
7236   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7237   DCI.CombineTo(N, SExt);
7238 
7239   // Promote all the setccs.
7240   for (SDNode *SetCC : SetCCs) {
7241     SmallVector<SDValue, 4> Ops;
7242 
7243     for (unsigned j = 0; j != 2; ++j) {
7244       SDValue SOp = SetCC->getOperand(j);
7245       if (SOp == Src)
7246         Ops.push_back(SExt);
7247       else
7248         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7249     }
7250 
7251     Ops.push_back(SetCC->getOperand(2));
7252     DCI.CombineTo(SetCC,
7253                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7254   }
7255   return SDValue(N, 0);
7256 }
7257 
7258 // Try to form VWMUL or VWMULU.
7259 // FIXME: Support VWMULSU.
7260 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7261                                        bool Commute) {
7262   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7263   SDValue Op0 = N->getOperand(0);
7264   SDValue Op1 = N->getOperand(1);
7265   if (Commute)
7266     std::swap(Op0, Op1);
7267 
7268   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7269   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7270   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7271     return SDValue();
7272 
7273   SDValue Mask = N->getOperand(2);
7274   SDValue VL = N->getOperand(3);
7275 
7276   // Make sure the mask and VL match.
7277   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7278     return SDValue();
7279 
7280   MVT VT = N->getSimpleValueType(0);
7281 
7282   // Determine the narrow size for a widening multiply.
7283   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7284   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7285                                   VT.getVectorElementCount());
7286 
7287   SDLoc DL(N);
7288 
7289   // See if the other operand is the same opcode.
7290   if (Op0.getOpcode() == Op1.getOpcode()) {
7291     if (!Op1.hasOneUse())
7292       return SDValue();
7293 
7294     // Make sure the mask and VL match.
7295     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7296       return SDValue();
7297 
7298     Op1 = Op1.getOperand(0);
7299   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7300     // The operand is a splat of a scalar.
7301 
7302     // The VL must be the same.
7303     if (Op1.getOperand(1) != VL)
7304       return SDValue();
7305 
7306     // Get the scalar value.
7307     Op1 = Op1.getOperand(0);
7308 
7309     // See if have enough sign bits or zero bits in the scalar to use a
7310     // widening multiply by splatting to smaller element size.
7311     unsigned EltBits = VT.getScalarSizeInBits();
7312     unsigned ScalarBits = Op1.getValueSizeInBits();
7313     // Make sure we're getting all element bits from the scalar register.
7314     // FIXME: Support implicit sign extension of vmv.v.x?
7315     if (ScalarBits < EltBits)
7316       return SDValue();
7317 
7318     if (IsSignExt) {
7319       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7320         return SDValue();
7321     } else {
7322       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7323       if (!DAG.MaskedValueIsZero(Op1, Mask))
7324         return SDValue();
7325     }
7326 
7327     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7328   } else
7329     return SDValue();
7330 
7331   Op0 = Op0.getOperand(0);
7332 
7333   // Re-introduce narrower extends if needed.
7334   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7335   if (Op0.getValueType() != NarrowVT)
7336     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7337   if (Op1.getValueType() != NarrowVT)
7338     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7339 
7340   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7341   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7342 }
7343 
7344 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7345   switch (Op.getOpcode()) {
7346   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7347   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7348   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7349   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7350   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7351   }
7352 
7353   return RISCVFPRndMode::Invalid;
7354 }
7355 
7356 // Fold
7357 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7358 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7359 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7360 //   (fp_to_int (fceil X))      -> fcvt X, rup
7361 //   (fp_to_int (fround X))     -> fcvt X, rmm
7362 static SDValue performFP_TO_INTCombine(SDNode *N,
7363                                        TargetLowering::DAGCombinerInfo &DCI,
7364                                        const RISCVSubtarget &Subtarget) {
7365   SelectionDAG &DAG = DCI.DAG;
7366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7367   MVT XLenVT = Subtarget.getXLenVT();
7368 
7369   // Only handle XLen or i32 types. Other types narrower than XLen will
7370   // eventually be legalized to XLenVT.
7371   EVT VT = N->getValueType(0);
7372   if (VT != MVT::i32 && VT != XLenVT)
7373     return SDValue();
7374 
7375   SDValue Src = N->getOperand(0);
7376 
7377   // Ensure the FP type is also legal.
7378   if (!TLI.isTypeLegal(Src.getValueType()))
7379     return SDValue();
7380 
7381   // Don't do this for f16 with Zfhmin and not Zfh.
7382   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7383     return SDValue();
7384 
7385   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7386   if (FRM == RISCVFPRndMode::Invalid)
7387     return SDValue();
7388 
7389   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7390 
7391   unsigned Opc;
7392   if (VT == XLenVT)
7393     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7394   else
7395     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7396 
7397   SDLoc DL(N);
7398   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7399                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7400   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7401 }
7402 
7403 // Fold
7404 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7405 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7406 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7407 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7408 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7409 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7410                                        TargetLowering::DAGCombinerInfo &DCI,
7411                                        const RISCVSubtarget &Subtarget) {
7412   SelectionDAG &DAG = DCI.DAG;
7413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7414   MVT XLenVT = Subtarget.getXLenVT();
7415 
7416   // Only handle XLen types. Other types narrower than XLen will eventually be
7417   // legalized to XLenVT.
7418   EVT DstVT = N->getValueType(0);
7419   if (DstVT != XLenVT)
7420     return SDValue();
7421 
7422   SDValue Src = N->getOperand(0);
7423 
7424   // Ensure the FP type is also legal.
7425   if (!TLI.isTypeLegal(Src.getValueType()))
7426     return SDValue();
7427 
7428   // Don't do this for f16 with Zfhmin and not Zfh.
7429   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7430     return SDValue();
7431 
7432   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7433 
7434   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7435   if (FRM == RISCVFPRndMode::Invalid)
7436     return SDValue();
7437 
7438   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7439 
7440   unsigned Opc;
7441   if (SatVT == DstVT)
7442     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7443   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7444     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7445   else
7446     return SDValue();
7447   // FIXME: Support other SatVTs by clamping before or after the conversion.
7448 
7449   Src = Src.getOperand(0);
7450 
7451   SDLoc DL(N);
7452   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7453                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7454 
7455   // RISCV FP-to-int conversions saturate to the destination register size, but
7456   // don't produce 0 for nan.
7457   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7458   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7459 }
7460 
7461 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7462                                                DAGCombinerInfo &DCI) const {
7463   SelectionDAG &DAG = DCI.DAG;
7464 
7465   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7466   // bits are demanded. N will be added to the Worklist if it was not deleted.
7467   // Caller should return SDValue(N, 0) if this returns true.
7468   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7469     SDValue Op = N->getOperand(OpNo);
7470     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7471     if (!SimplifyDemandedBits(Op, Mask, DCI))
7472       return false;
7473 
7474     if (N->getOpcode() != ISD::DELETED_NODE)
7475       DCI.AddToWorklist(N);
7476     return true;
7477   };
7478 
7479   switch (N->getOpcode()) {
7480   default:
7481     break;
7482   case RISCVISD::SplitF64: {
7483     SDValue Op0 = N->getOperand(0);
7484     // If the input to SplitF64 is just BuildPairF64 then the operation is
7485     // redundant. Instead, use BuildPairF64's operands directly.
7486     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7487       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7488 
7489     SDLoc DL(N);
7490 
7491     // It's cheaper to materialise two 32-bit integers than to load a double
7492     // from the constant pool and transfer it to integer registers through the
7493     // stack.
7494     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7495       APInt V = C->getValueAPF().bitcastToAPInt();
7496       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7497       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7498       return DCI.CombineTo(N, Lo, Hi);
7499     }
7500 
7501     // This is a target-specific version of a DAGCombine performed in
7502     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7503     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7504     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7505     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7506         !Op0.getNode()->hasOneUse())
7507       break;
7508     SDValue NewSplitF64 =
7509         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7510                     Op0.getOperand(0));
7511     SDValue Lo = NewSplitF64.getValue(0);
7512     SDValue Hi = NewSplitF64.getValue(1);
7513     APInt SignBit = APInt::getSignMask(32);
7514     if (Op0.getOpcode() == ISD::FNEG) {
7515       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7516                                   DAG.getConstant(SignBit, DL, MVT::i32));
7517       return DCI.CombineTo(N, Lo, NewHi);
7518     }
7519     assert(Op0.getOpcode() == ISD::FABS);
7520     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7521                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7522     return DCI.CombineTo(N, Lo, NewHi);
7523   }
7524   case RISCVISD::SLLW:
7525   case RISCVISD::SRAW:
7526   case RISCVISD::SRLW:
7527   case RISCVISD::ROLW:
7528   case RISCVISD::RORW: {
7529     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7530     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7531         SimplifyDemandedLowBitsHelper(1, 5))
7532       return SDValue(N, 0);
7533     break;
7534   }
7535   case RISCVISD::CLZW:
7536   case RISCVISD::CTZW: {
7537     // Only the lower 32 bits of the first operand are read
7538     if (SimplifyDemandedLowBitsHelper(0, 32))
7539       return SDValue(N, 0);
7540     break;
7541   }
7542   case RISCVISD::GREV:
7543   case RISCVISD::GORC: {
7544     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7545     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7546     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7547     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7548       return SDValue(N, 0);
7549 
7550     return combineGREVI_GORCI(N, DAG);
7551   }
7552   case RISCVISD::GREVW:
7553   case RISCVISD::GORCW: {
7554     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7555     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7556         SimplifyDemandedLowBitsHelper(1, 5))
7557       return SDValue(N, 0);
7558 
7559     return combineGREVI_GORCI(N, DAG);
7560   }
7561   case RISCVISD::SHFL:
7562   case RISCVISD::UNSHFL: {
7563     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7564     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7565     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7566     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7567       return SDValue(N, 0);
7568 
7569     break;
7570   }
7571   case RISCVISD::SHFLW:
7572   case RISCVISD::UNSHFLW: {
7573     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7574     SDValue LHS = N->getOperand(0);
7575     SDValue RHS = N->getOperand(1);
7576     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7577     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7578     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7579         SimplifyDemandedLowBitsHelper(1, 4))
7580       return SDValue(N, 0);
7581 
7582     break;
7583   }
7584   case RISCVISD::BCOMPRESSW:
7585   case RISCVISD::BDECOMPRESSW: {
7586     // Only the lower 32 bits of LHS and RHS are read.
7587     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7588         SimplifyDemandedLowBitsHelper(1, 32))
7589       return SDValue(N, 0);
7590 
7591     break;
7592   }
7593   case RISCVISD::FMV_X_ANYEXTH:
7594   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7595     SDLoc DL(N);
7596     SDValue Op0 = N->getOperand(0);
7597     MVT VT = N->getSimpleValueType(0);
7598     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7599     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7600     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7601     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7602          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7603         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7604          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7605       assert(Op0.getOperand(0).getValueType() == VT &&
7606              "Unexpected value type!");
7607       return Op0.getOperand(0);
7608     }
7609 
7610     // This is a target-specific version of a DAGCombine performed in
7611     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7612     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7613     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7614     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7615         !Op0.getNode()->hasOneUse())
7616       break;
7617     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7618     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7619     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7620     if (Op0.getOpcode() == ISD::FNEG)
7621       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7622                          DAG.getConstant(SignBit, DL, VT));
7623 
7624     assert(Op0.getOpcode() == ISD::FABS);
7625     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7626                        DAG.getConstant(~SignBit, DL, VT));
7627   }
7628   case ISD::ADD:
7629     return performADDCombine(N, DAG, Subtarget);
7630   case ISD::SUB:
7631     return performSUBCombine(N, DAG);
7632   case ISD::AND:
7633     return performANDCombine(N, DAG);
7634   case ISD::OR:
7635     return performORCombine(N, DAG, Subtarget);
7636   case ISD::XOR:
7637     return performXORCombine(N, DAG);
7638   case ISD::ANY_EXTEND:
7639     return performANY_EXTENDCombine(N, DCI, Subtarget);
7640   case ISD::ZERO_EXTEND:
7641     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7642     // type legalization. This is safe because fp_to_uint produces poison if
7643     // it overflows.
7644     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7645       SDValue Src = N->getOperand(0);
7646       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7647           isTypeLegal(Src.getOperand(0).getValueType()))
7648         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7649                            Src.getOperand(0));
7650       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7651           isTypeLegal(Src.getOperand(1).getValueType())) {
7652         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7653         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7654                                   Src.getOperand(0), Src.getOperand(1));
7655         DCI.CombineTo(N, Res);
7656         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7657         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7658         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7659       }
7660     }
7661     return SDValue();
7662   case RISCVISD::SELECT_CC: {
7663     // Transform
7664     SDValue LHS = N->getOperand(0);
7665     SDValue RHS = N->getOperand(1);
7666     SDValue TrueV = N->getOperand(3);
7667     SDValue FalseV = N->getOperand(4);
7668 
7669     // If the True and False values are the same, we don't need a select_cc.
7670     if (TrueV == FalseV)
7671       return TrueV;
7672 
7673     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7674     if (!ISD::isIntEqualitySetCC(CCVal))
7675       break;
7676 
7677     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7678     //      (select_cc X, Y, lt, trueV, falseV)
7679     // Sometimes the setcc is introduced after select_cc has been formed.
7680     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7681         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7682       // If we're looking for eq 0 instead of ne 0, we need to invert the
7683       // condition.
7684       bool Invert = CCVal == ISD::SETEQ;
7685       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7686       if (Invert)
7687         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7688 
7689       SDLoc DL(N);
7690       RHS = LHS.getOperand(1);
7691       LHS = LHS.getOperand(0);
7692       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7693 
7694       SDValue TargetCC = DAG.getCondCode(CCVal);
7695       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7696                          {LHS, RHS, TargetCC, TrueV, FalseV});
7697     }
7698 
7699     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7700     //      (select_cc X, Y, eq/ne, trueV, falseV)
7701     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7702       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7703                          {LHS.getOperand(0), LHS.getOperand(1),
7704                           N->getOperand(2), TrueV, FalseV});
7705     // (select_cc X, 1, setne, trueV, falseV) ->
7706     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7707     // This can occur when legalizing some floating point comparisons.
7708     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7709     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7710       SDLoc DL(N);
7711       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7712       SDValue TargetCC = DAG.getCondCode(CCVal);
7713       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7714       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7715                          {LHS, RHS, TargetCC, TrueV, FalseV});
7716     }
7717 
7718     break;
7719   }
7720   case RISCVISD::BR_CC: {
7721     SDValue LHS = N->getOperand(1);
7722     SDValue RHS = N->getOperand(2);
7723     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7724     if (!ISD::isIntEqualitySetCC(CCVal))
7725       break;
7726 
7727     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7728     //      (br_cc X, Y, lt, dest)
7729     // Sometimes the setcc is introduced after br_cc has been formed.
7730     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7731         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7732       // If we're looking for eq 0 instead of ne 0, we need to invert the
7733       // condition.
7734       bool Invert = CCVal == ISD::SETEQ;
7735       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7736       if (Invert)
7737         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7738 
7739       SDLoc DL(N);
7740       RHS = LHS.getOperand(1);
7741       LHS = LHS.getOperand(0);
7742       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7743 
7744       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7745                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7746                          N->getOperand(4));
7747     }
7748 
7749     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7750     //      (br_cc X, Y, eq/ne, trueV, falseV)
7751     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7752       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7753                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7754                          N->getOperand(3), N->getOperand(4));
7755 
7756     // (br_cc X, 1, setne, br_cc) ->
7757     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7758     // This can occur when legalizing some floating point comparisons.
7759     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7760     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7761       SDLoc DL(N);
7762       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7763       SDValue TargetCC = DAG.getCondCode(CCVal);
7764       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7765       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7766                          N->getOperand(0), LHS, RHS, TargetCC,
7767                          N->getOperand(4));
7768     }
7769     break;
7770   }
7771   case ISD::FP_TO_SINT:
7772   case ISD::FP_TO_UINT:
7773     return performFP_TO_INTCombine(N, DCI, Subtarget);
7774   case ISD::FP_TO_SINT_SAT:
7775   case ISD::FP_TO_UINT_SAT:
7776     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7777   case ISD::FCOPYSIGN: {
7778     EVT VT = N->getValueType(0);
7779     if (!VT.isVector())
7780       break;
7781     // There is a form of VFSGNJ which injects the negated sign of its second
7782     // operand. Try and bubble any FNEG up after the extend/round to produce
7783     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7784     // TRUNC=1.
7785     SDValue In2 = N->getOperand(1);
7786     // Avoid cases where the extend/round has multiple uses, as duplicating
7787     // those is typically more expensive than removing a fneg.
7788     if (!In2.hasOneUse())
7789       break;
7790     if (In2.getOpcode() != ISD::FP_EXTEND &&
7791         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7792       break;
7793     In2 = In2.getOperand(0);
7794     if (In2.getOpcode() != ISD::FNEG)
7795       break;
7796     SDLoc DL(N);
7797     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7798     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7799                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7800   }
7801   case ISD::MGATHER:
7802   case ISD::MSCATTER:
7803   case ISD::VP_GATHER:
7804   case ISD::VP_SCATTER: {
7805     if (!DCI.isBeforeLegalize())
7806       break;
7807     SDValue Index, ScaleOp;
7808     bool IsIndexScaled = false;
7809     bool IsIndexSigned = false;
7810     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7811       Index = VPGSN->getIndex();
7812       ScaleOp = VPGSN->getScale();
7813       IsIndexScaled = VPGSN->isIndexScaled();
7814       IsIndexSigned = VPGSN->isIndexSigned();
7815     } else {
7816       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7817       Index = MGSN->getIndex();
7818       ScaleOp = MGSN->getScale();
7819       IsIndexScaled = MGSN->isIndexScaled();
7820       IsIndexSigned = MGSN->isIndexSigned();
7821     }
7822     EVT IndexVT = Index.getValueType();
7823     MVT XLenVT = Subtarget.getXLenVT();
7824     // RISCV indexed loads only support the "unsigned unscaled" addressing
7825     // mode, so anything else must be manually legalized.
7826     bool NeedsIdxLegalization =
7827         IsIndexScaled ||
7828         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7829     if (!NeedsIdxLegalization)
7830       break;
7831 
7832     SDLoc DL(N);
7833 
7834     // Any index legalization should first promote to XLenVT, so we don't lose
7835     // bits when scaling. This may create an illegal index type so we let
7836     // LLVM's legalization take care of the splitting.
7837     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7838     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7839       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7840       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7841                           DL, IndexVT, Index);
7842     }
7843 
7844     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7845     if (IsIndexScaled && Scale != 1) {
7846       // Manually scale the indices by the element size.
7847       // TODO: Sanitize the scale operand here?
7848       // TODO: For VP nodes, should we use VP_SHL here?
7849       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7850       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7851       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7852     }
7853 
7854     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7855     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7856       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7857                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7858                               VPGN->getScale(), VPGN->getMask(),
7859                               VPGN->getVectorLength()},
7860                              VPGN->getMemOperand(), NewIndexTy);
7861     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7862       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7863                               {VPSN->getChain(), VPSN->getValue(),
7864                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7865                                VPSN->getMask(), VPSN->getVectorLength()},
7866                               VPSN->getMemOperand(), NewIndexTy);
7867     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7868       return DAG.getMaskedGather(
7869           N->getVTList(), MGN->getMemoryVT(), DL,
7870           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7871            MGN->getBasePtr(), Index, MGN->getScale()},
7872           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7873     const auto *MSN = cast<MaskedScatterSDNode>(N);
7874     return DAG.getMaskedScatter(
7875         N->getVTList(), MSN->getMemoryVT(), DL,
7876         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7877          Index, MSN->getScale()},
7878         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7879   }
7880   case RISCVISD::SRA_VL:
7881   case RISCVISD::SRL_VL:
7882   case RISCVISD::SHL_VL: {
7883     SDValue ShAmt = N->getOperand(1);
7884     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7885       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7886       SDLoc DL(N);
7887       SDValue VL = N->getOperand(3);
7888       EVT VT = N->getValueType(0);
7889       ShAmt =
7890           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7891       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7892                          N->getOperand(2), N->getOperand(3));
7893     }
7894     break;
7895   }
7896   case ISD::SRA:
7897   case ISD::SRL:
7898   case ISD::SHL: {
7899     SDValue ShAmt = N->getOperand(1);
7900     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7901       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7902       SDLoc DL(N);
7903       EVT VT = N->getValueType(0);
7904       ShAmt =
7905           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7906       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7907     }
7908     break;
7909   }
7910   case RISCVISD::MUL_VL:
7911     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
7912       return V;
7913     // Mul is commutative.
7914     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
7915   case ISD::STORE: {
7916     auto *Store = cast<StoreSDNode>(N);
7917     SDValue Val = Store->getValue();
7918     // Combine store of vmv.x.s to vse with VL of 1.
7919     // FIXME: Support FP.
7920     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7921       SDValue Src = Val.getOperand(0);
7922       EVT VecVT = Src.getValueType();
7923       EVT MemVT = Store->getMemoryVT();
7924       // The memory VT and the element type must match.
7925       if (VecVT.getVectorElementType() == MemVT) {
7926         SDLoc DL(N);
7927         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7928         return DAG.getStoreVP(
7929             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
7930             DAG.getConstant(1, DL, MaskVT),
7931             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
7932             Store->getMemOperand(), Store->getAddressingMode(),
7933             Store->isTruncatingStore(), /*IsCompress*/ false);
7934       }
7935     }
7936 
7937     break;
7938   }
7939   }
7940 
7941   return SDValue();
7942 }
7943 
7944 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7945     const SDNode *N, CombineLevel Level) const {
7946   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7947   // materialised in fewer instructions than `(OP _, c1)`:
7948   //
7949   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7950   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7951   SDValue N0 = N->getOperand(0);
7952   EVT Ty = N0.getValueType();
7953   if (Ty.isScalarInteger() &&
7954       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7955     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7956     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7957     if (C1 && C2) {
7958       const APInt &C1Int = C1->getAPIntValue();
7959       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7960 
7961       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7962       // and the combine should happen, to potentially allow further combines
7963       // later.
7964       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7965           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7966         return true;
7967 
7968       // We can materialise `c1` in an add immediate, so it's "free", and the
7969       // combine should be prevented.
7970       if (C1Int.getMinSignedBits() <= 64 &&
7971           isLegalAddImmediate(C1Int.getSExtValue()))
7972         return false;
7973 
7974       // Neither constant will fit into an immediate, so find materialisation
7975       // costs.
7976       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7977                                               Subtarget.getFeatureBits(),
7978                                               /*CompressionCost*/true);
7979       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7980           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7981           /*CompressionCost*/true);
7982 
7983       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7984       // combine should be prevented.
7985       if (C1Cost < ShiftedC1Cost)
7986         return false;
7987     }
7988   }
7989   return true;
7990 }
7991 
7992 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7993     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7994     TargetLoweringOpt &TLO) const {
7995   // Delay this optimization as late as possible.
7996   if (!TLO.LegalOps)
7997     return false;
7998 
7999   EVT VT = Op.getValueType();
8000   if (VT.isVector())
8001     return false;
8002 
8003   // Only handle AND for now.
8004   if (Op.getOpcode() != ISD::AND)
8005     return false;
8006 
8007   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8008   if (!C)
8009     return false;
8010 
8011   const APInt &Mask = C->getAPIntValue();
8012 
8013   // Clear all non-demanded bits initially.
8014   APInt ShrunkMask = Mask & DemandedBits;
8015 
8016   // Try to make a smaller immediate by setting undemanded bits.
8017 
8018   APInt ExpandedMask = Mask | ~DemandedBits;
8019 
8020   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8021     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8022   };
8023   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8024     if (NewMask == Mask)
8025       return true;
8026     SDLoc DL(Op);
8027     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8028     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8029     return TLO.CombineTo(Op, NewOp);
8030   };
8031 
8032   // If the shrunk mask fits in sign extended 12 bits, let the target
8033   // independent code apply it.
8034   if (ShrunkMask.isSignedIntN(12))
8035     return false;
8036 
8037   // Preserve (and X, 0xffff) when zext.h is supported.
8038   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8039     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8040     if (IsLegalMask(NewMask))
8041       return UseMask(NewMask);
8042   }
8043 
8044   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8045   if (VT == MVT::i64) {
8046     APInt NewMask = APInt(64, 0xffffffff);
8047     if (IsLegalMask(NewMask))
8048       return UseMask(NewMask);
8049   }
8050 
8051   // For the remaining optimizations, we need to be able to make a negative
8052   // number through a combination of mask and undemanded bits.
8053   if (!ExpandedMask.isNegative())
8054     return false;
8055 
8056   // What is the fewest number of bits we need to represent the negative number.
8057   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8058 
8059   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8060   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8061   APInt NewMask = ShrunkMask;
8062   if (MinSignedBits <= 12)
8063     NewMask.setBitsFrom(11);
8064   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8065     NewMask.setBitsFrom(31);
8066   else
8067     return false;
8068 
8069   // Check that our new mask is a subset of the demanded mask.
8070   assert(IsLegalMask(NewMask));
8071   return UseMask(NewMask);
8072 }
8073 
8074 static void computeGREV(APInt &Src, unsigned ShAmt) {
8075   ShAmt &= Src.getBitWidth() - 1;
8076   uint64_t x = Src.getZExtValue();
8077   if (ShAmt & 1)
8078     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8079   if (ShAmt & 2)
8080     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8081   if (ShAmt & 4)
8082     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8083   if (ShAmt & 8)
8084     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8085   if (ShAmt & 16)
8086     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8087   if (ShAmt & 32)
8088     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8089   Src = x;
8090 }
8091 
8092 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8093                                                         KnownBits &Known,
8094                                                         const APInt &DemandedElts,
8095                                                         const SelectionDAG &DAG,
8096                                                         unsigned Depth) const {
8097   unsigned BitWidth = Known.getBitWidth();
8098   unsigned Opc = Op.getOpcode();
8099   assert((Opc >= ISD::BUILTIN_OP_END ||
8100           Opc == ISD::INTRINSIC_WO_CHAIN ||
8101           Opc == ISD::INTRINSIC_W_CHAIN ||
8102           Opc == ISD::INTRINSIC_VOID) &&
8103          "Should use MaskedValueIsZero if you don't know whether Op"
8104          " is a target node!");
8105 
8106   Known.resetAll();
8107   switch (Opc) {
8108   default: break;
8109   case RISCVISD::SELECT_CC: {
8110     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8111     // If we don't know any bits, early out.
8112     if (Known.isUnknown())
8113       break;
8114     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8115 
8116     // Only known if known in both the LHS and RHS.
8117     Known = KnownBits::commonBits(Known, Known2);
8118     break;
8119   }
8120   case RISCVISD::REMUW: {
8121     KnownBits Known2;
8122     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8123     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8124     // We only care about the lower 32 bits.
8125     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8126     // Restore the original width by sign extending.
8127     Known = Known.sext(BitWidth);
8128     break;
8129   }
8130   case RISCVISD::DIVUW: {
8131     KnownBits Known2;
8132     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8133     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8134     // We only care about the lower 32 bits.
8135     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8136     // Restore the original width by sign extending.
8137     Known = Known.sext(BitWidth);
8138     break;
8139   }
8140   case RISCVISD::CTZW: {
8141     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8142     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8143     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8144     Known.Zero.setBitsFrom(LowBits);
8145     break;
8146   }
8147   case RISCVISD::CLZW: {
8148     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8149     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8150     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8151     Known.Zero.setBitsFrom(LowBits);
8152     break;
8153   }
8154   case RISCVISD::GREV:
8155   case RISCVISD::GREVW: {
8156     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8157       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8158       if (Opc == RISCVISD::GREVW)
8159         Known = Known.trunc(32);
8160       unsigned ShAmt = C->getZExtValue();
8161       computeGREV(Known.Zero, ShAmt);
8162       computeGREV(Known.One, ShAmt);
8163       if (Opc == RISCVISD::GREVW)
8164         Known = Known.sext(BitWidth);
8165     }
8166     break;
8167   }
8168   case RISCVISD::READ_VLENB:
8169     // We assume VLENB is at least 16 bytes.
8170     Known.Zero.setLowBits(4);
8171     // We assume VLENB is no more than 65536 / 8 bytes.
8172     Known.Zero.setBitsFrom(14);
8173     break;
8174   case ISD::INTRINSIC_W_CHAIN:
8175   case ISD::INTRINSIC_WO_CHAIN: {
8176     unsigned IntNo =
8177         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8178     switch (IntNo) {
8179     default:
8180       // We can't do anything for most intrinsics.
8181       break;
8182     case Intrinsic::riscv_vsetvli:
8183     case Intrinsic::riscv_vsetvlimax:
8184     case Intrinsic::riscv_vsetvli_opt:
8185     case Intrinsic::riscv_vsetvlimax_opt:
8186       // Assume that VL output is positive and would fit in an int32_t.
8187       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8188       if (BitWidth >= 32)
8189         Known.Zero.setBitsFrom(31);
8190       break;
8191     }
8192     break;
8193   }
8194   }
8195 }
8196 
8197 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8198     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8199     unsigned Depth) const {
8200   switch (Op.getOpcode()) {
8201   default:
8202     break;
8203   case RISCVISD::SELECT_CC: {
8204     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8205     if (Tmp == 1) return 1;  // Early out.
8206     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8207     return std::min(Tmp, Tmp2);
8208   }
8209   case RISCVISD::SLLW:
8210   case RISCVISD::SRAW:
8211   case RISCVISD::SRLW:
8212   case RISCVISD::DIVW:
8213   case RISCVISD::DIVUW:
8214   case RISCVISD::REMUW:
8215   case RISCVISD::ROLW:
8216   case RISCVISD::RORW:
8217   case RISCVISD::GREVW:
8218   case RISCVISD::GORCW:
8219   case RISCVISD::FSLW:
8220   case RISCVISD::FSRW:
8221   case RISCVISD::SHFLW:
8222   case RISCVISD::UNSHFLW:
8223   case RISCVISD::BCOMPRESSW:
8224   case RISCVISD::BDECOMPRESSW:
8225   case RISCVISD::BFPW:
8226   case RISCVISD::FCVT_W_RV64:
8227   case RISCVISD::FCVT_WU_RV64:
8228   case RISCVISD::STRICT_FCVT_W_RV64:
8229   case RISCVISD::STRICT_FCVT_WU_RV64:
8230     // TODO: As the result is sign-extended, this is conservatively correct. A
8231     // more precise answer could be calculated for SRAW depending on known
8232     // bits in the shift amount.
8233     return 33;
8234   case RISCVISD::SHFL:
8235   case RISCVISD::UNSHFL: {
8236     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8237     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8238     // will stay within the upper 32 bits. If there were more than 32 sign bits
8239     // before there will be at least 33 sign bits after.
8240     if (Op.getValueType() == MVT::i64 &&
8241         isa<ConstantSDNode>(Op.getOperand(1)) &&
8242         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8243       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8244       if (Tmp > 32)
8245         return 33;
8246     }
8247     break;
8248   }
8249   case RISCVISD::VMV_X_S:
8250     // The number of sign bits of the scalar result is computed by obtaining the
8251     // element type of the input vector operand, subtracting its width from the
8252     // XLEN, and then adding one (sign bit within the element type). If the
8253     // element type is wider than XLen, the least-significant XLEN bits are
8254     // taken.
8255     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
8256       return 1;
8257     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
8258   }
8259 
8260   return 1;
8261 }
8262 
8263 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8264                                                   MachineBasicBlock *BB) {
8265   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8266 
8267   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8268   // Should the count have wrapped while it was being read, we need to try
8269   // again.
8270   // ...
8271   // read:
8272   // rdcycleh x3 # load high word of cycle
8273   // rdcycle  x2 # load low word of cycle
8274   // rdcycleh x4 # load high word of cycle
8275   // bne x3, x4, read # check if high word reads match, otherwise try again
8276   // ...
8277 
8278   MachineFunction &MF = *BB->getParent();
8279   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8280   MachineFunction::iterator It = ++BB->getIterator();
8281 
8282   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8283   MF.insert(It, LoopMBB);
8284 
8285   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8286   MF.insert(It, DoneMBB);
8287 
8288   // Transfer the remainder of BB and its successor edges to DoneMBB.
8289   DoneMBB->splice(DoneMBB->begin(), BB,
8290                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8291   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8292 
8293   BB->addSuccessor(LoopMBB);
8294 
8295   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8296   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8297   Register LoReg = MI.getOperand(0).getReg();
8298   Register HiReg = MI.getOperand(1).getReg();
8299   DebugLoc DL = MI.getDebugLoc();
8300 
8301   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8302   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8303       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8304       .addReg(RISCV::X0);
8305   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8306       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8307       .addReg(RISCV::X0);
8308   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8309       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8310       .addReg(RISCV::X0);
8311 
8312   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8313       .addReg(HiReg)
8314       .addReg(ReadAgainReg)
8315       .addMBB(LoopMBB);
8316 
8317   LoopMBB->addSuccessor(LoopMBB);
8318   LoopMBB->addSuccessor(DoneMBB);
8319 
8320   MI.eraseFromParent();
8321 
8322   return DoneMBB;
8323 }
8324 
8325 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8326                                              MachineBasicBlock *BB) {
8327   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8328 
8329   MachineFunction &MF = *BB->getParent();
8330   DebugLoc DL = MI.getDebugLoc();
8331   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8332   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8333   Register LoReg = MI.getOperand(0).getReg();
8334   Register HiReg = MI.getOperand(1).getReg();
8335   Register SrcReg = MI.getOperand(2).getReg();
8336   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8337   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8338 
8339   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8340                           RI);
8341   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8342   MachineMemOperand *MMOLo =
8343       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8344   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8345       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8346   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8347       .addFrameIndex(FI)
8348       .addImm(0)
8349       .addMemOperand(MMOLo);
8350   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8351       .addFrameIndex(FI)
8352       .addImm(4)
8353       .addMemOperand(MMOHi);
8354   MI.eraseFromParent(); // The pseudo instruction is gone now.
8355   return BB;
8356 }
8357 
8358 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8359                                                  MachineBasicBlock *BB) {
8360   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8361          "Unexpected instruction");
8362 
8363   MachineFunction &MF = *BB->getParent();
8364   DebugLoc DL = MI.getDebugLoc();
8365   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8366   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8367   Register DstReg = MI.getOperand(0).getReg();
8368   Register LoReg = MI.getOperand(1).getReg();
8369   Register HiReg = MI.getOperand(2).getReg();
8370   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8371   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8372 
8373   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8374   MachineMemOperand *MMOLo =
8375       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8376   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8377       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8378   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8379       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8380       .addFrameIndex(FI)
8381       .addImm(0)
8382       .addMemOperand(MMOLo);
8383   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8384       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8385       .addFrameIndex(FI)
8386       .addImm(4)
8387       .addMemOperand(MMOHi);
8388   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8389   MI.eraseFromParent(); // The pseudo instruction is gone now.
8390   return BB;
8391 }
8392 
8393 static bool isSelectPseudo(MachineInstr &MI) {
8394   switch (MI.getOpcode()) {
8395   default:
8396     return false;
8397   case RISCV::Select_GPR_Using_CC_GPR:
8398   case RISCV::Select_FPR16_Using_CC_GPR:
8399   case RISCV::Select_FPR32_Using_CC_GPR:
8400   case RISCV::Select_FPR64_Using_CC_GPR:
8401     return true;
8402   }
8403 }
8404 
8405 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8406                                         unsigned RelOpcode, unsigned EqOpcode,
8407                                         const RISCVSubtarget &Subtarget) {
8408   DebugLoc DL = MI.getDebugLoc();
8409   Register DstReg = MI.getOperand(0).getReg();
8410   Register Src1Reg = MI.getOperand(1).getReg();
8411   Register Src2Reg = MI.getOperand(2).getReg();
8412   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8413   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8414   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8415 
8416   // Save the current FFLAGS.
8417   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8418 
8419   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8420                  .addReg(Src1Reg)
8421                  .addReg(Src2Reg);
8422   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8423     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8424 
8425   // Restore the FFLAGS.
8426   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8427       .addReg(SavedFFlags, RegState::Kill);
8428 
8429   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8430   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8431                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8432                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8433   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8434     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8435 
8436   // Erase the pseudoinstruction.
8437   MI.eraseFromParent();
8438   return BB;
8439 }
8440 
8441 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8442                                            MachineBasicBlock *BB,
8443                                            const RISCVSubtarget &Subtarget) {
8444   // To "insert" Select_* instructions, we actually have to insert the triangle
8445   // control-flow pattern.  The incoming instructions know the destination vreg
8446   // to set, the condition code register to branch on, the true/false values to
8447   // select between, and the condcode to use to select the appropriate branch.
8448   //
8449   // We produce the following control flow:
8450   //     HeadMBB
8451   //     |  \
8452   //     |  IfFalseMBB
8453   //     | /
8454   //    TailMBB
8455   //
8456   // When we find a sequence of selects we attempt to optimize their emission
8457   // by sharing the control flow. Currently we only handle cases where we have
8458   // multiple selects with the exact same condition (same LHS, RHS and CC).
8459   // The selects may be interleaved with other instructions if the other
8460   // instructions meet some requirements we deem safe:
8461   // - They are debug instructions. Otherwise,
8462   // - They do not have side-effects, do not access memory and their inputs do
8463   //   not depend on the results of the select pseudo-instructions.
8464   // The TrueV/FalseV operands of the selects cannot depend on the result of
8465   // previous selects in the sequence.
8466   // These conditions could be further relaxed. See the X86 target for a
8467   // related approach and more information.
8468   Register LHS = MI.getOperand(1).getReg();
8469   Register RHS = MI.getOperand(2).getReg();
8470   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8471 
8472   SmallVector<MachineInstr *, 4> SelectDebugValues;
8473   SmallSet<Register, 4> SelectDests;
8474   SelectDests.insert(MI.getOperand(0).getReg());
8475 
8476   MachineInstr *LastSelectPseudo = &MI;
8477 
8478   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8479        SequenceMBBI != E; ++SequenceMBBI) {
8480     if (SequenceMBBI->isDebugInstr())
8481       continue;
8482     else if (isSelectPseudo(*SequenceMBBI)) {
8483       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8484           SequenceMBBI->getOperand(2).getReg() != RHS ||
8485           SequenceMBBI->getOperand(3).getImm() != CC ||
8486           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8487           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8488         break;
8489       LastSelectPseudo = &*SequenceMBBI;
8490       SequenceMBBI->collectDebugValues(SelectDebugValues);
8491       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8492     } else {
8493       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8494           SequenceMBBI->mayLoadOrStore())
8495         break;
8496       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8497             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8498           }))
8499         break;
8500     }
8501   }
8502 
8503   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8504   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8505   DebugLoc DL = MI.getDebugLoc();
8506   MachineFunction::iterator I = ++BB->getIterator();
8507 
8508   MachineBasicBlock *HeadMBB = BB;
8509   MachineFunction *F = BB->getParent();
8510   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8511   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8512 
8513   F->insert(I, IfFalseMBB);
8514   F->insert(I, TailMBB);
8515 
8516   // Transfer debug instructions associated with the selects to TailMBB.
8517   for (MachineInstr *DebugInstr : SelectDebugValues) {
8518     TailMBB->push_back(DebugInstr->removeFromParent());
8519   }
8520 
8521   // Move all instructions after the sequence to TailMBB.
8522   TailMBB->splice(TailMBB->end(), HeadMBB,
8523                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8524   // Update machine-CFG edges by transferring all successors of the current
8525   // block to the new block which will contain the Phi nodes for the selects.
8526   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8527   // Set the successors for HeadMBB.
8528   HeadMBB->addSuccessor(IfFalseMBB);
8529   HeadMBB->addSuccessor(TailMBB);
8530 
8531   // Insert appropriate branch.
8532   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8533     .addReg(LHS)
8534     .addReg(RHS)
8535     .addMBB(TailMBB);
8536 
8537   // IfFalseMBB just falls through to TailMBB.
8538   IfFalseMBB->addSuccessor(TailMBB);
8539 
8540   // Create PHIs for all of the select pseudo-instructions.
8541   auto SelectMBBI = MI.getIterator();
8542   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8543   auto InsertionPoint = TailMBB->begin();
8544   while (SelectMBBI != SelectEnd) {
8545     auto Next = std::next(SelectMBBI);
8546     if (isSelectPseudo(*SelectMBBI)) {
8547       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8548       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8549               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8550           .addReg(SelectMBBI->getOperand(4).getReg())
8551           .addMBB(HeadMBB)
8552           .addReg(SelectMBBI->getOperand(5).getReg())
8553           .addMBB(IfFalseMBB);
8554       SelectMBBI->eraseFromParent();
8555     }
8556     SelectMBBI = Next;
8557   }
8558 
8559   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8560   return TailMBB;
8561 }
8562 
8563 MachineBasicBlock *
8564 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8565                                                  MachineBasicBlock *BB) const {
8566   switch (MI.getOpcode()) {
8567   default:
8568     llvm_unreachable("Unexpected instr type to insert");
8569   case RISCV::ReadCycleWide:
8570     assert(!Subtarget.is64Bit() &&
8571            "ReadCycleWrite is only to be used on riscv32");
8572     return emitReadCycleWidePseudo(MI, BB);
8573   case RISCV::Select_GPR_Using_CC_GPR:
8574   case RISCV::Select_FPR16_Using_CC_GPR:
8575   case RISCV::Select_FPR32_Using_CC_GPR:
8576   case RISCV::Select_FPR64_Using_CC_GPR:
8577     return emitSelectPseudo(MI, BB, Subtarget);
8578   case RISCV::BuildPairF64Pseudo:
8579     return emitBuildPairF64Pseudo(MI, BB);
8580   case RISCV::SplitF64Pseudo:
8581     return emitSplitF64Pseudo(MI, BB);
8582   case RISCV::PseudoQuietFLE_H:
8583     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8584   case RISCV::PseudoQuietFLT_H:
8585     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8586   case RISCV::PseudoQuietFLE_S:
8587     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8588   case RISCV::PseudoQuietFLT_S:
8589     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8590   case RISCV::PseudoQuietFLE_D:
8591     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8592   case RISCV::PseudoQuietFLT_D:
8593     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8594   }
8595 }
8596 
8597 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8598                                                         SDNode *Node) const {
8599   // Add FRM dependency to any instructions with dynamic rounding mode.
8600   unsigned Opc = MI.getOpcode();
8601   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8602   if (Idx < 0)
8603     return;
8604   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8605     return;
8606   // If the instruction already reads FRM, don't add another read.
8607   if (MI.readsRegister(RISCV::FRM))
8608     return;
8609   MI.addOperand(
8610       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8611 }
8612 
8613 // Calling Convention Implementation.
8614 // The expectations for frontend ABI lowering vary from target to target.
8615 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8616 // details, but this is a longer term goal. For now, we simply try to keep the
8617 // role of the frontend as simple and well-defined as possible. The rules can
8618 // be summarised as:
8619 // * Never split up large scalar arguments. We handle them here.
8620 // * If a hardfloat calling convention is being used, and the struct may be
8621 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8622 // available, then pass as two separate arguments. If either the GPRs or FPRs
8623 // are exhausted, then pass according to the rule below.
8624 // * If a struct could never be passed in registers or directly in a stack
8625 // slot (as it is larger than 2*XLEN and the floating point rules don't
8626 // apply), then pass it using a pointer with the byval attribute.
8627 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8628 // word-sized array or a 2*XLEN scalar (depending on alignment).
8629 // * The frontend can determine whether a struct is returned by reference or
8630 // not based on its size and fields. If it will be returned by reference, the
8631 // frontend must modify the prototype so a pointer with the sret annotation is
8632 // passed as the first argument. This is not necessary for large scalar
8633 // returns.
8634 // * Struct return values and varargs should be coerced to structs containing
8635 // register-size fields in the same situations they would be for fixed
8636 // arguments.
8637 
8638 static const MCPhysReg ArgGPRs[] = {
8639   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8640   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8641 };
8642 static const MCPhysReg ArgFPR16s[] = {
8643   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8644   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8645 };
8646 static const MCPhysReg ArgFPR32s[] = {
8647   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8648   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8649 };
8650 static const MCPhysReg ArgFPR64s[] = {
8651   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8652   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8653 };
8654 // This is an interim calling convention and it may be changed in the future.
8655 static const MCPhysReg ArgVRs[] = {
8656     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8657     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8658     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8659 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8660                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8661                                      RISCV::V20M2, RISCV::V22M2};
8662 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8663                                      RISCV::V20M4};
8664 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8665 
8666 // Pass a 2*XLEN argument that has been split into two XLEN values through
8667 // registers or the stack as necessary.
8668 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8669                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8670                                 MVT ValVT2, MVT LocVT2,
8671                                 ISD::ArgFlagsTy ArgFlags2) {
8672   unsigned XLenInBytes = XLen / 8;
8673   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8674     // At least one half can be passed via register.
8675     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8676                                      VA1.getLocVT(), CCValAssign::Full));
8677   } else {
8678     // Both halves must be passed on the stack, with proper alignment.
8679     Align StackAlign =
8680         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8681     State.addLoc(
8682         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8683                             State.AllocateStack(XLenInBytes, StackAlign),
8684                             VA1.getLocVT(), CCValAssign::Full));
8685     State.addLoc(CCValAssign::getMem(
8686         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8687         LocVT2, CCValAssign::Full));
8688     return false;
8689   }
8690 
8691   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8692     // The second half can also be passed via register.
8693     State.addLoc(
8694         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8695   } else {
8696     // The second half is passed via the stack, without additional alignment.
8697     State.addLoc(CCValAssign::getMem(
8698         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8699         LocVT2, CCValAssign::Full));
8700   }
8701 
8702   return false;
8703 }
8704 
8705 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8706                                Optional<unsigned> FirstMaskArgument,
8707                                CCState &State, const RISCVTargetLowering &TLI) {
8708   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8709   if (RC == &RISCV::VRRegClass) {
8710     // Assign the first mask argument to V0.
8711     // This is an interim calling convention and it may be changed in the
8712     // future.
8713     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8714       return State.AllocateReg(RISCV::V0);
8715     return State.AllocateReg(ArgVRs);
8716   }
8717   if (RC == &RISCV::VRM2RegClass)
8718     return State.AllocateReg(ArgVRM2s);
8719   if (RC == &RISCV::VRM4RegClass)
8720     return State.AllocateReg(ArgVRM4s);
8721   if (RC == &RISCV::VRM8RegClass)
8722     return State.AllocateReg(ArgVRM8s);
8723   llvm_unreachable("Unhandled register class for ValueType");
8724 }
8725 
8726 // Implements the RISC-V calling convention. Returns true upon failure.
8727 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8728                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8729                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8730                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8731                      Optional<unsigned> FirstMaskArgument) {
8732   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8733   assert(XLen == 32 || XLen == 64);
8734   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8735 
8736   // Any return value split in to more than two values can't be returned
8737   // directly. Vectors are returned via the available vector registers.
8738   if (!LocVT.isVector() && IsRet && ValNo > 1)
8739     return true;
8740 
8741   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8742   // variadic argument, or if no F16/F32 argument registers are available.
8743   bool UseGPRForF16_F32 = true;
8744   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8745   // variadic argument, or if no F64 argument registers are available.
8746   bool UseGPRForF64 = true;
8747 
8748   switch (ABI) {
8749   default:
8750     llvm_unreachable("Unexpected ABI");
8751   case RISCVABI::ABI_ILP32:
8752   case RISCVABI::ABI_LP64:
8753     break;
8754   case RISCVABI::ABI_ILP32F:
8755   case RISCVABI::ABI_LP64F:
8756     UseGPRForF16_F32 = !IsFixed;
8757     break;
8758   case RISCVABI::ABI_ILP32D:
8759   case RISCVABI::ABI_LP64D:
8760     UseGPRForF16_F32 = !IsFixed;
8761     UseGPRForF64 = !IsFixed;
8762     break;
8763   }
8764 
8765   // FPR16, FPR32, and FPR64 alias each other.
8766   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8767     UseGPRForF16_F32 = true;
8768     UseGPRForF64 = true;
8769   }
8770 
8771   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8772   // similar local variables rather than directly checking against the target
8773   // ABI.
8774 
8775   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8776     LocVT = XLenVT;
8777     LocInfo = CCValAssign::BCvt;
8778   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8779     LocVT = MVT::i64;
8780     LocInfo = CCValAssign::BCvt;
8781   }
8782 
8783   // If this is a variadic argument, the RISC-V calling convention requires
8784   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8785   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8786   // be used regardless of whether the original argument was split during
8787   // legalisation or not. The argument will not be passed by registers if the
8788   // original type is larger than 2*XLEN, so the register alignment rule does
8789   // not apply.
8790   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8791   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8792       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8793     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8794     // Skip 'odd' register if necessary.
8795     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8796       State.AllocateReg(ArgGPRs);
8797   }
8798 
8799   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8800   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8801       State.getPendingArgFlags();
8802 
8803   assert(PendingLocs.size() == PendingArgFlags.size() &&
8804          "PendingLocs and PendingArgFlags out of sync");
8805 
8806   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8807   // registers are exhausted.
8808   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8809     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8810            "Can't lower f64 if it is split");
8811     // Depending on available argument GPRS, f64 may be passed in a pair of
8812     // GPRs, split between a GPR and the stack, or passed completely on the
8813     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8814     // cases.
8815     Register Reg = State.AllocateReg(ArgGPRs);
8816     LocVT = MVT::i32;
8817     if (!Reg) {
8818       unsigned StackOffset = State.AllocateStack(8, Align(8));
8819       State.addLoc(
8820           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8821       return false;
8822     }
8823     if (!State.AllocateReg(ArgGPRs))
8824       State.AllocateStack(4, Align(4));
8825     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8826     return false;
8827   }
8828 
8829   // Fixed-length vectors are located in the corresponding scalable-vector
8830   // container types.
8831   if (ValVT.isFixedLengthVector())
8832     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8833 
8834   // Split arguments might be passed indirectly, so keep track of the pending
8835   // values. Split vectors are passed via a mix of registers and indirectly, so
8836   // treat them as we would any other argument.
8837   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8838     LocVT = XLenVT;
8839     LocInfo = CCValAssign::Indirect;
8840     PendingLocs.push_back(
8841         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8842     PendingArgFlags.push_back(ArgFlags);
8843     if (!ArgFlags.isSplitEnd()) {
8844       return false;
8845     }
8846   }
8847 
8848   // If the split argument only had two elements, it should be passed directly
8849   // in registers or on the stack.
8850   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8851       PendingLocs.size() <= 2) {
8852     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8853     // Apply the normal calling convention rules to the first half of the
8854     // split argument.
8855     CCValAssign VA = PendingLocs[0];
8856     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8857     PendingLocs.clear();
8858     PendingArgFlags.clear();
8859     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8860                                ArgFlags);
8861   }
8862 
8863   // Allocate to a register if possible, or else a stack slot.
8864   Register Reg;
8865   unsigned StoreSizeBytes = XLen / 8;
8866   Align StackAlign = Align(XLen / 8);
8867 
8868   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8869     Reg = State.AllocateReg(ArgFPR16s);
8870   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8871     Reg = State.AllocateReg(ArgFPR32s);
8872   else if (ValVT == MVT::f64 && !UseGPRForF64)
8873     Reg = State.AllocateReg(ArgFPR64s);
8874   else if (ValVT.isVector()) {
8875     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8876     if (!Reg) {
8877       // For return values, the vector must be passed fully via registers or
8878       // via the stack.
8879       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8880       // but we're using all of them.
8881       if (IsRet)
8882         return true;
8883       // Try using a GPR to pass the address
8884       if ((Reg = State.AllocateReg(ArgGPRs))) {
8885         LocVT = XLenVT;
8886         LocInfo = CCValAssign::Indirect;
8887       } else if (ValVT.isScalableVector()) {
8888         LocVT = XLenVT;
8889         LocInfo = CCValAssign::Indirect;
8890       } else {
8891         // Pass fixed-length vectors on the stack.
8892         LocVT = ValVT;
8893         StoreSizeBytes = ValVT.getStoreSize();
8894         // Align vectors to their element sizes, being careful for vXi1
8895         // vectors.
8896         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8897       }
8898     }
8899   } else {
8900     Reg = State.AllocateReg(ArgGPRs);
8901   }
8902 
8903   unsigned StackOffset =
8904       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8905 
8906   // If we reach this point and PendingLocs is non-empty, we must be at the
8907   // end of a split argument that must be passed indirectly.
8908   if (!PendingLocs.empty()) {
8909     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8910     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8911 
8912     for (auto &It : PendingLocs) {
8913       if (Reg)
8914         It.convertToReg(Reg);
8915       else
8916         It.convertToMem(StackOffset);
8917       State.addLoc(It);
8918     }
8919     PendingLocs.clear();
8920     PendingArgFlags.clear();
8921     return false;
8922   }
8923 
8924   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8925           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8926          "Expected an XLenVT or vector types at this stage");
8927 
8928   if (Reg) {
8929     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8930     return false;
8931   }
8932 
8933   // When a floating-point value is passed on the stack, no bit-conversion is
8934   // needed.
8935   if (ValVT.isFloatingPoint()) {
8936     LocVT = ValVT;
8937     LocInfo = CCValAssign::Full;
8938   }
8939   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8940   return false;
8941 }
8942 
8943 template <typename ArgTy>
8944 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8945   for (const auto &ArgIdx : enumerate(Args)) {
8946     MVT ArgVT = ArgIdx.value().VT;
8947     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8948       return ArgIdx.index();
8949   }
8950   return None;
8951 }
8952 
8953 void RISCVTargetLowering::analyzeInputArgs(
8954     MachineFunction &MF, CCState &CCInfo,
8955     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8956     RISCVCCAssignFn Fn) const {
8957   unsigned NumArgs = Ins.size();
8958   FunctionType *FType = MF.getFunction().getFunctionType();
8959 
8960   Optional<unsigned> FirstMaskArgument;
8961   if (Subtarget.hasVInstructions())
8962     FirstMaskArgument = preAssignMask(Ins);
8963 
8964   for (unsigned i = 0; i != NumArgs; ++i) {
8965     MVT ArgVT = Ins[i].VT;
8966     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8967 
8968     Type *ArgTy = nullptr;
8969     if (IsRet)
8970       ArgTy = FType->getReturnType();
8971     else if (Ins[i].isOrigArg())
8972       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8973 
8974     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8975     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8976            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8977            FirstMaskArgument)) {
8978       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8979                         << EVT(ArgVT).getEVTString() << '\n');
8980       llvm_unreachable(nullptr);
8981     }
8982   }
8983 }
8984 
8985 void RISCVTargetLowering::analyzeOutputArgs(
8986     MachineFunction &MF, CCState &CCInfo,
8987     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8988     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8989   unsigned NumArgs = Outs.size();
8990 
8991   Optional<unsigned> FirstMaskArgument;
8992   if (Subtarget.hasVInstructions())
8993     FirstMaskArgument = preAssignMask(Outs);
8994 
8995   for (unsigned i = 0; i != NumArgs; i++) {
8996     MVT ArgVT = Outs[i].VT;
8997     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8998     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8999 
9000     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9001     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9002            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9003            FirstMaskArgument)) {
9004       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9005                         << EVT(ArgVT).getEVTString() << "\n");
9006       llvm_unreachable(nullptr);
9007     }
9008   }
9009 }
9010 
9011 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9012 // values.
9013 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9014                                    const CCValAssign &VA, const SDLoc &DL,
9015                                    const RISCVSubtarget &Subtarget) {
9016   switch (VA.getLocInfo()) {
9017   default:
9018     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9019   case CCValAssign::Full:
9020     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9021       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9022     break;
9023   case CCValAssign::BCvt:
9024     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9025       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9026     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9027       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9028     else
9029       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9030     break;
9031   }
9032   return Val;
9033 }
9034 
9035 // The caller is responsible for loading the full value if the argument is
9036 // passed with CCValAssign::Indirect.
9037 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9038                                 const CCValAssign &VA, const SDLoc &DL,
9039                                 const RISCVTargetLowering &TLI) {
9040   MachineFunction &MF = DAG.getMachineFunction();
9041   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9042   EVT LocVT = VA.getLocVT();
9043   SDValue Val;
9044   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9045   Register VReg = RegInfo.createVirtualRegister(RC);
9046   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9047   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9048 
9049   if (VA.getLocInfo() == CCValAssign::Indirect)
9050     return Val;
9051 
9052   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9053 }
9054 
9055 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9056                                    const CCValAssign &VA, const SDLoc &DL,
9057                                    const RISCVSubtarget &Subtarget) {
9058   EVT LocVT = VA.getLocVT();
9059 
9060   switch (VA.getLocInfo()) {
9061   default:
9062     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9063   case CCValAssign::Full:
9064     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9065       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9066     break;
9067   case CCValAssign::BCvt:
9068     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9069       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9070     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9071       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9072     else
9073       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9074     break;
9075   }
9076   return Val;
9077 }
9078 
9079 // The caller is responsible for loading the full value if the argument is
9080 // passed with CCValAssign::Indirect.
9081 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9082                                 const CCValAssign &VA, const SDLoc &DL) {
9083   MachineFunction &MF = DAG.getMachineFunction();
9084   MachineFrameInfo &MFI = MF.getFrameInfo();
9085   EVT LocVT = VA.getLocVT();
9086   EVT ValVT = VA.getValVT();
9087   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9088   if (ValVT.isScalableVector()) {
9089     // When the value is a scalable vector, we save the pointer which points to
9090     // the scalable vector value in the stack. The ValVT will be the pointer
9091     // type, instead of the scalable vector type.
9092     ValVT = LocVT;
9093   }
9094   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9095                                  /*IsImmutable=*/true);
9096   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9097   SDValue Val;
9098 
9099   ISD::LoadExtType ExtType;
9100   switch (VA.getLocInfo()) {
9101   default:
9102     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9103   case CCValAssign::Full:
9104   case CCValAssign::Indirect:
9105   case CCValAssign::BCvt:
9106     ExtType = ISD::NON_EXTLOAD;
9107     break;
9108   }
9109   Val = DAG.getExtLoad(
9110       ExtType, DL, LocVT, Chain, FIN,
9111       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9112   return Val;
9113 }
9114 
9115 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9116                                        const CCValAssign &VA, const SDLoc &DL) {
9117   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9118          "Unexpected VA");
9119   MachineFunction &MF = DAG.getMachineFunction();
9120   MachineFrameInfo &MFI = MF.getFrameInfo();
9121   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9122 
9123   if (VA.isMemLoc()) {
9124     // f64 is passed on the stack.
9125     int FI =
9126         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9127     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9128     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9129                        MachinePointerInfo::getFixedStack(MF, FI));
9130   }
9131 
9132   assert(VA.isRegLoc() && "Expected register VA assignment");
9133 
9134   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9135   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9136   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9137   SDValue Hi;
9138   if (VA.getLocReg() == RISCV::X17) {
9139     // Second half of f64 is passed on the stack.
9140     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9141     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9142     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9143                      MachinePointerInfo::getFixedStack(MF, FI));
9144   } else {
9145     // Second half of f64 is passed in another GPR.
9146     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9147     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9148     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9149   }
9150   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9151 }
9152 
9153 // FastCC has less than 1% performance improvement for some particular
9154 // benchmark. But theoretically, it may has benenfit for some cases.
9155 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9156                             unsigned ValNo, MVT ValVT, MVT LocVT,
9157                             CCValAssign::LocInfo LocInfo,
9158                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9159                             bool IsFixed, bool IsRet, Type *OrigTy,
9160                             const RISCVTargetLowering &TLI,
9161                             Optional<unsigned> FirstMaskArgument) {
9162 
9163   // X5 and X6 might be used for save-restore libcall.
9164   static const MCPhysReg GPRList[] = {
9165       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9166       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9167       RISCV::X29, RISCV::X30, RISCV::X31};
9168 
9169   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9170     if (unsigned Reg = State.AllocateReg(GPRList)) {
9171       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9172       return false;
9173     }
9174   }
9175 
9176   if (LocVT == MVT::f16) {
9177     static const MCPhysReg FPR16List[] = {
9178         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9179         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9180         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9181         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9182     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9183       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9184       return false;
9185     }
9186   }
9187 
9188   if (LocVT == MVT::f32) {
9189     static const MCPhysReg FPR32List[] = {
9190         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9191         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9192         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9193         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9194     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9195       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9196       return false;
9197     }
9198   }
9199 
9200   if (LocVT == MVT::f64) {
9201     static const MCPhysReg FPR64List[] = {
9202         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9203         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9204         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9205         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9206     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9207       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9208       return false;
9209     }
9210   }
9211 
9212   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9213     unsigned Offset4 = State.AllocateStack(4, Align(4));
9214     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9215     return false;
9216   }
9217 
9218   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9219     unsigned Offset5 = State.AllocateStack(8, Align(8));
9220     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9221     return false;
9222   }
9223 
9224   if (LocVT.isVector()) {
9225     if (unsigned Reg =
9226             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9227       // Fixed-length vectors are located in the corresponding scalable-vector
9228       // container types.
9229       if (ValVT.isFixedLengthVector())
9230         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9231       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9232     } else {
9233       // Try and pass the address via a "fast" GPR.
9234       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9235         LocInfo = CCValAssign::Indirect;
9236         LocVT = TLI.getSubtarget().getXLenVT();
9237         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9238       } else if (ValVT.isFixedLengthVector()) {
9239         auto StackAlign =
9240             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9241         unsigned StackOffset =
9242             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9243         State.addLoc(
9244             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9245       } else {
9246         // Can't pass scalable vectors on the stack.
9247         return true;
9248       }
9249     }
9250 
9251     return false;
9252   }
9253 
9254   return true; // CC didn't match.
9255 }
9256 
9257 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9258                          CCValAssign::LocInfo LocInfo,
9259                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9260 
9261   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9262     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9263     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9264     static const MCPhysReg GPRList[] = {
9265         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9266         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9267     if (unsigned Reg = State.AllocateReg(GPRList)) {
9268       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9269       return false;
9270     }
9271   }
9272 
9273   if (LocVT == MVT::f32) {
9274     // Pass in STG registers: F1, ..., F6
9275     //                        fs0 ... fs5
9276     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9277                                           RISCV::F18_F, RISCV::F19_F,
9278                                           RISCV::F20_F, RISCV::F21_F};
9279     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9280       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9281       return false;
9282     }
9283   }
9284 
9285   if (LocVT == MVT::f64) {
9286     // Pass in STG registers: D1, ..., D6
9287     //                        fs6 ... fs11
9288     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9289                                           RISCV::F24_D, RISCV::F25_D,
9290                                           RISCV::F26_D, RISCV::F27_D};
9291     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9292       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9293       return false;
9294     }
9295   }
9296 
9297   report_fatal_error("No registers left in GHC calling convention");
9298   return true;
9299 }
9300 
9301 // Transform physical registers into virtual registers.
9302 SDValue RISCVTargetLowering::LowerFormalArguments(
9303     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9304     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9305     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9306 
9307   MachineFunction &MF = DAG.getMachineFunction();
9308 
9309   switch (CallConv) {
9310   default:
9311     report_fatal_error("Unsupported calling convention");
9312   case CallingConv::C:
9313   case CallingConv::Fast:
9314     break;
9315   case CallingConv::GHC:
9316     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9317         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9318       report_fatal_error(
9319         "GHC calling convention requires the F and D instruction set extensions");
9320   }
9321 
9322   const Function &Func = MF.getFunction();
9323   if (Func.hasFnAttribute("interrupt")) {
9324     if (!Func.arg_empty())
9325       report_fatal_error(
9326         "Functions with the interrupt attribute cannot have arguments!");
9327 
9328     StringRef Kind =
9329       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9330 
9331     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9332       report_fatal_error(
9333         "Function interrupt attribute argument not supported!");
9334   }
9335 
9336   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9337   MVT XLenVT = Subtarget.getXLenVT();
9338   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9339   // Used with vargs to acumulate store chains.
9340   std::vector<SDValue> OutChains;
9341 
9342   // Assign locations to all of the incoming arguments.
9343   SmallVector<CCValAssign, 16> ArgLocs;
9344   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9345 
9346   if (CallConv == CallingConv::GHC)
9347     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9348   else
9349     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9350                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9351                                                    : CC_RISCV);
9352 
9353   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9354     CCValAssign &VA = ArgLocs[i];
9355     SDValue ArgValue;
9356     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9357     // case.
9358     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9359       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9360     else if (VA.isRegLoc())
9361       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9362     else
9363       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9364 
9365     if (VA.getLocInfo() == CCValAssign::Indirect) {
9366       // If the original argument was split and passed by reference (e.g. i128
9367       // on RV32), we need to load all parts of it here (using the same
9368       // address). Vectors may be partly split to registers and partly to the
9369       // stack, in which case the base address is partly offset and subsequent
9370       // stores are relative to that.
9371       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9372                                    MachinePointerInfo()));
9373       unsigned ArgIndex = Ins[i].OrigArgIndex;
9374       unsigned ArgPartOffset = Ins[i].PartOffset;
9375       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9376       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9377         CCValAssign &PartVA = ArgLocs[i + 1];
9378         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9379         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9380         if (PartVA.getValVT().isScalableVector())
9381           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9382         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9383         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9384                                      MachinePointerInfo()));
9385         ++i;
9386       }
9387       continue;
9388     }
9389     InVals.push_back(ArgValue);
9390   }
9391 
9392   if (IsVarArg) {
9393     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9394     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9395     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9396     MachineFrameInfo &MFI = MF.getFrameInfo();
9397     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9398     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9399 
9400     // Offset of the first variable argument from stack pointer, and size of
9401     // the vararg save area. For now, the varargs save area is either zero or
9402     // large enough to hold a0-a7.
9403     int VaArgOffset, VarArgsSaveSize;
9404 
9405     // If all registers are allocated, then all varargs must be passed on the
9406     // stack and we don't need to save any argregs.
9407     if (ArgRegs.size() == Idx) {
9408       VaArgOffset = CCInfo.getNextStackOffset();
9409       VarArgsSaveSize = 0;
9410     } else {
9411       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9412       VaArgOffset = -VarArgsSaveSize;
9413     }
9414 
9415     // Record the frame index of the first variable argument
9416     // which is a value necessary to VASTART.
9417     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9418     RVFI->setVarArgsFrameIndex(FI);
9419 
9420     // If saving an odd number of registers then create an extra stack slot to
9421     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9422     // offsets to even-numbered registered remain 2*XLEN-aligned.
9423     if (Idx % 2) {
9424       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9425       VarArgsSaveSize += XLenInBytes;
9426     }
9427 
9428     // Copy the integer registers that may have been used for passing varargs
9429     // to the vararg save area.
9430     for (unsigned I = Idx; I < ArgRegs.size();
9431          ++I, VaArgOffset += XLenInBytes) {
9432       const Register Reg = RegInfo.createVirtualRegister(RC);
9433       RegInfo.addLiveIn(ArgRegs[I], Reg);
9434       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9435       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9436       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9437       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9438                                    MachinePointerInfo::getFixedStack(MF, FI));
9439       cast<StoreSDNode>(Store.getNode())
9440           ->getMemOperand()
9441           ->setValue((Value *)nullptr);
9442       OutChains.push_back(Store);
9443     }
9444     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9445   }
9446 
9447   // All stores are grouped in one node to allow the matching between
9448   // the size of Ins and InVals. This only happens for vararg functions.
9449   if (!OutChains.empty()) {
9450     OutChains.push_back(Chain);
9451     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9452   }
9453 
9454   return Chain;
9455 }
9456 
9457 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9458 /// for tail call optimization.
9459 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9460 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9461     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9462     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9463 
9464   auto &Callee = CLI.Callee;
9465   auto CalleeCC = CLI.CallConv;
9466   auto &Outs = CLI.Outs;
9467   auto &Caller = MF.getFunction();
9468   auto CallerCC = Caller.getCallingConv();
9469 
9470   // Exception-handling functions need a special set of instructions to
9471   // indicate a return to the hardware. Tail-calling another function would
9472   // probably break this.
9473   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9474   // should be expanded as new function attributes are introduced.
9475   if (Caller.hasFnAttribute("interrupt"))
9476     return false;
9477 
9478   // Do not tail call opt if the stack is used to pass parameters.
9479   if (CCInfo.getNextStackOffset() != 0)
9480     return false;
9481 
9482   // Do not tail call opt if any parameters need to be passed indirectly.
9483   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9484   // passed indirectly. So the address of the value will be passed in a
9485   // register, or if not available, then the address is put on the stack. In
9486   // order to pass indirectly, space on the stack often needs to be allocated
9487   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9488   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9489   // are passed CCValAssign::Indirect.
9490   for (auto &VA : ArgLocs)
9491     if (VA.getLocInfo() == CCValAssign::Indirect)
9492       return false;
9493 
9494   // Do not tail call opt if either caller or callee uses struct return
9495   // semantics.
9496   auto IsCallerStructRet = Caller.hasStructRetAttr();
9497   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9498   if (IsCallerStructRet || IsCalleeStructRet)
9499     return false;
9500 
9501   // Externally-defined functions with weak linkage should not be
9502   // tail-called. The behaviour of branch instructions in this situation (as
9503   // used for tail calls) is implementation-defined, so we cannot rely on the
9504   // linker replacing the tail call with a return.
9505   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9506     const GlobalValue *GV = G->getGlobal();
9507     if (GV->hasExternalWeakLinkage())
9508       return false;
9509   }
9510 
9511   // The callee has to preserve all registers the caller needs to preserve.
9512   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9513   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9514   if (CalleeCC != CallerCC) {
9515     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9516     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9517       return false;
9518   }
9519 
9520   // Byval parameters hand the function a pointer directly into the stack area
9521   // we want to reuse during a tail call. Working around this *is* possible
9522   // but less efficient and uglier in LowerCall.
9523   for (auto &Arg : Outs)
9524     if (Arg.Flags.isByVal())
9525       return false;
9526 
9527   return true;
9528 }
9529 
9530 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9531   return DAG.getDataLayout().getPrefTypeAlign(
9532       VT.getTypeForEVT(*DAG.getContext()));
9533 }
9534 
9535 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9536 // and output parameter nodes.
9537 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9538                                        SmallVectorImpl<SDValue> &InVals) const {
9539   SelectionDAG &DAG = CLI.DAG;
9540   SDLoc &DL = CLI.DL;
9541   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9542   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9543   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9544   SDValue Chain = CLI.Chain;
9545   SDValue Callee = CLI.Callee;
9546   bool &IsTailCall = CLI.IsTailCall;
9547   CallingConv::ID CallConv = CLI.CallConv;
9548   bool IsVarArg = CLI.IsVarArg;
9549   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9550   MVT XLenVT = Subtarget.getXLenVT();
9551 
9552   MachineFunction &MF = DAG.getMachineFunction();
9553 
9554   // Analyze the operands of the call, assigning locations to each operand.
9555   SmallVector<CCValAssign, 16> ArgLocs;
9556   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9557 
9558   if (CallConv == CallingConv::GHC)
9559     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9560   else
9561     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9562                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9563                                                     : CC_RISCV);
9564 
9565   // Check if it's really possible to do a tail call.
9566   if (IsTailCall)
9567     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9568 
9569   if (IsTailCall)
9570     ++NumTailCalls;
9571   else if (CLI.CB && CLI.CB->isMustTailCall())
9572     report_fatal_error("failed to perform tail call elimination on a call "
9573                        "site marked musttail");
9574 
9575   // Get a count of how many bytes are to be pushed on the stack.
9576   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9577 
9578   // Create local copies for byval args
9579   SmallVector<SDValue, 8> ByValArgs;
9580   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9581     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9582     if (!Flags.isByVal())
9583       continue;
9584 
9585     SDValue Arg = OutVals[i];
9586     unsigned Size = Flags.getByValSize();
9587     Align Alignment = Flags.getNonZeroByValAlign();
9588 
9589     int FI =
9590         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9591     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9592     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9593 
9594     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9595                           /*IsVolatile=*/false,
9596                           /*AlwaysInline=*/false, IsTailCall,
9597                           MachinePointerInfo(), MachinePointerInfo());
9598     ByValArgs.push_back(FIPtr);
9599   }
9600 
9601   if (!IsTailCall)
9602     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9603 
9604   // Copy argument values to their designated locations.
9605   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9606   SmallVector<SDValue, 8> MemOpChains;
9607   SDValue StackPtr;
9608   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9609     CCValAssign &VA = ArgLocs[i];
9610     SDValue ArgValue = OutVals[i];
9611     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9612 
9613     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9614     bool IsF64OnRV32DSoftABI =
9615         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9616     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9617       SDValue SplitF64 = DAG.getNode(
9618           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9619       SDValue Lo = SplitF64.getValue(0);
9620       SDValue Hi = SplitF64.getValue(1);
9621 
9622       Register RegLo = VA.getLocReg();
9623       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9624 
9625       if (RegLo == RISCV::X17) {
9626         // Second half of f64 is passed on the stack.
9627         // Work out the address of the stack slot.
9628         if (!StackPtr.getNode())
9629           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9630         // Emit the store.
9631         MemOpChains.push_back(
9632             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9633       } else {
9634         // Second half of f64 is passed in another GPR.
9635         assert(RegLo < RISCV::X31 && "Invalid register pair");
9636         Register RegHigh = RegLo + 1;
9637         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9638       }
9639       continue;
9640     }
9641 
9642     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9643     // as any other MemLoc.
9644 
9645     // Promote the value if needed.
9646     // For now, only handle fully promoted and indirect arguments.
9647     if (VA.getLocInfo() == CCValAssign::Indirect) {
9648       // Store the argument in a stack slot and pass its address.
9649       Align StackAlign =
9650           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9651                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9652       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9653       // If the original argument was split (e.g. i128), we need
9654       // to store the required parts of it here (and pass just one address).
9655       // Vectors may be partly split to registers and partly to the stack, in
9656       // which case the base address is partly offset and subsequent stores are
9657       // relative to that.
9658       unsigned ArgIndex = Outs[i].OrigArgIndex;
9659       unsigned ArgPartOffset = Outs[i].PartOffset;
9660       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9661       // Calculate the total size to store. We don't have access to what we're
9662       // actually storing other than performing the loop and collecting the
9663       // info.
9664       SmallVector<std::pair<SDValue, SDValue>> Parts;
9665       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9666         SDValue PartValue = OutVals[i + 1];
9667         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9668         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9669         EVT PartVT = PartValue.getValueType();
9670         if (PartVT.isScalableVector())
9671           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9672         StoredSize += PartVT.getStoreSize();
9673         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9674         Parts.push_back(std::make_pair(PartValue, Offset));
9675         ++i;
9676       }
9677       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9678       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9679       MemOpChains.push_back(
9680           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9681                        MachinePointerInfo::getFixedStack(MF, FI)));
9682       for (const auto &Part : Parts) {
9683         SDValue PartValue = Part.first;
9684         SDValue PartOffset = Part.second;
9685         SDValue Address =
9686             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9687         MemOpChains.push_back(
9688             DAG.getStore(Chain, DL, PartValue, Address,
9689                          MachinePointerInfo::getFixedStack(MF, FI)));
9690       }
9691       ArgValue = SpillSlot;
9692     } else {
9693       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9694     }
9695 
9696     // Use local copy if it is a byval arg.
9697     if (Flags.isByVal())
9698       ArgValue = ByValArgs[j++];
9699 
9700     if (VA.isRegLoc()) {
9701       // Queue up the argument copies and emit them at the end.
9702       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9703     } else {
9704       assert(VA.isMemLoc() && "Argument not register or memory");
9705       assert(!IsTailCall && "Tail call not allowed if stack is used "
9706                             "for passing parameters");
9707 
9708       // Work out the address of the stack slot.
9709       if (!StackPtr.getNode())
9710         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9711       SDValue Address =
9712           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9713                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9714 
9715       // Emit the store.
9716       MemOpChains.push_back(
9717           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9718     }
9719   }
9720 
9721   // Join the stores, which are independent of one another.
9722   if (!MemOpChains.empty())
9723     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9724 
9725   SDValue Glue;
9726 
9727   // Build a sequence of copy-to-reg nodes, chained and glued together.
9728   for (auto &Reg : RegsToPass) {
9729     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9730     Glue = Chain.getValue(1);
9731   }
9732 
9733   // Validate that none of the argument registers have been marked as
9734   // reserved, if so report an error. Do the same for the return address if this
9735   // is not a tailcall.
9736   validateCCReservedRegs(RegsToPass, MF);
9737   if (!IsTailCall &&
9738       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9739     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9740         MF.getFunction(),
9741         "Return address register required, but has been reserved."});
9742 
9743   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9744   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9745   // split it and then direct call can be matched by PseudoCALL.
9746   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9747     const GlobalValue *GV = S->getGlobal();
9748 
9749     unsigned OpFlags = RISCVII::MO_CALL;
9750     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9751       OpFlags = RISCVII::MO_PLT;
9752 
9753     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9754   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9755     unsigned OpFlags = RISCVII::MO_CALL;
9756 
9757     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9758                                                  nullptr))
9759       OpFlags = RISCVII::MO_PLT;
9760 
9761     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9762   }
9763 
9764   // The first call operand is the chain and the second is the target address.
9765   SmallVector<SDValue, 8> Ops;
9766   Ops.push_back(Chain);
9767   Ops.push_back(Callee);
9768 
9769   // Add argument registers to the end of the list so that they are
9770   // known live into the call.
9771   for (auto &Reg : RegsToPass)
9772     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9773 
9774   if (!IsTailCall) {
9775     // Add a register mask operand representing the call-preserved registers.
9776     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9777     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9778     assert(Mask && "Missing call preserved mask for calling convention");
9779     Ops.push_back(DAG.getRegisterMask(Mask));
9780   }
9781 
9782   // Glue the call to the argument copies, if any.
9783   if (Glue.getNode())
9784     Ops.push_back(Glue);
9785 
9786   // Emit the call.
9787   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9788 
9789   if (IsTailCall) {
9790     MF.getFrameInfo().setHasTailCall();
9791     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9792   }
9793 
9794   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9795   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9796   Glue = Chain.getValue(1);
9797 
9798   // Mark the end of the call, which is glued to the call itself.
9799   Chain = DAG.getCALLSEQ_END(Chain,
9800                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9801                              DAG.getConstant(0, DL, PtrVT, true),
9802                              Glue, DL);
9803   Glue = Chain.getValue(1);
9804 
9805   // Assign locations to each value returned by this call.
9806   SmallVector<CCValAssign, 16> RVLocs;
9807   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9808   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9809 
9810   // Copy all of the result registers out of their specified physreg.
9811   for (auto &VA : RVLocs) {
9812     // Copy the value out
9813     SDValue RetValue =
9814         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9815     // Glue the RetValue to the end of the call sequence
9816     Chain = RetValue.getValue(1);
9817     Glue = RetValue.getValue(2);
9818 
9819     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9820       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9821       SDValue RetValue2 =
9822           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9823       Chain = RetValue2.getValue(1);
9824       Glue = RetValue2.getValue(2);
9825       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9826                              RetValue2);
9827     }
9828 
9829     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9830 
9831     InVals.push_back(RetValue);
9832   }
9833 
9834   return Chain;
9835 }
9836 
9837 bool RISCVTargetLowering::CanLowerReturn(
9838     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9839     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9840   SmallVector<CCValAssign, 16> RVLocs;
9841   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9842 
9843   Optional<unsigned> FirstMaskArgument;
9844   if (Subtarget.hasVInstructions())
9845     FirstMaskArgument = preAssignMask(Outs);
9846 
9847   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9848     MVT VT = Outs[i].VT;
9849     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9850     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9851     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9852                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9853                  *this, FirstMaskArgument))
9854       return false;
9855   }
9856   return true;
9857 }
9858 
9859 SDValue
9860 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9861                                  bool IsVarArg,
9862                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9863                                  const SmallVectorImpl<SDValue> &OutVals,
9864                                  const SDLoc &DL, SelectionDAG &DAG) const {
9865   const MachineFunction &MF = DAG.getMachineFunction();
9866   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9867 
9868   // Stores the assignment of the return value to a location.
9869   SmallVector<CCValAssign, 16> RVLocs;
9870 
9871   // Info about the registers and stack slot.
9872   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9873                  *DAG.getContext());
9874 
9875   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9876                     nullptr, CC_RISCV);
9877 
9878   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9879     report_fatal_error("GHC functions return void only");
9880 
9881   SDValue Glue;
9882   SmallVector<SDValue, 4> RetOps(1, Chain);
9883 
9884   // Copy the result values into the output registers.
9885   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9886     SDValue Val = OutVals[i];
9887     CCValAssign &VA = RVLocs[i];
9888     assert(VA.isRegLoc() && "Can only return in registers!");
9889 
9890     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9891       // Handle returning f64 on RV32D with a soft float ABI.
9892       assert(VA.isRegLoc() && "Expected return via registers");
9893       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9894                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9895       SDValue Lo = SplitF64.getValue(0);
9896       SDValue Hi = SplitF64.getValue(1);
9897       Register RegLo = VA.getLocReg();
9898       assert(RegLo < RISCV::X31 && "Invalid register pair");
9899       Register RegHi = RegLo + 1;
9900 
9901       if (STI.isRegisterReservedByUser(RegLo) ||
9902           STI.isRegisterReservedByUser(RegHi))
9903         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9904             MF.getFunction(),
9905             "Return value register required, but has been reserved."});
9906 
9907       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9908       Glue = Chain.getValue(1);
9909       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9910       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9911       Glue = Chain.getValue(1);
9912       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9913     } else {
9914       // Handle a 'normal' return.
9915       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9916       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9917 
9918       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9919         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9920             MF.getFunction(),
9921             "Return value register required, but has been reserved."});
9922 
9923       // Guarantee that all emitted copies are stuck together.
9924       Glue = Chain.getValue(1);
9925       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9926     }
9927   }
9928 
9929   RetOps[0] = Chain; // Update chain.
9930 
9931   // Add the glue node if we have it.
9932   if (Glue.getNode()) {
9933     RetOps.push_back(Glue);
9934   }
9935 
9936   unsigned RetOpc = RISCVISD::RET_FLAG;
9937   // Interrupt service routines use different return instructions.
9938   const Function &Func = DAG.getMachineFunction().getFunction();
9939   if (Func.hasFnAttribute("interrupt")) {
9940     if (!Func.getReturnType()->isVoidTy())
9941       report_fatal_error(
9942           "Functions with the interrupt attribute must have void return type!");
9943 
9944     MachineFunction &MF = DAG.getMachineFunction();
9945     StringRef Kind =
9946       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9947 
9948     if (Kind == "user")
9949       RetOpc = RISCVISD::URET_FLAG;
9950     else if (Kind == "supervisor")
9951       RetOpc = RISCVISD::SRET_FLAG;
9952     else
9953       RetOpc = RISCVISD::MRET_FLAG;
9954   }
9955 
9956   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9957 }
9958 
9959 void RISCVTargetLowering::validateCCReservedRegs(
9960     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9961     MachineFunction &MF) const {
9962   const Function &F = MF.getFunction();
9963   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9964 
9965   if (llvm::any_of(Regs, [&STI](auto Reg) {
9966         return STI.isRegisterReservedByUser(Reg.first);
9967       }))
9968     F.getContext().diagnose(DiagnosticInfoUnsupported{
9969         F, "Argument register required, but has been reserved."});
9970 }
9971 
9972 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9973   return CI->isTailCall();
9974 }
9975 
9976 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9977 #define NODE_NAME_CASE(NODE)                                                   \
9978   case RISCVISD::NODE:                                                         \
9979     return "RISCVISD::" #NODE;
9980   // clang-format off
9981   switch ((RISCVISD::NodeType)Opcode) {
9982   case RISCVISD::FIRST_NUMBER:
9983     break;
9984   NODE_NAME_CASE(RET_FLAG)
9985   NODE_NAME_CASE(URET_FLAG)
9986   NODE_NAME_CASE(SRET_FLAG)
9987   NODE_NAME_CASE(MRET_FLAG)
9988   NODE_NAME_CASE(CALL)
9989   NODE_NAME_CASE(SELECT_CC)
9990   NODE_NAME_CASE(BR_CC)
9991   NODE_NAME_CASE(BuildPairF64)
9992   NODE_NAME_CASE(SplitF64)
9993   NODE_NAME_CASE(TAIL)
9994   NODE_NAME_CASE(MULHSU)
9995   NODE_NAME_CASE(SLLW)
9996   NODE_NAME_CASE(SRAW)
9997   NODE_NAME_CASE(SRLW)
9998   NODE_NAME_CASE(DIVW)
9999   NODE_NAME_CASE(DIVUW)
10000   NODE_NAME_CASE(REMUW)
10001   NODE_NAME_CASE(ROLW)
10002   NODE_NAME_CASE(RORW)
10003   NODE_NAME_CASE(CLZW)
10004   NODE_NAME_CASE(CTZW)
10005   NODE_NAME_CASE(FSLW)
10006   NODE_NAME_CASE(FSRW)
10007   NODE_NAME_CASE(FSL)
10008   NODE_NAME_CASE(FSR)
10009   NODE_NAME_CASE(FMV_H_X)
10010   NODE_NAME_CASE(FMV_X_ANYEXTH)
10011   NODE_NAME_CASE(FMV_W_X_RV64)
10012   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10013   NODE_NAME_CASE(FCVT_X)
10014   NODE_NAME_CASE(FCVT_XU)
10015   NODE_NAME_CASE(FCVT_W_RV64)
10016   NODE_NAME_CASE(FCVT_WU_RV64)
10017   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10018   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10019   NODE_NAME_CASE(READ_CYCLE_WIDE)
10020   NODE_NAME_CASE(GREV)
10021   NODE_NAME_CASE(GREVW)
10022   NODE_NAME_CASE(GORC)
10023   NODE_NAME_CASE(GORCW)
10024   NODE_NAME_CASE(SHFL)
10025   NODE_NAME_CASE(SHFLW)
10026   NODE_NAME_CASE(UNSHFL)
10027   NODE_NAME_CASE(UNSHFLW)
10028   NODE_NAME_CASE(BFP)
10029   NODE_NAME_CASE(BFPW)
10030   NODE_NAME_CASE(BCOMPRESS)
10031   NODE_NAME_CASE(BCOMPRESSW)
10032   NODE_NAME_CASE(BDECOMPRESS)
10033   NODE_NAME_CASE(BDECOMPRESSW)
10034   NODE_NAME_CASE(VMV_V_X_VL)
10035   NODE_NAME_CASE(VFMV_V_F_VL)
10036   NODE_NAME_CASE(VMV_X_S)
10037   NODE_NAME_CASE(VMV_S_X_VL)
10038   NODE_NAME_CASE(VFMV_S_F_VL)
10039   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10040   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10041   NODE_NAME_CASE(READ_VLENB)
10042   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10043   NODE_NAME_CASE(VSLIDEUP_VL)
10044   NODE_NAME_CASE(VSLIDE1UP_VL)
10045   NODE_NAME_CASE(VSLIDEDOWN_VL)
10046   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10047   NODE_NAME_CASE(VID_VL)
10048   NODE_NAME_CASE(VFNCVT_ROD_VL)
10049   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10050   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10051   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10052   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10053   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10054   NODE_NAME_CASE(VECREDUCE_AND_VL)
10055   NODE_NAME_CASE(VECREDUCE_OR_VL)
10056   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10057   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10058   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10059   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10060   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10061   NODE_NAME_CASE(ADD_VL)
10062   NODE_NAME_CASE(AND_VL)
10063   NODE_NAME_CASE(MUL_VL)
10064   NODE_NAME_CASE(OR_VL)
10065   NODE_NAME_CASE(SDIV_VL)
10066   NODE_NAME_CASE(SHL_VL)
10067   NODE_NAME_CASE(SREM_VL)
10068   NODE_NAME_CASE(SRA_VL)
10069   NODE_NAME_CASE(SRL_VL)
10070   NODE_NAME_CASE(SUB_VL)
10071   NODE_NAME_CASE(UDIV_VL)
10072   NODE_NAME_CASE(UREM_VL)
10073   NODE_NAME_CASE(XOR_VL)
10074   NODE_NAME_CASE(SADDSAT_VL)
10075   NODE_NAME_CASE(UADDSAT_VL)
10076   NODE_NAME_CASE(SSUBSAT_VL)
10077   NODE_NAME_CASE(USUBSAT_VL)
10078   NODE_NAME_CASE(FADD_VL)
10079   NODE_NAME_CASE(FSUB_VL)
10080   NODE_NAME_CASE(FMUL_VL)
10081   NODE_NAME_CASE(FDIV_VL)
10082   NODE_NAME_CASE(FNEG_VL)
10083   NODE_NAME_CASE(FABS_VL)
10084   NODE_NAME_CASE(FSQRT_VL)
10085   NODE_NAME_CASE(FMA_VL)
10086   NODE_NAME_CASE(FCOPYSIGN_VL)
10087   NODE_NAME_CASE(SMIN_VL)
10088   NODE_NAME_CASE(SMAX_VL)
10089   NODE_NAME_CASE(UMIN_VL)
10090   NODE_NAME_CASE(UMAX_VL)
10091   NODE_NAME_CASE(FMINNUM_VL)
10092   NODE_NAME_CASE(FMAXNUM_VL)
10093   NODE_NAME_CASE(MULHS_VL)
10094   NODE_NAME_CASE(MULHU_VL)
10095   NODE_NAME_CASE(FP_TO_SINT_VL)
10096   NODE_NAME_CASE(FP_TO_UINT_VL)
10097   NODE_NAME_CASE(SINT_TO_FP_VL)
10098   NODE_NAME_CASE(UINT_TO_FP_VL)
10099   NODE_NAME_CASE(FP_EXTEND_VL)
10100   NODE_NAME_CASE(FP_ROUND_VL)
10101   NODE_NAME_CASE(VWMUL_VL)
10102   NODE_NAME_CASE(VWMULU_VL)
10103   NODE_NAME_CASE(VWADDU_VL)
10104   NODE_NAME_CASE(SETCC_VL)
10105   NODE_NAME_CASE(VSELECT_VL)
10106   NODE_NAME_CASE(VP_MERGE_VL)
10107   NODE_NAME_CASE(VMAND_VL)
10108   NODE_NAME_CASE(VMOR_VL)
10109   NODE_NAME_CASE(VMXOR_VL)
10110   NODE_NAME_CASE(VMCLR_VL)
10111   NODE_NAME_CASE(VMSET_VL)
10112   NODE_NAME_CASE(VRGATHER_VX_VL)
10113   NODE_NAME_CASE(VRGATHER_VV_VL)
10114   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10115   NODE_NAME_CASE(VSEXT_VL)
10116   NODE_NAME_CASE(VZEXT_VL)
10117   NODE_NAME_CASE(VCPOP_VL)
10118   NODE_NAME_CASE(VLE_VL)
10119   NODE_NAME_CASE(VSE_VL)
10120   NODE_NAME_CASE(READ_CSR)
10121   NODE_NAME_CASE(WRITE_CSR)
10122   NODE_NAME_CASE(SWAP_CSR)
10123   }
10124   // clang-format on
10125   return nullptr;
10126 #undef NODE_NAME_CASE
10127 }
10128 
10129 /// getConstraintType - Given a constraint letter, return the type of
10130 /// constraint it is for this target.
10131 RISCVTargetLowering::ConstraintType
10132 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10133   if (Constraint.size() == 1) {
10134     switch (Constraint[0]) {
10135     default:
10136       break;
10137     case 'f':
10138       return C_RegisterClass;
10139     case 'I':
10140     case 'J':
10141     case 'K':
10142       return C_Immediate;
10143     case 'A':
10144       return C_Memory;
10145     case 'S': // A symbolic address
10146       return C_Other;
10147     }
10148   } else {
10149     if (Constraint == "vr" || Constraint == "vm")
10150       return C_RegisterClass;
10151   }
10152   return TargetLowering::getConstraintType(Constraint);
10153 }
10154 
10155 std::pair<unsigned, const TargetRegisterClass *>
10156 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10157                                                   StringRef Constraint,
10158                                                   MVT VT) const {
10159   // First, see if this is a constraint that directly corresponds to a
10160   // RISCV register class.
10161   if (Constraint.size() == 1) {
10162     switch (Constraint[0]) {
10163     case 'r':
10164       // TODO: Support fixed vectors up to XLen for P extension?
10165       if (VT.isVector())
10166         break;
10167       return std::make_pair(0U, &RISCV::GPRRegClass);
10168     case 'f':
10169       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10170         return std::make_pair(0U, &RISCV::FPR16RegClass);
10171       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10172         return std::make_pair(0U, &RISCV::FPR32RegClass);
10173       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10174         return std::make_pair(0U, &RISCV::FPR64RegClass);
10175       break;
10176     default:
10177       break;
10178     }
10179   } else if (Constraint == "vr") {
10180     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10181                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10182       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10183         return std::make_pair(0U, RC);
10184     }
10185   } else if (Constraint == "vm") {
10186     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10187       return std::make_pair(0U, &RISCV::VMV0RegClass);
10188   }
10189 
10190   // Clang will correctly decode the usage of register name aliases into their
10191   // official names. However, other frontends like `rustc` do not. This allows
10192   // users of these frontends to use the ABI names for registers in LLVM-style
10193   // register constraints.
10194   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10195                                .Case("{zero}", RISCV::X0)
10196                                .Case("{ra}", RISCV::X1)
10197                                .Case("{sp}", RISCV::X2)
10198                                .Case("{gp}", RISCV::X3)
10199                                .Case("{tp}", RISCV::X4)
10200                                .Case("{t0}", RISCV::X5)
10201                                .Case("{t1}", RISCV::X6)
10202                                .Case("{t2}", RISCV::X7)
10203                                .Cases("{s0}", "{fp}", RISCV::X8)
10204                                .Case("{s1}", RISCV::X9)
10205                                .Case("{a0}", RISCV::X10)
10206                                .Case("{a1}", RISCV::X11)
10207                                .Case("{a2}", RISCV::X12)
10208                                .Case("{a3}", RISCV::X13)
10209                                .Case("{a4}", RISCV::X14)
10210                                .Case("{a5}", RISCV::X15)
10211                                .Case("{a6}", RISCV::X16)
10212                                .Case("{a7}", RISCV::X17)
10213                                .Case("{s2}", RISCV::X18)
10214                                .Case("{s3}", RISCV::X19)
10215                                .Case("{s4}", RISCV::X20)
10216                                .Case("{s5}", RISCV::X21)
10217                                .Case("{s6}", RISCV::X22)
10218                                .Case("{s7}", RISCV::X23)
10219                                .Case("{s8}", RISCV::X24)
10220                                .Case("{s9}", RISCV::X25)
10221                                .Case("{s10}", RISCV::X26)
10222                                .Case("{s11}", RISCV::X27)
10223                                .Case("{t3}", RISCV::X28)
10224                                .Case("{t4}", RISCV::X29)
10225                                .Case("{t5}", RISCV::X30)
10226                                .Case("{t6}", RISCV::X31)
10227                                .Default(RISCV::NoRegister);
10228   if (XRegFromAlias != RISCV::NoRegister)
10229     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10230 
10231   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10232   // TableGen record rather than the AsmName to choose registers for InlineAsm
10233   // constraints, plus we want to match those names to the widest floating point
10234   // register type available, manually select floating point registers here.
10235   //
10236   // The second case is the ABI name of the register, so that frontends can also
10237   // use the ABI names in register constraint lists.
10238   if (Subtarget.hasStdExtF()) {
10239     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10240                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10241                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10242                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10243                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10244                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10245                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10246                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10247                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10248                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10249                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10250                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10251                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10252                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10253                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10254                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10255                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10256                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10257                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10258                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10259                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10260                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10261                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10262                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10263                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10264                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10265                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10266                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10267                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10268                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10269                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10270                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10271                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10272                         .Default(RISCV::NoRegister);
10273     if (FReg != RISCV::NoRegister) {
10274       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10275       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10276         unsigned RegNo = FReg - RISCV::F0_F;
10277         unsigned DReg = RISCV::F0_D + RegNo;
10278         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10279       }
10280       if (VT == MVT::f32 || VT == MVT::Other)
10281         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10282       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10283         unsigned RegNo = FReg - RISCV::F0_F;
10284         unsigned HReg = RISCV::F0_H + RegNo;
10285         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10286       }
10287     }
10288   }
10289 
10290   if (Subtarget.hasVInstructions()) {
10291     Register VReg = StringSwitch<Register>(Constraint.lower())
10292                         .Case("{v0}", RISCV::V0)
10293                         .Case("{v1}", RISCV::V1)
10294                         .Case("{v2}", RISCV::V2)
10295                         .Case("{v3}", RISCV::V3)
10296                         .Case("{v4}", RISCV::V4)
10297                         .Case("{v5}", RISCV::V5)
10298                         .Case("{v6}", RISCV::V6)
10299                         .Case("{v7}", RISCV::V7)
10300                         .Case("{v8}", RISCV::V8)
10301                         .Case("{v9}", RISCV::V9)
10302                         .Case("{v10}", RISCV::V10)
10303                         .Case("{v11}", RISCV::V11)
10304                         .Case("{v12}", RISCV::V12)
10305                         .Case("{v13}", RISCV::V13)
10306                         .Case("{v14}", RISCV::V14)
10307                         .Case("{v15}", RISCV::V15)
10308                         .Case("{v16}", RISCV::V16)
10309                         .Case("{v17}", RISCV::V17)
10310                         .Case("{v18}", RISCV::V18)
10311                         .Case("{v19}", RISCV::V19)
10312                         .Case("{v20}", RISCV::V20)
10313                         .Case("{v21}", RISCV::V21)
10314                         .Case("{v22}", RISCV::V22)
10315                         .Case("{v23}", RISCV::V23)
10316                         .Case("{v24}", RISCV::V24)
10317                         .Case("{v25}", RISCV::V25)
10318                         .Case("{v26}", RISCV::V26)
10319                         .Case("{v27}", RISCV::V27)
10320                         .Case("{v28}", RISCV::V28)
10321                         .Case("{v29}", RISCV::V29)
10322                         .Case("{v30}", RISCV::V30)
10323                         .Case("{v31}", RISCV::V31)
10324                         .Default(RISCV::NoRegister);
10325     if (VReg != RISCV::NoRegister) {
10326       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10327         return std::make_pair(VReg, &RISCV::VMRegClass);
10328       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10329         return std::make_pair(VReg, &RISCV::VRRegClass);
10330       for (const auto *RC :
10331            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10332         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10333           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10334           return std::make_pair(VReg, RC);
10335         }
10336       }
10337     }
10338   }
10339 
10340   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10341 }
10342 
10343 unsigned
10344 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10345   // Currently only support length 1 constraints.
10346   if (ConstraintCode.size() == 1) {
10347     switch (ConstraintCode[0]) {
10348     case 'A':
10349       return InlineAsm::Constraint_A;
10350     default:
10351       break;
10352     }
10353   }
10354 
10355   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10356 }
10357 
10358 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10359     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10360     SelectionDAG &DAG) const {
10361   // Currently only support length 1 constraints.
10362   if (Constraint.length() == 1) {
10363     switch (Constraint[0]) {
10364     case 'I':
10365       // Validate & create a 12-bit signed immediate operand.
10366       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10367         uint64_t CVal = C->getSExtValue();
10368         if (isInt<12>(CVal))
10369           Ops.push_back(
10370               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10371       }
10372       return;
10373     case 'J':
10374       // Validate & create an integer zero operand.
10375       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10376         if (C->getZExtValue() == 0)
10377           Ops.push_back(
10378               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10379       return;
10380     case 'K':
10381       // Validate & create a 5-bit unsigned immediate operand.
10382       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10383         uint64_t CVal = C->getZExtValue();
10384         if (isUInt<5>(CVal))
10385           Ops.push_back(
10386               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10387       }
10388       return;
10389     case 'S':
10390       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10391         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10392                                                  GA->getValueType(0)));
10393       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10394         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10395                                                 BA->getValueType(0)));
10396       }
10397       return;
10398     default:
10399       break;
10400     }
10401   }
10402   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10403 }
10404 
10405 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10406                                                    Instruction *Inst,
10407                                                    AtomicOrdering Ord) const {
10408   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10409     return Builder.CreateFence(Ord);
10410   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10411     return Builder.CreateFence(AtomicOrdering::Release);
10412   return nullptr;
10413 }
10414 
10415 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10416                                                     Instruction *Inst,
10417                                                     AtomicOrdering Ord) const {
10418   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10419     return Builder.CreateFence(AtomicOrdering::Acquire);
10420   return nullptr;
10421 }
10422 
10423 TargetLowering::AtomicExpansionKind
10424 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10425   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10426   // point operations can't be used in an lr/sc sequence without breaking the
10427   // forward-progress guarantee.
10428   if (AI->isFloatingPointOperation())
10429     return AtomicExpansionKind::CmpXChg;
10430 
10431   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10432   if (Size == 8 || Size == 16)
10433     return AtomicExpansionKind::MaskedIntrinsic;
10434   return AtomicExpansionKind::None;
10435 }
10436 
10437 static Intrinsic::ID
10438 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10439   if (XLen == 32) {
10440     switch (BinOp) {
10441     default:
10442       llvm_unreachable("Unexpected AtomicRMW BinOp");
10443     case AtomicRMWInst::Xchg:
10444       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10445     case AtomicRMWInst::Add:
10446       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10447     case AtomicRMWInst::Sub:
10448       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10449     case AtomicRMWInst::Nand:
10450       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10451     case AtomicRMWInst::Max:
10452       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10453     case AtomicRMWInst::Min:
10454       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10455     case AtomicRMWInst::UMax:
10456       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10457     case AtomicRMWInst::UMin:
10458       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10459     }
10460   }
10461 
10462   if (XLen == 64) {
10463     switch (BinOp) {
10464     default:
10465       llvm_unreachable("Unexpected AtomicRMW BinOp");
10466     case AtomicRMWInst::Xchg:
10467       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10468     case AtomicRMWInst::Add:
10469       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10470     case AtomicRMWInst::Sub:
10471       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10472     case AtomicRMWInst::Nand:
10473       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10474     case AtomicRMWInst::Max:
10475       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10476     case AtomicRMWInst::Min:
10477       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10478     case AtomicRMWInst::UMax:
10479       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10480     case AtomicRMWInst::UMin:
10481       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10482     }
10483   }
10484 
10485   llvm_unreachable("Unexpected XLen\n");
10486 }
10487 
10488 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10489     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10490     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10491   unsigned XLen = Subtarget.getXLen();
10492   Value *Ordering =
10493       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10494   Type *Tys[] = {AlignedAddr->getType()};
10495   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10496       AI->getModule(),
10497       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10498 
10499   if (XLen == 64) {
10500     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10501     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10502     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10503   }
10504 
10505   Value *Result;
10506 
10507   // Must pass the shift amount needed to sign extend the loaded value prior
10508   // to performing a signed comparison for min/max. ShiftAmt is the number of
10509   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10510   // is the number of bits to left+right shift the value in order to
10511   // sign-extend.
10512   if (AI->getOperation() == AtomicRMWInst::Min ||
10513       AI->getOperation() == AtomicRMWInst::Max) {
10514     const DataLayout &DL = AI->getModule()->getDataLayout();
10515     unsigned ValWidth =
10516         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10517     Value *SextShamt =
10518         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10519     Result = Builder.CreateCall(LrwOpScwLoop,
10520                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10521   } else {
10522     Result =
10523         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10524   }
10525 
10526   if (XLen == 64)
10527     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10528   return Result;
10529 }
10530 
10531 TargetLowering::AtomicExpansionKind
10532 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10533     AtomicCmpXchgInst *CI) const {
10534   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10535   if (Size == 8 || Size == 16)
10536     return AtomicExpansionKind::MaskedIntrinsic;
10537   return AtomicExpansionKind::None;
10538 }
10539 
10540 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10541     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10542     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10543   unsigned XLen = Subtarget.getXLen();
10544   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10545   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10546   if (XLen == 64) {
10547     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10548     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10549     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10550     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10551   }
10552   Type *Tys[] = {AlignedAddr->getType()};
10553   Function *MaskedCmpXchg =
10554       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10555   Value *Result = Builder.CreateCall(
10556       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10557   if (XLen == 64)
10558     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10559   return Result;
10560 }
10561 
10562 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10563   return false;
10564 }
10565 
10566 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10567                                                EVT VT) const {
10568   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10569     return false;
10570 
10571   switch (FPVT.getSimpleVT().SimpleTy) {
10572   case MVT::f16:
10573     return Subtarget.hasStdExtZfh();
10574   case MVT::f32:
10575     return Subtarget.hasStdExtF();
10576   case MVT::f64:
10577     return Subtarget.hasStdExtD();
10578   default:
10579     return false;
10580   }
10581 }
10582 
10583 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10584   // If we are using the small code model, we can reduce size of jump table
10585   // entry to 4 bytes.
10586   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10587       getTargetMachine().getCodeModel() == CodeModel::Small) {
10588     return MachineJumpTableInfo::EK_Custom32;
10589   }
10590   return TargetLowering::getJumpTableEncoding();
10591 }
10592 
10593 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10594     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10595     unsigned uid, MCContext &Ctx) const {
10596   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10597          getTargetMachine().getCodeModel() == CodeModel::Small);
10598   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10599 }
10600 
10601 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10602                                                      EVT VT) const {
10603   VT = VT.getScalarType();
10604 
10605   if (!VT.isSimple())
10606     return false;
10607 
10608   switch (VT.getSimpleVT().SimpleTy) {
10609   case MVT::f16:
10610     return Subtarget.hasStdExtZfh();
10611   case MVT::f32:
10612     return Subtarget.hasStdExtF();
10613   case MVT::f64:
10614     return Subtarget.hasStdExtD();
10615   default:
10616     break;
10617   }
10618 
10619   return false;
10620 }
10621 
10622 Register RISCVTargetLowering::getExceptionPointerRegister(
10623     const Constant *PersonalityFn) const {
10624   return RISCV::X10;
10625 }
10626 
10627 Register RISCVTargetLowering::getExceptionSelectorRegister(
10628     const Constant *PersonalityFn) const {
10629   return RISCV::X11;
10630 }
10631 
10632 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10633   // Return false to suppress the unnecessary extensions if the LibCall
10634   // arguments or return value is f32 type for LP64 ABI.
10635   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10636   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10637     return false;
10638 
10639   return true;
10640 }
10641 
10642 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10643   if (Subtarget.is64Bit() && Type == MVT::i32)
10644     return true;
10645 
10646   return IsSigned;
10647 }
10648 
10649 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10650                                                  SDValue C) const {
10651   // Check integral scalar types.
10652   if (VT.isScalarInteger()) {
10653     // Omit the optimization if the sub target has the M extension and the data
10654     // size exceeds XLen.
10655     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10656       return false;
10657     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10658       // Break the MUL to a SLLI and an ADD/SUB.
10659       const APInt &Imm = ConstNode->getAPIntValue();
10660       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10661           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10662         return true;
10663       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10664       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10665           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10666            (Imm - 8).isPowerOf2()))
10667         return true;
10668       // Omit the following optimization if the sub target has the M extension
10669       // and the data size >= XLen.
10670       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10671         return false;
10672       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10673       // a pair of LUI/ADDI.
10674       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10675         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10676         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10677             (1 - ImmS).isPowerOf2())
10678         return true;
10679       }
10680     }
10681   }
10682 
10683   return false;
10684 }
10685 
10686 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10687     const SDValue &AddNode, const SDValue &ConstNode) const {
10688   // Let the DAGCombiner decide for vectors.
10689   EVT VT = AddNode.getValueType();
10690   if (VT.isVector())
10691     return true;
10692 
10693   // Let the DAGCombiner decide for larger types.
10694   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10695     return true;
10696 
10697   // It is worse if c1 is simm12 while c1*c2 is not.
10698   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10699   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10700   const APInt &C1 = C1Node->getAPIntValue();
10701   const APInt &C2 = C2Node->getAPIntValue();
10702   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10703     return false;
10704 
10705   // Default to true and let the DAGCombiner decide.
10706   return true;
10707 }
10708 
10709 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10710     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10711     bool *Fast) const {
10712   if (!VT.isVector())
10713     return false;
10714 
10715   EVT ElemVT = VT.getVectorElementType();
10716   if (Alignment >= ElemVT.getStoreSize()) {
10717     if (Fast)
10718       *Fast = true;
10719     return true;
10720   }
10721 
10722   return false;
10723 }
10724 
10725 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10726     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10727     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10728   bool IsABIRegCopy = CC.hasValue();
10729   EVT ValueVT = Val.getValueType();
10730   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10731     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10732     // and cast to f32.
10733     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10734     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10735     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10736                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10737     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10738     Parts[0] = Val;
10739     return true;
10740   }
10741 
10742   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10743     LLVMContext &Context = *DAG.getContext();
10744     EVT ValueEltVT = ValueVT.getVectorElementType();
10745     EVT PartEltVT = PartVT.getVectorElementType();
10746     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10747     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10748     if (PartVTBitSize % ValueVTBitSize == 0) {
10749       assert(PartVTBitSize >= ValueVTBitSize);
10750       // If the element types are different, bitcast to the same element type of
10751       // PartVT first.
10752       // Give an example here, we want copy a <vscale x 1 x i8> value to
10753       // <vscale x 4 x i16>.
10754       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10755       // subvector, then we can bitcast to <vscale x 4 x i16>.
10756       if (ValueEltVT != PartEltVT) {
10757         if (PartVTBitSize > ValueVTBitSize) {
10758           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10759           assert(Count != 0 && "The number of element should not be zero.");
10760           EVT SameEltTypeVT =
10761               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10762           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10763                             DAG.getUNDEF(SameEltTypeVT), Val,
10764                             DAG.getVectorIdxConstant(0, DL));
10765         }
10766         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10767       } else {
10768         Val =
10769             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10770                         Val, DAG.getVectorIdxConstant(0, DL));
10771       }
10772       Parts[0] = Val;
10773       return true;
10774     }
10775   }
10776   return false;
10777 }
10778 
10779 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10780     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10781     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10782   bool IsABIRegCopy = CC.hasValue();
10783   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10784     SDValue Val = Parts[0];
10785 
10786     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10787     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10788     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10789     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10790     return Val;
10791   }
10792 
10793   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10794     LLVMContext &Context = *DAG.getContext();
10795     SDValue Val = Parts[0];
10796     EVT ValueEltVT = ValueVT.getVectorElementType();
10797     EVT PartEltVT = PartVT.getVectorElementType();
10798     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10799     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10800     if (PartVTBitSize % ValueVTBitSize == 0) {
10801       assert(PartVTBitSize >= ValueVTBitSize);
10802       EVT SameEltTypeVT = ValueVT;
10803       // If the element types are different, convert it to the same element type
10804       // of PartVT.
10805       // Give an example here, we want copy a <vscale x 1 x i8> value from
10806       // <vscale x 4 x i16>.
10807       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10808       // then we can extract <vscale x 1 x i8>.
10809       if (ValueEltVT != PartEltVT) {
10810         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10811         assert(Count != 0 && "The number of element should not be zero.");
10812         SameEltTypeVT =
10813             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10814         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10815       }
10816       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10817                         DAG.getVectorIdxConstant(0, DL));
10818       return Val;
10819     }
10820   }
10821   return SDValue();
10822 }
10823 
10824 SDValue
10825 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10826                                    SelectionDAG &DAG,
10827                                    SmallVectorImpl<SDNode *> &Created) const {
10828   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10829   if (isIntDivCheap(N->getValueType(0), Attr))
10830     return SDValue(N, 0); // Lower SDIV as SDIV
10831 
10832   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10833          "Unexpected divisor!");
10834 
10835   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10836   if (!Subtarget.hasStdExtZbt())
10837     return SDValue();
10838 
10839   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10840   // Besides, more critical path instructions will be generated when dividing
10841   // by 2. So we keep using the original DAGs for these cases.
10842   unsigned Lg2 = Divisor.countTrailingZeros();
10843   if (Lg2 == 1 || Lg2 >= 12)
10844     return SDValue();
10845 
10846   // fold (sdiv X, pow2)
10847   EVT VT = N->getValueType(0);
10848   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10849     return SDValue();
10850 
10851   SDLoc DL(N);
10852   SDValue N0 = N->getOperand(0);
10853   SDValue Zero = DAG.getConstant(0, DL, VT);
10854   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10855 
10856   // Add (N0 < 0) ? Pow2 - 1 : 0;
10857   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10858   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10859   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10860 
10861   Created.push_back(Cmp.getNode());
10862   Created.push_back(Add.getNode());
10863   Created.push_back(Sel.getNode());
10864 
10865   // Divide by pow2.
10866   SDValue SRA =
10867       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10868 
10869   // If we're dividing by a positive value, we're done.  Otherwise, we must
10870   // negate the result.
10871   if (Divisor.isNonNegative())
10872     return SRA;
10873 
10874   Created.push_back(SRA.getNode());
10875   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10876 }
10877 
10878 #define GET_REGISTER_MATCHER
10879 #include "RISCVGenAsmMatcher.inc"
10880 
10881 Register
10882 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10883                                        const MachineFunction &MF) const {
10884   Register Reg = MatchRegisterAltName(RegName);
10885   if (Reg == RISCV::NoRegister)
10886     Reg = MatchRegisterName(RegName);
10887   if (Reg == RISCV::NoRegister)
10888     report_fatal_error(
10889         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10890   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10891   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10892     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10893                              StringRef(RegName) + "\"."));
10894   return Reg;
10895 }
10896 
10897 namespace llvm {
10898 namespace RISCVVIntrinsicsTable {
10899 
10900 #define GET_RISCVVIntrinsicsTable_IMPL
10901 #include "RISCVGenSearchableTables.inc"
10902 
10903 } // namespace RISCVVIntrinsicsTable
10904 
10905 } // namespace llvm
10906