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/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasVInstructions()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs) {
132       if (VT.getVectorElementType() == MVT::i64 &&
133           !Subtarget.hasVInstructionsI64())
134         continue;
135       addRegClassForRVV(VT);
136     }
137 
138     if (Subtarget.hasVInstructionsF16())
139       for (MVT VT : F16VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasVInstructionsF32())
143       for (MVT VT : F32VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.hasVInstructionsF64())
147       for (MVT VT : F64VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.useRVVForFixedLengthVectors()) {
151       auto addRegClassForFixedVectors = [this](MVT VT) {
152         MVT ContainerVT = getContainerForFixedLengthVector(VT);
153         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
154         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
155         addRegisterClass(VT, TRI.getRegClass(RCID));
156       };
157       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160 
161       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164     }
165   }
166 
167   // Compute derived properties from the register classes.
168   computeRegisterProperties(STI.getRegisterInfo());
169 
170   setStackPointerRegisterToSaveRestore(RISCV::X2);
171 
172   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
173     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
174 
175   // TODO: add all necessary setOperationAction calls.
176   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
177 
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::BR_CC, XLenVT, Expand);
180   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
181   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
182 
183   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
184   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction(ISD::VAARG, MVT::Other, Expand);
188   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
189   setOperationAction(ISD::VAEND, MVT::Other, Expand);
190 
191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
192   if (!Subtarget.hasStdExtZbb()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195   }
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::ADD, MVT::i32, Custom);
199     setOperationAction(ISD::SUB, MVT::i32, Custom);
200     setOperationAction(ISD::SHL, MVT::i32, Custom);
201     setOperationAction(ISD::SRA, MVT::i32, Custom);
202     setOperationAction(ISD::SRL, MVT::i32, Custom);
203 
204     setOperationAction(ISD::UADDO, MVT::i32, Custom);
205     setOperationAction(ISD::USUBO, MVT::i32, Custom);
206     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
207     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
208   } else {
209     setLibcallName(RTLIB::SHL_I128, nullptr);
210     setLibcallName(RTLIB::SRL_I128, nullptr);
211     setLibcallName(RTLIB::SRA_I128, nullptr);
212     setLibcallName(RTLIB::MUL_I128, nullptr);
213     setLibcallName(RTLIB::MULO_I64, nullptr);
214   }
215 
216   if (!Subtarget.hasStdExtM()) {
217     setOperationAction(ISD::MUL, XLenVT, Expand);
218     setOperationAction(ISD::MULHS, XLenVT, Expand);
219     setOperationAction(ISD::MULHU, XLenVT, Expand);
220     setOperationAction(ISD::SDIV, XLenVT, Expand);
221     setOperationAction(ISD::UDIV, XLenVT, Expand);
222     setOperationAction(ISD::SREM, XLenVT, Expand);
223     setOperationAction(ISD::UREM, XLenVT, Expand);
224   } else {
225     if (Subtarget.is64Bit()) {
226       setOperationAction(ISD::MUL, MVT::i32, Custom);
227       setOperationAction(ISD::MUL, MVT::i128, Custom);
228 
229       setOperationAction(ISD::SDIV, MVT::i8, Custom);
230       setOperationAction(ISD::UDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UREM, MVT::i8, Custom);
232       setOperationAction(ISD::SDIV, MVT::i16, Custom);
233       setOperationAction(ISD::UDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UREM, MVT::i16, Custom);
235       setOperationAction(ISD::SDIV, MVT::i32, Custom);
236       setOperationAction(ISD::UDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UREM, MVT::i32, Custom);
238     } else {
239       setOperationAction(ISD::MUL, MVT::i64, Custom);
240     }
241   }
242 
243   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
244   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
246   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
247 
248   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
249   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
251 
252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
253     if (Subtarget.is64Bit()) {
254       setOperationAction(ISD::ROTL, MVT::i32, Custom);
255       setOperationAction(ISD::ROTR, MVT::i32, Custom);
256     }
257   } else {
258     setOperationAction(ISD::ROTL, XLenVT, Expand);
259     setOperationAction(ISD::ROTR, XLenVT, Expand);
260   }
261 
262   if (Subtarget.hasStdExtZbp()) {
263     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
264     // more combining.
265     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
266     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
267     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
268     // BSWAP i8 doesn't exist.
269     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
270     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
271 
272     if (Subtarget.is64Bit()) {
273       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
274       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
275     }
276   } else {
277     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
278     // pattern match it directly in isel.
279     setOperationAction(ISD::BSWAP, XLenVT,
280                        Subtarget.hasStdExtZbb() ? Legal : Expand);
281   }
282 
283   if (Subtarget.hasStdExtZbb()) {
284     setOperationAction(ISD::SMIN, XLenVT, Legal);
285     setOperationAction(ISD::SMAX, XLenVT, Legal);
286     setOperationAction(ISD::UMIN, XLenVT, Legal);
287     setOperationAction(ISD::UMAX, XLenVT, Legal);
288 
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
291       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
292       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
294     }
295   } else {
296     setOperationAction(ISD::CTTZ, XLenVT, Expand);
297     setOperationAction(ISD::CTLZ, XLenVT, Expand);
298     setOperationAction(ISD::CTPOP, XLenVT, Expand);
299   }
300 
301   if (Subtarget.hasStdExtZbt()) {
302     setOperationAction(ISD::FSHL, XLenVT, Custom);
303     setOperationAction(ISD::FSHR, XLenVT, Custom);
304     setOperationAction(ISD::SELECT, XLenVT, Legal);
305 
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FSHL, MVT::i32, Custom);
308       setOperationAction(ISD::FSHR, MVT::i32, Custom);
309     }
310   } else {
311     setOperationAction(ISD::SELECT, XLenVT, Custom);
312   }
313 
314   static const ISD::CondCode FPCCToExpand[] = {
315       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
316       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
317       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
318 
319   static const ISD::NodeType FPOpToExpand[] = {
320       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
321       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
322 
323   if (Subtarget.hasStdExtZfh())
324     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
325 
326   if (Subtarget.hasStdExtZfh()) {
327     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
328     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
329     setOperationAction(ISD::LRINT, MVT::f16, Legal);
330     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LROUND, MVT::f16, Legal);
332     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
333     for (auto CC : FPCCToExpand)
334       setCondCodeAction(CC, MVT::f16, Expand);
335     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
336     setOperationAction(ISD::SELECT, MVT::f16, Custom);
337     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
338     for (auto Op : FPOpToExpand)
339       setOperationAction(Op, MVT::f16, Expand);
340   }
341 
342   if (Subtarget.hasStdExtF()) {
343     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
344     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
345     setOperationAction(ISD::LRINT, MVT::f32, Legal);
346     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
347     setOperationAction(ISD::LROUND, MVT::f32, Legal);
348     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f32, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
352     setOperationAction(ISD::SELECT, MVT::f32, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
354     for (auto Op : FPOpToExpand)
355       setOperationAction(Op, MVT::f32, Expand);
356     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
357     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
358   }
359 
360   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
361     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
362 
363   if (Subtarget.hasStdExtD()) {
364     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
365     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
366     setOperationAction(ISD::LRINT, MVT::f64, Legal);
367     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
368     setOperationAction(ISD::LROUND, MVT::f64, Legal);
369     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
370     for (auto CC : FPCCToExpand)
371       setCondCodeAction(CC, MVT::f64, Expand);
372     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
373     setOperationAction(ISD::SELECT, MVT::f64, Custom);
374     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
376     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
377     for (auto Op : FPOpToExpand)
378       setOperationAction(Op, MVT::f64, Expand);
379     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   }
382 
383   if (Subtarget.is64Bit()) {
384     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
385     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
386     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
387     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
388   }
389 
390   if (Subtarget.hasStdExtF()) {
391     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
392     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
393 
394     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
395     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
396   }
397 
398   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
399   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
400   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
401   setOperationAction(ISD::JumpTable, XLenVT, Custom);
402 
403   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
404 
405   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
406   // Unfortunately this can't be determined just from the ISA naming string.
407   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
408                      Subtarget.is64Bit() ? Legal : Custom);
409 
410   setOperationAction(ISD::TRAP, MVT::Other, Legal);
411   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
412   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
413   if (Subtarget.is64Bit())
414     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
415 
416   if (Subtarget.hasStdExtA()) {
417     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
418     setMinCmpXchgSizeInBits(32);
419   } else {
420     setMaxAtomicSizeInBitsSupported(0);
421   }
422 
423   setBooleanContents(ZeroOrOneBooleanContent);
424 
425   if (Subtarget.hasVInstructions()) {
426     setBooleanVectorContents(ZeroOrOneBooleanContent);
427 
428     setOperationAction(ISD::VSCALE, XLenVT, Custom);
429 
430     // RVV intrinsics may have illegal operands.
431     // We also need to custom legalize vmv.x.s.
432     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
433     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
434     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
435     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
436     if (Subtarget.is64Bit()) {
437       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
438     } else {
439       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
440       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
441     }
442 
443     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
444     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
445 
446     static const unsigned IntegerVPOps[] = {
447         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
448         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
449         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
450         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
451         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
452         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
453         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN};
454 
455     static const unsigned FloatingPointVPOps[] = {
456         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
457         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
458         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX};
459 
460     if (!Subtarget.is64Bit()) {
461       // We must custom-lower certain vXi64 operations on RV32 due to the vector
462       // element type being illegal.
463       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
464       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
465 
466       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
467       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
468       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
469       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
470       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
471       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
472       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
473       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
474 
475       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
476       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
477       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
478       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
479       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
480       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
481       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
482       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
483     }
484 
485     for (MVT VT : BoolVecVTs) {
486       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
487 
488       // Mask VTs are custom-expanded into a series of standard nodes
489       setOperationAction(ISD::TRUNCATE, VT, Custom);
490       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
491       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
492       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
493 
494       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
495       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
496 
497       setOperationAction(ISD::SELECT, VT, Custom);
498       setOperationAction(ISD::SELECT_CC, VT, Expand);
499       setOperationAction(ISD::VSELECT, VT, Expand);
500 
501       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
502       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
503       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
504 
505       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
506       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
507       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
508 
509       // RVV has native int->float & float->int conversions where the
510       // element type sizes are within one power-of-two of each other. Any
511       // wider distances between type sizes have to be lowered as sequences
512       // which progressively narrow the gap in stages.
513       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
514       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
515       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
516       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
517 
518       // Expand all extending loads to types larger than this, and truncating
519       // stores from types larger than this.
520       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
521         setTruncStoreAction(OtherVT, VT, Expand);
522         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
523         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
524         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
525       }
526     }
527 
528     for (MVT VT : IntVecVTs) {
529       if (VT.getVectorElementType() == MVT::i64 &&
530           !Subtarget.hasVInstructionsI64())
531         continue;
532 
533       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
534       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
535 
536       // Vectors implement MULHS/MULHU.
537       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
538       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
539 
540       setOperationAction(ISD::SMIN, VT, Legal);
541       setOperationAction(ISD::SMAX, VT, Legal);
542       setOperationAction(ISD::UMIN, VT, Legal);
543       setOperationAction(ISD::UMAX, VT, Legal);
544 
545       setOperationAction(ISD::ROTL, VT, Expand);
546       setOperationAction(ISD::ROTR, VT, Expand);
547 
548       setOperationAction(ISD::CTTZ, VT, Expand);
549       setOperationAction(ISD::CTLZ, VT, Expand);
550       setOperationAction(ISD::CTPOP, VT, Expand);
551 
552       setOperationAction(ISD::BSWAP, VT, Expand);
553 
554       // Custom-lower extensions and truncations from/to mask types.
555       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
556       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
557       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
558 
559       // RVV has native int->float & float->int conversions where the
560       // element type sizes are within one power-of-two of each other. Any
561       // wider distances between type sizes have to be lowered as sequences
562       // which progressively narrow the gap in stages.
563       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
564       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
565       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
566       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
567 
568       setOperationAction(ISD::SADDSAT, VT, Legal);
569       setOperationAction(ISD::UADDSAT, VT, Legal);
570       setOperationAction(ISD::SSUBSAT, VT, Legal);
571       setOperationAction(ISD::USUBSAT, VT, Legal);
572 
573       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
574       // nodes which truncate by one power of two at a time.
575       setOperationAction(ISD::TRUNCATE, VT, Custom);
576 
577       // Custom-lower insert/extract operations to simplify patterns.
578       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
579       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
580 
581       // Custom-lower reduction operations to set up the corresponding custom
582       // nodes' operands.
583       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
584       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
585       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
586       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
587       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
588       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
589       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
590       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
591 
592       for (unsigned VPOpc : IntegerVPOps)
593         setOperationAction(VPOpc, VT, Custom);
594 
595       setOperationAction(ISD::LOAD, VT, Custom);
596       setOperationAction(ISD::STORE, VT, Custom);
597 
598       setOperationAction(ISD::MLOAD, VT, Custom);
599       setOperationAction(ISD::MSTORE, VT, Custom);
600       setOperationAction(ISD::MGATHER, VT, Custom);
601       setOperationAction(ISD::MSCATTER, VT, Custom);
602 
603       setOperationAction(ISD::VP_LOAD, VT, Custom);
604       setOperationAction(ISD::VP_STORE, VT, Custom);
605       setOperationAction(ISD::VP_GATHER, VT, Custom);
606       setOperationAction(ISD::VP_SCATTER, VT, Custom);
607 
608       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
609       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
610       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
611 
612       setOperationAction(ISD::SELECT, VT, Custom);
613       setOperationAction(ISD::SELECT_CC, VT, Expand);
614 
615       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
616       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
617 
618       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
619         setTruncStoreAction(VT, OtherVT, Expand);
620         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
621         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
622         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
623       }
624     }
625 
626     // Expand various CCs to best match the RVV ISA, which natively supports UNE
627     // but no other unordered comparisons, and supports all ordered comparisons
628     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
629     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
630     // and we pattern-match those back to the "original", swapping operands once
631     // more. This way we catch both operations and both "vf" and "fv" forms with
632     // fewer patterns.
633     static const ISD::CondCode VFPCCToExpand[] = {
634         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
635         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
636         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
637     };
638 
639     // Sets common operation actions on RVV floating-point vector types.
640     const auto SetCommonVFPActions = [&](MVT VT) {
641       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
642       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
643       // sizes are within one power-of-two of each other. Therefore conversions
644       // between vXf16 and vXf64 must be lowered as sequences which convert via
645       // vXf32.
646       setOperationAction(ISD::FP_ROUND, VT, Custom);
647       setOperationAction(ISD::FP_EXTEND, VT, Custom);
648       // Custom-lower insert/extract operations to simplify patterns.
649       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
650       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
651       // Expand various condition codes (explained above).
652       for (auto CC : VFPCCToExpand)
653         setCondCodeAction(CC, VT, Expand);
654 
655       setOperationAction(ISD::FMINNUM, VT, Legal);
656       setOperationAction(ISD::FMAXNUM, VT, Legal);
657 
658       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
659       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
660       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
661       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
662 
663       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
664 
665       setOperationAction(ISD::LOAD, VT, Custom);
666       setOperationAction(ISD::STORE, VT, Custom);
667 
668       setOperationAction(ISD::MLOAD, VT, Custom);
669       setOperationAction(ISD::MSTORE, VT, Custom);
670       setOperationAction(ISD::MGATHER, VT, Custom);
671       setOperationAction(ISD::MSCATTER, VT, Custom);
672 
673       setOperationAction(ISD::VP_LOAD, VT, Custom);
674       setOperationAction(ISD::VP_STORE, VT, Custom);
675       setOperationAction(ISD::VP_GATHER, VT, Custom);
676       setOperationAction(ISD::VP_SCATTER, VT, Custom);
677 
678       setOperationAction(ISD::SELECT, VT, Custom);
679       setOperationAction(ISD::SELECT_CC, VT, Expand);
680 
681       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
682       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
683       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
684 
685       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
686 
687       for (unsigned VPOpc : FloatingPointVPOps)
688         setOperationAction(VPOpc, VT, Custom);
689     };
690 
691     // Sets common extload/truncstore actions on RVV floating-point vector
692     // types.
693     const auto SetCommonVFPExtLoadTruncStoreActions =
694         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
695           for (auto SmallVT : SmallerVTs) {
696             setTruncStoreAction(VT, SmallVT, Expand);
697             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
698           }
699         };
700 
701     if (Subtarget.hasVInstructionsF16())
702       for (MVT VT : F16VecVTs)
703         SetCommonVFPActions(VT);
704 
705     for (MVT VT : F32VecVTs) {
706       if (Subtarget.hasVInstructionsF32())
707         SetCommonVFPActions(VT);
708       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
709     }
710 
711     for (MVT VT : F64VecVTs) {
712       if (Subtarget.hasVInstructionsF64())
713         SetCommonVFPActions(VT);
714       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
715       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
716     }
717 
718     if (Subtarget.useRVVForFixedLengthVectors()) {
719       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
720         if (!useRVVForFixedLengthVectorVT(VT))
721           continue;
722 
723         // By default everything must be expanded.
724         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
725           setOperationAction(Op, VT, Expand);
726         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
727           setTruncStoreAction(VT, OtherVT, Expand);
728           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
729           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
730           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
731         }
732 
733         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
734         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
735         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
736 
737         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
738         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
739 
740         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
741         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
742 
743         setOperationAction(ISD::LOAD, VT, Custom);
744         setOperationAction(ISD::STORE, VT, Custom);
745 
746         setOperationAction(ISD::SETCC, VT, Custom);
747 
748         setOperationAction(ISD::SELECT, VT, Custom);
749 
750         setOperationAction(ISD::TRUNCATE, VT, Custom);
751 
752         setOperationAction(ISD::BITCAST, VT, Custom);
753 
754         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
755         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
756         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
757 
758         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
759         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
760         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
761 
762         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
763         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
764         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
765         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
766 
767         // Operations below are different for between masks and other vectors.
768         if (VT.getVectorElementType() == MVT::i1) {
769           setOperationAction(ISD::AND, VT, Custom);
770           setOperationAction(ISD::OR, VT, Custom);
771           setOperationAction(ISD::XOR, VT, Custom);
772           continue;
773         }
774 
775         // Use SPLAT_VECTOR to prevent type legalization from destroying the
776         // splats when type legalizing i64 scalar on RV32.
777         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
778         // improvements first.
779         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
780           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
781           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
782         }
783 
784         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
785         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
786 
787         setOperationAction(ISD::MLOAD, VT, Custom);
788         setOperationAction(ISD::MSTORE, VT, Custom);
789         setOperationAction(ISD::MGATHER, VT, Custom);
790         setOperationAction(ISD::MSCATTER, VT, Custom);
791 
792         setOperationAction(ISD::VP_LOAD, VT, Custom);
793         setOperationAction(ISD::VP_STORE, VT, Custom);
794         setOperationAction(ISD::VP_GATHER, VT, Custom);
795         setOperationAction(ISD::VP_SCATTER, VT, Custom);
796 
797         setOperationAction(ISD::ADD, VT, Custom);
798         setOperationAction(ISD::MUL, VT, Custom);
799         setOperationAction(ISD::SUB, VT, Custom);
800         setOperationAction(ISD::AND, VT, Custom);
801         setOperationAction(ISD::OR, VT, Custom);
802         setOperationAction(ISD::XOR, VT, Custom);
803         setOperationAction(ISD::SDIV, VT, Custom);
804         setOperationAction(ISD::SREM, VT, Custom);
805         setOperationAction(ISD::UDIV, VT, Custom);
806         setOperationAction(ISD::UREM, VT, Custom);
807         setOperationAction(ISD::SHL, VT, Custom);
808         setOperationAction(ISD::SRA, VT, Custom);
809         setOperationAction(ISD::SRL, VT, Custom);
810 
811         setOperationAction(ISD::SMIN, VT, Custom);
812         setOperationAction(ISD::SMAX, VT, Custom);
813         setOperationAction(ISD::UMIN, VT, Custom);
814         setOperationAction(ISD::UMAX, VT, Custom);
815         setOperationAction(ISD::ABS,  VT, Custom);
816 
817         setOperationAction(ISD::MULHS, VT, Custom);
818         setOperationAction(ISD::MULHU, VT, Custom);
819 
820         setOperationAction(ISD::SADDSAT, VT, Custom);
821         setOperationAction(ISD::UADDSAT, VT, Custom);
822         setOperationAction(ISD::SSUBSAT, VT, Custom);
823         setOperationAction(ISD::USUBSAT, VT, Custom);
824 
825         setOperationAction(ISD::VSELECT, VT, Custom);
826         setOperationAction(ISD::SELECT_CC, VT, Expand);
827 
828         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
829         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
830         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
831 
832         // Custom-lower reduction operations to set up the corresponding custom
833         // nodes' operands.
834         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
835         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
836         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
837         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
838         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
839 
840         for (unsigned VPOpc : IntegerVPOps)
841           setOperationAction(VPOpc, VT, Custom);
842       }
843 
844       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
845         if (!useRVVForFixedLengthVectorVT(VT))
846           continue;
847 
848         // By default everything must be expanded.
849         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
850           setOperationAction(Op, VT, Expand);
851         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
852           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
853           setTruncStoreAction(VT, OtherVT, Expand);
854         }
855 
856         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
857         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
858         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
859 
860         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
861         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
862         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
863         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
864         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
865 
866         setOperationAction(ISD::LOAD, VT, Custom);
867         setOperationAction(ISD::STORE, VT, Custom);
868         setOperationAction(ISD::MLOAD, VT, Custom);
869         setOperationAction(ISD::MSTORE, VT, Custom);
870         setOperationAction(ISD::MGATHER, VT, Custom);
871         setOperationAction(ISD::MSCATTER, VT, Custom);
872 
873         setOperationAction(ISD::VP_LOAD, VT, Custom);
874         setOperationAction(ISD::VP_STORE, VT, Custom);
875         setOperationAction(ISD::VP_GATHER, VT, Custom);
876         setOperationAction(ISD::VP_SCATTER, VT, Custom);
877 
878         setOperationAction(ISD::FADD, VT, Custom);
879         setOperationAction(ISD::FSUB, VT, Custom);
880         setOperationAction(ISD::FMUL, VT, Custom);
881         setOperationAction(ISD::FDIV, VT, Custom);
882         setOperationAction(ISD::FNEG, VT, Custom);
883         setOperationAction(ISD::FABS, VT, Custom);
884         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
885         setOperationAction(ISD::FSQRT, VT, Custom);
886         setOperationAction(ISD::FMA, VT, Custom);
887         setOperationAction(ISD::FMINNUM, VT, Custom);
888         setOperationAction(ISD::FMAXNUM, VT, Custom);
889 
890         setOperationAction(ISD::FP_ROUND, VT, Custom);
891         setOperationAction(ISD::FP_EXTEND, VT, Custom);
892 
893         for (auto CC : VFPCCToExpand)
894           setCondCodeAction(CC, VT, Expand);
895 
896         setOperationAction(ISD::VSELECT, VT, Custom);
897         setOperationAction(ISD::SELECT, VT, Custom);
898         setOperationAction(ISD::SELECT_CC, VT, Expand);
899 
900         setOperationAction(ISD::BITCAST, VT, Custom);
901 
902         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
903         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
904         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
905         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
906 
907         for (unsigned VPOpc : FloatingPointVPOps)
908           setOperationAction(VPOpc, VT, Custom);
909       }
910 
911       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
912       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
913       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
914       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
915       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
916       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
917       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
918       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
919     }
920   }
921 
922   // Function alignments.
923   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
924   setMinFunctionAlignment(FunctionAlignment);
925   setPrefFunctionAlignment(FunctionAlignment);
926 
927   setMinimumJumpTableEntries(5);
928 
929   // Jumps are expensive, compared to logic
930   setJumpIsExpensive();
931 
932   // We can use any register for comparisons
933   setHasMultipleConditionRegisters();
934 
935   setTargetDAGCombine(ISD::ADD);
936   setTargetDAGCombine(ISD::SUB);
937   setTargetDAGCombine(ISD::AND);
938   setTargetDAGCombine(ISD::OR);
939   setTargetDAGCombine(ISD::XOR);
940   setTargetDAGCombine(ISD::ANY_EXTEND);
941   setTargetDAGCombine(ISD::ZERO_EXTEND);
942   if (Subtarget.hasVInstructions()) {
943     setTargetDAGCombine(ISD::FCOPYSIGN);
944     setTargetDAGCombine(ISD::MGATHER);
945     setTargetDAGCombine(ISD::MSCATTER);
946     setTargetDAGCombine(ISD::VP_GATHER);
947     setTargetDAGCombine(ISD::VP_SCATTER);
948     setTargetDAGCombine(ISD::SRA);
949     setTargetDAGCombine(ISD::SRL);
950     setTargetDAGCombine(ISD::SHL);
951     setTargetDAGCombine(ISD::STORE);
952   }
953 }
954 
955 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
956                                             LLVMContext &Context,
957                                             EVT VT) const {
958   if (!VT.isVector())
959     return getPointerTy(DL);
960   if (Subtarget.hasVInstructions() &&
961       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
962     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
963   return VT.changeVectorElementTypeToInteger();
964 }
965 
966 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
967   return Subtarget.getXLenVT();
968 }
969 
970 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
971                                              const CallInst &I,
972                                              MachineFunction &MF,
973                                              unsigned Intrinsic) const {
974   auto &DL = I.getModule()->getDataLayout();
975   switch (Intrinsic) {
976   default:
977     return false;
978   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
979   case Intrinsic::riscv_masked_atomicrmw_add_i32:
980   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
981   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
982   case Intrinsic::riscv_masked_atomicrmw_max_i32:
983   case Intrinsic::riscv_masked_atomicrmw_min_i32:
984   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
985   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
986   case Intrinsic::riscv_masked_cmpxchg_i32: {
987     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
988     Info.opc = ISD::INTRINSIC_W_CHAIN;
989     Info.memVT = MVT::getVT(PtrTy->getElementType());
990     Info.ptrVal = I.getArgOperand(0);
991     Info.offset = 0;
992     Info.align = Align(4);
993     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
994                  MachineMemOperand::MOVolatile;
995     return true;
996   }
997   case Intrinsic::riscv_masked_strided_load:
998     Info.opc = ISD::INTRINSIC_W_CHAIN;
999     Info.ptrVal = I.getArgOperand(1);
1000     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1001     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1002     Info.size = MemoryLocation::UnknownSize;
1003     Info.flags |= MachineMemOperand::MOLoad;
1004     return true;
1005   case Intrinsic::riscv_masked_strided_store:
1006     Info.opc = ISD::INTRINSIC_VOID;
1007     Info.ptrVal = I.getArgOperand(1);
1008     Info.memVT =
1009         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1010     Info.align = Align(
1011         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1012         8);
1013     Info.size = MemoryLocation::UnknownSize;
1014     Info.flags |= MachineMemOperand::MOStore;
1015     return true;
1016   }
1017 }
1018 
1019 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1020                                                 const AddrMode &AM, Type *Ty,
1021                                                 unsigned AS,
1022                                                 Instruction *I) const {
1023   // No global is ever allowed as a base.
1024   if (AM.BaseGV)
1025     return false;
1026 
1027   // Require a 12-bit signed offset.
1028   if (!isInt<12>(AM.BaseOffs))
1029     return false;
1030 
1031   switch (AM.Scale) {
1032   case 0: // "r+i" or just "i", depending on HasBaseReg.
1033     break;
1034   case 1:
1035     if (!AM.HasBaseReg) // allow "r+i".
1036       break;
1037     return false; // disallow "r+r" or "r+r+i".
1038   default:
1039     return false;
1040   }
1041 
1042   return true;
1043 }
1044 
1045 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1046   return isInt<12>(Imm);
1047 }
1048 
1049 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1050   return isInt<12>(Imm);
1051 }
1052 
1053 // On RV32, 64-bit integers are split into their high and low parts and held
1054 // in two different registers, so the trunc is free since the low register can
1055 // just be used.
1056 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1057   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1058     return false;
1059   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1060   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1061   return (SrcBits == 64 && DestBits == 32);
1062 }
1063 
1064 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1065   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1066       !SrcVT.isInteger() || !DstVT.isInteger())
1067     return false;
1068   unsigned SrcBits = SrcVT.getSizeInBits();
1069   unsigned DestBits = DstVT.getSizeInBits();
1070   return (SrcBits == 64 && DestBits == 32);
1071 }
1072 
1073 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1074   // Zexts are free if they can be combined with a load.
1075   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1076     EVT MemVT = LD->getMemoryVT();
1077     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1078          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1079         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1080          LD->getExtensionType() == ISD::ZEXTLOAD))
1081       return true;
1082   }
1083 
1084   return TargetLowering::isZExtFree(Val, VT2);
1085 }
1086 
1087 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1088   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1089 }
1090 
1091 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1092   return Subtarget.hasStdExtZbb();
1093 }
1094 
1095 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1096   return Subtarget.hasStdExtZbb();
1097 }
1098 
1099 /// Check if sinking \p I's operands to I's basic block is profitable, because
1100 /// the operands can be folded into a target instruction, e.g.
1101 /// splats of scalars can fold into vector instructions.
1102 bool RISCVTargetLowering::shouldSinkOperands(
1103     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1104   using namespace llvm::PatternMatch;
1105 
1106   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1107     return false;
1108 
1109   auto IsSinker = [&](Instruction *I, int Operand) {
1110     switch (I->getOpcode()) {
1111     case Instruction::Add:
1112     case Instruction::Sub:
1113     case Instruction::Mul:
1114     case Instruction::And:
1115     case Instruction::Or:
1116     case Instruction::Xor:
1117     case Instruction::FAdd:
1118     case Instruction::FSub:
1119     case Instruction::FMul:
1120     case Instruction::FDiv:
1121     case Instruction::ICmp:
1122     case Instruction::FCmp:
1123       return true;
1124     case Instruction::Shl:
1125     case Instruction::LShr:
1126     case Instruction::AShr:
1127       return Operand == 1;
1128     case Instruction::Call:
1129       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1130         switch (II->getIntrinsicID()) {
1131         case Intrinsic::fma:
1132           return Operand == 0 || Operand == 1;
1133         default:
1134           return false;
1135         }
1136       }
1137       return false;
1138     default:
1139       return false;
1140     }
1141   };
1142 
1143   for (auto OpIdx : enumerate(I->operands())) {
1144     if (!IsSinker(I, OpIdx.index()))
1145       continue;
1146 
1147     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1148     // Make sure we are not already sinking this operand
1149     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1150       continue;
1151 
1152     // We are looking for a splat that can be sunk.
1153     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1154                              m_Undef(), m_ZeroMask())))
1155       continue;
1156 
1157     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1158     // and vector registers
1159     for (Use &U : Op->uses()) {
1160       Instruction *Insn = cast<Instruction>(U.getUser());
1161       if (!IsSinker(Insn, U.getOperandNo()))
1162         return false;
1163     }
1164 
1165     Ops.push_back(&Op->getOperandUse(0));
1166     Ops.push_back(&OpIdx.value());
1167   }
1168   return true;
1169 }
1170 
1171 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1172                                        bool ForCodeSize) const {
1173   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1174     return false;
1175   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1176     return false;
1177   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1178     return false;
1179   if (Imm.isNegZero())
1180     return false;
1181   return Imm.isZero();
1182 }
1183 
1184 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1185   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1186          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1187          (VT == MVT::f64 && Subtarget.hasStdExtD());
1188 }
1189 
1190 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1191                                                       CallingConv::ID CC,
1192                                                       EVT VT) const {
1193   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1194   // We might still end up using a GPR but that will be decided based on ABI.
1195   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1196     return MVT::f32;
1197 
1198   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1199 }
1200 
1201 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1202                                                            CallingConv::ID CC,
1203                                                            EVT VT) const {
1204   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1205   // We might still end up using a GPR but that will be decided based on ABI.
1206   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1207     return 1;
1208 
1209   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1210 }
1211 
1212 // Changes the condition code and swaps operands if necessary, so the SetCC
1213 // operation matches one of the comparisons supported directly by branches
1214 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1215 // with 1/-1.
1216 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1217                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1218   // Convert X > -1 to X >= 0.
1219   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1220     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1221     CC = ISD::SETGE;
1222     return;
1223   }
1224   // Convert X < 1 to 0 >= X.
1225   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1226     RHS = LHS;
1227     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1228     CC = ISD::SETGE;
1229     return;
1230   }
1231 
1232   switch (CC) {
1233   default:
1234     break;
1235   case ISD::SETGT:
1236   case ISD::SETLE:
1237   case ISD::SETUGT:
1238   case ISD::SETULE:
1239     CC = ISD::getSetCCSwappedOperands(CC);
1240     std::swap(LHS, RHS);
1241     break;
1242   }
1243 }
1244 
1245 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1246   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1247   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1248   if (VT.getVectorElementType() == MVT::i1)
1249     KnownSize *= 8;
1250 
1251   switch (KnownSize) {
1252   default:
1253     llvm_unreachable("Invalid LMUL.");
1254   case 8:
1255     return RISCVII::VLMUL::LMUL_F8;
1256   case 16:
1257     return RISCVII::VLMUL::LMUL_F4;
1258   case 32:
1259     return RISCVII::VLMUL::LMUL_F2;
1260   case 64:
1261     return RISCVII::VLMUL::LMUL_1;
1262   case 128:
1263     return RISCVII::VLMUL::LMUL_2;
1264   case 256:
1265     return RISCVII::VLMUL::LMUL_4;
1266   case 512:
1267     return RISCVII::VLMUL::LMUL_8;
1268   }
1269 }
1270 
1271 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1272   switch (LMul) {
1273   default:
1274     llvm_unreachable("Invalid LMUL.");
1275   case RISCVII::VLMUL::LMUL_F8:
1276   case RISCVII::VLMUL::LMUL_F4:
1277   case RISCVII::VLMUL::LMUL_F2:
1278   case RISCVII::VLMUL::LMUL_1:
1279     return RISCV::VRRegClassID;
1280   case RISCVII::VLMUL::LMUL_2:
1281     return RISCV::VRM2RegClassID;
1282   case RISCVII::VLMUL::LMUL_4:
1283     return RISCV::VRM4RegClassID;
1284   case RISCVII::VLMUL::LMUL_8:
1285     return RISCV::VRM8RegClassID;
1286   }
1287 }
1288 
1289 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1290   RISCVII::VLMUL LMUL = getLMUL(VT);
1291   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1292       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1293       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1294       LMUL == RISCVII::VLMUL::LMUL_1) {
1295     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1296                   "Unexpected subreg numbering");
1297     return RISCV::sub_vrm1_0 + Index;
1298   }
1299   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1300     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1301                   "Unexpected subreg numbering");
1302     return RISCV::sub_vrm2_0 + Index;
1303   }
1304   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1305     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1306                   "Unexpected subreg numbering");
1307     return RISCV::sub_vrm4_0 + Index;
1308   }
1309   llvm_unreachable("Invalid vector type.");
1310 }
1311 
1312 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1313   if (VT.getVectorElementType() == MVT::i1)
1314     return RISCV::VRRegClassID;
1315   return getRegClassIDForLMUL(getLMUL(VT));
1316 }
1317 
1318 // Attempt to decompose a subvector insert/extract between VecVT and
1319 // SubVecVT via subregister indices. Returns the subregister index that
1320 // can perform the subvector insert/extract with the given element index, as
1321 // well as the index corresponding to any leftover subvectors that must be
1322 // further inserted/extracted within the register class for SubVecVT.
1323 std::pair<unsigned, unsigned>
1324 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1325     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1326     const RISCVRegisterInfo *TRI) {
1327   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1328                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1329                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1330                 "Register classes not ordered");
1331   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1332   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1333   // Try to compose a subregister index that takes us from the incoming
1334   // LMUL>1 register class down to the outgoing one. At each step we half
1335   // the LMUL:
1336   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1337   // Note that this is not guaranteed to find a subregister index, such as
1338   // when we are extracting from one VR type to another.
1339   unsigned SubRegIdx = RISCV::NoSubRegister;
1340   for (const unsigned RCID :
1341        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1342     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1343       VecVT = VecVT.getHalfNumVectorElementsVT();
1344       bool IsHi =
1345           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1346       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1347                                             getSubregIndexByMVT(VecVT, IsHi));
1348       if (IsHi)
1349         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1350     }
1351   return {SubRegIdx, InsertExtractIdx};
1352 }
1353 
1354 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1355 // stores for those types.
1356 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1357   return !Subtarget.useRVVForFixedLengthVectors() ||
1358          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1359 }
1360 
1361 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1362   if (ScalarTy->isPointerTy())
1363     return true;
1364 
1365   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1366       ScalarTy->isIntegerTy(32))
1367     return true;
1368 
1369   if (ScalarTy->isIntegerTy(64))
1370     return Subtarget.hasVInstructionsI64();
1371 
1372   if (ScalarTy->isHalfTy())
1373     return Subtarget.hasVInstructionsF16();
1374   if (ScalarTy->isFloatTy())
1375     return Subtarget.hasVInstructionsF32();
1376   if (ScalarTy->isDoubleTy())
1377     return Subtarget.hasVInstructionsF64();
1378 
1379   return false;
1380 }
1381 
1382 static bool useRVVForFixedLengthVectorVT(MVT VT,
1383                                          const RISCVSubtarget &Subtarget) {
1384   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1385   if (!Subtarget.useRVVForFixedLengthVectors())
1386     return false;
1387 
1388   // We only support a set of vector types with a consistent maximum fixed size
1389   // across all supported vector element types to avoid legalization issues.
1390   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1391   // fixed-length vector type we support is 1024 bytes.
1392   if (VT.getFixedSizeInBits() > 1024 * 8)
1393     return false;
1394 
1395   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1396 
1397   MVT EltVT = VT.getVectorElementType();
1398 
1399   // Don't use RVV for vectors we cannot scalarize if required.
1400   switch (EltVT.SimpleTy) {
1401   // i1 is supported but has different rules.
1402   default:
1403     return false;
1404   case MVT::i1:
1405     // Masks can only use a single register.
1406     if (VT.getVectorNumElements() > MinVLen)
1407       return false;
1408     MinVLen /= 8;
1409     break;
1410   case MVT::i8:
1411   case MVT::i16:
1412   case MVT::i32:
1413     break;
1414   case MVT::i64:
1415     if (!Subtarget.hasVInstructionsI64())
1416       return false;
1417     break;
1418   case MVT::f16:
1419     if (!Subtarget.hasVInstructionsF16())
1420       return false;
1421     break;
1422   case MVT::f32:
1423     if (!Subtarget.hasVInstructionsF32())
1424       return false;
1425     break;
1426   case MVT::f64:
1427     if (!Subtarget.hasVInstructionsF64())
1428       return false;
1429     break;
1430   }
1431 
1432   // Reject elements larger than ELEN.
1433   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1434     return false;
1435 
1436   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1437   // Don't use RVV for types that don't fit.
1438   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1439     return false;
1440 
1441   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1442   // the base fixed length RVV support in place.
1443   if (!VT.isPow2VectorType())
1444     return false;
1445 
1446   return true;
1447 }
1448 
1449 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1450   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1451 }
1452 
1453 // Return the largest legal scalable vector type that matches VT's element type.
1454 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1455                                             const RISCVSubtarget &Subtarget) {
1456   // This may be called before legal types are setup.
1457   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1458           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1459          "Expected legal fixed length vector!");
1460 
1461   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1462   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1463 
1464   MVT EltVT = VT.getVectorElementType();
1465   switch (EltVT.SimpleTy) {
1466   default:
1467     llvm_unreachable("unexpected element type for RVV container");
1468   case MVT::i1:
1469   case MVT::i8:
1470   case MVT::i16:
1471   case MVT::i32:
1472   case MVT::i64:
1473   case MVT::f16:
1474   case MVT::f32:
1475   case MVT::f64: {
1476     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1477     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1478     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1479     unsigned NumElts =
1480         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1481     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1482     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1483     return MVT::getScalableVectorVT(EltVT, NumElts);
1484   }
1485   }
1486 }
1487 
1488 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1489                                             const RISCVSubtarget &Subtarget) {
1490   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1491                                           Subtarget);
1492 }
1493 
1494 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1495   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1496 }
1497 
1498 // Grow V to consume an entire RVV register.
1499 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1500                                        const RISCVSubtarget &Subtarget) {
1501   assert(VT.isScalableVector() &&
1502          "Expected to convert into a scalable vector!");
1503   assert(V.getValueType().isFixedLengthVector() &&
1504          "Expected a fixed length vector operand!");
1505   SDLoc DL(V);
1506   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1507   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1508 }
1509 
1510 // Shrink V so it's just big enough to maintain a VT's worth of data.
1511 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1512                                          const RISCVSubtarget &Subtarget) {
1513   assert(VT.isFixedLengthVector() &&
1514          "Expected to convert into a fixed length vector!");
1515   assert(V.getValueType().isScalableVector() &&
1516          "Expected a scalable vector operand!");
1517   SDLoc DL(V);
1518   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1519   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1520 }
1521 
1522 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1523 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1524 // the vector type that it is contained in.
1525 static std::pair<SDValue, SDValue>
1526 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1527                 const RISCVSubtarget &Subtarget) {
1528   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1529   MVT XLenVT = Subtarget.getXLenVT();
1530   SDValue VL = VecVT.isFixedLengthVector()
1531                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1532                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1533   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1534   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1535   return {Mask, VL};
1536 }
1537 
1538 // As above but assuming the given type is a scalable vector type.
1539 static std::pair<SDValue, SDValue>
1540 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1541                         const RISCVSubtarget &Subtarget) {
1542   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1543   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1544 }
1545 
1546 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1547 // of either is (currently) supported. This can get us into an infinite loop
1548 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1549 // as a ..., etc.
1550 // Until either (or both) of these can reliably lower any node, reporting that
1551 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1552 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1553 // which is not desirable.
1554 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1555     EVT VT, unsigned DefinedValues) const {
1556   return false;
1557 }
1558 
1559 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1560   // Only splats are currently supported.
1561   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1562     return true;
1563 
1564   return false;
1565 }
1566 
1567 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1568   // RISCV FP-to-int conversions saturate to the destination register size, but
1569   // don't produce 0 for nan. We can use a conversion instruction and fix the
1570   // nan case with a compare and a select.
1571   SDValue Src = Op.getOperand(0);
1572 
1573   EVT DstVT = Op.getValueType();
1574   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1575 
1576   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1577   unsigned Opc;
1578   if (SatVT == DstVT)
1579     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1580   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1581     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1582   else
1583     return SDValue();
1584   // FIXME: Support other SatVTs by clamping before or after the conversion.
1585 
1586   SDLoc DL(Op);
1587   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1588 
1589   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1590   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1591 }
1592 
1593 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1594                                  const RISCVSubtarget &Subtarget) {
1595   MVT VT = Op.getSimpleValueType();
1596   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1597 
1598   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1599 
1600   SDLoc DL(Op);
1601   SDValue Mask, VL;
1602   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1603 
1604   unsigned Opc =
1605       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1606   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1607   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1608 }
1609 
1610 struct VIDSequence {
1611   int64_t StepNumerator;
1612   unsigned StepDenominator;
1613   int64_t Addend;
1614 };
1615 
1616 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1617 // to the (non-zero) step S and start value X. This can be then lowered as the
1618 // RVV sequence (VID * S) + X, for example.
1619 // The step S is represented as an integer numerator divided by a positive
1620 // denominator. Note that the implementation currently only identifies
1621 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1622 // cannot detect 2/3, for example.
1623 // Note that this method will also match potentially unappealing index
1624 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1625 // determine whether this is worth generating code for.
1626 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1627   unsigned NumElts = Op.getNumOperands();
1628   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1629   if (!Op.getValueType().isInteger())
1630     return None;
1631 
1632   Optional<unsigned> SeqStepDenom;
1633   Optional<int64_t> SeqStepNum, SeqAddend;
1634   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1635   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1636   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1637     // Assume undef elements match the sequence; we just have to be careful
1638     // when interpolating across them.
1639     if (Op.getOperand(Idx).isUndef())
1640       continue;
1641     // The BUILD_VECTOR must be all constants.
1642     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1643       return None;
1644 
1645     uint64_t Val = Op.getConstantOperandVal(Idx) &
1646                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1647 
1648     if (PrevElt) {
1649       // Calculate the step since the last non-undef element, and ensure
1650       // it's consistent across the entire sequence.
1651       unsigned IdxDiff = Idx - PrevElt->second;
1652       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1653 
1654       // A zero-value value difference means that we're somewhere in the middle
1655       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1656       // step change before evaluating the sequence.
1657       if (ValDiff != 0) {
1658         int64_t Remainder = ValDiff % IdxDiff;
1659         // Normalize the step if it's greater than 1.
1660         if (Remainder != ValDiff) {
1661           // The difference must cleanly divide the element span.
1662           if (Remainder != 0)
1663             return None;
1664           ValDiff /= IdxDiff;
1665           IdxDiff = 1;
1666         }
1667 
1668         if (!SeqStepNum)
1669           SeqStepNum = ValDiff;
1670         else if (ValDiff != SeqStepNum)
1671           return None;
1672 
1673         if (!SeqStepDenom)
1674           SeqStepDenom = IdxDiff;
1675         else if (IdxDiff != *SeqStepDenom)
1676           return None;
1677       }
1678     }
1679 
1680     // Record and/or check any addend.
1681     if (SeqStepNum && SeqStepDenom) {
1682       uint64_t ExpectedVal =
1683           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1684       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1685       if (!SeqAddend)
1686         SeqAddend = Addend;
1687       else if (SeqAddend != Addend)
1688         return None;
1689     }
1690 
1691     // Record this non-undef element for later.
1692     if (!PrevElt || PrevElt->first != Val)
1693       PrevElt = std::make_pair(Val, Idx);
1694   }
1695   // We need to have logged both a step and an addend for this to count as
1696   // a legal index sequence.
1697   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1698     return None;
1699 
1700   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1701 }
1702 
1703 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1704                                  const RISCVSubtarget &Subtarget) {
1705   MVT VT = Op.getSimpleValueType();
1706   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1707 
1708   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1709 
1710   SDLoc DL(Op);
1711   SDValue Mask, VL;
1712   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1713 
1714   MVT XLenVT = Subtarget.getXLenVT();
1715   unsigned NumElts = Op.getNumOperands();
1716 
1717   if (VT.getVectorElementType() == MVT::i1) {
1718     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1719       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1720       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1721     }
1722 
1723     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1724       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1725       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1726     }
1727 
1728     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1729     // scalar integer chunks whose bit-width depends on the number of mask
1730     // bits and XLEN.
1731     // First, determine the most appropriate scalar integer type to use. This
1732     // is at most XLenVT, but may be shrunk to a smaller vector element type
1733     // according to the size of the final vector - use i8 chunks rather than
1734     // XLenVT if we're producing a v8i1. This results in more consistent
1735     // codegen across RV32 and RV64.
1736     unsigned NumViaIntegerBits =
1737         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1738     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1739       // If we have to use more than one INSERT_VECTOR_ELT then this
1740       // optimization is likely to increase code size; avoid peforming it in
1741       // such a case. We can use a load from a constant pool in this case.
1742       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1743         return SDValue();
1744       // Now we can create our integer vector type. Note that it may be larger
1745       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1746       MVT IntegerViaVecVT =
1747           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1748                            divideCeil(NumElts, NumViaIntegerBits));
1749 
1750       uint64_t Bits = 0;
1751       unsigned BitPos = 0, IntegerEltIdx = 0;
1752       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1753 
1754       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1755         // Once we accumulate enough bits to fill our scalar type, insert into
1756         // our vector and clear our accumulated data.
1757         if (I != 0 && I % NumViaIntegerBits == 0) {
1758           if (NumViaIntegerBits <= 32)
1759             Bits = SignExtend64(Bits, 32);
1760           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1761           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1762                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1763           Bits = 0;
1764           BitPos = 0;
1765           IntegerEltIdx++;
1766         }
1767         SDValue V = Op.getOperand(I);
1768         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1769         Bits |= ((uint64_t)BitValue << BitPos);
1770       }
1771 
1772       // Insert the (remaining) scalar value into position in our integer
1773       // vector type.
1774       if (NumViaIntegerBits <= 32)
1775         Bits = SignExtend64(Bits, 32);
1776       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1777       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1778                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1779 
1780       if (NumElts < NumViaIntegerBits) {
1781         // If we're producing a smaller vector than our minimum legal integer
1782         // type, bitcast to the equivalent (known-legal) mask type, and extract
1783         // our final mask.
1784         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1785         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1786         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1787                           DAG.getConstant(0, DL, XLenVT));
1788       } else {
1789         // Else we must have produced an integer type with the same size as the
1790         // mask type; bitcast for the final result.
1791         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1792         Vec = DAG.getBitcast(VT, Vec);
1793       }
1794 
1795       return Vec;
1796     }
1797 
1798     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1799     // vector type, we have a legal equivalently-sized i8 type, so we can use
1800     // that.
1801     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1802     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1803 
1804     SDValue WideVec;
1805     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1806       // For a splat, perform a scalar truncate before creating the wider
1807       // vector.
1808       assert(Splat.getValueType() == XLenVT &&
1809              "Unexpected type for i1 splat value");
1810       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1811                           DAG.getConstant(1, DL, XLenVT));
1812       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1813     } else {
1814       SmallVector<SDValue, 8> Ops(Op->op_values());
1815       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1816       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1817       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1818     }
1819 
1820     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1821   }
1822 
1823   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1824     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1825                                         : RISCVISD::VMV_V_X_VL;
1826     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1827     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1828   }
1829 
1830   // Try and match index sequences, which we can lower to the vid instruction
1831   // with optional modifications. An all-undef vector is matched by
1832   // getSplatValue, above.
1833   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1834     int64_t StepNumerator = SimpleVID->StepNumerator;
1835     unsigned StepDenominator = SimpleVID->StepDenominator;
1836     int64_t Addend = SimpleVID->Addend;
1837     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1838     // threshold since it's the immediate value many RVV instructions accept.
1839     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1840         isInt<5>(Addend)) {
1841       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1842       // Convert right out of the scalable type so we can use standard ISD
1843       // nodes for the rest of the computation. If we used scalable types with
1844       // these, we'd lose the fixed-length vector info and generate worse
1845       // vsetvli code.
1846       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1847       assert(StepNumerator != 0 && "Invalid step");
1848       bool Negate = false;
1849       if (StepNumerator != 1) {
1850         int64_t SplatStepVal = StepNumerator;
1851         unsigned Opcode = ISD::MUL;
1852         if (isPowerOf2_64(std::abs(StepNumerator))) {
1853           Negate = StepNumerator < 0;
1854           Opcode = ISD::SHL;
1855           SplatStepVal = Log2_64(std::abs(StepNumerator));
1856         }
1857         SDValue SplatStep = DAG.getSplatVector(
1858             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1859         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1860       }
1861       if (StepDenominator != 1) {
1862         SDValue SplatStep = DAG.getSplatVector(
1863             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1864         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1865       }
1866       if (Addend != 0 || Negate) {
1867         SDValue SplatAddend =
1868             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1869         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1870       }
1871       return VID;
1872     }
1873   }
1874 
1875   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1876   // when re-interpreted as a vector with a larger element type. For example,
1877   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1878   // could be instead splat as
1879   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1880   // TODO: This optimization could also work on non-constant splats, but it
1881   // would require bit-manipulation instructions to construct the splat value.
1882   SmallVector<SDValue> Sequence;
1883   unsigned EltBitSize = VT.getScalarSizeInBits();
1884   const auto *BV = cast<BuildVectorSDNode>(Op);
1885   if (VT.isInteger() && EltBitSize < 64 &&
1886       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1887       BV->getRepeatedSequence(Sequence) &&
1888       (Sequence.size() * EltBitSize) <= 64) {
1889     unsigned SeqLen = Sequence.size();
1890     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1891     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1892     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1893             ViaIntVT == MVT::i64) &&
1894            "Unexpected sequence type");
1895 
1896     unsigned EltIdx = 0;
1897     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1898     uint64_t SplatValue = 0;
1899     // Construct the amalgamated value which can be splatted as this larger
1900     // vector type.
1901     for (const auto &SeqV : Sequence) {
1902       if (!SeqV.isUndef())
1903         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1904                        << (EltIdx * EltBitSize));
1905       EltIdx++;
1906     }
1907 
1908     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1909     // achieve better constant materializion.
1910     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1911       SplatValue = SignExtend64(SplatValue, 32);
1912 
1913     // Since we can't introduce illegal i64 types at this stage, we can only
1914     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1915     // way we can use RVV instructions to splat.
1916     assert((ViaIntVT.bitsLE(XLenVT) ||
1917             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1918            "Unexpected bitcast sequence");
1919     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1920       SDValue ViaVL =
1921           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1922       MVT ViaContainerVT =
1923           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1924       SDValue Splat =
1925           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1926                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1927       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1928       return DAG.getBitcast(VT, Splat);
1929     }
1930   }
1931 
1932   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1933   // which constitute a large proportion of the elements. In such cases we can
1934   // splat a vector with the dominant element and make up the shortfall with
1935   // INSERT_VECTOR_ELTs.
1936   // Note that this includes vectors of 2 elements by association. The
1937   // upper-most element is the "dominant" one, allowing us to use a splat to
1938   // "insert" the upper element, and an insert of the lower element at position
1939   // 0, which improves codegen.
1940   SDValue DominantValue;
1941   unsigned MostCommonCount = 0;
1942   DenseMap<SDValue, unsigned> ValueCounts;
1943   unsigned NumUndefElts =
1944       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1945 
1946   // Track the number of scalar loads we know we'd be inserting, estimated as
1947   // any non-zero floating-point constant. Other kinds of element are either
1948   // already in registers or are materialized on demand. The threshold at which
1949   // a vector load is more desirable than several scalar materializion and
1950   // vector-insertion instructions is not known.
1951   unsigned NumScalarLoads = 0;
1952 
1953   for (SDValue V : Op->op_values()) {
1954     if (V.isUndef())
1955       continue;
1956 
1957     ValueCounts.insert(std::make_pair(V, 0));
1958     unsigned &Count = ValueCounts[V];
1959 
1960     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1961       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1962 
1963     // Is this value dominant? In case of a tie, prefer the highest element as
1964     // it's cheaper to insert near the beginning of a vector than it is at the
1965     // end.
1966     if (++Count >= MostCommonCount) {
1967       DominantValue = V;
1968       MostCommonCount = Count;
1969     }
1970   }
1971 
1972   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1973   unsigned NumDefElts = NumElts - NumUndefElts;
1974   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1975 
1976   // Don't perform this optimization when optimizing for size, since
1977   // materializing elements and inserting them tends to cause code bloat.
1978   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1979       ((MostCommonCount > DominantValueCountThreshold) ||
1980        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1981     // Start by splatting the most common element.
1982     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1983 
1984     DenseSet<SDValue> Processed{DominantValue};
1985     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1986     for (const auto &OpIdx : enumerate(Op->ops())) {
1987       const SDValue &V = OpIdx.value();
1988       if (V.isUndef() || !Processed.insert(V).second)
1989         continue;
1990       if (ValueCounts[V] == 1) {
1991         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1992                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1993       } else {
1994         // Blend in all instances of this value using a VSELECT, using a
1995         // mask where each bit signals whether that element is the one
1996         // we're after.
1997         SmallVector<SDValue> Ops;
1998         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1999           return DAG.getConstant(V == V1, DL, XLenVT);
2000         });
2001         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2002                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2003                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2004       }
2005     }
2006 
2007     return Vec;
2008   }
2009 
2010   return SDValue();
2011 }
2012 
2013 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2014                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2015   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2016     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2017     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2018     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2019     // node in order to try and match RVV vector/scalar instructions.
2020     if ((LoC >> 31) == HiC)
2021       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2022   }
2023 
2024   // Fall back to a stack store and stride x0 vector load.
2025   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2026 }
2027 
2028 // Called by type legalization to handle splat of i64 on RV32.
2029 // FIXME: We can optimize this when the type has sign or zero bits in one
2030 // of the halves.
2031 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2032                                    SDValue VL, SelectionDAG &DAG) {
2033   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2034   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2035                            DAG.getConstant(0, DL, MVT::i32));
2036   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2037                            DAG.getConstant(1, DL, MVT::i32));
2038   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2039 }
2040 
2041 // This function lowers a splat of a scalar operand Splat with the vector
2042 // length VL. It ensures the final sequence is type legal, which is useful when
2043 // lowering a splat after type legalization.
2044 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2045                                 SelectionDAG &DAG,
2046                                 const RISCVSubtarget &Subtarget) {
2047   if (VT.isFloatingPoint())
2048     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2049 
2050   MVT XLenVT = Subtarget.getXLenVT();
2051 
2052   // Simplest case is that the operand needs to be promoted to XLenVT.
2053   if (Scalar.getValueType().bitsLE(XLenVT)) {
2054     // If the operand is a constant, sign extend to increase our chances
2055     // of being able to use a .vi instruction. ANY_EXTEND would become a
2056     // a zero extend and the simm5 check in isel would fail.
2057     // FIXME: Should we ignore the upper bits in isel instead?
2058     unsigned ExtOpc =
2059         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2060     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2061     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2062   }
2063 
2064   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2065          "Unexpected scalar for splat lowering!");
2066 
2067   // Otherwise use the more complicated splatting algorithm.
2068   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2069 }
2070 
2071 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2072                                    const RISCVSubtarget &Subtarget) {
2073   SDValue V1 = Op.getOperand(0);
2074   SDValue V2 = Op.getOperand(1);
2075   SDLoc DL(Op);
2076   MVT XLenVT = Subtarget.getXLenVT();
2077   MVT VT = Op.getSimpleValueType();
2078   unsigned NumElts = VT.getVectorNumElements();
2079   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2080 
2081   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2082 
2083   SDValue TrueMask, VL;
2084   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2085 
2086   if (SVN->isSplat()) {
2087     const int Lane = SVN->getSplatIndex();
2088     if (Lane >= 0) {
2089       MVT SVT = VT.getVectorElementType();
2090 
2091       // Turn splatted vector load into a strided load with an X0 stride.
2092       SDValue V = V1;
2093       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2094       // with undef.
2095       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2096       int Offset = Lane;
2097       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2098         int OpElements =
2099             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2100         V = V.getOperand(Offset / OpElements);
2101         Offset %= OpElements;
2102       }
2103 
2104       // We need to ensure the load isn't atomic or volatile.
2105       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2106         auto *Ld = cast<LoadSDNode>(V);
2107         Offset *= SVT.getStoreSize();
2108         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2109                                                    TypeSize::Fixed(Offset), DL);
2110 
2111         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2112         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2113           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2114           SDValue IntID =
2115               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2116           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2117                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2118           SDValue NewLoad = DAG.getMemIntrinsicNode(
2119               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2120               DAG.getMachineFunction().getMachineMemOperand(
2121                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2122           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2123           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2124         }
2125 
2126         // Otherwise use a scalar load and splat. This will give the best
2127         // opportunity to fold a splat into the operation. ISel can turn it into
2128         // the x0 strided load if we aren't able to fold away the select.
2129         if (SVT.isFloatingPoint())
2130           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2131                           Ld->getPointerInfo().getWithOffset(Offset),
2132                           Ld->getOriginalAlign(),
2133                           Ld->getMemOperand()->getFlags());
2134         else
2135           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2136                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2137                              Ld->getOriginalAlign(),
2138                              Ld->getMemOperand()->getFlags());
2139         DAG.makeEquivalentMemoryOrdering(Ld, V);
2140 
2141         unsigned Opc =
2142             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2143         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2144         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2145       }
2146 
2147       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2148       assert(Lane < (int)NumElts && "Unexpected lane!");
2149       SDValue Gather =
2150           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2151                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2152       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2153     }
2154   }
2155 
2156   // Detect shuffles which can be re-expressed as vector selects; these are
2157   // shuffles in which each element in the destination is taken from an element
2158   // at the corresponding index in either source vectors.
2159   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2160     int MaskIndex = MaskIdx.value();
2161     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2162   });
2163 
2164   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2165 
2166   SmallVector<SDValue> MaskVals;
2167   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2168   // merged with a second vrgather.
2169   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2170 
2171   // By default we preserve the original operand order, and use a mask to
2172   // select LHS as true and RHS as false. However, since RVV vector selects may
2173   // feature splats but only on the LHS, we may choose to invert our mask and
2174   // instead select between RHS and LHS.
2175   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2176   bool InvertMask = IsSelect == SwapOps;
2177 
2178   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2179   // half.
2180   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2181 
2182   // Now construct the mask that will be used by the vselect or blended
2183   // vrgather operation. For vrgathers, construct the appropriate indices into
2184   // each vector.
2185   for (int MaskIndex : SVN->getMask()) {
2186     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2187     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2188     if (!IsSelect) {
2189       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2190       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2191                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2192                                      : DAG.getUNDEF(XLenVT));
2193       GatherIndicesRHS.push_back(
2194           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2195                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2196       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2197         ++LHSIndexCounts[MaskIndex];
2198       if (!IsLHSOrUndefIndex)
2199         ++RHSIndexCounts[MaskIndex - NumElts];
2200     }
2201   }
2202 
2203   if (SwapOps) {
2204     std::swap(V1, V2);
2205     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2206   }
2207 
2208   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2209   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2210   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2211 
2212   if (IsSelect)
2213     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2214 
2215   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2216     // On such a large vector we're unable to use i8 as the index type.
2217     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2218     // may involve vector splitting if we're already at LMUL=8, or our
2219     // user-supplied maximum fixed-length LMUL.
2220     return SDValue();
2221   }
2222 
2223   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2224   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2225   MVT IndexVT = VT.changeTypeToInteger();
2226   // Since we can't introduce illegal index types at this stage, use i16 and
2227   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2228   // than XLenVT.
2229   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2230     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2231     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2232   }
2233 
2234   MVT IndexContainerVT =
2235       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2236 
2237   SDValue Gather;
2238   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2239   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2240   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2241     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2242   } else {
2243     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2244     // If only one index is used, we can use a "splat" vrgather.
2245     // TODO: We can splat the most-common index and fix-up any stragglers, if
2246     // that's beneficial.
2247     if (LHSIndexCounts.size() == 1) {
2248       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2249       Gather =
2250           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2251                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2252     } else {
2253       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2254       LHSIndices =
2255           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2256 
2257       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2258                            TrueMask, VL);
2259     }
2260   }
2261 
2262   // If a second vector operand is used by this shuffle, blend it in with an
2263   // additional vrgather.
2264   if (!V2.isUndef()) {
2265     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2266     // If only one index is used, we can use a "splat" vrgather.
2267     // TODO: We can splat the most-common index and fix-up any stragglers, if
2268     // that's beneficial.
2269     if (RHSIndexCounts.size() == 1) {
2270       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2271       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2272                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2273     } else {
2274       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2275       RHSIndices =
2276           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2277       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2278                        VL);
2279     }
2280 
2281     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2282     SelectMask =
2283         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2284 
2285     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2286                          Gather, VL);
2287   }
2288 
2289   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2290 }
2291 
2292 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2293                                      SDLoc DL, SelectionDAG &DAG,
2294                                      const RISCVSubtarget &Subtarget) {
2295   if (VT.isScalableVector())
2296     return DAG.getFPExtendOrRound(Op, DL, VT);
2297   assert(VT.isFixedLengthVector() &&
2298          "Unexpected value type for RVV FP extend/round lowering");
2299   SDValue Mask, VL;
2300   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2301   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2302                         ? RISCVISD::FP_EXTEND_VL
2303                         : RISCVISD::FP_ROUND_VL;
2304   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2305 }
2306 
2307 // While RVV has alignment restrictions, we should always be able to load as a
2308 // legal equivalently-sized byte-typed vector instead. This method is
2309 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2310 // the load is already correctly-aligned, it returns SDValue().
2311 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2312                                                     SelectionDAG &DAG) const {
2313   auto *Load = cast<LoadSDNode>(Op);
2314   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2315 
2316   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2317                                      Load->getMemoryVT(),
2318                                      *Load->getMemOperand()))
2319     return SDValue();
2320 
2321   SDLoc DL(Op);
2322   MVT VT = Op.getSimpleValueType();
2323   unsigned EltSizeBits = VT.getScalarSizeInBits();
2324   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2325          "Unexpected unaligned RVV load type");
2326   MVT NewVT =
2327       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2328   assert(NewVT.isValid() &&
2329          "Expecting equally-sized RVV vector types to be legal");
2330   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2331                           Load->getPointerInfo(), Load->getOriginalAlign(),
2332                           Load->getMemOperand()->getFlags());
2333   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2334 }
2335 
2336 // While RVV has alignment restrictions, we should always be able to store as a
2337 // legal equivalently-sized byte-typed vector instead. This method is
2338 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2339 // returns SDValue() if the store is already correctly aligned.
2340 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2341                                                      SelectionDAG &DAG) const {
2342   auto *Store = cast<StoreSDNode>(Op);
2343   assert(Store && Store->getValue().getValueType().isVector() &&
2344          "Expected vector store");
2345 
2346   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2347                                      Store->getMemoryVT(),
2348                                      *Store->getMemOperand()))
2349     return SDValue();
2350 
2351   SDLoc DL(Op);
2352   SDValue StoredVal = Store->getValue();
2353   MVT VT = StoredVal.getSimpleValueType();
2354   unsigned EltSizeBits = VT.getScalarSizeInBits();
2355   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2356          "Unexpected unaligned RVV store type");
2357   MVT NewVT =
2358       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2359   assert(NewVT.isValid() &&
2360          "Expecting equally-sized RVV vector types to be legal");
2361   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2362   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2363                       Store->getPointerInfo(), Store->getOriginalAlign(),
2364                       Store->getMemOperand()->getFlags());
2365 }
2366 
2367 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2368                                             SelectionDAG &DAG) const {
2369   switch (Op.getOpcode()) {
2370   default:
2371     report_fatal_error("unimplemented operand");
2372   case ISD::GlobalAddress:
2373     return lowerGlobalAddress(Op, DAG);
2374   case ISD::BlockAddress:
2375     return lowerBlockAddress(Op, DAG);
2376   case ISD::ConstantPool:
2377     return lowerConstantPool(Op, DAG);
2378   case ISD::JumpTable:
2379     return lowerJumpTable(Op, DAG);
2380   case ISD::GlobalTLSAddress:
2381     return lowerGlobalTLSAddress(Op, DAG);
2382   case ISD::SELECT:
2383     return lowerSELECT(Op, DAG);
2384   case ISD::BRCOND:
2385     return lowerBRCOND(Op, DAG);
2386   case ISD::VASTART:
2387     return lowerVASTART(Op, DAG);
2388   case ISD::FRAMEADDR:
2389     return lowerFRAMEADDR(Op, DAG);
2390   case ISD::RETURNADDR:
2391     return lowerRETURNADDR(Op, DAG);
2392   case ISD::SHL_PARTS:
2393     return lowerShiftLeftParts(Op, DAG);
2394   case ISD::SRA_PARTS:
2395     return lowerShiftRightParts(Op, DAG, true);
2396   case ISD::SRL_PARTS:
2397     return lowerShiftRightParts(Op, DAG, false);
2398   case ISD::BITCAST: {
2399     SDLoc DL(Op);
2400     EVT VT = Op.getValueType();
2401     SDValue Op0 = Op.getOperand(0);
2402     EVT Op0VT = Op0.getValueType();
2403     MVT XLenVT = Subtarget.getXLenVT();
2404     if (VT.isFixedLengthVector()) {
2405       // We can handle fixed length vector bitcasts with a simple replacement
2406       // in isel.
2407       if (Op0VT.isFixedLengthVector())
2408         return Op;
2409       // When bitcasting from scalar to fixed-length vector, insert the scalar
2410       // into a one-element vector of the result type, and perform a vector
2411       // bitcast.
2412       if (!Op0VT.isVector()) {
2413         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2414         if (!isTypeLegal(BVT))
2415           return SDValue();
2416         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2417                                               DAG.getUNDEF(BVT), Op0,
2418                                               DAG.getConstant(0, DL, XLenVT)));
2419       }
2420       return SDValue();
2421     }
2422     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2423     // thus: bitcast the vector to a one-element vector type whose element type
2424     // is the same as the result type, and extract the first element.
2425     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2426       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2427       if (!isTypeLegal(BVT))
2428         return SDValue();
2429       SDValue BVec = DAG.getBitcast(BVT, Op0);
2430       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2431                          DAG.getConstant(0, DL, XLenVT));
2432     }
2433     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2434       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2435       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2436       return FPConv;
2437     }
2438     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2439         Subtarget.hasStdExtF()) {
2440       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2441       SDValue FPConv =
2442           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2443       return FPConv;
2444     }
2445     return SDValue();
2446   }
2447   case ISD::INTRINSIC_WO_CHAIN:
2448     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2449   case ISD::INTRINSIC_W_CHAIN:
2450     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2451   case ISD::INTRINSIC_VOID:
2452     return LowerINTRINSIC_VOID(Op, DAG);
2453   case ISD::BSWAP:
2454   case ISD::BITREVERSE: {
2455     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2456     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2457     MVT VT = Op.getSimpleValueType();
2458     SDLoc DL(Op);
2459     // Start with the maximum immediate value which is the bitwidth - 1.
2460     unsigned Imm = VT.getSizeInBits() - 1;
2461     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2462     if (Op.getOpcode() == ISD::BSWAP)
2463       Imm &= ~0x7U;
2464     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2465                        DAG.getConstant(Imm, DL, VT));
2466   }
2467   case ISD::FSHL:
2468   case ISD::FSHR: {
2469     MVT VT = Op.getSimpleValueType();
2470     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2471     SDLoc DL(Op);
2472     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2473       return Op;
2474     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2475     // use log(XLen) bits. Mask the shift amount accordingly.
2476     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2477     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2478                                 DAG.getConstant(ShAmtWidth, DL, VT));
2479     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2480     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2481   }
2482   case ISD::TRUNCATE: {
2483     SDLoc DL(Op);
2484     MVT VT = Op.getSimpleValueType();
2485     // Only custom-lower vector truncates
2486     if (!VT.isVector())
2487       return Op;
2488 
2489     // Truncates to mask types are handled differently
2490     if (VT.getVectorElementType() == MVT::i1)
2491       return lowerVectorMaskTrunc(Op, DAG);
2492 
2493     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2494     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2495     // truncate by one power of two at a time.
2496     MVT DstEltVT = VT.getVectorElementType();
2497 
2498     SDValue Src = Op.getOperand(0);
2499     MVT SrcVT = Src.getSimpleValueType();
2500     MVT SrcEltVT = SrcVT.getVectorElementType();
2501 
2502     assert(DstEltVT.bitsLT(SrcEltVT) &&
2503            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2504            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2505            "Unexpected vector truncate lowering");
2506 
2507     MVT ContainerVT = SrcVT;
2508     if (SrcVT.isFixedLengthVector()) {
2509       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2510       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2511     }
2512 
2513     SDValue Result = Src;
2514     SDValue Mask, VL;
2515     std::tie(Mask, VL) =
2516         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2517     LLVMContext &Context = *DAG.getContext();
2518     const ElementCount Count = ContainerVT.getVectorElementCount();
2519     do {
2520       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2521       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2522       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2523                            Mask, VL);
2524     } while (SrcEltVT != DstEltVT);
2525 
2526     if (SrcVT.isFixedLengthVector())
2527       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2528 
2529     return Result;
2530   }
2531   case ISD::ANY_EXTEND:
2532   case ISD::ZERO_EXTEND:
2533     if (Op.getOperand(0).getValueType().isVector() &&
2534         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2535       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2536     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2537   case ISD::SIGN_EXTEND:
2538     if (Op.getOperand(0).getValueType().isVector() &&
2539         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2540       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2541     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2542   case ISD::SPLAT_VECTOR_PARTS:
2543     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2544   case ISD::INSERT_VECTOR_ELT:
2545     return lowerINSERT_VECTOR_ELT(Op, DAG);
2546   case ISD::EXTRACT_VECTOR_ELT:
2547     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2548   case ISD::VSCALE: {
2549     MVT VT = Op.getSimpleValueType();
2550     SDLoc DL(Op);
2551     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2552     // We define our scalable vector types for lmul=1 to use a 64 bit known
2553     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2554     // vscale as VLENB / 8.
2555     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2556     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2557       // We assume VLENB is a multiple of 8. We manually choose the best shift
2558       // here because SimplifyDemandedBits isn't always able to simplify it.
2559       uint64_t Val = Op.getConstantOperandVal(0);
2560       if (isPowerOf2_64(Val)) {
2561         uint64_t Log2 = Log2_64(Val);
2562         if (Log2 < 3)
2563           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2564                              DAG.getConstant(3 - Log2, DL, VT));
2565         if (Log2 > 3)
2566           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2567                              DAG.getConstant(Log2 - 3, DL, VT));
2568         return VLENB;
2569       }
2570       // If the multiplier is a multiple of 8, scale it down to avoid needing
2571       // to shift the VLENB value.
2572       if ((Val % 8) == 0)
2573         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2574                            DAG.getConstant(Val / 8, DL, VT));
2575     }
2576 
2577     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2578                                  DAG.getConstant(3, DL, VT));
2579     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2580   }
2581   case ISD::FP_EXTEND: {
2582     // RVV can only do fp_extend to types double the size as the source. We
2583     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2584     // via f32.
2585     SDLoc DL(Op);
2586     MVT VT = Op.getSimpleValueType();
2587     SDValue Src = Op.getOperand(0);
2588     MVT SrcVT = Src.getSimpleValueType();
2589 
2590     // Prepare any fixed-length vector operands.
2591     MVT ContainerVT = VT;
2592     if (SrcVT.isFixedLengthVector()) {
2593       ContainerVT = getContainerForFixedLengthVector(VT);
2594       MVT SrcContainerVT =
2595           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2596       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2597     }
2598 
2599     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2600         SrcVT.getVectorElementType() != MVT::f16) {
2601       // For scalable vectors, we only need to close the gap between
2602       // vXf16->vXf64.
2603       if (!VT.isFixedLengthVector())
2604         return Op;
2605       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2606       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2607       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2608     }
2609 
2610     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2611     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2612     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2613         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2614 
2615     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2616                                            DL, DAG, Subtarget);
2617     if (VT.isFixedLengthVector())
2618       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2619     return Extend;
2620   }
2621   case ISD::FP_ROUND: {
2622     // RVV can only do fp_round to types half the size as the source. We
2623     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2624     // conversion instruction.
2625     SDLoc DL(Op);
2626     MVT VT = Op.getSimpleValueType();
2627     SDValue Src = Op.getOperand(0);
2628     MVT SrcVT = Src.getSimpleValueType();
2629 
2630     // Prepare any fixed-length vector operands.
2631     MVT ContainerVT = VT;
2632     if (VT.isFixedLengthVector()) {
2633       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2634       ContainerVT =
2635           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2636       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2637     }
2638 
2639     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2640         SrcVT.getVectorElementType() != MVT::f64) {
2641       // For scalable vectors, we only need to close the gap between
2642       // vXf64<->vXf16.
2643       if (!VT.isFixedLengthVector())
2644         return Op;
2645       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2646       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2647       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2648     }
2649 
2650     SDValue Mask, VL;
2651     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2652 
2653     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2654     SDValue IntermediateRound =
2655         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2656     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2657                                           DL, DAG, Subtarget);
2658 
2659     if (VT.isFixedLengthVector())
2660       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2661     return Round;
2662   }
2663   case ISD::FP_TO_SINT:
2664   case ISD::FP_TO_UINT:
2665   case ISD::SINT_TO_FP:
2666   case ISD::UINT_TO_FP: {
2667     // RVV can only do fp<->int conversions to types half/double the size as
2668     // the source. We custom-lower any conversions that do two hops into
2669     // sequences.
2670     MVT VT = Op.getSimpleValueType();
2671     if (!VT.isVector())
2672       return Op;
2673     SDLoc DL(Op);
2674     SDValue Src = Op.getOperand(0);
2675     MVT EltVT = VT.getVectorElementType();
2676     MVT SrcVT = Src.getSimpleValueType();
2677     MVT SrcEltVT = SrcVT.getVectorElementType();
2678     unsigned EltSize = EltVT.getSizeInBits();
2679     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2680     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2681            "Unexpected vector element types");
2682 
2683     bool IsInt2FP = SrcEltVT.isInteger();
2684     // Widening conversions
2685     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2686       if (IsInt2FP) {
2687         // Do a regular integer sign/zero extension then convert to float.
2688         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2689                                       VT.getVectorElementCount());
2690         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2691                                  ? ISD::ZERO_EXTEND
2692                                  : ISD::SIGN_EXTEND;
2693         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2694         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2695       }
2696       // FP2Int
2697       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2698       // Do one doubling fp_extend then complete the operation by converting
2699       // to int.
2700       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2701       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2702       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2703     }
2704 
2705     // Narrowing conversions
2706     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2707       if (IsInt2FP) {
2708         // One narrowing int_to_fp, then an fp_round.
2709         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2710         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2711         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2712         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2713       }
2714       // FP2Int
2715       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2716       // representable by the integer, the result is poison.
2717       MVT IVecVT =
2718           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2719                            VT.getVectorElementCount());
2720       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2721       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2722     }
2723 
2724     // Scalable vectors can exit here. Patterns will handle equally-sized
2725     // conversions halving/doubling ones.
2726     if (!VT.isFixedLengthVector())
2727       return Op;
2728 
2729     // For fixed-length vectors we lower to a custom "VL" node.
2730     unsigned RVVOpc = 0;
2731     switch (Op.getOpcode()) {
2732     default:
2733       llvm_unreachable("Impossible opcode");
2734     case ISD::FP_TO_SINT:
2735       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2736       break;
2737     case ISD::FP_TO_UINT:
2738       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2739       break;
2740     case ISD::SINT_TO_FP:
2741       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2742       break;
2743     case ISD::UINT_TO_FP:
2744       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2745       break;
2746     }
2747 
2748     MVT ContainerVT, SrcContainerVT;
2749     // Derive the reference container type from the larger vector type.
2750     if (SrcEltSize > EltSize) {
2751       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2752       ContainerVT =
2753           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2754     } else {
2755       ContainerVT = getContainerForFixedLengthVector(VT);
2756       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2757     }
2758 
2759     SDValue Mask, VL;
2760     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2761 
2762     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2763     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2764     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2765   }
2766   case ISD::FP_TO_SINT_SAT:
2767   case ISD::FP_TO_UINT_SAT:
2768     return lowerFP_TO_INT_SAT(Op, DAG);
2769   case ISD::VECREDUCE_ADD:
2770   case ISD::VECREDUCE_UMAX:
2771   case ISD::VECREDUCE_SMAX:
2772   case ISD::VECREDUCE_UMIN:
2773   case ISD::VECREDUCE_SMIN:
2774     return lowerVECREDUCE(Op, DAG);
2775   case ISD::VECREDUCE_AND:
2776   case ISD::VECREDUCE_OR:
2777   case ISD::VECREDUCE_XOR:
2778     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2779       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2780     return lowerVECREDUCE(Op, DAG);
2781   case ISD::VECREDUCE_FADD:
2782   case ISD::VECREDUCE_SEQ_FADD:
2783   case ISD::VECREDUCE_FMIN:
2784   case ISD::VECREDUCE_FMAX:
2785     return lowerFPVECREDUCE(Op, DAG);
2786   case ISD::VP_REDUCE_ADD:
2787   case ISD::VP_REDUCE_UMAX:
2788   case ISD::VP_REDUCE_SMAX:
2789   case ISD::VP_REDUCE_UMIN:
2790   case ISD::VP_REDUCE_SMIN:
2791   case ISD::VP_REDUCE_FADD:
2792   case ISD::VP_REDUCE_SEQ_FADD:
2793   case ISD::VP_REDUCE_FMIN:
2794   case ISD::VP_REDUCE_FMAX:
2795     return lowerVPREDUCE(Op, DAG);
2796   case ISD::VP_REDUCE_AND:
2797   case ISD::VP_REDUCE_OR:
2798   case ISD::VP_REDUCE_XOR:
2799     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2800       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2801     return lowerVPREDUCE(Op, DAG);
2802   case ISD::INSERT_SUBVECTOR:
2803     return lowerINSERT_SUBVECTOR(Op, DAG);
2804   case ISD::EXTRACT_SUBVECTOR:
2805     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2806   case ISD::STEP_VECTOR:
2807     return lowerSTEP_VECTOR(Op, DAG);
2808   case ISD::VECTOR_REVERSE:
2809     return lowerVECTOR_REVERSE(Op, DAG);
2810   case ISD::BUILD_VECTOR:
2811     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2812   case ISD::SPLAT_VECTOR:
2813     if (Op.getValueType().getVectorElementType() == MVT::i1)
2814       return lowerVectorMaskSplat(Op, DAG);
2815     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2816   case ISD::VECTOR_SHUFFLE:
2817     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2818   case ISD::CONCAT_VECTORS: {
2819     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2820     // better than going through the stack, as the default expansion does.
2821     SDLoc DL(Op);
2822     MVT VT = Op.getSimpleValueType();
2823     unsigned NumOpElts =
2824         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2825     SDValue Vec = DAG.getUNDEF(VT);
2826     for (const auto &OpIdx : enumerate(Op->ops()))
2827       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2828                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2829     return Vec;
2830   }
2831   case ISD::LOAD:
2832     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2833       return V;
2834     if (Op.getValueType().isFixedLengthVector())
2835       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2836     return Op;
2837   case ISD::STORE:
2838     if (auto V = expandUnalignedRVVStore(Op, DAG))
2839       return V;
2840     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2841       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2842     return Op;
2843   case ISD::MLOAD:
2844   case ISD::VP_LOAD:
2845     return lowerMaskedLoad(Op, DAG);
2846   case ISD::MSTORE:
2847   case ISD::VP_STORE:
2848     return lowerMaskedStore(Op, DAG);
2849   case ISD::SETCC:
2850     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2851   case ISD::ADD:
2852     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2853   case ISD::SUB:
2854     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2855   case ISD::MUL:
2856     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2857   case ISD::MULHS:
2858     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2859   case ISD::MULHU:
2860     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2861   case ISD::AND:
2862     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2863                                               RISCVISD::AND_VL);
2864   case ISD::OR:
2865     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2866                                               RISCVISD::OR_VL);
2867   case ISD::XOR:
2868     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2869                                               RISCVISD::XOR_VL);
2870   case ISD::SDIV:
2871     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2872   case ISD::SREM:
2873     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2874   case ISD::UDIV:
2875     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2876   case ISD::UREM:
2877     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2878   case ISD::SHL:
2879   case ISD::SRA:
2880   case ISD::SRL:
2881     if (Op.getSimpleValueType().isFixedLengthVector())
2882       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2883     // This can be called for an i32 shift amount that needs to be promoted.
2884     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2885            "Unexpected custom legalisation");
2886     return SDValue();
2887   case ISD::SADDSAT:
2888     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2889   case ISD::UADDSAT:
2890     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2891   case ISD::SSUBSAT:
2892     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2893   case ISD::USUBSAT:
2894     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2895   case ISD::FADD:
2896     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2897   case ISD::FSUB:
2898     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2899   case ISD::FMUL:
2900     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2901   case ISD::FDIV:
2902     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2903   case ISD::FNEG:
2904     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2905   case ISD::FABS:
2906     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2907   case ISD::FSQRT:
2908     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2909   case ISD::FMA:
2910     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2911   case ISD::SMIN:
2912     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2913   case ISD::SMAX:
2914     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2915   case ISD::UMIN:
2916     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2917   case ISD::UMAX:
2918     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2919   case ISD::FMINNUM:
2920     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2921   case ISD::FMAXNUM:
2922     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2923   case ISD::ABS:
2924     return lowerABS(Op, DAG);
2925   case ISD::VSELECT:
2926     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2927   case ISD::FCOPYSIGN:
2928     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2929   case ISD::MGATHER:
2930   case ISD::VP_GATHER:
2931     return lowerMaskedGather(Op, DAG);
2932   case ISD::MSCATTER:
2933   case ISD::VP_SCATTER:
2934     return lowerMaskedScatter(Op, DAG);
2935   case ISD::FLT_ROUNDS_:
2936     return lowerGET_ROUNDING(Op, DAG);
2937   case ISD::SET_ROUNDING:
2938     return lowerSET_ROUNDING(Op, DAG);
2939   case ISD::VP_ADD:
2940     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2941   case ISD::VP_SUB:
2942     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2943   case ISD::VP_MUL:
2944     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2945   case ISD::VP_SDIV:
2946     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2947   case ISD::VP_UDIV:
2948     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2949   case ISD::VP_SREM:
2950     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2951   case ISD::VP_UREM:
2952     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2953   case ISD::VP_AND:
2954     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2955   case ISD::VP_OR:
2956     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2957   case ISD::VP_XOR:
2958     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2959   case ISD::VP_ASHR:
2960     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2961   case ISD::VP_LSHR:
2962     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2963   case ISD::VP_SHL:
2964     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2965   case ISD::VP_FADD:
2966     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2967   case ISD::VP_FSUB:
2968     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2969   case ISD::VP_FMUL:
2970     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2971   case ISD::VP_FDIV:
2972     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2973   }
2974 }
2975 
2976 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2977                              SelectionDAG &DAG, unsigned Flags) {
2978   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2979 }
2980 
2981 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2982                              SelectionDAG &DAG, unsigned Flags) {
2983   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2984                                    Flags);
2985 }
2986 
2987 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2988                              SelectionDAG &DAG, unsigned Flags) {
2989   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2990                                    N->getOffset(), Flags);
2991 }
2992 
2993 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2994                              SelectionDAG &DAG, unsigned Flags) {
2995   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2996 }
2997 
2998 template <class NodeTy>
2999 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3000                                      bool IsLocal) const {
3001   SDLoc DL(N);
3002   EVT Ty = getPointerTy(DAG.getDataLayout());
3003 
3004   if (isPositionIndependent()) {
3005     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3006     if (IsLocal)
3007       // Use PC-relative addressing to access the symbol. This generates the
3008       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3009       // %pcrel_lo(auipc)).
3010       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3011 
3012     // Use PC-relative addressing to access the GOT for this symbol, then load
3013     // the address from the GOT. This generates the pattern (PseudoLA sym),
3014     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3015     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3016   }
3017 
3018   switch (getTargetMachine().getCodeModel()) {
3019   default:
3020     report_fatal_error("Unsupported code model for lowering");
3021   case CodeModel::Small: {
3022     // Generate a sequence for accessing addresses within the first 2 GiB of
3023     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3024     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3025     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3026     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3027     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3028   }
3029   case CodeModel::Medium: {
3030     // Generate a sequence for accessing addresses within any 2GiB range within
3031     // the address space. This generates the pattern (PseudoLLA sym), which
3032     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3033     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3034     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3035   }
3036   }
3037 }
3038 
3039 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3040                                                 SelectionDAG &DAG) const {
3041   SDLoc DL(Op);
3042   EVT Ty = Op.getValueType();
3043   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3044   int64_t Offset = N->getOffset();
3045   MVT XLenVT = Subtarget.getXLenVT();
3046 
3047   const GlobalValue *GV = N->getGlobal();
3048   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3049   SDValue Addr = getAddr(N, DAG, IsLocal);
3050 
3051   // In order to maximise the opportunity for common subexpression elimination,
3052   // emit a separate ADD node for the global address offset instead of folding
3053   // it in the global address node. Later peephole optimisations may choose to
3054   // fold it back in when profitable.
3055   if (Offset != 0)
3056     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3057                        DAG.getConstant(Offset, DL, XLenVT));
3058   return Addr;
3059 }
3060 
3061 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3062                                                SelectionDAG &DAG) const {
3063   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3064 
3065   return getAddr(N, DAG);
3066 }
3067 
3068 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3069                                                SelectionDAG &DAG) const {
3070   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3071 
3072   return getAddr(N, DAG);
3073 }
3074 
3075 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3076                                             SelectionDAG &DAG) const {
3077   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3078 
3079   return getAddr(N, DAG);
3080 }
3081 
3082 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3083                                               SelectionDAG &DAG,
3084                                               bool UseGOT) const {
3085   SDLoc DL(N);
3086   EVT Ty = getPointerTy(DAG.getDataLayout());
3087   const GlobalValue *GV = N->getGlobal();
3088   MVT XLenVT = Subtarget.getXLenVT();
3089 
3090   if (UseGOT) {
3091     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3092     // load the address from the GOT and add the thread pointer. This generates
3093     // the pattern (PseudoLA_TLS_IE sym), which expands to
3094     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3095     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3096     SDValue Load =
3097         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3098 
3099     // Add the thread pointer.
3100     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3101     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3102   }
3103 
3104   // Generate a sequence for accessing the address relative to the thread
3105   // pointer, with the appropriate adjustment for the thread pointer offset.
3106   // This generates the pattern
3107   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3108   SDValue AddrHi =
3109       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3110   SDValue AddrAdd =
3111       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3112   SDValue AddrLo =
3113       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3114 
3115   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3116   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3117   SDValue MNAdd = SDValue(
3118       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3119       0);
3120   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3121 }
3122 
3123 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3124                                                SelectionDAG &DAG) const {
3125   SDLoc DL(N);
3126   EVT Ty = getPointerTy(DAG.getDataLayout());
3127   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3128   const GlobalValue *GV = N->getGlobal();
3129 
3130   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3131   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3132   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3133   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3134   SDValue Load =
3135       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3136 
3137   // Prepare argument list to generate call.
3138   ArgListTy Args;
3139   ArgListEntry Entry;
3140   Entry.Node = Load;
3141   Entry.Ty = CallTy;
3142   Args.push_back(Entry);
3143 
3144   // Setup call to __tls_get_addr.
3145   TargetLowering::CallLoweringInfo CLI(DAG);
3146   CLI.setDebugLoc(DL)
3147       .setChain(DAG.getEntryNode())
3148       .setLibCallee(CallingConv::C, CallTy,
3149                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3150                     std::move(Args));
3151 
3152   return LowerCallTo(CLI).first;
3153 }
3154 
3155 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3156                                                    SelectionDAG &DAG) const {
3157   SDLoc DL(Op);
3158   EVT Ty = Op.getValueType();
3159   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3160   int64_t Offset = N->getOffset();
3161   MVT XLenVT = Subtarget.getXLenVT();
3162 
3163   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3164 
3165   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3166       CallingConv::GHC)
3167     report_fatal_error("In GHC calling convention TLS is not supported");
3168 
3169   SDValue Addr;
3170   switch (Model) {
3171   case TLSModel::LocalExec:
3172     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3173     break;
3174   case TLSModel::InitialExec:
3175     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3176     break;
3177   case TLSModel::LocalDynamic:
3178   case TLSModel::GeneralDynamic:
3179     Addr = getDynamicTLSAddr(N, DAG);
3180     break;
3181   }
3182 
3183   // In order to maximise the opportunity for common subexpression elimination,
3184   // emit a separate ADD node for the global address offset instead of folding
3185   // it in the global address node. Later peephole optimisations may choose to
3186   // fold it back in when profitable.
3187   if (Offset != 0)
3188     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3189                        DAG.getConstant(Offset, DL, XLenVT));
3190   return Addr;
3191 }
3192 
3193 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3194   SDValue CondV = Op.getOperand(0);
3195   SDValue TrueV = Op.getOperand(1);
3196   SDValue FalseV = Op.getOperand(2);
3197   SDLoc DL(Op);
3198   MVT VT = Op.getSimpleValueType();
3199   MVT XLenVT = Subtarget.getXLenVT();
3200 
3201   // Lower vector SELECTs to VSELECTs by splatting the condition.
3202   if (VT.isVector()) {
3203     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3204     SDValue CondSplat = VT.isScalableVector()
3205                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3206                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3207     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3208   }
3209 
3210   // If the result type is XLenVT and CondV is the output of a SETCC node
3211   // which also operated on XLenVT inputs, then merge the SETCC node into the
3212   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3213   // compare+branch instructions. i.e.:
3214   // (select (setcc lhs, rhs, cc), truev, falsev)
3215   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3216   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3217       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3218     SDValue LHS = CondV.getOperand(0);
3219     SDValue RHS = CondV.getOperand(1);
3220     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3221     ISD::CondCode CCVal = CC->get();
3222 
3223     // Special case for a select of 2 constants that have a diffence of 1.
3224     // Normally this is done by DAGCombine, but if the select is introduced by
3225     // type legalization or op legalization, we miss it. Restricting to SETLT
3226     // case for now because that is what signed saturating add/sub need.
3227     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3228     // but we would probably want to swap the true/false values if the condition
3229     // is SETGE/SETLE to avoid an XORI.
3230     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3231         CCVal == ISD::SETLT) {
3232       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3233       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3234       if (TrueVal - 1 == FalseVal)
3235         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3236       if (TrueVal + 1 == FalseVal)
3237         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3238     }
3239 
3240     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3241 
3242     SDValue TargetCC = DAG.getCondCode(CCVal);
3243     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3244     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3245   }
3246 
3247   // Otherwise:
3248   // (select condv, truev, falsev)
3249   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3250   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3251   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3252 
3253   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3254 
3255   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3256 }
3257 
3258 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3259   SDValue CondV = Op.getOperand(1);
3260   SDLoc DL(Op);
3261   MVT XLenVT = Subtarget.getXLenVT();
3262 
3263   if (CondV.getOpcode() == ISD::SETCC &&
3264       CondV.getOperand(0).getValueType() == XLenVT) {
3265     SDValue LHS = CondV.getOperand(0);
3266     SDValue RHS = CondV.getOperand(1);
3267     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3268 
3269     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3270 
3271     SDValue TargetCC = DAG.getCondCode(CCVal);
3272     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3273                        LHS, RHS, TargetCC, Op.getOperand(2));
3274   }
3275 
3276   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3277                      CondV, DAG.getConstant(0, DL, XLenVT),
3278                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3279 }
3280 
3281 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3282   MachineFunction &MF = DAG.getMachineFunction();
3283   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3284 
3285   SDLoc DL(Op);
3286   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3287                                  getPointerTy(MF.getDataLayout()));
3288 
3289   // vastart just stores the address of the VarArgsFrameIndex slot into the
3290   // memory location argument.
3291   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3292   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3293                       MachinePointerInfo(SV));
3294 }
3295 
3296 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3297                                             SelectionDAG &DAG) const {
3298   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3299   MachineFunction &MF = DAG.getMachineFunction();
3300   MachineFrameInfo &MFI = MF.getFrameInfo();
3301   MFI.setFrameAddressIsTaken(true);
3302   Register FrameReg = RI.getFrameRegister(MF);
3303   int XLenInBytes = Subtarget.getXLen() / 8;
3304 
3305   EVT VT = Op.getValueType();
3306   SDLoc DL(Op);
3307   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3308   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3309   while (Depth--) {
3310     int Offset = -(XLenInBytes * 2);
3311     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3312                               DAG.getIntPtrConstant(Offset, DL));
3313     FrameAddr =
3314         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3315   }
3316   return FrameAddr;
3317 }
3318 
3319 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3320                                              SelectionDAG &DAG) const {
3321   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3322   MachineFunction &MF = DAG.getMachineFunction();
3323   MachineFrameInfo &MFI = MF.getFrameInfo();
3324   MFI.setReturnAddressIsTaken(true);
3325   MVT XLenVT = Subtarget.getXLenVT();
3326   int XLenInBytes = Subtarget.getXLen() / 8;
3327 
3328   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3329     return SDValue();
3330 
3331   EVT VT = Op.getValueType();
3332   SDLoc DL(Op);
3333   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3334   if (Depth) {
3335     int Off = -XLenInBytes;
3336     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3337     SDValue Offset = DAG.getConstant(Off, DL, VT);
3338     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3339                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3340                        MachinePointerInfo());
3341   }
3342 
3343   // Return the value of the return address register, marking it an implicit
3344   // live-in.
3345   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3346   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3347 }
3348 
3349 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3350                                                  SelectionDAG &DAG) const {
3351   SDLoc DL(Op);
3352   SDValue Lo = Op.getOperand(0);
3353   SDValue Hi = Op.getOperand(1);
3354   SDValue Shamt = Op.getOperand(2);
3355   EVT VT = Lo.getValueType();
3356 
3357   // if Shamt-XLEN < 0: // Shamt < XLEN
3358   //   Lo = Lo << Shamt
3359   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3360   // else:
3361   //   Lo = 0
3362   //   Hi = Lo << (Shamt-XLEN)
3363 
3364   SDValue Zero = DAG.getConstant(0, DL, VT);
3365   SDValue One = DAG.getConstant(1, DL, VT);
3366   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3367   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3368   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3369   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3370 
3371   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3372   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3373   SDValue ShiftRightLo =
3374       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3375   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3376   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3377   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3378 
3379   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3380 
3381   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3382   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3383 
3384   SDValue Parts[2] = {Lo, Hi};
3385   return DAG.getMergeValues(Parts, DL);
3386 }
3387 
3388 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3389                                                   bool IsSRA) const {
3390   SDLoc DL(Op);
3391   SDValue Lo = Op.getOperand(0);
3392   SDValue Hi = Op.getOperand(1);
3393   SDValue Shamt = Op.getOperand(2);
3394   EVT VT = Lo.getValueType();
3395 
3396   // SRA expansion:
3397   //   if Shamt-XLEN < 0: // Shamt < XLEN
3398   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3399   //     Hi = Hi >>s Shamt
3400   //   else:
3401   //     Lo = Hi >>s (Shamt-XLEN);
3402   //     Hi = Hi >>s (XLEN-1)
3403   //
3404   // SRL expansion:
3405   //   if Shamt-XLEN < 0: // Shamt < XLEN
3406   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3407   //     Hi = Hi >>u Shamt
3408   //   else:
3409   //     Lo = Hi >>u (Shamt-XLEN);
3410   //     Hi = 0;
3411 
3412   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3413 
3414   SDValue Zero = DAG.getConstant(0, DL, VT);
3415   SDValue One = DAG.getConstant(1, DL, VT);
3416   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3417   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3418   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3419   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3420 
3421   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3422   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3423   SDValue ShiftLeftHi =
3424       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3425   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3426   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3427   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3428   SDValue HiFalse =
3429       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3430 
3431   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3432 
3433   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3434   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3435 
3436   SDValue Parts[2] = {Lo, Hi};
3437   return DAG.getMergeValues(Parts, DL);
3438 }
3439 
3440 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3441 // legal equivalently-sized i8 type, so we can use that as a go-between.
3442 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3443                                                   SelectionDAG &DAG) const {
3444   SDLoc DL(Op);
3445   MVT VT = Op.getSimpleValueType();
3446   SDValue SplatVal = Op.getOperand(0);
3447   // All-zeros or all-ones splats are handled specially.
3448   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3449     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3450     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3451   }
3452   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3453     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3454     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3455   }
3456   MVT XLenVT = Subtarget.getXLenVT();
3457   assert(SplatVal.getValueType() == XLenVT &&
3458          "Unexpected type for i1 splat value");
3459   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3460   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3461                          DAG.getConstant(1, DL, XLenVT));
3462   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3463   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3464   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3465 }
3466 
3467 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3468 // illegal (currently only vXi64 RV32).
3469 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3470 // them to SPLAT_VECTOR_I64
3471 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3472                                                      SelectionDAG &DAG) const {
3473   SDLoc DL(Op);
3474   MVT VecVT = Op.getSimpleValueType();
3475   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3476          "Unexpected SPLAT_VECTOR_PARTS lowering");
3477 
3478   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3479   SDValue Lo = Op.getOperand(0);
3480   SDValue Hi = Op.getOperand(1);
3481 
3482   if (VecVT.isFixedLengthVector()) {
3483     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3484     SDLoc DL(Op);
3485     SDValue Mask, VL;
3486     std::tie(Mask, VL) =
3487         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3488 
3489     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3490     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3491   }
3492 
3493   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3494     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3495     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3496     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3497     // node in order to try and match RVV vector/scalar instructions.
3498     if ((LoC >> 31) == HiC)
3499       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3500   }
3501 
3502   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3503   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3504       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3505       Hi.getConstantOperandVal(1) == 31)
3506     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3507 
3508   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3509   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3510                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3511 }
3512 
3513 // Custom-lower extensions from mask vectors by using a vselect either with 1
3514 // for zero/any-extension or -1 for sign-extension:
3515 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3516 // Note that any-extension is lowered identically to zero-extension.
3517 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3518                                                 int64_t ExtTrueVal) const {
3519   SDLoc DL(Op);
3520   MVT VecVT = Op.getSimpleValueType();
3521   SDValue Src = Op.getOperand(0);
3522   // Only custom-lower extensions from mask types
3523   assert(Src.getValueType().isVector() &&
3524          Src.getValueType().getVectorElementType() == MVT::i1);
3525 
3526   MVT XLenVT = Subtarget.getXLenVT();
3527   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3528   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3529 
3530   if (VecVT.isScalableVector()) {
3531     // Be careful not to introduce illegal scalar types at this stage, and be
3532     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3533     // illegal and must be expanded. Since we know that the constants are
3534     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3535     bool IsRV32E64 =
3536         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3537 
3538     if (!IsRV32E64) {
3539       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3540       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3541     } else {
3542       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3543       SplatTrueVal =
3544           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3545     }
3546 
3547     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3548   }
3549 
3550   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3551   MVT I1ContainerVT =
3552       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3553 
3554   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3555 
3556   SDValue Mask, VL;
3557   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3558 
3559   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3560   SplatTrueVal =
3561       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3562   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3563                                SplatTrueVal, SplatZero, VL);
3564 
3565   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3566 }
3567 
3568 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3569     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3570   MVT ExtVT = Op.getSimpleValueType();
3571   // Only custom-lower extensions from fixed-length vector types.
3572   if (!ExtVT.isFixedLengthVector())
3573     return Op;
3574   MVT VT = Op.getOperand(0).getSimpleValueType();
3575   // Grab the canonical container type for the extended type. Infer the smaller
3576   // type from that to ensure the same number of vector elements, as we know
3577   // the LMUL will be sufficient to hold the smaller type.
3578   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3579   // Get the extended container type manually to ensure the same number of
3580   // vector elements between source and dest.
3581   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3582                                      ContainerExtVT.getVectorElementCount());
3583 
3584   SDValue Op1 =
3585       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3586 
3587   SDLoc DL(Op);
3588   SDValue Mask, VL;
3589   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3590 
3591   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3592 
3593   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3594 }
3595 
3596 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3597 // setcc operation:
3598 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3599 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3600                                                   SelectionDAG &DAG) const {
3601   SDLoc DL(Op);
3602   EVT MaskVT = Op.getValueType();
3603   // Only expect to custom-lower truncations to mask types
3604   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3605          "Unexpected type for vector mask lowering");
3606   SDValue Src = Op.getOperand(0);
3607   MVT VecVT = Src.getSimpleValueType();
3608 
3609   // If this is a fixed vector, we need to convert it to a scalable vector.
3610   MVT ContainerVT = VecVT;
3611   if (VecVT.isFixedLengthVector()) {
3612     ContainerVT = getContainerForFixedLengthVector(VecVT);
3613     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3614   }
3615 
3616   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3617   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3618 
3619   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3620   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3621 
3622   if (VecVT.isScalableVector()) {
3623     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3624     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3625   }
3626 
3627   SDValue Mask, VL;
3628   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3629 
3630   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3631   SDValue Trunc =
3632       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3633   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3634                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3635   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3636 }
3637 
3638 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3639 // first position of a vector, and that vector is slid up to the insert index.
3640 // By limiting the active vector length to index+1 and merging with the
3641 // original vector (with an undisturbed tail policy for elements >= VL), we
3642 // achieve the desired result of leaving all elements untouched except the one
3643 // at VL-1, which is replaced with the desired value.
3644 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3645                                                     SelectionDAG &DAG) const {
3646   SDLoc DL(Op);
3647   MVT VecVT = Op.getSimpleValueType();
3648   SDValue Vec = Op.getOperand(0);
3649   SDValue Val = Op.getOperand(1);
3650   SDValue Idx = Op.getOperand(2);
3651 
3652   if (VecVT.getVectorElementType() == MVT::i1) {
3653     // FIXME: For now we just promote to an i8 vector and insert into that,
3654     // but this is probably not optimal.
3655     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3656     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3657     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3658     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3659   }
3660 
3661   MVT ContainerVT = VecVT;
3662   // If the operand is a fixed-length vector, convert to a scalable one.
3663   if (VecVT.isFixedLengthVector()) {
3664     ContainerVT = getContainerForFixedLengthVector(VecVT);
3665     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3666   }
3667 
3668   MVT XLenVT = Subtarget.getXLenVT();
3669 
3670   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3671   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3672   // Even i64-element vectors on RV32 can be lowered without scalar
3673   // legalization if the most-significant 32 bits of the value are not affected
3674   // by the sign-extension of the lower 32 bits.
3675   // TODO: We could also catch sign extensions of a 32-bit value.
3676   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3677     const auto *CVal = cast<ConstantSDNode>(Val);
3678     if (isInt<32>(CVal->getSExtValue())) {
3679       IsLegalInsert = true;
3680       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3681     }
3682   }
3683 
3684   SDValue Mask, VL;
3685   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3686 
3687   SDValue ValInVec;
3688 
3689   if (IsLegalInsert) {
3690     unsigned Opc =
3691         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3692     if (isNullConstant(Idx)) {
3693       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3694       if (!VecVT.isFixedLengthVector())
3695         return Vec;
3696       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3697     }
3698     ValInVec =
3699         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3700   } else {
3701     // On RV32, i64-element vectors must be specially handled to place the
3702     // value at element 0, by using two vslide1up instructions in sequence on
3703     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3704     // this.
3705     SDValue One = DAG.getConstant(1, DL, XLenVT);
3706     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3707     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3708     MVT I32ContainerVT =
3709         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3710     SDValue I32Mask =
3711         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3712     // Limit the active VL to two.
3713     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3714     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3715     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3716     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3717                            InsertI64VL);
3718     // First slide in the hi value, then the lo in underneath it.
3719     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3720                            ValHi, I32Mask, InsertI64VL);
3721     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3722                            ValLo, I32Mask, InsertI64VL);
3723     // Bitcast back to the right container type.
3724     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3725   }
3726 
3727   // Now that the value is in a vector, slide it into position.
3728   SDValue InsertVL =
3729       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3730   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3731                                 ValInVec, Idx, Mask, InsertVL);
3732   if (!VecVT.isFixedLengthVector())
3733     return Slideup;
3734   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3735 }
3736 
3737 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3738 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3739 // types this is done using VMV_X_S to allow us to glean information about the
3740 // sign bits of the result.
3741 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3742                                                      SelectionDAG &DAG) const {
3743   SDLoc DL(Op);
3744   SDValue Idx = Op.getOperand(1);
3745   SDValue Vec = Op.getOperand(0);
3746   EVT EltVT = Op.getValueType();
3747   MVT VecVT = Vec.getSimpleValueType();
3748   MVT XLenVT = Subtarget.getXLenVT();
3749 
3750   if (VecVT.getVectorElementType() == MVT::i1) {
3751     // FIXME: For now we just promote to an i8 vector and extract from that,
3752     // but this is probably not optimal.
3753     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3754     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3755     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3756   }
3757 
3758   // If this is a fixed vector, we need to convert it to a scalable vector.
3759   MVT ContainerVT = VecVT;
3760   if (VecVT.isFixedLengthVector()) {
3761     ContainerVT = getContainerForFixedLengthVector(VecVT);
3762     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3763   }
3764 
3765   // If the index is 0, the vector is already in the right position.
3766   if (!isNullConstant(Idx)) {
3767     // Use a VL of 1 to avoid processing more elements than we need.
3768     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3769     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3770     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3771     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3772                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3773   }
3774 
3775   if (!EltVT.isInteger()) {
3776     // Floating-point extracts are handled in TableGen.
3777     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3778                        DAG.getConstant(0, DL, XLenVT));
3779   }
3780 
3781   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3782   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3783 }
3784 
3785 // Some RVV intrinsics may claim that they want an integer operand to be
3786 // promoted or expanded.
3787 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3788                                           const RISCVSubtarget &Subtarget) {
3789   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3790           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3791          "Unexpected opcode");
3792 
3793   if (!Subtarget.hasVInstructions())
3794     return SDValue();
3795 
3796   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3797   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3798   SDLoc DL(Op);
3799 
3800   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3801       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3802   if (!II || !II->SplatOperand)
3803     return SDValue();
3804 
3805   unsigned SplatOp = II->SplatOperand + HasChain;
3806   assert(SplatOp < Op.getNumOperands());
3807 
3808   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3809   SDValue &ScalarOp = Operands[SplatOp];
3810   MVT OpVT = ScalarOp.getSimpleValueType();
3811   MVT XLenVT = Subtarget.getXLenVT();
3812 
3813   // If this isn't a scalar, or its type is XLenVT we're done.
3814   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3815     return SDValue();
3816 
3817   // Simplest case is that the operand needs to be promoted to XLenVT.
3818   if (OpVT.bitsLT(XLenVT)) {
3819     // If the operand is a constant, sign extend to increase our chances
3820     // of being able to use a .vi instruction. ANY_EXTEND would become a
3821     // a zero extend and the simm5 check in isel would fail.
3822     // FIXME: Should we ignore the upper bits in isel instead?
3823     unsigned ExtOpc =
3824         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3825     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3826     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3827   }
3828 
3829   // Use the previous operand to get the vXi64 VT. The result might be a mask
3830   // VT for compares. Using the previous operand assumes that the previous
3831   // operand will never have a smaller element size than a scalar operand and
3832   // that a widening operation never uses SEW=64.
3833   // NOTE: If this fails the below assert, we can probably just find the
3834   // element count from any operand or result and use it to construct the VT.
3835   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3836   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3837 
3838   // The more complex case is when the scalar is larger than XLenVT.
3839   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3840          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3841 
3842   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3843   // on the instruction to sign-extend since SEW>XLEN.
3844   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3845     if (isInt<32>(CVal->getSExtValue())) {
3846       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3847       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3848     }
3849   }
3850 
3851   // We need to convert the scalar to a splat vector.
3852   // FIXME: Can we implicitly truncate the scalar if it is known to
3853   // be sign extended?
3854   // VL should be the last operand.
3855   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3856   assert(VL.getValueType() == XLenVT);
3857   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3858   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3859 }
3860 
3861 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3862                                                      SelectionDAG &DAG) const {
3863   unsigned IntNo = Op.getConstantOperandVal(0);
3864   SDLoc DL(Op);
3865   MVT XLenVT = Subtarget.getXLenVT();
3866 
3867   switch (IntNo) {
3868   default:
3869     break; // Don't custom lower most intrinsics.
3870   case Intrinsic::thread_pointer: {
3871     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3872     return DAG.getRegister(RISCV::X4, PtrVT);
3873   }
3874   case Intrinsic::riscv_orc_b:
3875     // Lower to the GORCI encoding for orc.b.
3876     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3877                        DAG.getConstant(7, DL, XLenVT));
3878   case Intrinsic::riscv_grev:
3879   case Intrinsic::riscv_gorc: {
3880     unsigned Opc =
3881         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3882     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3883   }
3884   case Intrinsic::riscv_shfl:
3885   case Intrinsic::riscv_unshfl: {
3886     unsigned Opc =
3887         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3888     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3889   }
3890   case Intrinsic::riscv_bcompress:
3891   case Intrinsic::riscv_bdecompress: {
3892     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3893                                                        : RISCVISD::BDECOMPRESS;
3894     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3895   }
3896   case Intrinsic::riscv_vmv_x_s:
3897     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3898     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3899                        Op.getOperand(1));
3900   case Intrinsic::riscv_vmv_v_x:
3901     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3902                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3903   case Intrinsic::riscv_vfmv_v_f:
3904     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3905                        Op.getOperand(1), Op.getOperand(2));
3906   case Intrinsic::riscv_vmv_s_x: {
3907     SDValue Scalar = Op.getOperand(2);
3908 
3909     if (Scalar.getValueType().bitsLE(XLenVT)) {
3910       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3911       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3912                          Op.getOperand(1), Scalar, Op.getOperand(3));
3913     }
3914 
3915     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3916 
3917     // This is an i64 value that lives in two scalar registers. We have to
3918     // insert this in a convoluted way. First we build vXi64 splat containing
3919     // the/ two values that we assemble using some bit math. Next we'll use
3920     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3921     // to merge element 0 from our splat into the source vector.
3922     // FIXME: This is probably not the best way to do this, but it is
3923     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3924     // point.
3925     //   sw lo, (a0)
3926     //   sw hi, 4(a0)
3927     //   vlse vX, (a0)
3928     //
3929     //   vid.v      vVid
3930     //   vmseq.vx   mMask, vVid, 0
3931     //   vmerge.vvm vDest, vSrc, vVal, mMask
3932     MVT VT = Op.getSimpleValueType();
3933     SDValue Vec = Op.getOperand(1);
3934     SDValue VL = Op.getOperand(3);
3935 
3936     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3937     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3938                                       DAG.getConstant(0, DL, MVT::i32), VL);
3939 
3940     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3941     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3942     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3943     SDValue SelectCond =
3944         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3945                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3946     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3947                        Vec, VL);
3948   }
3949   case Intrinsic::riscv_vslide1up:
3950   case Intrinsic::riscv_vslide1down:
3951   case Intrinsic::riscv_vslide1up_mask:
3952   case Intrinsic::riscv_vslide1down_mask: {
3953     // We need to special case these when the scalar is larger than XLen.
3954     unsigned NumOps = Op.getNumOperands();
3955     bool IsMasked = NumOps == 7;
3956     unsigned OpOffset = IsMasked ? 1 : 0;
3957     SDValue Scalar = Op.getOperand(2 + OpOffset);
3958     if (Scalar.getValueType().bitsLE(XLenVT))
3959       break;
3960 
3961     // Splatting a sign extended constant is fine.
3962     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3963       if (isInt<32>(CVal->getSExtValue()))
3964         break;
3965 
3966     MVT VT = Op.getSimpleValueType();
3967     assert(VT.getVectorElementType() == MVT::i64 &&
3968            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3969 
3970     // Convert the vector source to the equivalent nxvXi32 vector.
3971     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3972     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3973 
3974     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3975                                    DAG.getConstant(0, DL, XLenVT));
3976     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3977                                    DAG.getConstant(1, DL, XLenVT));
3978 
3979     // Double the VL since we halved SEW.
3980     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
3981     SDValue I32VL =
3982         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3983 
3984     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3985     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3986 
3987     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3988     // instructions.
3989     if (IntNo == Intrinsic::riscv_vslide1up ||
3990         IntNo == Intrinsic::riscv_vslide1up_mask) {
3991       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3992                         I32Mask, I32VL);
3993       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3994                         I32Mask, I32VL);
3995     } else {
3996       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3997                         I32Mask, I32VL);
3998       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3999                         I32Mask, I32VL);
4000     }
4001 
4002     // Convert back to nxvXi64.
4003     Vec = DAG.getBitcast(VT, Vec);
4004 
4005     if (!IsMasked)
4006       return Vec;
4007 
4008     // Apply mask after the operation.
4009     SDValue Mask = Op.getOperand(NumOps - 3);
4010     SDValue MaskedOff = Op.getOperand(1);
4011     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4012   }
4013   }
4014 
4015   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4016 }
4017 
4018 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4019                                                     SelectionDAG &DAG) const {
4020   unsigned IntNo = Op.getConstantOperandVal(1);
4021   switch (IntNo) {
4022   default:
4023     break;
4024   case Intrinsic::riscv_masked_strided_load: {
4025     SDLoc DL(Op);
4026     MVT XLenVT = Subtarget.getXLenVT();
4027 
4028     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4029     // the selection of the masked intrinsics doesn't do this for us.
4030     SDValue Mask = Op.getOperand(5);
4031     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4032 
4033     MVT VT = Op->getSimpleValueType(0);
4034     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4035 
4036     SDValue PassThru = Op.getOperand(2);
4037     if (!IsUnmasked) {
4038       MVT MaskVT =
4039           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4040       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4041       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4042     }
4043 
4044     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4045 
4046     SDValue IntID = DAG.getTargetConstant(
4047         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4048         XLenVT);
4049 
4050     auto *Load = cast<MemIntrinsicSDNode>(Op);
4051     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4052     if (!IsUnmasked)
4053       Ops.push_back(PassThru);
4054     Ops.push_back(Op.getOperand(3)); // Ptr
4055     Ops.push_back(Op.getOperand(4)); // Stride
4056     if (!IsUnmasked)
4057       Ops.push_back(Mask);
4058     Ops.push_back(VL);
4059     if (!IsUnmasked) {
4060       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4061       Ops.push_back(Policy);
4062     }
4063 
4064     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4065     SDValue Result =
4066         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4067                                 Load->getMemoryVT(), Load->getMemOperand());
4068     SDValue Chain = Result.getValue(1);
4069     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4070     return DAG.getMergeValues({Result, Chain}, DL);
4071   }
4072   }
4073 
4074   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4075 }
4076 
4077 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4078                                                  SelectionDAG &DAG) const {
4079   unsigned IntNo = Op.getConstantOperandVal(1);
4080   switch (IntNo) {
4081   default:
4082     break;
4083   case Intrinsic::riscv_masked_strided_store: {
4084     SDLoc DL(Op);
4085     MVT XLenVT = Subtarget.getXLenVT();
4086 
4087     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4088     // the selection of the masked intrinsics doesn't do this for us.
4089     SDValue Mask = Op.getOperand(5);
4090     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4091 
4092     SDValue Val = Op.getOperand(2);
4093     MVT VT = Val.getSimpleValueType();
4094     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4095 
4096     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4097     if (!IsUnmasked) {
4098       MVT MaskVT =
4099           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4100       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4101     }
4102 
4103     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4104 
4105     SDValue IntID = DAG.getTargetConstant(
4106         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4107         XLenVT);
4108 
4109     auto *Store = cast<MemIntrinsicSDNode>(Op);
4110     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4111     Ops.push_back(Val);
4112     Ops.push_back(Op.getOperand(3)); // Ptr
4113     Ops.push_back(Op.getOperand(4)); // Stride
4114     if (!IsUnmasked)
4115       Ops.push_back(Mask);
4116     Ops.push_back(VL);
4117 
4118     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4119                                    Ops, Store->getMemoryVT(),
4120                                    Store->getMemOperand());
4121   }
4122   }
4123 
4124   return SDValue();
4125 }
4126 
4127 static MVT getLMUL1VT(MVT VT) {
4128   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4129          "Unexpected vector MVT");
4130   return MVT::getScalableVectorVT(
4131       VT.getVectorElementType(),
4132       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4133 }
4134 
4135 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4136   switch (ISDOpcode) {
4137   default:
4138     llvm_unreachable("Unhandled reduction");
4139   case ISD::VECREDUCE_ADD:
4140     return RISCVISD::VECREDUCE_ADD_VL;
4141   case ISD::VECREDUCE_UMAX:
4142     return RISCVISD::VECREDUCE_UMAX_VL;
4143   case ISD::VECREDUCE_SMAX:
4144     return RISCVISD::VECREDUCE_SMAX_VL;
4145   case ISD::VECREDUCE_UMIN:
4146     return RISCVISD::VECREDUCE_UMIN_VL;
4147   case ISD::VECREDUCE_SMIN:
4148     return RISCVISD::VECREDUCE_SMIN_VL;
4149   case ISD::VECREDUCE_AND:
4150     return RISCVISD::VECREDUCE_AND_VL;
4151   case ISD::VECREDUCE_OR:
4152     return RISCVISD::VECREDUCE_OR_VL;
4153   case ISD::VECREDUCE_XOR:
4154     return RISCVISD::VECREDUCE_XOR_VL;
4155   }
4156 }
4157 
4158 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4159                                                          SelectionDAG &DAG,
4160                                                          bool IsVP) const {
4161   SDLoc DL(Op);
4162   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4163   MVT VecVT = Vec.getSimpleValueType();
4164   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4165           Op.getOpcode() == ISD::VECREDUCE_OR ||
4166           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4167           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4168           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4169           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4170          "Unexpected reduction lowering");
4171 
4172   MVT XLenVT = Subtarget.getXLenVT();
4173   assert(Op.getValueType() == XLenVT &&
4174          "Expected reduction output to be legalized to XLenVT");
4175 
4176   MVT ContainerVT = VecVT;
4177   if (VecVT.isFixedLengthVector()) {
4178     ContainerVT = getContainerForFixedLengthVector(VecVT);
4179     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4180   }
4181 
4182   SDValue Mask, VL;
4183   if (IsVP) {
4184     Mask = Op.getOperand(2);
4185     VL = Op.getOperand(3);
4186   } else {
4187     std::tie(Mask, VL) =
4188         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4189   }
4190 
4191   unsigned BaseOpc;
4192   ISD::CondCode CC;
4193   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4194 
4195   switch (Op.getOpcode()) {
4196   default:
4197     llvm_unreachable("Unhandled reduction");
4198   case ISD::VECREDUCE_AND:
4199   case ISD::VP_REDUCE_AND: {
4200     // vcpop ~x == 0
4201     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4202     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4203     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4204     CC = ISD::SETEQ;
4205     BaseOpc = ISD::AND;
4206     break;
4207   }
4208   case ISD::VECREDUCE_OR:
4209   case ISD::VP_REDUCE_OR:
4210     // vcpop x != 0
4211     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4212     CC = ISD::SETNE;
4213     BaseOpc = ISD::OR;
4214     break;
4215   case ISD::VECREDUCE_XOR:
4216   case ISD::VP_REDUCE_XOR: {
4217     // ((vcpop x) & 1) != 0
4218     SDValue One = DAG.getConstant(1, DL, XLenVT);
4219     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4220     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4221     CC = ISD::SETNE;
4222     BaseOpc = ISD::XOR;
4223     break;
4224   }
4225   }
4226 
4227   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4228 
4229   if (!IsVP)
4230     return SetCC;
4231 
4232   // Now include the start value in the operation.
4233   // Note that we must return the start value when no elements are operated
4234   // upon. The vcpop instructions we've emitted in each case above will return
4235   // 0 for an inactive vector, and so we've already received the neutral value:
4236   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4237   // can simply include the start value.
4238   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4239 }
4240 
4241 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4242                                             SelectionDAG &DAG) const {
4243   SDLoc DL(Op);
4244   SDValue Vec = Op.getOperand(0);
4245   EVT VecEVT = Vec.getValueType();
4246 
4247   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4248 
4249   // Due to ordering in legalize types we may have a vector type that needs to
4250   // be split. Do that manually so we can get down to a legal type.
4251   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4252          TargetLowering::TypeSplitVector) {
4253     SDValue Lo, Hi;
4254     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4255     VecEVT = Lo.getValueType();
4256     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4257   }
4258 
4259   // TODO: The type may need to be widened rather than split. Or widened before
4260   // it can be split.
4261   if (!isTypeLegal(VecEVT))
4262     return SDValue();
4263 
4264   MVT VecVT = VecEVT.getSimpleVT();
4265   MVT VecEltVT = VecVT.getVectorElementType();
4266   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4267 
4268   MVT ContainerVT = VecVT;
4269   if (VecVT.isFixedLengthVector()) {
4270     ContainerVT = getContainerForFixedLengthVector(VecVT);
4271     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4272   }
4273 
4274   MVT M1VT = getLMUL1VT(ContainerVT);
4275 
4276   SDValue Mask, VL;
4277   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4278 
4279   // FIXME: This is a VLMAX splat which might be too large and can prevent
4280   // vsetvli removal.
4281   SDValue NeutralElem =
4282       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4283   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4284   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4285                                   IdentitySplat, Mask, VL);
4286   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4287                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4288   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4289 }
4290 
4291 // Given a reduction op, this function returns the matching reduction opcode,
4292 // the vector SDValue and the scalar SDValue required to lower this to a
4293 // RISCVISD node.
4294 static std::tuple<unsigned, SDValue, SDValue>
4295 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4296   SDLoc DL(Op);
4297   auto Flags = Op->getFlags();
4298   unsigned Opcode = Op.getOpcode();
4299   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4300   switch (Opcode) {
4301   default:
4302     llvm_unreachable("Unhandled reduction");
4303   case ISD::VECREDUCE_FADD:
4304     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4305                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4306   case ISD::VECREDUCE_SEQ_FADD:
4307     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4308                            Op.getOperand(0));
4309   case ISD::VECREDUCE_FMIN:
4310     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4311                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4312   case ISD::VECREDUCE_FMAX:
4313     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4314                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4315   }
4316 }
4317 
4318 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4319                                               SelectionDAG &DAG) const {
4320   SDLoc DL(Op);
4321   MVT VecEltVT = Op.getSimpleValueType();
4322 
4323   unsigned RVVOpcode;
4324   SDValue VectorVal, ScalarVal;
4325   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4326       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4327   MVT VecVT = VectorVal.getSimpleValueType();
4328 
4329   MVT ContainerVT = VecVT;
4330   if (VecVT.isFixedLengthVector()) {
4331     ContainerVT = getContainerForFixedLengthVector(VecVT);
4332     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4333   }
4334 
4335   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4336 
4337   SDValue Mask, VL;
4338   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4339 
4340   // FIXME: This is a VLMAX splat which might be too large and can prevent
4341   // vsetvli removal.
4342   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4343   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4344                                   VectorVal, ScalarSplat, Mask, VL);
4345   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4346                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4347 }
4348 
4349 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4350   switch (ISDOpcode) {
4351   default:
4352     llvm_unreachable("Unhandled reduction");
4353   case ISD::VP_REDUCE_ADD:
4354     return RISCVISD::VECREDUCE_ADD_VL;
4355   case ISD::VP_REDUCE_UMAX:
4356     return RISCVISD::VECREDUCE_UMAX_VL;
4357   case ISD::VP_REDUCE_SMAX:
4358     return RISCVISD::VECREDUCE_SMAX_VL;
4359   case ISD::VP_REDUCE_UMIN:
4360     return RISCVISD::VECREDUCE_UMIN_VL;
4361   case ISD::VP_REDUCE_SMIN:
4362     return RISCVISD::VECREDUCE_SMIN_VL;
4363   case ISD::VP_REDUCE_AND:
4364     return RISCVISD::VECREDUCE_AND_VL;
4365   case ISD::VP_REDUCE_OR:
4366     return RISCVISD::VECREDUCE_OR_VL;
4367   case ISD::VP_REDUCE_XOR:
4368     return RISCVISD::VECREDUCE_XOR_VL;
4369   case ISD::VP_REDUCE_FADD:
4370     return RISCVISD::VECREDUCE_FADD_VL;
4371   case ISD::VP_REDUCE_SEQ_FADD:
4372     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4373   case ISD::VP_REDUCE_FMAX:
4374     return RISCVISD::VECREDUCE_FMAX_VL;
4375   case ISD::VP_REDUCE_FMIN:
4376     return RISCVISD::VECREDUCE_FMIN_VL;
4377   }
4378 }
4379 
4380 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4381                                            SelectionDAG &DAG) const {
4382   SDLoc DL(Op);
4383   SDValue Vec = Op.getOperand(1);
4384   EVT VecEVT = Vec.getValueType();
4385 
4386   // TODO: The type may need to be widened rather than split. Or widened before
4387   // it can be split.
4388   if (!isTypeLegal(VecEVT))
4389     return SDValue();
4390 
4391   MVT VecVT = VecEVT.getSimpleVT();
4392   MVT VecEltVT = VecVT.getVectorElementType();
4393   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4394 
4395   MVT ContainerVT = VecVT;
4396   if (VecVT.isFixedLengthVector()) {
4397     ContainerVT = getContainerForFixedLengthVector(VecVT);
4398     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4399   }
4400 
4401   SDValue VL = Op.getOperand(3);
4402   SDValue Mask = Op.getOperand(2);
4403 
4404   MVT M1VT = getLMUL1VT(ContainerVT);
4405   MVT XLenVT = Subtarget.getXLenVT();
4406   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4407 
4408   // FIXME: This is a VLMAX splat which might be too large and can prevent
4409   // vsetvli removal.
4410   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4411   SDValue Reduction =
4412       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4413   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4414                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4415   if (!VecVT.isInteger())
4416     return Elt0;
4417   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4418 }
4419 
4420 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4421                                                    SelectionDAG &DAG) const {
4422   SDValue Vec = Op.getOperand(0);
4423   SDValue SubVec = Op.getOperand(1);
4424   MVT VecVT = Vec.getSimpleValueType();
4425   MVT SubVecVT = SubVec.getSimpleValueType();
4426 
4427   SDLoc DL(Op);
4428   MVT XLenVT = Subtarget.getXLenVT();
4429   unsigned OrigIdx = Op.getConstantOperandVal(2);
4430   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4431 
4432   // We don't have the ability to slide mask vectors up indexed by their i1
4433   // elements; the smallest we can do is i8. Often we are able to bitcast to
4434   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4435   // into a scalable one, we might not necessarily have enough scalable
4436   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4437   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4438       (OrigIdx != 0 || !Vec.isUndef())) {
4439     if (VecVT.getVectorMinNumElements() >= 8 &&
4440         SubVecVT.getVectorMinNumElements() >= 8) {
4441       assert(OrigIdx % 8 == 0 && "Invalid index");
4442       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4443              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4444              "Unexpected mask vector lowering");
4445       OrigIdx /= 8;
4446       SubVecVT =
4447           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4448                            SubVecVT.isScalableVector());
4449       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4450                                VecVT.isScalableVector());
4451       Vec = DAG.getBitcast(VecVT, Vec);
4452       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4453     } else {
4454       // We can't slide this mask vector up indexed by its i1 elements.
4455       // This poses a problem when we wish to insert a scalable vector which
4456       // can't be re-expressed as a larger type. Just choose the slow path and
4457       // extend to a larger type, then truncate back down.
4458       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4459       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4460       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4461       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4462       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4463                         Op.getOperand(2));
4464       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4465       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4466     }
4467   }
4468 
4469   // If the subvector vector is a fixed-length type, we cannot use subregister
4470   // manipulation to simplify the codegen; we don't know which register of a
4471   // LMUL group contains the specific subvector as we only know the minimum
4472   // register size. Therefore we must slide the vector group up the full
4473   // amount.
4474   if (SubVecVT.isFixedLengthVector()) {
4475     if (OrigIdx == 0 && Vec.isUndef())
4476       return Op;
4477     MVT ContainerVT = VecVT;
4478     if (VecVT.isFixedLengthVector()) {
4479       ContainerVT = getContainerForFixedLengthVector(VecVT);
4480       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4481     }
4482     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4483                          DAG.getUNDEF(ContainerVT), SubVec,
4484                          DAG.getConstant(0, DL, XLenVT));
4485     SDValue Mask =
4486         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4487     // Set the vector length to only the number of elements we care about. Note
4488     // that for slideup this includes the offset.
4489     SDValue VL =
4490         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4491     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4492     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4493                                   SubVec, SlideupAmt, Mask, VL);
4494     if (VecVT.isFixedLengthVector())
4495       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4496     return DAG.getBitcast(Op.getValueType(), Slideup);
4497   }
4498 
4499   unsigned SubRegIdx, RemIdx;
4500   std::tie(SubRegIdx, RemIdx) =
4501       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4502           VecVT, SubVecVT, OrigIdx, TRI);
4503 
4504   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4505   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4506                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4507                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4508 
4509   // 1. If the Idx has been completely eliminated and this subvector's size is
4510   // a vector register or a multiple thereof, or the surrounding elements are
4511   // undef, then this is a subvector insert which naturally aligns to a vector
4512   // register. These can easily be handled using subregister manipulation.
4513   // 2. If the subvector is smaller than a vector register, then the insertion
4514   // must preserve the undisturbed elements of the register. We do this by
4515   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4516   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4517   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4518   // LMUL=1 type back into the larger vector (resolving to another subregister
4519   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4520   // to avoid allocating a large register group to hold our subvector.
4521   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4522     return Op;
4523 
4524   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4525   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4526   // (in our case undisturbed). This means we can set up a subvector insertion
4527   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4528   // size of the subvector.
4529   MVT InterSubVT = VecVT;
4530   SDValue AlignedExtract = Vec;
4531   unsigned AlignedIdx = OrigIdx - RemIdx;
4532   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4533     InterSubVT = getLMUL1VT(VecVT);
4534     // Extract a subvector equal to the nearest full vector register type. This
4535     // should resolve to a EXTRACT_SUBREG instruction.
4536     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4537                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4538   }
4539 
4540   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4541   // For scalable vectors this must be further multiplied by vscale.
4542   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4543 
4544   SDValue Mask, VL;
4545   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4546 
4547   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4548   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4549   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4550   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4551 
4552   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4553                        DAG.getUNDEF(InterSubVT), SubVec,
4554                        DAG.getConstant(0, DL, XLenVT));
4555 
4556   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4557                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4558 
4559   // If required, insert this subvector back into the correct vector register.
4560   // This should resolve to an INSERT_SUBREG instruction.
4561   if (VecVT.bitsGT(InterSubVT))
4562     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4563                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4564 
4565   // We might have bitcast from a mask type: cast back to the original type if
4566   // required.
4567   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4568 }
4569 
4570 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4571                                                     SelectionDAG &DAG) const {
4572   SDValue Vec = Op.getOperand(0);
4573   MVT SubVecVT = Op.getSimpleValueType();
4574   MVT VecVT = Vec.getSimpleValueType();
4575 
4576   SDLoc DL(Op);
4577   MVT XLenVT = Subtarget.getXLenVT();
4578   unsigned OrigIdx = Op.getConstantOperandVal(1);
4579   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4580 
4581   // We don't have the ability to slide mask vectors down indexed by their i1
4582   // elements; the smallest we can do is i8. Often we are able to bitcast to
4583   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4584   // from a scalable one, we might not necessarily have enough scalable
4585   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4586   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4587     if (VecVT.getVectorMinNumElements() >= 8 &&
4588         SubVecVT.getVectorMinNumElements() >= 8) {
4589       assert(OrigIdx % 8 == 0 && "Invalid index");
4590       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4591              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4592              "Unexpected mask vector lowering");
4593       OrigIdx /= 8;
4594       SubVecVT =
4595           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4596                            SubVecVT.isScalableVector());
4597       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4598                                VecVT.isScalableVector());
4599       Vec = DAG.getBitcast(VecVT, Vec);
4600     } else {
4601       // We can't slide this mask vector down, indexed by its i1 elements.
4602       // This poses a problem when we wish to extract a scalable vector which
4603       // can't be re-expressed as a larger type. Just choose the slow path and
4604       // extend to a larger type, then truncate back down.
4605       // TODO: We could probably improve this when extracting certain fixed
4606       // from fixed, where we can extract as i8 and shift the correct element
4607       // right to reach the desired subvector?
4608       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4609       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4610       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4611       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4612                         Op.getOperand(1));
4613       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4614       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4615     }
4616   }
4617 
4618   // If the subvector vector is a fixed-length type, we cannot use subregister
4619   // manipulation to simplify the codegen; we don't know which register of a
4620   // LMUL group contains the specific subvector as we only know the minimum
4621   // register size. Therefore we must slide the vector group down the full
4622   // amount.
4623   if (SubVecVT.isFixedLengthVector()) {
4624     // With an index of 0 this is a cast-like subvector, which can be performed
4625     // with subregister operations.
4626     if (OrigIdx == 0)
4627       return Op;
4628     MVT ContainerVT = VecVT;
4629     if (VecVT.isFixedLengthVector()) {
4630       ContainerVT = getContainerForFixedLengthVector(VecVT);
4631       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4632     }
4633     SDValue Mask =
4634         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4635     // Set the vector length to only the number of elements we care about. This
4636     // avoids sliding down elements we're going to discard straight away.
4637     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4638     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4639     SDValue Slidedown =
4640         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4641                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4642     // Now we can use a cast-like subvector extract to get the result.
4643     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4644                             DAG.getConstant(0, DL, XLenVT));
4645     return DAG.getBitcast(Op.getValueType(), Slidedown);
4646   }
4647 
4648   unsigned SubRegIdx, RemIdx;
4649   std::tie(SubRegIdx, RemIdx) =
4650       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4651           VecVT, SubVecVT, OrigIdx, TRI);
4652 
4653   // If the Idx has been completely eliminated then this is a subvector extract
4654   // which naturally aligns to a vector register. These can easily be handled
4655   // using subregister manipulation.
4656   if (RemIdx == 0)
4657     return Op;
4658 
4659   // Else we must shift our vector register directly to extract the subvector.
4660   // Do this using VSLIDEDOWN.
4661 
4662   // If the vector type is an LMUL-group type, extract a subvector equal to the
4663   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4664   // instruction.
4665   MVT InterSubVT = VecVT;
4666   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4667     InterSubVT = getLMUL1VT(VecVT);
4668     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4669                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4670   }
4671 
4672   // Slide this vector register down by the desired number of elements in order
4673   // to place the desired subvector starting at element 0.
4674   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4675   // For scalable vectors this must be further multiplied by vscale.
4676   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4677 
4678   SDValue Mask, VL;
4679   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4680   SDValue Slidedown =
4681       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4682                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4683 
4684   // Now the vector is in the right position, extract our final subvector. This
4685   // should resolve to a COPY.
4686   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4687                           DAG.getConstant(0, DL, XLenVT));
4688 
4689   // We might have bitcast from a mask type: cast back to the original type if
4690   // required.
4691   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4692 }
4693 
4694 // Lower step_vector to the vid instruction. Any non-identity step value must
4695 // be accounted for my manual expansion.
4696 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4697                                               SelectionDAG &DAG) const {
4698   SDLoc DL(Op);
4699   MVT VT = Op.getSimpleValueType();
4700   MVT XLenVT = Subtarget.getXLenVT();
4701   SDValue Mask, VL;
4702   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4703   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4704   uint64_t StepValImm = Op.getConstantOperandVal(0);
4705   if (StepValImm != 1) {
4706     if (isPowerOf2_64(StepValImm)) {
4707       SDValue StepVal =
4708           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4709                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4710       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4711     } else {
4712       SDValue StepVal = lowerScalarSplat(
4713           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4714           DL, DAG, Subtarget);
4715       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4716     }
4717   }
4718   return StepVec;
4719 }
4720 
4721 // Implement vector_reverse using vrgather.vv with indices determined by
4722 // subtracting the id of each element from (VLMAX-1). This will convert
4723 // the indices like so:
4724 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4725 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4726 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4727                                                  SelectionDAG &DAG) const {
4728   SDLoc DL(Op);
4729   MVT VecVT = Op.getSimpleValueType();
4730   unsigned EltSize = VecVT.getScalarSizeInBits();
4731   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4732 
4733   unsigned MaxVLMAX = 0;
4734   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4735   if (VectorBitsMax != 0)
4736     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4737 
4738   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4739   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4740 
4741   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4742   // to use vrgatherei16.vv.
4743   // TODO: It's also possible to use vrgatherei16.vv for other types to
4744   // decrease register width for the index calculation.
4745   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4746     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4747     // Reverse each half, then reassemble them in reverse order.
4748     // NOTE: It's also possible that after splitting that VLMAX no longer
4749     // requires vrgatherei16.vv.
4750     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4751       SDValue Lo, Hi;
4752       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4753       EVT LoVT, HiVT;
4754       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4755       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4756       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4757       // Reassemble the low and high pieces reversed.
4758       // FIXME: This is a CONCAT_VECTORS.
4759       SDValue Res =
4760           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4761                       DAG.getIntPtrConstant(0, DL));
4762       return DAG.getNode(
4763           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4764           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4765     }
4766 
4767     // Just promote the int type to i16 which will double the LMUL.
4768     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4769     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4770   }
4771 
4772   MVT XLenVT = Subtarget.getXLenVT();
4773   SDValue Mask, VL;
4774   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4775 
4776   // Calculate VLMAX-1 for the desired SEW.
4777   unsigned MinElts = VecVT.getVectorMinNumElements();
4778   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4779                               DAG.getConstant(MinElts, DL, XLenVT));
4780   SDValue VLMinus1 =
4781       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4782 
4783   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4784   bool IsRV32E64 =
4785       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4786   SDValue SplatVL;
4787   if (!IsRV32E64)
4788     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4789   else
4790     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4791 
4792   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4793   SDValue Indices =
4794       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4795 
4796   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4797 }
4798 
4799 SDValue
4800 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4801                                                      SelectionDAG &DAG) const {
4802   SDLoc DL(Op);
4803   auto *Load = cast<LoadSDNode>(Op);
4804 
4805   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4806                                         Load->getMemoryVT(),
4807                                         *Load->getMemOperand()) &&
4808          "Expecting a correctly-aligned load");
4809 
4810   MVT VT = Op.getSimpleValueType();
4811   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4812 
4813   SDValue VL =
4814       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4815 
4816   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4817   SDValue NewLoad = DAG.getMemIntrinsicNode(
4818       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4819       Load->getMemoryVT(), Load->getMemOperand());
4820 
4821   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4822   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4823 }
4824 
4825 SDValue
4826 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4827                                                       SelectionDAG &DAG) const {
4828   SDLoc DL(Op);
4829   auto *Store = cast<StoreSDNode>(Op);
4830 
4831   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4832                                         Store->getMemoryVT(),
4833                                         *Store->getMemOperand()) &&
4834          "Expecting a correctly-aligned store");
4835 
4836   SDValue StoreVal = Store->getValue();
4837   MVT VT = StoreVal.getSimpleValueType();
4838 
4839   // If the size less than a byte, we need to pad with zeros to make a byte.
4840   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4841     VT = MVT::v8i1;
4842     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4843                            DAG.getConstant(0, DL, VT), StoreVal,
4844                            DAG.getIntPtrConstant(0, DL));
4845   }
4846 
4847   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4848 
4849   SDValue VL =
4850       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4851 
4852   SDValue NewValue =
4853       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4854   return DAG.getMemIntrinsicNode(
4855       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4856       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4857       Store->getMemoryVT(), Store->getMemOperand());
4858 }
4859 
4860 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4861                                              SelectionDAG &DAG) const {
4862   SDLoc DL(Op);
4863   MVT VT = Op.getSimpleValueType();
4864 
4865   const auto *MemSD = cast<MemSDNode>(Op);
4866   EVT MemVT = MemSD->getMemoryVT();
4867   MachineMemOperand *MMO = MemSD->getMemOperand();
4868   SDValue Chain = MemSD->getChain();
4869   SDValue BasePtr = MemSD->getBasePtr();
4870 
4871   SDValue Mask, PassThru, VL;
4872   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4873     Mask = VPLoad->getMask();
4874     PassThru = DAG.getUNDEF(VT);
4875     VL = VPLoad->getVectorLength();
4876   } else {
4877     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4878     Mask = MLoad->getMask();
4879     PassThru = MLoad->getPassThru();
4880   }
4881 
4882   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4883 
4884   MVT XLenVT = Subtarget.getXLenVT();
4885 
4886   MVT ContainerVT = VT;
4887   if (VT.isFixedLengthVector()) {
4888     ContainerVT = getContainerForFixedLengthVector(VT);
4889     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4890     if (!IsUnmasked) {
4891       MVT MaskVT =
4892           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4893       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4894     }
4895   }
4896 
4897   if (!VL)
4898     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4899 
4900   unsigned IntID =
4901       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
4902   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4903   if (!IsUnmasked)
4904     Ops.push_back(PassThru);
4905   Ops.push_back(BasePtr);
4906   if (!IsUnmasked)
4907     Ops.push_back(Mask);
4908   Ops.push_back(VL);
4909   if (!IsUnmasked)
4910     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
4911 
4912   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4913 
4914   SDValue Result =
4915       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4916   Chain = Result.getValue(1);
4917 
4918   if (VT.isFixedLengthVector())
4919     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4920 
4921   return DAG.getMergeValues({Result, Chain}, DL);
4922 }
4923 
4924 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4925                                               SelectionDAG &DAG) const {
4926   SDLoc DL(Op);
4927 
4928   const auto *MemSD = cast<MemSDNode>(Op);
4929   EVT MemVT = MemSD->getMemoryVT();
4930   MachineMemOperand *MMO = MemSD->getMemOperand();
4931   SDValue Chain = MemSD->getChain();
4932   SDValue BasePtr = MemSD->getBasePtr();
4933   SDValue Val, Mask, VL;
4934 
4935   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4936     Val = VPStore->getValue();
4937     Mask = VPStore->getMask();
4938     VL = VPStore->getVectorLength();
4939   } else {
4940     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4941     Val = MStore->getValue();
4942     Mask = MStore->getMask();
4943   }
4944 
4945   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4946 
4947   MVT VT = Val.getSimpleValueType();
4948   MVT XLenVT = Subtarget.getXLenVT();
4949 
4950   MVT ContainerVT = VT;
4951   if (VT.isFixedLengthVector()) {
4952     ContainerVT = getContainerForFixedLengthVector(VT);
4953 
4954     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4955     if (!IsUnmasked) {
4956       MVT MaskVT =
4957           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4958       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4959     }
4960   }
4961 
4962   if (!VL)
4963     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4964 
4965   unsigned IntID =
4966       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4967   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4968   Ops.push_back(Val);
4969   Ops.push_back(BasePtr);
4970   if (!IsUnmasked)
4971     Ops.push_back(Mask);
4972   Ops.push_back(VL);
4973 
4974   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4975                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4976 }
4977 
4978 SDValue
4979 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4980                                                       SelectionDAG &DAG) const {
4981   MVT InVT = Op.getOperand(0).getSimpleValueType();
4982   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4983 
4984   MVT VT = Op.getSimpleValueType();
4985 
4986   SDValue Op1 =
4987       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4988   SDValue Op2 =
4989       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4990 
4991   SDLoc DL(Op);
4992   SDValue VL =
4993       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4994 
4995   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4996   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4997 
4998   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4999                             Op.getOperand(2), Mask, VL);
5000 
5001   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5002 }
5003 
5004 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5005     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5006   MVT VT = Op.getSimpleValueType();
5007 
5008   if (VT.getVectorElementType() == MVT::i1)
5009     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5010 
5011   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5012 }
5013 
5014 SDValue
5015 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5016                                                       SelectionDAG &DAG) const {
5017   unsigned Opc;
5018   switch (Op.getOpcode()) {
5019   default: llvm_unreachable("Unexpected opcode!");
5020   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5021   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5022   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5023   }
5024 
5025   return lowerToScalableOp(Op, DAG, Opc);
5026 }
5027 
5028 // Lower vector ABS to smax(X, sub(0, X)).
5029 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5030   SDLoc DL(Op);
5031   MVT VT = Op.getSimpleValueType();
5032   SDValue X = Op.getOperand(0);
5033 
5034   assert(VT.isFixedLengthVector() && "Unexpected type");
5035 
5036   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5037   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5038 
5039   SDValue Mask, VL;
5040   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5041 
5042   SDValue SplatZero =
5043       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5044                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5045   SDValue NegX =
5046       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5047   SDValue Max =
5048       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5049 
5050   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5051 }
5052 
5053 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5054     SDValue Op, SelectionDAG &DAG) const {
5055   SDLoc DL(Op);
5056   MVT VT = Op.getSimpleValueType();
5057   SDValue Mag = Op.getOperand(0);
5058   SDValue Sign = Op.getOperand(1);
5059   assert(Mag.getValueType() == Sign.getValueType() &&
5060          "Can only handle COPYSIGN with matching types.");
5061 
5062   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5063   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5064   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5065 
5066   SDValue Mask, VL;
5067   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5068 
5069   SDValue CopySign =
5070       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5071 
5072   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5073 }
5074 
5075 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5076     SDValue Op, SelectionDAG &DAG) const {
5077   MVT VT = Op.getSimpleValueType();
5078   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5079 
5080   MVT I1ContainerVT =
5081       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5082 
5083   SDValue CC =
5084       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5085   SDValue Op1 =
5086       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5087   SDValue Op2 =
5088       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5089 
5090   SDLoc DL(Op);
5091   SDValue Mask, VL;
5092   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5093 
5094   SDValue Select =
5095       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5096 
5097   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5098 }
5099 
5100 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5101                                                unsigned NewOpc,
5102                                                bool HasMask) const {
5103   MVT VT = Op.getSimpleValueType();
5104   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5105 
5106   // Create list of operands by converting existing ones to scalable types.
5107   SmallVector<SDValue, 6> Ops;
5108   for (const SDValue &V : Op->op_values()) {
5109     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5110 
5111     // Pass through non-vector operands.
5112     if (!V.getValueType().isVector()) {
5113       Ops.push_back(V);
5114       continue;
5115     }
5116 
5117     // "cast" fixed length vector to a scalable vector.
5118     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5119            "Only fixed length vectors are supported!");
5120     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5121   }
5122 
5123   SDLoc DL(Op);
5124   SDValue Mask, VL;
5125   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5126   if (HasMask)
5127     Ops.push_back(Mask);
5128   Ops.push_back(VL);
5129 
5130   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5131   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5132 }
5133 
5134 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5135 // * Operands of each node are assumed to be in the same order.
5136 // * The EVL operand is promoted from i32 to i64 on RV64.
5137 // * Fixed-length vectors are converted to their scalable-vector container
5138 //   types.
5139 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5140                                        unsigned RISCVISDOpc) const {
5141   SDLoc DL(Op);
5142   MVT VT = Op.getSimpleValueType();
5143   SmallVector<SDValue, 4> Ops;
5144 
5145   for (const auto &OpIdx : enumerate(Op->ops())) {
5146     SDValue V = OpIdx.value();
5147     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5148     // Pass through operands which aren't fixed-length vectors.
5149     if (!V.getValueType().isFixedLengthVector()) {
5150       Ops.push_back(V);
5151       continue;
5152     }
5153     // "cast" fixed length vector to a scalable vector.
5154     MVT OpVT = V.getSimpleValueType();
5155     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5156     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5157            "Only fixed length vectors are supported!");
5158     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5159   }
5160 
5161   if (!VT.isFixedLengthVector())
5162     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5163 
5164   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5165 
5166   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5167 
5168   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5169 }
5170 
5171 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5172 // matched to a RVV indexed load. The RVV indexed load instructions only
5173 // support the "unsigned unscaled" addressing mode; indices are implicitly
5174 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5175 // signed or scaled indexing is extended to the XLEN value type and scaled
5176 // accordingly.
5177 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5178                                                SelectionDAG &DAG) const {
5179   SDLoc DL(Op);
5180   MVT VT = Op.getSimpleValueType();
5181 
5182   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5183   EVT MemVT = MemSD->getMemoryVT();
5184   MachineMemOperand *MMO = MemSD->getMemOperand();
5185   SDValue Chain = MemSD->getChain();
5186   SDValue BasePtr = MemSD->getBasePtr();
5187 
5188   ISD::LoadExtType LoadExtType;
5189   SDValue Index, Mask, PassThru, VL;
5190 
5191   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5192     Index = VPGN->getIndex();
5193     Mask = VPGN->getMask();
5194     PassThru = DAG.getUNDEF(VT);
5195     VL = VPGN->getVectorLength();
5196     // VP doesn't support extending loads.
5197     LoadExtType = ISD::NON_EXTLOAD;
5198   } else {
5199     // Else it must be a MGATHER.
5200     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5201     Index = MGN->getIndex();
5202     Mask = MGN->getMask();
5203     PassThru = MGN->getPassThru();
5204     LoadExtType = MGN->getExtensionType();
5205   }
5206 
5207   MVT IndexVT = Index.getSimpleValueType();
5208   MVT XLenVT = Subtarget.getXLenVT();
5209 
5210   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5211          "Unexpected VTs!");
5212   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5213   // Targets have to explicitly opt-in for extending vector loads.
5214   assert(LoadExtType == ISD::NON_EXTLOAD &&
5215          "Unexpected extending MGATHER/VP_GATHER");
5216   (void)LoadExtType;
5217 
5218   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5219   // the selection of the masked intrinsics doesn't do this for us.
5220   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5221 
5222   MVT ContainerVT = VT;
5223   if (VT.isFixedLengthVector()) {
5224     // We need to use the larger of the result and index type to determine the
5225     // scalable type to use so we don't increase LMUL for any operand/result.
5226     if (VT.bitsGE(IndexVT)) {
5227       ContainerVT = getContainerForFixedLengthVector(VT);
5228       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5229                                  ContainerVT.getVectorElementCount());
5230     } else {
5231       IndexVT = getContainerForFixedLengthVector(IndexVT);
5232       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5233                                      IndexVT.getVectorElementCount());
5234     }
5235 
5236     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5237 
5238     if (!IsUnmasked) {
5239       MVT MaskVT =
5240           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5241       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5242       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5243     }
5244   }
5245 
5246   if (!VL)
5247     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5248 
5249   unsigned IntID =
5250       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5251   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5252   if (!IsUnmasked)
5253     Ops.push_back(PassThru);
5254   Ops.push_back(BasePtr);
5255   Ops.push_back(Index);
5256   if (!IsUnmasked)
5257     Ops.push_back(Mask);
5258   Ops.push_back(VL);
5259   if (!IsUnmasked)
5260     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5261 
5262   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5263   SDValue Result =
5264       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5265   Chain = Result.getValue(1);
5266 
5267   if (VT.isFixedLengthVector())
5268     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5269 
5270   return DAG.getMergeValues({Result, Chain}, DL);
5271 }
5272 
5273 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5274 // matched to a RVV indexed store. The RVV indexed store instructions only
5275 // support the "unsigned unscaled" addressing mode; indices are implicitly
5276 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5277 // signed or scaled indexing is extended to the XLEN value type and scaled
5278 // accordingly.
5279 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5280                                                 SelectionDAG &DAG) const {
5281   SDLoc DL(Op);
5282   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5283   EVT MemVT = MemSD->getMemoryVT();
5284   MachineMemOperand *MMO = MemSD->getMemOperand();
5285   SDValue Chain = MemSD->getChain();
5286   SDValue BasePtr = MemSD->getBasePtr();
5287 
5288   bool IsTruncatingStore = false;
5289   SDValue Index, Mask, Val, VL;
5290 
5291   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5292     Index = VPSN->getIndex();
5293     Mask = VPSN->getMask();
5294     Val = VPSN->getValue();
5295     VL = VPSN->getVectorLength();
5296     // VP doesn't support truncating stores.
5297     IsTruncatingStore = false;
5298   } else {
5299     // Else it must be a MSCATTER.
5300     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5301     Index = MSN->getIndex();
5302     Mask = MSN->getMask();
5303     Val = MSN->getValue();
5304     IsTruncatingStore = MSN->isTruncatingStore();
5305   }
5306 
5307   MVT VT = Val.getSimpleValueType();
5308   MVT IndexVT = Index.getSimpleValueType();
5309   MVT XLenVT = Subtarget.getXLenVT();
5310 
5311   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5312          "Unexpected VTs!");
5313   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5314   // Targets have to explicitly opt-in for extending vector loads and
5315   // truncating vector stores.
5316   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5317   (void)IsTruncatingStore;
5318 
5319   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5320   // the selection of the masked intrinsics doesn't do this for us.
5321   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5322 
5323   MVT ContainerVT = VT;
5324   if (VT.isFixedLengthVector()) {
5325     // We need to use the larger of the value and index type to determine the
5326     // scalable type to use so we don't increase LMUL for any operand/result.
5327     if (VT.bitsGE(IndexVT)) {
5328       ContainerVT = getContainerForFixedLengthVector(VT);
5329       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5330                                  ContainerVT.getVectorElementCount());
5331     } else {
5332       IndexVT = getContainerForFixedLengthVector(IndexVT);
5333       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5334                                      IndexVT.getVectorElementCount());
5335     }
5336 
5337     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5338     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5339 
5340     if (!IsUnmasked) {
5341       MVT MaskVT =
5342           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5343       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5344     }
5345   }
5346 
5347   if (!VL)
5348     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5349 
5350   unsigned IntID =
5351       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5352   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5353   Ops.push_back(Val);
5354   Ops.push_back(BasePtr);
5355   Ops.push_back(Index);
5356   if (!IsUnmasked)
5357     Ops.push_back(Mask);
5358   Ops.push_back(VL);
5359 
5360   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5361                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5362 }
5363 
5364 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5365                                                SelectionDAG &DAG) const {
5366   const MVT XLenVT = Subtarget.getXLenVT();
5367   SDLoc DL(Op);
5368   SDValue Chain = Op->getOperand(0);
5369   SDValue SysRegNo = DAG.getTargetConstant(
5370       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5371   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5372   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5373 
5374   // Encoding used for rounding mode in RISCV differs from that used in
5375   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5376   // table, which consists of a sequence of 4-bit fields, each representing
5377   // corresponding FLT_ROUNDS mode.
5378   static const int Table =
5379       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5380       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5381       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5382       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5383       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5384 
5385   SDValue Shift =
5386       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5387   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5388                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5389   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5390                                DAG.getConstant(7, DL, XLenVT));
5391 
5392   return DAG.getMergeValues({Masked, Chain}, DL);
5393 }
5394 
5395 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5396                                                SelectionDAG &DAG) const {
5397   const MVT XLenVT = Subtarget.getXLenVT();
5398   SDLoc DL(Op);
5399   SDValue Chain = Op->getOperand(0);
5400   SDValue RMValue = Op->getOperand(1);
5401   SDValue SysRegNo = DAG.getTargetConstant(
5402       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5403 
5404   // Encoding used for rounding mode in RISCV differs from that used in
5405   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5406   // a table, which consists of a sequence of 4-bit fields, each representing
5407   // corresponding RISCV mode.
5408   static const unsigned Table =
5409       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5410       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5411       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5412       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5413       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5414 
5415   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5416                               DAG.getConstant(2, DL, XLenVT));
5417   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5418                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5419   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5420                         DAG.getConstant(0x7, DL, XLenVT));
5421   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5422                      RMValue);
5423 }
5424 
5425 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5426 // form of the given Opcode.
5427 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5428   switch (Opcode) {
5429   default:
5430     llvm_unreachable("Unexpected opcode");
5431   case ISD::SHL:
5432     return RISCVISD::SLLW;
5433   case ISD::SRA:
5434     return RISCVISD::SRAW;
5435   case ISD::SRL:
5436     return RISCVISD::SRLW;
5437   case ISD::SDIV:
5438     return RISCVISD::DIVW;
5439   case ISD::UDIV:
5440     return RISCVISD::DIVUW;
5441   case ISD::UREM:
5442     return RISCVISD::REMUW;
5443   case ISD::ROTL:
5444     return RISCVISD::ROLW;
5445   case ISD::ROTR:
5446     return RISCVISD::RORW;
5447   case RISCVISD::GREV:
5448     return RISCVISD::GREVW;
5449   case RISCVISD::GORC:
5450     return RISCVISD::GORCW;
5451   }
5452 }
5453 
5454 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5455 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5456 // otherwise be promoted to i64, making it difficult to select the
5457 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5458 // type i8/i16/i32 is lost.
5459 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5460                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5461   SDLoc DL(N);
5462   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5463   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5464   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5465   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5466   // ReplaceNodeResults requires we maintain the same type for the return value.
5467   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5468 }
5469 
5470 // Converts the given 32-bit operation to a i64 operation with signed extension
5471 // semantic to reduce the signed extension instructions.
5472 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5473   SDLoc DL(N);
5474   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5475   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5476   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5477   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5478                                DAG.getValueType(MVT::i32));
5479   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5480 }
5481 
5482 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5483                                              SmallVectorImpl<SDValue> &Results,
5484                                              SelectionDAG &DAG) const {
5485   SDLoc DL(N);
5486   switch (N->getOpcode()) {
5487   default:
5488     llvm_unreachable("Don't know how to custom type legalize this operation!");
5489   case ISD::STRICT_FP_TO_SINT:
5490   case ISD::STRICT_FP_TO_UINT:
5491   case ISD::FP_TO_SINT:
5492   case ISD::FP_TO_UINT: {
5493     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5494            "Unexpected custom legalisation");
5495     bool IsStrict = N->isStrictFPOpcode();
5496     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5497                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5498     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5499     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5500         TargetLowering::TypeSoftenFloat) {
5501       // FIXME: Support strict FP.
5502       if (IsStrict)
5503         return;
5504       if (!isTypeLegal(Op0.getValueType()))
5505         return;
5506       unsigned Opc =
5507           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5508       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5509       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5510       return;
5511     }
5512     // If the FP type needs to be softened, emit a library call using the 'si'
5513     // version. If we left it to default legalization we'd end up with 'di'. If
5514     // the FP type doesn't need to be softened just let generic type
5515     // legalization promote the result type.
5516     RTLIB::Libcall LC;
5517     if (IsSigned)
5518       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5519     else
5520       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5521     MakeLibCallOptions CallOptions;
5522     EVT OpVT = Op0.getValueType();
5523     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5524     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5525     SDValue Result;
5526     std::tie(Result, Chain) =
5527         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5528     Results.push_back(Result);
5529     if (IsStrict)
5530       Results.push_back(Chain);
5531     break;
5532   }
5533   case ISD::READCYCLECOUNTER: {
5534     assert(!Subtarget.is64Bit() &&
5535            "READCYCLECOUNTER only has custom type legalization on riscv32");
5536 
5537     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5538     SDValue RCW =
5539         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5540 
5541     Results.push_back(
5542         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5543     Results.push_back(RCW.getValue(2));
5544     break;
5545   }
5546   case ISD::MUL: {
5547     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5548     unsigned XLen = Subtarget.getXLen();
5549     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5550     if (Size > XLen) {
5551       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5552       SDValue LHS = N->getOperand(0);
5553       SDValue RHS = N->getOperand(1);
5554       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5555 
5556       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5557       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5558       // We need exactly one side to be unsigned.
5559       if (LHSIsU == RHSIsU)
5560         return;
5561 
5562       auto MakeMULPair = [&](SDValue S, SDValue U) {
5563         MVT XLenVT = Subtarget.getXLenVT();
5564         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5565         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5566         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5567         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5568         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5569       };
5570 
5571       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5572       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5573 
5574       // The other operand should be signed, but still prefer MULH when
5575       // possible.
5576       if (RHSIsU && LHSIsS && !RHSIsS)
5577         Results.push_back(MakeMULPair(LHS, RHS));
5578       else if (LHSIsU && RHSIsS && !LHSIsS)
5579         Results.push_back(MakeMULPair(RHS, LHS));
5580 
5581       return;
5582     }
5583     LLVM_FALLTHROUGH;
5584   }
5585   case ISD::ADD:
5586   case ISD::SUB:
5587     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5588            "Unexpected custom legalisation");
5589     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5590     break;
5591   case ISD::SHL:
5592   case ISD::SRA:
5593   case ISD::SRL:
5594     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5595            "Unexpected custom legalisation");
5596     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5597       Results.push_back(customLegalizeToWOp(N, DAG));
5598       break;
5599     }
5600 
5601     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5602     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5603     // shift amount.
5604     if (N->getOpcode() == ISD::SHL) {
5605       SDLoc DL(N);
5606       SDValue NewOp0 =
5607           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5608       SDValue NewOp1 =
5609           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5610       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5611       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5612                                    DAG.getValueType(MVT::i32));
5613       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5614     }
5615 
5616     break;
5617   case ISD::ROTL:
5618   case ISD::ROTR:
5619     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5620            "Unexpected custom legalisation");
5621     Results.push_back(customLegalizeToWOp(N, DAG));
5622     break;
5623   case ISD::CTTZ:
5624   case ISD::CTTZ_ZERO_UNDEF:
5625   case ISD::CTLZ:
5626   case ISD::CTLZ_ZERO_UNDEF: {
5627     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5628            "Unexpected custom legalisation");
5629 
5630     SDValue NewOp0 =
5631         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5632     bool IsCTZ =
5633         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5634     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5635     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5636     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5637     return;
5638   }
5639   case ISD::SDIV:
5640   case ISD::UDIV:
5641   case ISD::UREM: {
5642     MVT VT = N->getSimpleValueType(0);
5643     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5644            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5645            "Unexpected custom legalisation");
5646     // Don't promote division/remainder by constant since we should expand those
5647     // to multiply by magic constant.
5648     // FIXME: What if the expansion is disabled for minsize.
5649     if (N->getOperand(1).getOpcode() == ISD::Constant)
5650       return;
5651 
5652     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5653     // the upper 32 bits. For other types we need to sign or zero extend
5654     // based on the opcode.
5655     unsigned ExtOpc = ISD::ANY_EXTEND;
5656     if (VT != MVT::i32)
5657       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5658                                            : ISD::ZERO_EXTEND;
5659 
5660     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5661     break;
5662   }
5663   case ISD::UADDO:
5664   case ISD::USUBO: {
5665     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5666            "Unexpected custom legalisation");
5667     bool IsAdd = N->getOpcode() == ISD::UADDO;
5668     // Create an ADDW or SUBW.
5669     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5670     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5671     SDValue Res =
5672         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5673     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5674                       DAG.getValueType(MVT::i32));
5675 
5676     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5677     // Since the inputs are sign extended from i32, this is equivalent to
5678     // comparing the lower 32 bits.
5679     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5680     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5681                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5682 
5683     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5684     Results.push_back(Overflow);
5685     return;
5686   }
5687   case ISD::UADDSAT:
5688   case ISD::USUBSAT: {
5689     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5690            "Unexpected custom legalisation");
5691     if (Subtarget.hasStdExtZbb()) {
5692       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5693       // sign extend allows overflow of the lower 32 bits to be detected on
5694       // the promoted size.
5695       SDValue LHS =
5696           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5697       SDValue RHS =
5698           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5699       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5700       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5701       return;
5702     }
5703 
5704     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5705     // promotion for UADDO/USUBO.
5706     Results.push_back(expandAddSubSat(N, DAG));
5707     return;
5708   }
5709   case ISD::BITCAST: {
5710     EVT VT = N->getValueType(0);
5711     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5712     SDValue Op0 = N->getOperand(0);
5713     EVT Op0VT = Op0.getValueType();
5714     MVT XLenVT = Subtarget.getXLenVT();
5715     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5716       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5717       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5718     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5719                Subtarget.hasStdExtF()) {
5720       SDValue FPConv =
5721           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5722       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5723     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5724                isTypeLegal(Op0VT)) {
5725       // Custom-legalize bitcasts from fixed-length vector types to illegal
5726       // scalar types in order to improve codegen. Bitcast the vector to a
5727       // one-element vector type whose element type is the same as the result
5728       // type, and extract the first element.
5729       LLVMContext &Context = *DAG.getContext();
5730       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5731       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5732                                     DAG.getConstant(0, DL, XLenVT)));
5733     }
5734     break;
5735   }
5736   case RISCVISD::GREV:
5737   case RISCVISD::GORC: {
5738     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5739            "Unexpected custom legalisation");
5740     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5741     // This is similar to customLegalizeToWOp, except that we pass the second
5742     // operand (a TargetConstant) straight through: it is already of type
5743     // XLenVT.
5744     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5745     SDValue NewOp0 =
5746         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5747     SDValue NewOp1 =
5748         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5749     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5750     // ReplaceNodeResults requires we maintain the same type for the return
5751     // value.
5752     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5753     break;
5754   }
5755   case RISCVISD::SHFL: {
5756     // There is no SHFLIW instruction, but we can just promote the operation.
5757     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5758            "Unexpected custom legalisation");
5759     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5760     SDValue NewOp0 =
5761         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5762     SDValue NewOp1 =
5763         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5764     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5765     // ReplaceNodeResults requires we maintain the same type for the return
5766     // value.
5767     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5768     break;
5769   }
5770   case ISD::BSWAP:
5771   case ISD::BITREVERSE: {
5772     MVT VT = N->getSimpleValueType(0);
5773     MVT XLenVT = Subtarget.getXLenVT();
5774     assert((VT == MVT::i8 || VT == MVT::i16 ||
5775             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5776            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5777     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5778     unsigned Imm = VT.getSizeInBits() - 1;
5779     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5780     if (N->getOpcode() == ISD::BSWAP)
5781       Imm &= ~0x7U;
5782     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5783     SDValue GREVI =
5784         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5785     // ReplaceNodeResults requires we maintain the same type for the return
5786     // value.
5787     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5788     break;
5789   }
5790   case ISD::FSHL:
5791   case ISD::FSHR: {
5792     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5793            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5794     SDValue NewOp0 =
5795         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5796     SDValue NewOp1 =
5797         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5798     SDValue NewOp2 =
5799         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5800     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5801     // Mask the shift amount to 5 bits.
5802     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5803                          DAG.getConstant(0x1f, DL, MVT::i64));
5804     unsigned Opc =
5805         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5806     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5807     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5808     break;
5809   }
5810   case ISD::EXTRACT_VECTOR_ELT: {
5811     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5812     // type is illegal (currently only vXi64 RV32).
5813     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5814     // transferred to the destination register. We issue two of these from the
5815     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5816     // first element.
5817     SDValue Vec = N->getOperand(0);
5818     SDValue Idx = N->getOperand(1);
5819 
5820     // The vector type hasn't been legalized yet so we can't issue target
5821     // specific nodes if it needs legalization.
5822     // FIXME: We would manually legalize if it's important.
5823     if (!isTypeLegal(Vec.getValueType()))
5824       return;
5825 
5826     MVT VecVT = Vec.getSimpleValueType();
5827 
5828     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5829            VecVT.getVectorElementType() == MVT::i64 &&
5830            "Unexpected EXTRACT_VECTOR_ELT legalization");
5831 
5832     // If this is a fixed vector, we need to convert it to a scalable vector.
5833     MVT ContainerVT = VecVT;
5834     if (VecVT.isFixedLengthVector()) {
5835       ContainerVT = getContainerForFixedLengthVector(VecVT);
5836       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5837     }
5838 
5839     MVT XLenVT = Subtarget.getXLenVT();
5840 
5841     // Use a VL of 1 to avoid processing more elements than we need.
5842     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5843     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5844     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5845 
5846     // Unless the index is known to be 0, we must slide the vector down to get
5847     // the desired element into index 0.
5848     if (!isNullConstant(Idx)) {
5849       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5850                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5851     }
5852 
5853     // Extract the lower XLEN bits of the correct vector element.
5854     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5855 
5856     // To extract the upper XLEN bits of the vector element, shift the first
5857     // element right by 32 bits and re-extract the lower XLEN bits.
5858     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5859                                      DAG.getConstant(32, DL, XLenVT), VL);
5860     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5861                                  ThirtyTwoV, Mask, VL);
5862 
5863     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5864 
5865     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5866     break;
5867   }
5868   case ISD::INTRINSIC_WO_CHAIN: {
5869     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5870     switch (IntNo) {
5871     default:
5872       llvm_unreachable(
5873           "Don't know how to custom type legalize this intrinsic!");
5874     case Intrinsic::riscv_orc_b: {
5875       // Lower to the GORCI encoding for orc.b with the operand extended.
5876       SDValue NewOp =
5877           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5878       // If Zbp is enabled, use GORCIW which will sign extend the result.
5879       unsigned Opc =
5880           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5881       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5882                                 DAG.getConstant(7, DL, MVT::i64));
5883       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5884       return;
5885     }
5886     case Intrinsic::riscv_grev:
5887     case Intrinsic::riscv_gorc: {
5888       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5889              "Unexpected custom legalisation");
5890       SDValue NewOp1 =
5891           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5892       SDValue NewOp2 =
5893           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5894       unsigned Opc =
5895           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5896       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5897       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5898       break;
5899     }
5900     case Intrinsic::riscv_shfl:
5901     case Intrinsic::riscv_unshfl: {
5902       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5903              "Unexpected custom legalisation");
5904       SDValue NewOp1 =
5905           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5906       SDValue NewOp2 =
5907           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5908       unsigned Opc =
5909           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5910       if (isa<ConstantSDNode>(N->getOperand(2))) {
5911         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5912                              DAG.getConstant(0xf, DL, MVT::i64));
5913         Opc =
5914             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5915       }
5916       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5917       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5918       break;
5919     }
5920     case Intrinsic::riscv_bcompress:
5921     case Intrinsic::riscv_bdecompress: {
5922       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5923              "Unexpected custom legalisation");
5924       SDValue NewOp1 =
5925           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5926       SDValue NewOp2 =
5927           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5928       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5929                          ? RISCVISD::BCOMPRESSW
5930                          : RISCVISD::BDECOMPRESSW;
5931       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5932       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5933       break;
5934     }
5935     case Intrinsic::riscv_vmv_x_s: {
5936       EVT VT = N->getValueType(0);
5937       MVT XLenVT = Subtarget.getXLenVT();
5938       if (VT.bitsLT(XLenVT)) {
5939         // Simple case just extract using vmv.x.s and truncate.
5940         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5941                                       Subtarget.getXLenVT(), N->getOperand(1));
5942         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5943         return;
5944       }
5945 
5946       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5947              "Unexpected custom legalization");
5948 
5949       // We need to do the move in two steps.
5950       SDValue Vec = N->getOperand(1);
5951       MVT VecVT = Vec.getSimpleValueType();
5952 
5953       // First extract the lower XLEN bits of the element.
5954       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5955 
5956       // To extract the upper XLEN bits of the vector element, shift the first
5957       // element right by 32 bits and re-extract the lower XLEN bits.
5958       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5959       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5960       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5961       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5962                                        DAG.getConstant(32, DL, XLenVT), VL);
5963       SDValue LShr32 =
5964           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5965       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5966 
5967       Results.push_back(
5968           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5969       break;
5970     }
5971     }
5972     break;
5973   }
5974   case ISD::VECREDUCE_ADD:
5975   case ISD::VECREDUCE_AND:
5976   case ISD::VECREDUCE_OR:
5977   case ISD::VECREDUCE_XOR:
5978   case ISD::VECREDUCE_SMAX:
5979   case ISD::VECREDUCE_UMAX:
5980   case ISD::VECREDUCE_SMIN:
5981   case ISD::VECREDUCE_UMIN:
5982     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5983       Results.push_back(V);
5984     break;
5985   case ISD::VP_REDUCE_ADD:
5986   case ISD::VP_REDUCE_AND:
5987   case ISD::VP_REDUCE_OR:
5988   case ISD::VP_REDUCE_XOR:
5989   case ISD::VP_REDUCE_SMAX:
5990   case ISD::VP_REDUCE_UMAX:
5991   case ISD::VP_REDUCE_SMIN:
5992   case ISD::VP_REDUCE_UMIN:
5993     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
5994       Results.push_back(V);
5995     break;
5996   case ISD::FLT_ROUNDS_: {
5997     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5998     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5999     Results.push_back(Res.getValue(0));
6000     Results.push_back(Res.getValue(1));
6001     break;
6002   }
6003   }
6004 }
6005 
6006 // A structure to hold one of the bit-manipulation patterns below. Together, a
6007 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6008 //   (or (and (shl x, 1), 0xAAAAAAAA),
6009 //       (and (srl x, 1), 0x55555555))
6010 struct RISCVBitmanipPat {
6011   SDValue Op;
6012   unsigned ShAmt;
6013   bool IsSHL;
6014 
6015   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6016     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6017   }
6018 };
6019 
6020 // Matches patterns of the form
6021 //   (and (shl x, C2), (C1 << C2))
6022 //   (and (srl x, C2), C1)
6023 //   (shl (and x, C1), C2)
6024 //   (srl (and x, (C1 << C2)), C2)
6025 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6026 // The expected masks for each shift amount are specified in BitmanipMasks where
6027 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6028 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6029 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6030 // XLen is 64.
6031 static Optional<RISCVBitmanipPat>
6032 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6033   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6034          "Unexpected number of masks");
6035   Optional<uint64_t> Mask;
6036   // Optionally consume a mask around the shift operation.
6037   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6038     Mask = Op.getConstantOperandVal(1);
6039     Op = Op.getOperand(0);
6040   }
6041   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6042     return None;
6043   bool IsSHL = Op.getOpcode() == ISD::SHL;
6044 
6045   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6046     return None;
6047   uint64_t ShAmt = Op.getConstantOperandVal(1);
6048 
6049   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6050   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6051     return None;
6052   // If we don't have enough masks for 64 bit, then we must be trying to
6053   // match SHFL so we're only allowed to shift 1/4 of the width.
6054   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6055     return None;
6056 
6057   SDValue Src = Op.getOperand(0);
6058 
6059   // The expected mask is shifted left when the AND is found around SHL
6060   // patterns.
6061   //   ((x >> 1) & 0x55555555)
6062   //   ((x << 1) & 0xAAAAAAAA)
6063   bool SHLExpMask = IsSHL;
6064 
6065   if (!Mask) {
6066     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6067     // the mask is all ones: consume that now.
6068     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6069       Mask = Src.getConstantOperandVal(1);
6070       Src = Src.getOperand(0);
6071       // The expected mask is now in fact shifted left for SRL, so reverse the
6072       // decision.
6073       //   ((x & 0xAAAAAAAA) >> 1)
6074       //   ((x & 0x55555555) << 1)
6075       SHLExpMask = !SHLExpMask;
6076     } else {
6077       // Use a default shifted mask of all-ones if there's no AND, truncated
6078       // down to the expected width. This simplifies the logic later on.
6079       Mask = maskTrailingOnes<uint64_t>(Width);
6080       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6081     }
6082   }
6083 
6084   unsigned MaskIdx = Log2_32(ShAmt);
6085   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6086 
6087   if (SHLExpMask)
6088     ExpMask <<= ShAmt;
6089 
6090   if (Mask != ExpMask)
6091     return None;
6092 
6093   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6094 }
6095 
6096 // Matches any of the following bit-manipulation patterns:
6097 //   (and (shl x, 1), (0x55555555 << 1))
6098 //   (and (srl x, 1), 0x55555555)
6099 //   (shl (and x, 0x55555555), 1)
6100 //   (srl (and x, (0x55555555 << 1)), 1)
6101 // where the shift amount and mask may vary thus:
6102 //   [1]  = 0x55555555 / 0xAAAAAAAA
6103 //   [2]  = 0x33333333 / 0xCCCCCCCC
6104 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6105 //   [8]  = 0x00FF00FF / 0xFF00FF00
6106 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6107 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6108 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6109   // These are the unshifted masks which we use to match bit-manipulation
6110   // patterns. They may be shifted left in certain circumstances.
6111   static const uint64_t BitmanipMasks[] = {
6112       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6113       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6114 
6115   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6116 }
6117 
6118 // Match the following pattern as a GREVI(W) operation
6119 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6120 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6121                                const RISCVSubtarget &Subtarget) {
6122   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6123   EVT VT = Op.getValueType();
6124 
6125   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6126     auto LHS = matchGREVIPat(Op.getOperand(0));
6127     auto RHS = matchGREVIPat(Op.getOperand(1));
6128     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6129       SDLoc DL(Op);
6130       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6131                          DAG.getConstant(LHS->ShAmt, DL, VT));
6132     }
6133   }
6134   return SDValue();
6135 }
6136 
6137 // Matches any the following pattern as a GORCI(W) operation
6138 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6139 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6140 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6141 // Note that with the variant of 3.,
6142 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6143 // the inner pattern will first be matched as GREVI and then the outer
6144 // pattern will be matched to GORC via the first rule above.
6145 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6146 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6147                                const RISCVSubtarget &Subtarget) {
6148   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6149   EVT VT = Op.getValueType();
6150 
6151   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6152     SDLoc DL(Op);
6153     SDValue Op0 = Op.getOperand(0);
6154     SDValue Op1 = Op.getOperand(1);
6155 
6156     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6157       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6158           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6159           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6160         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6161       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6162       if ((Reverse.getOpcode() == ISD::ROTL ||
6163            Reverse.getOpcode() == ISD::ROTR) &&
6164           Reverse.getOperand(0) == X &&
6165           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6166         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6167         if (RotAmt == (VT.getSizeInBits() / 2))
6168           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6169                              DAG.getConstant(RotAmt, DL, VT));
6170       }
6171       return SDValue();
6172     };
6173 
6174     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6175     if (SDValue V = MatchOROfReverse(Op0, Op1))
6176       return V;
6177     if (SDValue V = MatchOROfReverse(Op1, Op0))
6178       return V;
6179 
6180     // OR is commutable so canonicalize its OR operand to the left
6181     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6182       std::swap(Op0, Op1);
6183     if (Op0.getOpcode() != ISD::OR)
6184       return SDValue();
6185     SDValue OrOp0 = Op0.getOperand(0);
6186     SDValue OrOp1 = Op0.getOperand(1);
6187     auto LHS = matchGREVIPat(OrOp0);
6188     // OR is commutable so swap the operands and try again: x might have been
6189     // on the left
6190     if (!LHS) {
6191       std::swap(OrOp0, OrOp1);
6192       LHS = matchGREVIPat(OrOp0);
6193     }
6194     auto RHS = matchGREVIPat(Op1);
6195     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6196       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6197                          DAG.getConstant(LHS->ShAmt, DL, VT));
6198     }
6199   }
6200   return SDValue();
6201 }
6202 
6203 // Matches any of the following bit-manipulation patterns:
6204 //   (and (shl x, 1), (0x22222222 << 1))
6205 //   (and (srl x, 1), 0x22222222)
6206 //   (shl (and x, 0x22222222), 1)
6207 //   (srl (and x, (0x22222222 << 1)), 1)
6208 // where the shift amount and mask may vary thus:
6209 //   [1]  = 0x22222222 / 0x44444444
6210 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6211 //   [4]  = 0x00F000F0 / 0x0F000F00
6212 //   [8]  = 0x0000FF00 / 0x00FF0000
6213 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6214 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6215   // These are the unshifted masks which we use to match bit-manipulation
6216   // patterns. They may be shifted left in certain circumstances.
6217   static const uint64_t BitmanipMasks[] = {
6218       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6219       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6220 
6221   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6222 }
6223 
6224 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6225 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6226                                const RISCVSubtarget &Subtarget) {
6227   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6228   EVT VT = Op.getValueType();
6229 
6230   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6231     return SDValue();
6232 
6233   SDValue Op0 = Op.getOperand(0);
6234   SDValue Op1 = Op.getOperand(1);
6235 
6236   // Or is commutable so canonicalize the second OR to the LHS.
6237   if (Op0.getOpcode() != ISD::OR)
6238     std::swap(Op0, Op1);
6239   if (Op0.getOpcode() != ISD::OR)
6240     return SDValue();
6241 
6242   // We found an inner OR, so our operands are the operands of the inner OR
6243   // and the other operand of the outer OR.
6244   SDValue A = Op0.getOperand(0);
6245   SDValue B = Op0.getOperand(1);
6246   SDValue C = Op1;
6247 
6248   auto Match1 = matchSHFLPat(A);
6249   auto Match2 = matchSHFLPat(B);
6250 
6251   // If neither matched, we failed.
6252   if (!Match1 && !Match2)
6253     return SDValue();
6254 
6255   // We had at least one match. if one failed, try the remaining C operand.
6256   if (!Match1) {
6257     std::swap(A, C);
6258     Match1 = matchSHFLPat(A);
6259     if (!Match1)
6260       return SDValue();
6261   } else if (!Match2) {
6262     std::swap(B, C);
6263     Match2 = matchSHFLPat(B);
6264     if (!Match2)
6265       return SDValue();
6266   }
6267   assert(Match1 && Match2);
6268 
6269   // Make sure our matches pair up.
6270   if (!Match1->formsPairWith(*Match2))
6271     return SDValue();
6272 
6273   // All the remains is to make sure C is an AND with the same input, that masks
6274   // out the bits that are being shuffled.
6275   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6276       C.getOperand(0) != Match1->Op)
6277     return SDValue();
6278 
6279   uint64_t Mask = C.getConstantOperandVal(1);
6280 
6281   static const uint64_t BitmanipMasks[] = {
6282       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6283       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6284   };
6285 
6286   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6287   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6288   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6289 
6290   if (Mask != ExpMask)
6291     return SDValue();
6292 
6293   SDLoc DL(Op);
6294   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6295                      DAG.getConstant(Match1->ShAmt, DL, VT));
6296 }
6297 
6298 // Optimize (add (shl x, c0), (shl y, c1)) ->
6299 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6300 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6301                                   const RISCVSubtarget &Subtarget) {
6302   // Perform this optimization only in the zba extension.
6303   if (!Subtarget.hasStdExtZba())
6304     return SDValue();
6305 
6306   // Skip for vector types and larger types.
6307   EVT VT = N->getValueType(0);
6308   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6309     return SDValue();
6310 
6311   // The two operand nodes must be SHL and have no other use.
6312   SDValue N0 = N->getOperand(0);
6313   SDValue N1 = N->getOperand(1);
6314   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6315       !N0->hasOneUse() || !N1->hasOneUse())
6316     return SDValue();
6317 
6318   // Check c0 and c1.
6319   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6320   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6321   if (!N0C || !N1C)
6322     return SDValue();
6323   int64_t C0 = N0C->getSExtValue();
6324   int64_t C1 = N1C->getSExtValue();
6325   if (C0 <= 0 || C1 <= 0)
6326     return SDValue();
6327 
6328   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6329   int64_t Bits = std::min(C0, C1);
6330   int64_t Diff = std::abs(C0 - C1);
6331   if (Diff != 1 && Diff != 2 && Diff != 3)
6332     return SDValue();
6333 
6334   // Build nodes.
6335   SDLoc DL(N);
6336   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6337   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6338   SDValue NA0 =
6339       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6340   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6341   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6342 }
6343 
6344 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6345 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6346 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6347 // not undo itself, but they are redundant.
6348 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6349   SDValue Src = N->getOperand(0);
6350 
6351   if (Src.getOpcode() != N->getOpcode())
6352     return SDValue();
6353 
6354   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6355       !isa<ConstantSDNode>(Src.getOperand(1)))
6356     return SDValue();
6357 
6358   unsigned ShAmt1 = N->getConstantOperandVal(1);
6359   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6360   Src = Src.getOperand(0);
6361 
6362   unsigned CombinedShAmt;
6363   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6364     CombinedShAmt = ShAmt1 | ShAmt2;
6365   else
6366     CombinedShAmt = ShAmt1 ^ ShAmt2;
6367 
6368   if (CombinedShAmt == 0)
6369     return Src;
6370 
6371   SDLoc DL(N);
6372   return DAG.getNode(
6373       N->getOpcode(), DL, N->getValueType(0), Src,
6374       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6375 }
6376 
6377 // Combine a constant select operand into its use:
6378 //
6379 // (and (select cond, -1, c), x)
6380 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6381 // (or  (select cond, 0, c), x)
6382 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6383 // (xor (select cond, 0, c), x)
6384 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6385 // (add (select cond, 0, c), x)
6386 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6387 // (sub x, (select cond, 0, c))
6388 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6389 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6390                                    SelectionDAG &DAG, bool AllOnes) {
6391   EVT VT = N->getValueType(0);
6392 
6393   // Skip vectors.
6394   if (VT.isVector())
6395     return SDValue();
6396 
6397   if ((Slct.getOpcode() != ISD::SELECT &&
6398        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6399       !Slct.hasOneUse())
6400     return SDValue();
6401 
6402   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6403     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6404   };
6405 
6406   bool SwapSelectOps;
6407   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6408   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6409   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6410   SDValue NonConstantVal;
6411   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6412     SwapSelectOps = false;
6413     NonConstantVal = FalseVal;
6414   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6415     SwapSelectOps = true;
6416     NonConstantVal = TrueVal;
6417   } else
6418     return SDValue();
6419 
6420   // Slct is now know to be the desired identity constant when CC is true.
6421   TrueVal = OtherOp;
6422   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6423   // Unless SwapSelectOps says the condition should be false.
6424   if (SwapSelectOps)
6425     std::swap(TrueVal, FalseVal);
6426 
6427   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6428     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6429                        {Slct.getOperand(0), Slct.getOperand(1),
6430                         Slct.getOperand(2), TrueVal, FalseVal});
6431 
6432   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6433                      {Slct.getOperand(0), TrueVal, FalseVal});
6434 }
6435 
6436 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6437 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6438                                               bool AllOnes) {
6439   SDValue N0 = N->getOperand(0);
6440   SDValue N1 = N->getOperand(1);
6441   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6442     return Result;
6443   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6444     return Result;
6445   return SDValue();
6446 }
6447 
6448 // Transform (add (mul x, c0), c1) ->
6449 //           (add (mul (add x, c1/c0), c0), c1%c0).
6450 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6451 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6452 // to an infinite loop in DAGCombine if transformed.
6453 // Or transform (add (mul x, c0), c1) ->
6454 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6455 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6456 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6457 // lead to an infinite loop in DAGCombine if transformed.
6458 // Or transform (add (mul x, c0), c1) ->
6459 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6460 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6461 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6462 // lead to an infinite loop in DAGCombine if transformed.
6463 // Or transform (add (mul x, c0), c1) ->
6464 //              (mul (add x, c1/c0), c0).
6465 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6466 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6467                                      const RISCVSubtarget &Subtarget) {
6468   // Skip for vector types and larger types.
6469   EVT VT = N->getValueType(0);
6470   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6471     return SDValue();
6472   // The first operand node must be a MUL and has no other use.
6473   SDValue N0 = N->getOperand(0);
6474   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6475     return SDValue();
6476   // Check if c0 and c1 match above conditions.
6477   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6478   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6479   if (!N0C || !N1C)
6480     return SDValue();
6481   int64_t C0 = N0C->getSExtValue();
6482   int64_t C1 = N1C->getSExtValue();
6483   int64_t CA, CB;
6484   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6485     return SDValue();
6486   // Search for proper CA (non-zero) and CB that both are simm12.
6487   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6488       !isInt<12>(C0 * (C1 / C0))) {
6489     CA = C1 / C0;
6490     CB = C1 % C0;
6491   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6492              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6493     CA = C1 / C0 + 1;
6494     CB = C1 % C0 - C0;
6495   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6496              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6497     CA = C1 / C0 - 1;
6498     CB = C1 % C0 + C0;
6499   } else
6500     return SDValue();
6501   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6502   SDLoc DL(N);
6503   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6504                              DAG.getConstant(CA, DL, VT));
6505   SDValue New1 =
6506       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6507   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6508 }
6509 
6510 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6511                                  const RISCVSubtarget &Subtarget) {
6512   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6513     return V;
6514   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6515     return V;
6516   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6517   //      (select lhs, rhs, cc, x, (add x, y))
6518   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6519 }
6520 
6521 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6522   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6523   //      (select lhs, rhs, cc, x, (sub x, y))
6524   SDValue N0 = N->getOperand(0);
6525   SDValue N1 = N->getOperand(1);
6526   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6527 }
6528 
6529 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6530   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6531   //      (select lhs, rhs, cc, x, (and x, y))
6532   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6533 }
6534 
6535 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6536                                 const RISCVSubtarget &Subtarget) {
6537   if (Subtarget.hasStdExtZbp()) {
6538     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6539       return GREV;
6540     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6541       return GORC;
6542     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6543       return SHFL;
6544   }
6545 
6546   // fold (or (select cond, 0, y), x) ->
6547   //      (select cond, x, (or x, y))
6548   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6549 }
6550 
6551 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6552   // fold (xor (select cond, 0, y), x) ->
6553   //      (select cond, x, (xor x, y))
6554   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6555 }
6556 
6557 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6558 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6559 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6560 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6561 // ADDW/SUBW/MULW.
6562 static SDValue performANY_EXTENDCombine(SDNode *N,
6563                                         TargetLowering::DAGCombinerInfo &DCI,
6564                                         const RISCVSubtarget &Subtarget) {
6565   if (!Subtarget.is64Bit())
6566     return SDValue();
6567 
6568   SelectionDAG &DAG = DCI.DAG;
6569 
6570   SDValue Src = N->getOperand(0);
6571   EVT VT = N->getValueType(0);
6572   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6573     return SDValue();
6574 
6575   // The opcode must be one that can implicitly sign_extend.
6576   // FIXME: Additional opcodes.
6577   switch (Src.getOpcode()) {
6578   default:
6579     return SDValue();
6580   case ISD::MUL:
6581     if (!Subtarget.hasStdExtM())
6582       return SDValue();
6583     LLVM_FALLTHROUGH;
6584   case ISD::ADD:
6585   case ISD::SUB:
6586     break;
6587   }
6588 
6589   // Only handle cases where the result is used by a CopyToReg. That likely
6590   // means the value is a liveout of the basic block. This helps prevent
6591   // infinite combine loops like PR51206.
6592   if (none_of(N->uses(),
6593               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6594     return SDValue();
6595 
6596   SmallVector<SDNode *, 4> SetCCs;
6597   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6598                             UE = Src.getNode()->use_end();
6599        UI != UE; ++UI) {
6600     SDNode *User = *UI;
6601     if (User == N)
6602       continue;
6603     if (UI.getUse().getResNo() != Src.getResNo())
6604       continue;
6605     // All i32 setccs are legalized by sign extending operands.
6606     if (User->getOpcode() == ISD::SETCC) {
6607       SetCCs.push_back(User);
6608       continue;
6609     }
6610     // We don't know if we can extend this user.
6611     break;
6612   }
6613 
6614   // If we don't have any SetCCs, this isn't worthwhile.
6615   if (SetCCs.empty())
6616     return SDValue();
6617 
6618   SDLoc DL(N);
6619   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6620   DCI.CombineTo(N, SExt);
6621 
6622   // Promote all the setccs.
6623   for (SDNode *SetCC : SetCCs) {
6624     SmallVector<SDValue, 4> Ops;
6625 
6626     for (unsigned j = 0; j != 2; ++j) {
6627       SDValue SOp = SetCC->getOperand(j);
6628       if (SOp == Src)
6629         Ops.push_back(SExt);
6630       else
6631         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6632     }
6633 
6634     Ops.push_back(SetCC->getOperand(2));
6635     DCI.CombineTo(SetCC,
6636                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6637   }
6638   return SDValue(N, 0);
6639 }
6640 
6641 // Try to form VWMUL or VWMULU.
6642 // FIXME: Support VWMULSU.
6643 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6644                                     SelectionDAG &DAG) {
6645   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6646   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6647   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6648   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6649     return SDValue();
6650 
6651   SDValue Mask = N->getOperand(2);
6652   SDValue VL = N->getOperand(3);
6653 
6654   // Make sure the mask and VL match.
6655   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6656     return SDValue();
6657 
6658   MVT VT = N->getSimpleValueType(0);
6659 
6660   // Determine the narrow size for a widening multiply.
6661   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6662   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6663                                   VT.getVectorElementCount());
6664 
6665   SDLoc DL(N);
6666 
6667   // See if the other operand is the same opcode.
6668   if (Op0.getOpcode() == Op1.getOpcode()) {
6669     if (!Op1.hasOneUse())
6670       return SDValue();
6671 
6672     // Make sure the mask and VL match.
6673     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6674       return SDValue();
6675 
6676     Op1 = Op1.getOperand(0);
6677   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6678     // The operand is a splat of a scalar.
6679 
6680     // The VL must be the same.
6681     if (Op1.getOperand(1) != VL)
6682       return SDValue();
6683 
6684     // Get the scalar value.
6685     Op1 = Op1.getOperand(0);
6686 
6687     // See if have enough sign bits or zero bits in the scalar to use a
6688     // widening multiply by splatting to smaller element size.
6689     unsigned EltBits = VT.getScalarSizeInBits();
6690     unsigned ScalarBits = Op1.getValueSizeInBits();
6691     // Make sure we're getting all element bits from the scalar register.
6692     // FIXME: Support implicit sign extension of vmv.v.x?
6693     if (ScalarBits < EltBits)
6694       return SDValue();
6695 
6696     if (IsSignExt) {
6697       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6698         return SDValue();
6699     } else {
6700       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6701       if (!DAG.MaskedValueIsZero(Op1, Mask))
6702         return SDValue();
6703     }
6704 
6705     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6706   } else
6707     return SDValue();
6708 
6709   Op0 = Op0.getOperand(0);
6710 
6711   // Re-introduce narrower extends if needed.
6712   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6713   if (Op0.getValueType() != NarrowVT)
6714     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6715   if (Op1.getValueType() != NarrowVT)
6716     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6717 
6718   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6719   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6720 }
6721 
6722 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6723                                                DAGCombinerInfo &DCI) const {
6724   SelectionDAG &DAG = DCI.DAG;
6725 
6726   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6727   // bits are demanded. N will be added to the Worklist if it was not deleted.
6728   // Caller should return SDValue(N, 0) if this returns true.
6729   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6730     SDValue Op = N->getOperand(OpNo);
6731     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6732     if (!SimplifyDemandedBits(Op, Mask, DCI))
6733       return false;
6734 
6735     if (N->getOpcode() != ISD::DELETED_NODE)
6736       DCI.AddToWorklist(N);
6737     return true;
6738   };
6739 
6740   switch (N->getOpcode()) {
6741   default:
6742     break;
6743   case RISCVISD::SplitF64: {
6744     SDValue Op0 = N->getOperand(0);
6745     // If the input to SplitF64 is just BuildPairF64 then the operation is
6746     // redundant. Instead, use BuildPairF64's operands directly.
6747     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6748       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6749 
6750     SDLoc DL(N);
6751 
6752     // It's cheaper to materialise two 32-bit integers than to load a double
6753     // from the constant pool and transfer it to integer registers through the
6754     // stack.
6755     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6756       APInt V = C->getValueAPF().bitcastToAPInt();
6757       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6758       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6759       return DCI.CombineTo(N, Lo, Hi);
6760     }
6761 
6762     // This is a target-specific version of a DAGCombine performed in
6763     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6764     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6765     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6766     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6767         !Op0.getNode()->hasOneUse())
6768       break;
6769     SDValue NewSplitF64 =
6770         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6771                     Op0.getOperand(0));
6772     SDValue Lo = NewSplitF64.getValue(0);
6773     SDValue Hi = NewSplitF64.getValue(1);
6774     APInt SignBit = APInt::getSignMask(32);
6775     if (Op0.getOpcode() == ISD::FNEG) {
6776       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6777                                   DAG.getConstant(SignBit, DL, MVT::i32));
6778       return DCI.CombineTo(N, Lo, NewHi);
6779     }
6780     assert(Op0.getOpcode() == ISD::FABS);
6781     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6782                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6783     return DCI.CombineTo(N, Lo, NewHi);
6784   }
6785   case RISCVISD::SLLW:
6786   case RISCVISD::SRAW:
6787   case RISCVISD::SRLW:
6788   case RISCVISD::ROLW:
6789   case RISCVISD::RORW: {
6790     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6791     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6792         SimplifyDemandedLowBitsHelper(1, 5))
6793       return SDValue(N, 0);
6794     break;
6795   }
6796   case RISCVISD::CLZW:
6797   case RISCVISD::CTZW: {
6798     // Only the lower 32 bits of the first operand are read
6799     if (SimplifyDemandedLowBitsHelper(0, 32))
6800       return SDValue(N, 0);
6801     break;
6802   }
6803   case RISCVISD::FSL:
6804   case RISCVISD::FSR: {
6805     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6806     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6807     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6808     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6809       return SDValue(N, 0);
6810     break;
6811   }
6812   case RISCVISD::FSLW:
6813   case RISCVISD::FSRW: {
6814     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6815     // read.
6816     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6817         SimplifyDemandedLowBitsHelper(1, 32) ||
6818         SimplifyDemandedLowBitsHelper(2, 6))
6819       return SDValue(N, 0);
6820     break;
6821   }
6822   case RISCVISD::GREV:
6823   case RISCVISD::GORC: {
6824     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6825     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6826     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6827     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6828       return SDValue(N, 0);
6829 
6830     return combineGREVI_GORCI(N, DCI.DAG);
6831   }
6832   case RISCVISD::GREVW:
6833   case RISCVISD::GORCW: {
6834     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6835     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6836         SimplifyDemandedLowBitsHelper(1, 5))
6837       return SDValue(N, 0);
6838 
6839     return combineGREVI_GORCI(N, DCI.DAG);
6840   }
6841   case RISCVISD::SHFL:
6842   case RISCVISD::UNSHFL: {
6843     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6844     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6845     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6846     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6847       return SDValue(N, 0);
6848 
6849     break;
6850   }
6851   case RISCVISD::SHFLW:
6852   case RISCVISD::UNSHFLW: {
6853     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6854     SDValue LHS = N->getOperand(0);
6855     SDValue RHS = N->getOperand(1);
6856     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6857     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6858     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6859         SimplifyDemandedLowBitsHelper(1, 4))
6860       return SDValue(N, 0);
6861 
6862     break;
6863   }
6864   case RISCVISD::BCOMPRESSW:
6865   case RISCVISD::BDECOMPRESSW: {
6866     // Only the lower 32 bits of LHS and RHS are read.
6867     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6868         SimplifyDemandedLowBitsHelper(1, 32))
6869       return SDValue(N, 0);
6870 
6871     break;
6872   }
6873   case RISCVISD::FMV_X_ANYEXTH:
6874   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6875     SDLoc DL(N);
6876     SDValue Op0 = N->getOperand(0);
6877     MVT VT = N->getSimpleValueType(0);
6878     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6879     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6880     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6881     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6882          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6883         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6884          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6885       assert(Op0.getOperand(0).getValueType() == VT &&
6886              "Unexpected value type!");
6887       return Op0.getOperand(0);
6888     }
6889 
6890     // This is a target-specific version of a DAGCombine performed in
6891     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6892     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6893     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6894     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6895         !Op0.getNode()->hasOneUse())
6896       break;
6897     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6898     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6899     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6900     if (Op0.getOpcode() == ISD::FNEG)
6901       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6902                          DAG.getConstant(SignBit, DL, VT));
6903 
6904     assert(Op0.getOpcode() == ISD::FABS);
6905     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6906                        DAG.getConstant(~SignBit, DL, VT));
6907   }
6908   case ISD::ADD:
6909     return performADDCombine(N, DAG, Subtarget);
6910   case ISD::SUB:
6911     return performSUBCombine(N, DAG);
6912   case ISD::AND:
6913     return performANDCombine(N, DAG);
6914   case ISD::OR:
6915     return performORCombine(N, DAG, Subtarget);
6916   case ISD::XOR:
6917     return performXORCombine(N, DAG);
6918   case ISD::ANY_EXTEND:
6919     return performANY_EXTENDCombine(N, DCI, Subtarget);
6920   case ISD::ZERO_EXTEND:
6921     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6922     // type legalization. This is safe because fp_to_uint produces poison if
6923     // it overflows.
6924     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6925         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6926         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6927       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6928                          N->getOperand(0).getOperand(0));
6929     return SDValue();
6930   case RISCVISD::SELECT_CC: {
6931     // Transform
6932     SDValue LHS = N->getOperand(0);
6933     SDValue RHS = N->getOperand(1);
6934     SDValue TrueV = N->getOperand(3);
6935     SDValue FalseV = N->getOperand(4);
6936 
6937     // If the True and False values are the same, we don't need a select_cc.
6938     if (TrueV == FalseV)
6939       return TrueV;
6940 
6941     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6942     if (!ISD::isIntEqualitySetCC(CCVal))
6943       break;
6944 
6945     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6946     //      (select_cc X, Y, lt, trueV, falseV)
6947     // Sometimes the setcc is introduced after select_cc has been formed.
6948     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6949         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6950       // If we're looking for eq 0 instead of ne 0, we need to invert the
6951       // condition.
6952       bool Invert = CCVal == ISD::SETEQ;
6953       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6954       if (Invert)
6955         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6956 
6957       SDLoc DL(N);
6958       RHS = LHS.getOperand(1);
6959       LHS = LHS.getOperand(0);
6960       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6961 
6962       SDValue TargetCC = DAG.getCondCode(CCVal);
6963       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6964                          {LHS, RHS, TargetCC, TrueV, FalseV});
6965     }
6966 
6967     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6968     //      (select_cc X, Y, eq/ne, trueV, falseV)
6969     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6970       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6971                          {LHS.getOperand(0), LHS.getOperand(1),
6972                           N->getOperand(2), TrueV, FalseV});
6973     // (select_cc X, 1, setne, trueV, falseV) ->
6974     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6975     // This can occur when legalizing some floating point comparisons.
6976     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6977     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6978       SDLoc DL(N);
6979       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6980       SDValue TargetCC = DAG.getCondCode(CCVal);
6981       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6982       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6983                          {LHS, RHS, TargetCC, TrueV, FalseV});
6984     }
6985 
6986     break;
6987   }
6988   case RISCVISD::BR_CC: {
6989     SDValue LHS = N->getOperand(1);
6990     SDValue RHS = N->getOperand(2);
6991     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6992     if (!ISD::isIntEqualitySetCC(CCVal))
6993       break;
6994 
6995     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6996     //      (br_cc X, Y, lt, dest)
6997     // Sometimes the setcc is introduced after br_cc has been formed.
6998     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6999         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7000       // If we're looking for eq 0 instead of ne 0, we need to invert the
7001       // condition.
7002       bool Invert = CCVal == ISD::SETEQ;
7003       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7004       if (Invert)
7005         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7006 
7007       SDLoc DL(N);
7008       RHS = LHS.getOperand(1);
7009       LHS = LHS.getOperand(0);
7010       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7011 
7012       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7013                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7014                          N->getOperand(4));
7015     }
7016 
7017     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7018     //      (br_cc X, Y, eq/ne, trueV, falseV)
7019     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7020       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7021                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7022                          N->getOperand(3), N->getOperand(4));
7023 
7024     // (br_cc X, 1, setne, br_cc) ->
7025     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7026     // This can occur when legalizing some floating point comparisons.
7027     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7028     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7029       SDLoc DL(N);
7030       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7031       SDValue TargetCC = DAG.getCondCode(CCVal);
7032       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7033       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7034                          N->getOperand(0), LHS, RHS, TargetCC,
7035                          N->getOperand(4));
7036     }
7037     break;
7038   }
7039   case ISD::FCOPYSIGN: {
7040     EVT VT = N->getValueType(0);
7041     if (!VT.isVector())
7042       break;
7043     // There is a form of VFSGNJ which injects the negated sign of its second
7044     // operand. Try and bubble any FNEG up after the extend/round to produce
7045     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7046     // TRUNC=1.
7047     SDValue In2 = N->getOperand(1);
7048     // Avoid cases where the extend/round has multiple uses, as duplicating
7049     // those is typically more expensive than removing a fneg.
7050     if (!In2.hasOneUse())
7051       break;
7052     if (In2.getOpcode() != ISD::FP_EXTEND &&
7053         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7054       break;
7055     In2 = In2.getOperand(0);
7056     if (In2.getOpcode() != ISD::FNEG)
7057       break;
7058     SDLoc DL(N);
7059     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7060     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7061                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7062   }
7063   case ISD::MGATHER:
7064   case ISD::MSCATTER:
7065   case ISD::VP_GATHER:
7066   case ISD::VP_SCATTER: {
7067     if (!DCI.isBeforeLegalize())
7068       break;
7069     SDValue Index, ScaleOp;
7070     bool IsIndexScaled = false;
7071     bool IsIndexSigned = false;
7072     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7073       Index = VPGSN->getIndex();
7074       ScaleOp = VPGSN->getScale();
7075       IsIndexScaled = VPGSN->isIndexScaled();
7076       IsIndexSigned = VPGSN->isIndexSigned();
7077     } else {
7078       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7079       Index = MGSN->getIndex();
7080       ScaleOp = MGSN->getScale();
7081       IsIndexScaled = MGSN->isIndexScaled();
7082       IsIndexSigned = MGSN->isIndexSigned();
7083     }
7084     EVT IndexVT = Index.getValueType();
7085     MVT XLenVT = Subtarget.getXLenVT();
7086     // RISCV indexed loads only support the "unsigned unscaled" addressing
7087     // mode, so anything else must be manually legalized.
7088     bool NeedsIdxLegalization =
7089         IsIndexScaled ||
7090         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7091     if (!NeedsIdxLegalization)
7092       break;
7093 
7094     SDLoc DL(N);
7095 
7096     // Any index legalization should first promote to XLenVT, so we don't lose
7097     // bits when scaling. This may create an illegal index type so we let
7098     // LLVM's legalization take care of the splitting.
7099     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7100     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7101       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7102       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7103                           DL, IndexVT, Index);
7104     }
7105 
7106     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7107     if (IsIndexScaled && Scale != 1) {
7108       // Manually scale the indices by the element size.
7109       // TODO: Sanitize the scale operand here?
7110       // TODO: For VP nodes, should we use VP_SHL here?
7111       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7112       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7113       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7114     }
7115 
7116     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7117     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7118       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7119                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7120                               VPGN->getScale(), VPGN->getMask(),
7121                               VPGN->getVectorLength()},
7122                              VPGN->getMemOperand(), NewIndexTy);
7123     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7124       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7125                               {VPSN->getChain(), VPSN->getValue(),
7126                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7127                                VPSN->getMask(), VPSN->getVectorLength()},
7128                               VPSN->getMemOperand(), NewIndexTy);
7129     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7130       return DAG.getMaskedGather(
7131           N->getVTList(), MGN->getMemoryVT(), DL,
7132           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7133            MGN->getBasePtr(), Index, MGN->getScale()},
7134           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7135     const auto *MSN = cast<MaskedScatterSDNode>(N);
7136     return DAG.getMaskedScatter(
7137         N->getVTList(), MSN->getMemoryVT(), DL,
7138         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7139          Index, MSN->getScale()},
7140         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7141   }
7142   case RISCVISD::SRA_VL:
7143   case RISCVISD::SRL_VL:
7144   case RISCVISD::SHL_VL: {
7145     SDValue ShAmt = N->getOperand(1);
7146     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7147       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7148       SDLoc DL(N);
7149       SDValue VL = N->getOperand(3);
7150       EVT VT = N->getValueType(0);
7151       ShAmt =
7152           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7153       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7154                          N->getOperand(2), N->getOperand(3));
7155     }
7156     break;
7157   }
7158   case ISD::SRA:
7159   case ISD::SRL:
7160   case ISD::SHL: {
7161     SDValue ShAmt = N->getOperand(1);
7162     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7163       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7164       SDLoc DL(N);
7165       EVT VT = N->getValueType(0);
7166       ShAmt =
7167           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7168       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7169     }
7170     break;
7171   }
7172   case RISCVISD::MUL_VL: {
7173     SDValue Op0 = N->getOperand(0);
7174     SDValue Op1 = N->getOperand(1);
7175     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7176       return V;
7177     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7178       return V;
7179     return SDValue();
7180   }
7181   case ISD::STORE: {
7182     auto *Store = cast<StoreSDNode>(N);
7183     SDValue Val = Store->getValue();
7184     // Combine store of vmv.x.s to vse with VL of 1.
7185     // FIXME: Support FP.
7186     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7187       SDValue Src = Val.getOperand(0);
7188       EVT VecVT = Src.getValueType();
7189       EVT MemVT = Store->getMemoryVT();
7190       // The memory VT and the element type must match.
7191       if (VecVT.getVectorElementType() == MemVT) {
7192         SDLoc DL(N);
7193         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7194         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7195                               DAG.getConstant(1, DL, MaskVT),
7196                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7197                               Store->getPointerInfo(),
7198                               Store->getOriginalAlign(),
7199                               Store->getMemOperand()->getFlags());
7200       }
7201     }
7202 
7203     break;
7204   }
7205   }
7206 
7207   return SDValue();
7208 }
7209 
7210 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7211     const SDNode *N, CombineLevel Level) const {
7212   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7213   // materialised in fewer instructions than `(OP _, c1)`:
7214   //
7215   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7216   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7217   SDValue N0 = N->getOperand(0);
7218   EVT Ty = N0.getValueType();
7219   if (Ty.isScalarInteger() &&
7220       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7221     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7222     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7223     if (C1 && C2) {
7224       const APInt &C1Int = C1->getAPIntValue();
7225       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7226 
7227       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7228       // and the combine should happen, to potentially allow further combines
7229       // later.
7230       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7231           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7232         return true;
7233 
7234       // We can materialise `c1` in an add immediate, so it's "free", and the
7235       // combine should be prevented.
7236       if (C1Int.getMinSignedBits() <= 64 &&
7237           isLegalAddImmediate(C1Int.getSExtValue()))
7238         return false;
7239 
7240       // Neither constant will fit into an immediate, so find materialisation
7241       // costs.
7242       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7243                                               Subtarget.getFeatureBits(),
7244                                               /*CompressionCost*/true);
7245       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7246           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7247           /*CompressionCost*/true);
7248 
7249       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7250       // combine should be prevented.
7251       if (C1Cost < ShiftedC1Cost)
7252         return false;
7253     }
7254   }
7255   return true;
7256 }
7257 
7258 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7259     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7260     TargetLoweringOpt &TLO) const {
7261   // Delay this optimization as late as possible.
7262   if (!TLO.LegalOps)
7263     return false;
7264 
7265   EVT VT = Op.getValueType();
7266   if (VT.isVector())
7267     return false;
7268 
7269   // Only handle AND for now.
7270   if (Op.getOpcode() != ISD::AND)
7271     return false;
7272 
7273   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7274   if (!C)
7275     return false;
7276 
7277   const APInt &Mask = C->getAPIntValue();
7278 
7279   // Clear all non-demanded bits initially.
7280   APInt ShrunkMask = Mask & DemandedBits;
7281 
7282   // Try to make a smaller immediate by setting undemanded bits.
7283 
7284   APInt ExpandedMask = Mask | ~DemandedBits;
7285 
7286   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7287     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7288   };
7289   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7290     if (NewMask == Mask)
7291       return true;
7292     SDLoc DL(Op);
7293     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7294     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7295     return TLO.CombineTo(Op, NewOp);
7296   };
7297 
7298   // If the shrunk mask fits in sign extended 12 bits, let the target
7299   // independent code apply it.
7300   if (ShrunkMask.isSignedIntN(12))
7301     return false;
7302 
7303   // Preserve (and X, 0xffff) when zext.h is supported.
7304   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7305     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7306     if (IsLegalMask(NewMask))
7307       return UseMask(NewMask);
7308   }
7309 
7310   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7311   if (VT == MVT::i64) {
7312     APInt NewMask = APInt(64, 0xffffffff);
7313     if (IsLegalMask(NewMask))
7314       return UseMask(NewMask);
7315   }
7316 
7317   // For the remaining optimizations, we need to be able to make a negative
7318   // number through a combination of mask and undemanded bits.
7319   if (!ExpandedMask.isNegative())
7320     return false;
7321 
7322   // What is the fewest number of bits we need to represent the negative number.
7323   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7324 
7325   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7326   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7327   APInt NewMask = ShrunkMask;
7328   if (MinSignedBits <= 12)
7329     NewMask.setBitsFrom(11);
7330   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7331     NewMask.setBitsFrom(31);
7332   else
7333     return false;
7334 
7335   // Sanity check that our new mask is a subset of the demanded mask.
7336   assert(IsLegalMask(NewMask));
7337   return UseMask(NewMask);
7338 }
7339 
7340 static void computeGREV(APInt &Src, unsigned ShAmt) {
7341   ShAmt &= Src.getBitWidth() - 1;
7342   uint64_t x = Src.getZExtValue();
7343   if (ShAmt & 1)
7344     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7345   if (ShAmt & 2)
7346     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7347   if (ShAmt & 4)
7348     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7349   if (ShAmt & 8)
7350     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7351   if (ShAmt & 16)
7352     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7353   if (ShAmt & 32)
7354     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7355   Src = x;
7356 }
7357 
7358 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7359                                                         KnownBits &Known,
7360                                                         const APInt &DemandedElts,
7361                                                         const SelectionDAG &DAG,
7362                                                         unsigned Depth) const {
7363   unsigned BitWidth = Known.getBitWidth();
7364   unsigned Opc = Op.getOpcode();
7365   assert((Opc >= ISD::BUILTIN_OP_END ||
7366           Opc == ISD::INTRINSIC_WO_CHAIN ||
7367           Opc == ISD::INTRINSIC_W_CHAIN ||
7368           Opc == ISD::INTRINSIC_VOID) &&
7369          "Should use MaskedValueIsZero if you don't know whether Op"
7370          " is a target node!");
7371 
7372   Known.resetAll();
7373   switch (Opc) {
7374   default: break;
7375   case RISCVISD::SELECT_CC: {
7376     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7377     // If we don't know any bits, early out.
7378     if (Known.isUnknown())
7379       break;
7380     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7381 
7382     // Only known if known in both the LHS and RHS.
7383     Known = KnownBits::commonBits(Known, Known2);
7384     break;
7385   }
7386   case RISCVISD::REMUW: {
7387     KnownBits Known2;
7388     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7389     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7390     // We only care about the lower 32 bits.
7391     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7392     // Restore the original width by sign extending.
7393     Known = Known.sext(BitWidth);
7394     break;
7395   }
7396   case RISCVISD::DIVUW: {
7397     KnownBits Known2;
7398     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7399     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7400     // We only care about the lower 32 bits.
7401     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7402     // Restore the original width by sign extending.
7403     Known = Known.sext(BitWidth);
7404     break;
7405   }
7406   case RISCVISD::CTZW: {
7407     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7408     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7409     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7410     Known.Zero.setBitsFrom(LowBits);
7411     break;
7412   }
7413   case RISCVISD::CLZW: {
7414     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7415     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7416     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7417     Known.Zero.setBitsFrom(LowBits);
7418     break;
7419   }
7420   case RISCVISD::GREV:
7421   case RISCVISD::GREVW: {
7422     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7423       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7424       if (Opc == RISCVISD::GREVW)
7425         Known = Known.trunc(32);
7426       unsigned ShAmt = C->getZExtValue();
7427       computeGREV(Known.Zero, ShAmt);
7428       computeGREV(Known.One, ShAmt);
7429       if (Opc == RISCVISD::GREVW)
7430         Known = Known.sext(BitWidth);
7431     }
7432     break;
7433   }
7434   case RISCVISD::READ_VLENB:
7435     // We assume VLENB is at least 16 bytes.
7436     Known.Zero.setLowBits(4);
7437     // We assume VLENB is no more than 65536 / 8 bytes.
7438     Known.Zero.setBitsFrom(14);
7439     break;
7440   case ISD::INTRINSIC_W_CHAIN: {
7441     unsigned IntNo = Op.getConstantOperandVal(1);
7442     switch (IntNo) {
7443     default:
7444       // We can't do anything for most intrinsics.
7445       break;
7446     case Intrinsic::riscv_vsetvli:
7447     case Intrinsic::riscv_vsetvlimax:
7448       // Assume that VL output is positive and would fit in an int32_t.
7449       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7450       if (BitWidth >= 32)
7451         Known.Zero.setBitsFrom(31);
7452       break;
7453     }
7454     break;
7455   }
7456   }
7457 }
7458 
7459 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7460     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7461     unsigned Depth) const {
7462   switch (Op.getOpcode()) {
7463   default:
7464     break;
7465   case RISCVISD::SELECT_CC: {
7466     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7467     if (Tmp == 1) return 1;  // Early out.
7468     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7469     return std::min(Tmp, Tmp2);
7470   }
7471   case RISCVISD::SLLW:
7472   case RISCVISD::SRAW:
7473   case RISCVISD::SRLW:
7474   case RISCVISD::DIVW:
7475   case RISCVISD::DIVUW:
7476   case RISCVISD::REMUW:
7477   case RISCVISD::ROLW:
7478   case RISCVISD::RORW:
7479   case RISCVISD::GREVW:
7480   case RISCVISD::GORCW:
7481   case RISCVISD::FSLW:
7482   case RISCVISD::FSRW:
7483   case RISCVISD::SHFLW:
7484   case RISCVISD::UNSHFLW:
7485   case RISCVISD::BCOMPRESSW:
7486   case RISCVISD::BDECOMPRESSW:
7487   case RISCVISD::FCVT_W_RTZ_RV64:
7488   case RISCVISD::FCVT_WU_RTZ_RV64:
7489     // TODO: As the result is sign-extended, this is conservatively correct. A
7490     // more precise answer could be calculated for SRAW depending on known
7491     // bits in the shift amount.
7492     return 33;
7493   case RISCVISD::SHFL:
7494   case RISCVISD::UNSHFL: {
7495     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7496     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7497     // will stay within the upper 32 bits. If there were more than 32 sign bits
7498     // before there will be at least 33 sign bits after.
7499     if (Op.getValueType() == MVT::i64 &&
7500         isa<ConstantSDNode>(Op.getOperand(1)) &&
7501         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7502       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7503       if (Tmp > 32)
7504         return 33;
7505     }
7506     break;
7507   }
7508   case RISCVISD::VMV_X_S:
7509     // The number of sign bits of the scalar result is computed by obtaining the
7510     // element type of the input vector operand, subtracting its width from the
7511     // XLEN, and then adding one (sign bit within the element type). If the
7512     // element type is wider than XLen, the least-significant XLEN bits are
7513     // taken.
7514     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7515       return 1;
7516     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7517   }
7518 
7519   return 1;
7520 }
7521 
7522 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7523                                                   MachineBasicBlock *BB) {
7524   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7525 
7526   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7527   // Should the count have wrapped while it was being read, we need to try
7528   // again.
7529   // ...
7530   // read:
7531   // rdcycleh x3 # load high word of cycle
7532   // rdcycle  x2 # load low word of cycle
7533   // rdcycleh x4 # load high word of cycle
7534   // bne x3, x4, read # check if high word reads match, otherwise try again
7535   // ...
7536 
7537   MachineFunction &MF = *BB->getParent();
7538   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7539   MachineFunction::iterator It = ++BB->getIterator();
7540 
7541   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7542   MF.insert(It, LoopMBB);
7543 
7544   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7545   MF.insert(It, DoneMBB);
7546 
7547   // Transfer the remainder of BB and its successor edges to DoneMBB.
7548   DoneMBB->splice(DoneMBB->begin(), BB,
7549                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7550   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7551 
7552   BB->addSuccessor(LoopMBB);
7553 
7554   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7555   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7556   Register LoReg = MI.getOperand(0).getReg();
7557   Register HiReg = MI.getOperand(1).getReg();
7558   DebugLoc DL = MI.getDebugLoc();
7559 
7560   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7561   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7562       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7563       .addReg(RISCV::X0);
7564   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7565       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7566       .addReg(RISCV::X0);
7567   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7568       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7569       .addReg(RISCV::X0);
7570 
7571   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7572       .addReg(HiReg)
7573       .addReg(ReadAgainReg)
7574       .addMBB(LoopMBB);
7575 
7576   LoopMBB->addSuccessor(LoopMBB);
7577   LoopMBB->addSuccessor(DoneMBB);
7578 
7579   MI.eraseFromParent();
7580 
7581   return DoneMBB;
7582 }
7583 
7584 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7585                                              MachineBasicBlock *BB) {
7586   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7587 
7588   MachineFunction &MF = *BB->getParent();
7589   DebugLoc DL = MI.getDebugLoc();
7590   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7591   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7592   Register LoReg = MI.getOperand(0).getReg();
7593   Register HiReg = MI.getOperand(1).getReg();
7594   Register SrcReg = MI.getOperand(2).getReg();
7595   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7596   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7597 
7598   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7599                           RI);
7600   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7601   MachineMemOperand *MMOLo =
7602       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7603   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7604       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7605   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7606       .addFrameIndex(FI)
7607       .addImm(0)
7608       .addMemOperand(MMOLo);
7609   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7610       .addFrameIndex(FI)
7611       .addImm(4)
7612       .addMemOperand(MMOHi);
7613   MI.eraseFromParent(); // The pseudo instruction is gone now.
7614   return BB;
7615 }
7616 
7617 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7618                                                  MachineBasicBlock *BB) {
7619   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7620          "Unexpected instruction");
7621 
7622   MachineFunction &MF = *BB->getParent();
7623   DebugLoc DL = MI.getDebugLoc();
7624   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7625   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7626   Register DstReg = MI.getOperand(0).getReg();
7627   Register LoReg = MI.getOperand(1).getReg();
7628   Register HiReg = MI.getOperand(2).getReg();
7629   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7630   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7631 
7632   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7633   MachineMemOperand *MMOLo =
7634       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7635   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7636       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7637   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7638       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7639       .addFrameIndex(FI)
7640       .addImm(0)
7641       .addMemOperand(MMOLo);
7642   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7643       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7644       .addFrameIndex(FI)
7645       .addImm(4)
7646       .addMemOperand(MMOHi);
7647   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7648   MI.eraseFromParent(); // The pseudo instruction is gone now.
7649   return BB;
7650 }
7651 
7652 static bool isSelectPseudo(MachineInstr &MI) {
7653   switch (MI.getOpcode()) {
7654   default:
7655     return false;
7656   case RISCV::Select_GPR_Using_CC_GPR:
7657   case RISCV::Select_FPR16_Using_CC_GPR:
7658   case RISCV::Select_FPR32_Using_CC_GPR:
7659   case RISCV::Select_FPR64_Using_CC_GPR:
7660     return true;
7661   }
7662 }
7663 
7664 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7665                                            MachineBasicBlock *BB,
7666                                            const RISCVSubtarget &Subtarget) {
7667   // To "insert" Select_* instructions, we actually have to insert the triangle
7668   // control-flow pattern.  The incoming instructions know the destination vreg
7669   // to set, the condition code register to branch on, the true/false values to
7670   // select between, and the condcode to use to select the appropriate branch.
7671   //
7672   // We produce the following control flow:
7673   //     HeadMBB
7674   //     |  \
7675   //     |  IfFalseMBB
7676   //     | /
7677   //    TailMBB
7678   //
7679   // When we find a sequence of selects we attempt to optimize their emission
7680   // by sharing the control flow. Currently we only handle cases where we have
7681   // multiple selects with the exact same condition (same LHS, RHS and CC).
7682   // The selects may be interleaved with other instructions if the other
7683   // instructions meet some requirements we deem safe:
7684   // - They are debug instructions. Otherwise,
7685   // - They do not have side-effects, do not access memory and their inputs do
7686   //   not depend on the results of the select pseudo-instructions.
7687   // The TrueV/FalseV operands of the selects cannot depend on the result of
7688   // previous selects in the sequence.
7689   // These conditions could be further relaxed. See the X86 target for a
7690   // related approach and more information.
7691   Register LHS = MI.getOperand(1).getReg();
7692   Register RHS = MI.getOperand(2).getReg();
7693   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7694 
7695   SmallVector<MachineInstr *, 4> SelectDebugValues;
7696   SmallSet<Register, 4> SelectDests;
7697   SelectDests.insert(MI.getOperand(0).getReg());
7698 
7699   MachineInstr *LastSelectPseudo = &MI;
7700 
7701   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7702        SequenceMBBI != E; ++SequenceMBBI) {
7703     if (SequenceMBBI->isDebugInstr())
7704       continue;
7705     else if (isSelectPseudo(*SequenceMBBI)) {
7706       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7707           SequenceMBBI->getOperand(2).getReg() != RHS ||
7708           SequenceMBBI->getOperand(3).getImm() != CC ||
7709           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7710           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7711         break;
7712       LastSelectPseudo = &*SequenceMBBI;
7713       SequenceMBBI->collectDebugValues(SelectDebugValues);
7714       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7715     } else {
7716       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7717           SequenceMBBI->mayLoadOrStore())
7718         break;
7719       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7720             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7721           }))
7722         break;
7723     }
7724   }
7725 
7726   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7727   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7728   DebugLoc DL = MI.getDebugLoc();
7729   MachineFunction::iterator I = ++BB->getIterator();
7730 
7731   MachineBasicBlock *HeadMBB = BB;
7732   MachineFunction *F = BB->getParent();
7733   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7734   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7735 
7736   F->insert(I, IfFalseMBB);
7737   F->insert(I, TailMBB);
7738 
7739   // Transfer debug instructions associated with the selects to TailMBB.
7740   for (MachineInstr *DebugInstr : SelectDebugValues) {
7741     TailMBB->push_back(DebugInstr->removeFromParent());
7742   }
7743 
7744   // Move all instructions after the sequence to TailMBB.
7745   TailMBB->splice(TailMBB->end(), HeadMBB,
7746                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7747   // Update machine-CFG edges by transferring all successors of the current
7748   // block to the new block which will contain the Phi nodes for the selects.
7749   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7750   // Set the successors for HeadMBB.
7751   HeadMBB->addSuccessor(IfFalseMBB);
7752   HeadMBB->addSuccessor(TailMBB);
7753 
7754   // Insert appropriate branch.
7755   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7756     .addReg(LHS)
7757     .addReg(RHS)
7758     .addMBB(TailMBB);
7759 
7760   // IfFalseMBB just falls through to TailMBB.
7761   IfFalseMBB->addSuccessor(TailMBB);
7762 
7763   // Create PHIs for all of the select pseudo-instructions.
7764   auto SelectMBBI = MI.getIterator();
7765   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7766   auto InsertionPoint = TailMBB->begin();
7767   while (SelectMBBI != SelectEnd) {
7768     auto Next = std::next(SelectMBBI);
7769     if (isSelectPseudo(*SelectMBBI)) {
7770       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7771       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7772               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7773           .addReg(SelectMBBI->getOperand(4).getReg())
7774           .addMBB(HeadMBB)
7775           .addReg(SelectMBBI->getOperand(5).getReg())
7776           .addMBB(IfFalseMBB);
7777       SelectMBBI->eraseFromParent();
7778     }
7779     SelectMBBI = Next;
7780   }
7781 
7782   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7783   return TailMBB;
7784 }
7785 
7786 MachineBasicBlock *
7787 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7788                                                  MachineBasicBlock *BB) const {
7789   switch (MI.getOpcode()) {
7790   default:
7791     llvm_unreachable("Unexpected instr type to insert");
7792   case RISCV::ReadCycleWide:
7793     assert(!Subtarget.is64Bit() &&
7794            "ReadCycleWrite is only to be used on riscv32");
7795     return emitReadCycleWidePseudo(MI, BB);
7796   case RISCV::Select_GPR_Using_CC_GPR:
7797   case RISCV::Select_FPR16_Using_CC_GPR:
7798   case RISCV::Select_FPR32_Using_CC_GPR:
7799   case RISCV::Select_FPR64_Using_CC_GPR:
7800     return emitSelectPseudo(MI, BB, Subtarget);
7801   case RISCV::BuildPairF64Pseudo:
7802     return emitBuildPairF64Pseudo(MI, BB);
7803   case RISCV::SplitF64Pseudo:
7804     return emitSplitF64Pseudo(MI, BB);
7805   }
7806 }
7807 
7808 // Calling Convention Implementation.
7809 // The expectations for frontend ABI lowering vary from target to target.
7810 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7811 // details, but this is a longer term goal. For now, we simply try to keep the
7812 // role of the frontend as simple and well-defined as possible. The rules can
7813 // be summarised as:
7814 // * Never split up large scalar arguments. We handle them here.
7815 // * If a hardfloat calling convention is being used, and the struct may be
7816 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7817 // available, then pass as two separate arguments. If either the GPRs or FPRs
7818 // are exhausted, then pass according to the rule below.
7819 // * If a struct could never be passed in registers or directly in a stack
7820 // slot (as it is larger than 2*XLEN and the floating point rules don't
7821 // apply), then pass it using a pointer with the byval attribute.
7822 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7823 // word-sized array or a 2*XLEN scalar (depending on alignment).
7824 // * The frontend can determine whether a struct is returned by reference or
7825 // not based on its size and fields. If it will be returned by reference, the
7826 // frontend must modify the prototype so a pointer with the sret annotation is
7827 // passed as the first argument. This is not necessary for large scalar
7828 // returns.
7829 // * Struct return values and varargs should be coerced to structs containing
7830 // register-size fields in the same situations they would be for fixed
7831 // arguments.
7832 
7833 static const MCPhysReg ArgGPRs[] = {
7834   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7835   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7836 };
7837 static const MCPhysReg ArgFPR16s[] = {
7838   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7839   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7840 };
7841 static const MCPhysReg ArgFPR32s[] = {
7842   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7843   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7844 };
7845 static const MCPhysReg ArgFPR64s[] = {
7846   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7847   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7848 };
7849 // This is an interim calling convention and it may be changed in the future.
7850 static const MCPhysReg ArgVRs[] = {
7851     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7852     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7853     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7854 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7855                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7856                                      RISCV::V20M2, RISCV::V22M2};
7857 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7858                                      RISCV::V20M4};
7859 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7860 
7861 // Pass a 2*XLEN argument that has been split into two XLEN values through
7862 // registers or the stack as necessary.
7863 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7864                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7865                                 MVT ValVT2, MVT LocVT2,
7866                                 ISD::ArgFlagsTy ArgFlags2) {
7867   unsigned XLenInBytes = XLen / 8;
7868   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7869     // At least one half can be passed via register.
7870     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7871                                      VA1.getLocVT(), CCValAssign::Full));
7872   } else {
7873     // Both halves must be passed on the stack, with proper alignment.
7874     Align StackAlign =
7875         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7876     State.addLoc(
7877         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7878                             State.AllocateStack(XLenInBytes, StackAlign),
7879                             VA1.getLocVT(), CCValAssign::Full));
7880     State.addLoc(CCValAssign::getMem(
7881         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7882         LocVT2, CCValAssign::Full));
7883     return false;
7884   }
7885 
7886   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7887     // The second half can also be passed via register.
7888     State.addLoc(
7889         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7890   } else {
7891     // The second half is passed via the stack, without additional alignment.
7892     State.addLoc(CCValAssign::getMem(
7893         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7894         LocVT2, CCValAssign::Full));
7895   }
7896 
7897   return false;
7898 }
7899 
7900 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7901                                Optional<unsigned> FirstMaskArgument,
7902                                CCState &State, const RISCVTargetLowering &TLI) {
7903   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7904   if (RC == &RISCV::VRRegClass) {
7905     // Assign the first mask argument to V0.
7906     // This is an interim calling convention and it may be changed in the
7907     // future.
7908     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7909       return State.AllocateReg(RISCV::V0);
7910     return State.AllocateReg(ArgVRs);
7911   }
7912   if (RC == &RISCV::VRM2RegClass)
7913     return State.AllocateReg(ArgVRM2s);
7914   if (RC == &RISCV::VRM4RegClass)
7915     return State.AllocateReg(ArgVRM4s);
7916   if (RC == &RISCV::VRM8RegClass)
7917     return State.AllocateReg(ArgVRM8s);
7918   llvm_unreachable("Unhandled register class for ValueType");
7919 }
7920 
7921 // Implements the RISC-V calling convention. Returns true upon failure.
7922 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7923                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7924                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7925                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7926                      Optional<unsigned> FirstMaskArgument) {
7927   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7928   assert(XLen == 32 || XLen == 64);
7929   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7930 
7931   // Any return value split in to more than two values can't be returned
7932   // directly. Vectors are returned via the available vector registers.
7933   if (!LocVT.isVector() && IsRet && ValNo > 1)
7934     return true;
7935 
7936   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7937   // variadic argument, or if no F16/F32 argument registers are available.
7938   bool UseGPRForF16_F32 = true;
7939   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7940   // variadic argument, or if no F64 argument registers are available.
7941   bool UseGPRForF64 = true;
7942 
7943   switch (ABI) {
7944   default:
7945     llvm_unreachable("Unexpected ABI");
7946   case RISCVABI::ABI_ILP32:
7947   case RISCVABI::ABI_LP64:
7948     break;
7949   case RISCVABI::ABI_ILP32F:
7950   case RISCVABI::ABI_LP64F:
7951     UseGPRForF16_F32 = !IsFixed;
7952     break;
7953   case RISCVABI::ABI_ILP32D:
7954   case RISCVABI::ABI_LP64D:
7955     UseGPRForF16_F32 = !IsFixed;
7956     UseGPRForF64 = !IsFixed;
7957     break;
7958   }
7959 
7960   // FPR16, FPR32, and FPR64 alias each other.
7961   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7962     UseGPRForF16_F32 = true;
7963     UseGPRForF64 = true;
7964   }
7965 
7966   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7967   // similar local variables rather than directly checking against the target
7968   // ABI.
7969 
7970   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7971     LocVT = XLenVT;
7972     LocInfo = CCValAssign::BCvt;
7973   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7974     LocVT = MVT::i64;
7975     LocInfo = CCValAssign::BCvt;
7976   }
7977 
7978   // If this is a variadic argument, the RISC-V calling convention requires
7979   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7980   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7981   // be used regardless of whether the original argument was split during
7982   // legalisation or not. The argument will not be passed by registers if the
7983   // original type is larger than 2*XLEN, so the register alignment rule does
7984   // not apply.
7985   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7986   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7987       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7988     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7989     // Skip 'odd' register if necessary.
7990     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7991       State.AllocateReg(ArgGPRs);
7992   }
7993 
7994   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7995   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7996       State.getPendingArgFlags();
7997 
7998   assert(PendingLocs.size() == PendingArgFlags.size() &&
7999          "PendingLocs and PendingArgFlags out of sync");
8000 
8001   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8002   // registers are exhausted.
8003   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8004     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8005            "Can't lower f64 if it is split");
8006     // Depending on available argument GPRS, f64 may be passed in a pair of
8007     // GPRs, split between a GPR and the stack, or passed completely on the
8008     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8009     // cases.
8010     Register Reg = State.AllocateReg(ArgGPRs);
8011     LocVT = MVT::i32;
8012     if (!Reg) {
8013       unsigned StackOffset = State.AllocateStack(8, Align(8));
8014       State.addLoc(
8015           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8016       return false;
8017     }
8018     if (!State.AllocateReg(ArgGPRs))
8019       State.AllocateStack(4, Align(4));
8020     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8021     return false;
8022   }
8023 
8024   // Fixed-length vectors are located in the corresponding scalable-vector
8025   // container types.
8026   if (ValVT.isFixedLengthVector())
8027     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8028 
8029   // Split arguments might be passed indirectly, so keep track of the pending
8030   // values. Split vectors are passed via a mix of registers and indirectly, so
8031   // treat them as we would any other argument.
8032   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8033     LocVT = XLenVT;
8034     LocInfo = CCValAssign::Indirect;
8035     PendingLocs.push_back(
8036         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8037     PendingArgFlags.push_back(ArgFlags);
8038     if (!ArgFlags.isSplitEnd()) {
8039       return false;
8040     }
8041   }
8042 
8043   // If the split argument only had two elements, it should be passed directly
8044   // in registers or on the stack.
8045   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8046       PendingLocs.size() <= 2) {
8047     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8048     // Apply the normal calling convention rules to the first half of the
8049     // split argument.
8050     CCValAssign VA = PendingLocs[0];
8051     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8052     PendingLocs.clear();
8053     PendingArgFlags.clear();
8054     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8055                                ArgFlags);
8056   }
8057 
8058   // Allocate to a register if possible, or else a stack slot.
8059   Register Reg;
8060   unsigned StoreSizeBytes = XLen / 8;
8061   Align StackAlign = Align(XLen / 8);
8062 
8063   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8064     Reg = State.AllocateReg(ArgFPR16s);
8065   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8066     Reg = State.AllocateReg(ArgFPR32s);
8067   else if (ValVT == MVT::f64 && !UseGPRForF64)
8068     Reg = State.AllocateReg(ArgFPR64s);
8069   else if (ValVT.isVector()) {
8070     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8071     if (!Reg) {
8072       // For return values, the vector must be passed fully via registers or
8073       // via the stack.
8074       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8075       // but we're using all of them.
8076       if (IsRet)
8077         return true;
8078       // Try using a GPR to pass the address
8079       if ((Reg = State.AllocateReg(ArgGPRs))) {
8080         LocVT = XLenVT;
8081         LocInfo = CCValAssign::Indirect;
8082       } else if (ValVT.isScalableVector()) {
8083         report_fatal_error("Unable to pass scalable vector types on the stack");
8084       } else {
8085         // Pass fixed-length vectors on the stack.
8086         LocVT = ValVT;
8087         StoreSizeBytes = ValVT.getStoreSize();
8088         // Align vectors to their element sizes, being careful for vXi1
8089         // vectors.
8090         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8091       }
8092     }
8093   } else {
8094     Reg = State.AllocateReg(ArgGPRs);
8095   }
8096 
8097   unsigned StackOffset =
8098       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8099 
8100   // If we reach this point and PendingLocs is non-empty, we must be at the
8101   // end of a split argument that must be passed indirectly.
8102   if (!PendingLocs.empty()) {
8103     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8104     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8105 
8106     for (auto &It : PendingLocs) {
8107       if (Reg)
8108         It.convertToReg(Reg);
8109       else
8110         It.convertToMem(StackOffset);
8111       State.addLoc(It);
8112     }
8113     PendingLocs.clear();
8114     PendingArgFlags.clear();
8115     return false;
8116   }
8117 
8118   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8119           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8120          "Expected an XLenVT or vector types at this stage");
8121 
8122   if (Reg) {
8123     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8124     return false;
8125   }
8126 
8127   // When a floating-point value is passed on the stack, no bit-conversion is
8128   // needed.
8129   if (ValVT.isFloatingPoint()) {
8130     LocVT = ValVT;
8131     LocInfo = CCValAssign::Full;
8132   }
8133   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8134   return false;
8135 }
8136 
8137 template <typename ArgTy>
8138 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8139   for (const auto &ArgIdx : enumerate(Args)) {
8140     MVT ArgVT = ArgIdx.value().VT;
8141     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8142       return ArgIdx.index();
8143   }
8144   return None;
8145 }
8146 
8147 void RISCVTargetLowering::analyzeInputArgs(
8148     MachineFunction &MF, CCState &CCInfo,
8149     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8150     RISCVCCAssignFn Fn) const {
8151   unsigned NumArgs = Ins.size();
8152   FunctionType *FType = MF.getFunction().getFunctionType();
8153 
8154   Optional<unsigned> FirstMaskArgument;
8155   if (Subtarget.hasVInstructions())
8156     FirstMaskArgument = preAssignMask(Ins);
8157 
8158   for (unsigned i = 0; i != NumArgs; ++i) {
8159     MVT ArgVT = Ins[i].VT;
8160     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8161 
8162     Type *ArgTy = nullptr;
8163     if (IsRet)
8164       ArgTy = FType->getReturnType();
8165     else if (Ins[i].isOrigArg())
8166       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8167 
8168     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8169     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8170            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8171            FirstMaskArgument)) {
8172       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8173                         << EVT(ArgVT).getEVTString() << '\n');
8174       llvm_unreachable(nullptr);
8175     }
8176   }
8177 }
8178 
8179 void RISCVTargetLowering::analyzeOutputArgs(
8180     MachineFunction &MF, CCState &CCInfo,
8181     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8182     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8183   unsigned NumArgs = Outs.size();
8184 
8185   Optional<unsigned> FirstMaskArgument;
8186   if (Subtarget.hasVInstructions())
8187     FirstMaskArgument = preAssignMask(Outs);
8188 
8189   for (unsigned i = 0; i != NumArgs; i++) {
8190     MVT ArgVT = Outs[i].VT;
8191     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8192     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8193 
8194     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8195     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8196            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8197            FirstMaskArgument)) {
8198       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8199                         << EVT(ArgVT).getEVTString() << "\n");
8200       llvm_unreachable(nullptr);
8201     }
8202   }
8203 }
8204 
8205 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8206 // values.
8207 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8208                                    const CCValAssign &VA, const SDLoc &DL,
8209                                    const RISCVSubtarget &Subtarget) {
8210   switch (VA.getLocInfo()) {
8211   default:
8212     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8213   case CCValAssign::Full:
8214     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8215       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8216     break;
8217   case CCValAssign::BCvt:
8218     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8219       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8220     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8221       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8222     else
8223       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8224     break;
8225   }
8226   return Val;
8227 }
8228 
8229 // The caller is responsible for loading the full value if the argument is
8230 // passed with CCValAssign::Indirect.
8231 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8232                                 const CCValAssign &VA, const SDLoc &DL,
8233                                 const RISCVTargetLowering &TLI) {
8234   MachineFunction &MF = DAG.getMachineFunction();
8235   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8236   EVT LocVT = VA.getLocVT();
8237   SDValue Val;
8238   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8239   Register VReg = RegInfo.createVirtualRegister(RC);
8240   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8241   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8242 
8243   if (VA.getLocInfo() == CCValAssign::Indirect)
8244     return Val;
8245 
8246   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8247 }
8248 
8249 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8250                                    const CCValAssign &VA, const SDLoc &DL,
8251                                    const RISCVSubtarget &Subtarget) {
8252   EVT LocVT = VA.getLocVT();
8253 
8254   switch (VA.getLocInfo()) {
8255   default:
8256     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8257   case CCValAssign::Full:
8258     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8259       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8260     break;
8261   case CCValAssign::BCvt:
8262     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8263       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8264     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8265       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8266     else
8267       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8268     break;
8269   }
8270   return Val;
8271 }
8272 
8273 // The caller is responsible for loading the full value if the argument is
8274 // passed with CCValAssign::Indirect.
8275 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8276                                 const CCValAssign &VA, const SDLoc &DL) {
8277   MachineFunction &MF = DAG.getMachineFunction();
8278   MachineFrameInfo &MFI = MF.getFrameInfo();
8279   EVT LocVT = VA.getLocVT();
8280   EVT ValVT = VA.getValVT();
8281   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8282   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8283                                  /*Immutable=*/true);
8284   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8285   SDValue Val;
8286 
8287   ISD::LoadExtType ExtType;
8288   switch (VA.getLocInfo()) {
8289   default:
8290     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8291   case CCValAssign::Full:
8292   case CCValAssign::Indirect:
8293   case CCValAssign::BCvt:
8294     ExtType = ISD::NON_EXTLOAD;
8295     break;
8296   }
8297   Val = DAG.getExtLoad(
8298       ExtType, DL, LocVT, Chain, FIN,
8299       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8300   return Val;
8301 }
8302 
8303 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8304                                        const CCValAssign &VA, const SDLoc &DL) {
8305   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8306          "Unexpected VA");
8307   MachineFunction &MF = DAG.getMachineFunction();
8308   MachineFrameInfo &MFI = MF.getFrameInfo();
8309   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8310 
8311   if (VA.isMemLoc()) {
8312     // f64 is passed on the stack.
8313     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8314     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8315     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8316                        MachinePointerInfo::getFixedStack(MF, FI));
8317   }
8318 
8319   assert(VA.isRegLoc() && "Expected register VA assignment");
8320 
8321   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8322   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8323   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8324   SDValue Hi;
8325   if (VA.getLocReg() == RISCV::X17) {
8326     // Second half of f64 is passed on the stack.
8327     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8328     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8329     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8330                      MachinePointerInfo::getFixedStack(MF, FI));
8331   } else {
8332     // Second half of f64 is passed in another GPR.
8333     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8334     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8335     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8336   }
8337   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8338 }
8339 
8340 // FastCC has less than 1% performance improvement for some particular
8341 // benchmark. But theoretically, it may has benenfit for some cases.
8342 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8343                             unsigned ValNo, MVT ValVT, MVT LocVT,
8344                             CCValAssign::LocInfo LocInfo,
8345                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8346                             bool IsFixed, bool IsRet, Type *OrigTy,
8347                             const RISCVTargetLowering &TLI,
8348                             Optional<unsigned> FirstMaskArgument) {
8349 
8350   // X5 and X6 might be used for save-restore libcall.
8351   static const MCPhysReg GPRList[] = {
8352       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8353       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8354       RISCV::X29, RISCV::X30, RISCV::X31};
8355 
8356   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8357     if (unsigned Reg = State.AllocateReg(GPRList)) {
8358       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8359       return false;
8360     }
8361   }
8362 
8363   if (LocVT == MVT::f16) {
8364     static const MCPhysReg FPR16List[] = {
8365         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8366         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8367         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8368         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8369     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8370       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8371       return false;
8372     }
8373   }
8374 
8375   if (LocVT == MVT::f32) {
8376     static const MCPhysReg FPR32List[] = {
8377         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8378         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8379         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8380         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8381     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8382       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8383       return false;
8384     }
8385   }
8386 
8387   if (LocVT == MVT::f64) {
8388     static const MCPhysReg FPR64List[] = {
8389         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8390         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8391         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8392         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8393     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8394       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8395       return false;
8396     }
8397   }
8398 
8399   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8400     unsigned Offset4 = State.AllocateStack(4, Align(4));
8401     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8402     return false;
8403   }
8404 
8405   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8406     unsigned Offset5 = State.AllocateStack(8, Align(8));
8407     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8408     return false;
8409   }
8410 
8411   if (LocVT.isVector()) {
8412     if (unsigned Reg =
8413             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8414       // Fixed-length vectors are located in the corresponding scalable-vector
8415       // container types.
8416       if (ValVT.isFixedLengthVector())
8417         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8418       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8419     } else {
8420       // Try and pass the address via a "fast" GPR.
8421       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8422         LocInfo = CCValAssign::Indirect;
8423         LocVT = TLI.getSubtarget().getXLenVT();
8424         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8425       } else if (ValVT.isFixedLengthVector()) {
8426         auto StackAlign =
8427             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8428         unsigned StackOffset =
8429             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8430         State.addLoc(
8431             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8432       } else {
8433         // Can't pass scalable vectors on the stack.
8434         return true;
8435       }
8436     }
8437 
8438     return false;
8439   }
8440 
8441   return true; // CC didn't match.
8442 }
8443 
8444 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8445                          CCValAssign::LocInfo LocInfo,
8446                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8447 
8448   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8449     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8450     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8451     static const MCPhysReg GPRList[] = {
8452         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8453         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8454     if (unsigned Reg = State.AllocateReg(GPRList)) {
8455       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8456       return false;
8457     }
8458   }
8459 
8460   if (LocVT == MVT::f32) {
8461     // Pass in STG registers: F1, ..., F6
8462     //                        fs0 ... fs5
8463     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8464                                           RISCV::F18_F, RISCV::F19_F,
8465                                           RISCV::F20_F, RISCV::F21_F};
8466     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8467       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8468       return false;
8469     }
8470   }
8471 
8472   if (LocVT == MVT::f64) {
8473     // Pass in STG registers: D1, ..., D6
8474     //                        fs6 ... fs11
8475     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8476                                           RISCV::F24_D, RISCV::F25_D,
8477                                           RISCV::F26_D, RISCV::F27_D};
8478     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8479       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8480       return false;
8481     }
8482   }
8483 
8484   report_fatal_error("No registers left in GHC calling convention");
8485   return true;
8486 }
8487 
8488 // Transform physical registers into virtual registers.
8489 SDValue RISCVTargetLowering::LowerFormalArguments(
8490     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8491     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8492     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8493 
8494   MachineFunction &MF = DAG.getMachineFunction();
8495 
8496   switch (CallConv) {
8497   default:
8498     report_fatal_error("Unsupported calling convention");
8499   case CallingConv::C:
8500   case CallingConv::Fast:
8501     break;
8502   case CallingConv::GHC:
8503     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8504         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8505       report_fatal_error(
8506         "GHC calling convention requires the F and D instruction set extensions");
8507   }
8508 
8509   const Function &Func = MF.getFunction();
8510   if (Func.hasFnAttribute("interrupt")) {
8511     if (!Func.arg_empty())
8512       report_fatal_error(
8513         "Functions with the interrupt attribute cannot have arguments!");
8514 
8515     StringRef Kind =
8516       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8517 
8518     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8519       report_fatal_error(
8520         "Function interrupt attribute argument not supported!");
8521   }
8522 
8523   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8524   MVT XLenVT = Subtarget.getXLenVT();
8525   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8526   // Used with vargs to acumulate store chains.
8527   std::vector<SDValue> OutChains;
8528 
8529   // Assign locations to all of the incoming arguments.
8530   SmallVector<CCValAssign, 16> ArgLocs;
8531   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8532 
8533   if (CallConv == CallingConv::GHC)
8534     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8535   else
8536     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8537                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8538                                                    : CC_RISCV);
8539 
8540   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8541     CCValAssign &VA = ArgLocs[i];
8542     SDValue ArgValue;
8543     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8544     // case.
8545     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8546       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8547     else if (VA.isRegLoc())
8548       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8549     else
8550       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8551 
8552     if (VA.getLocInfo() == CCValAssign::Indirect) {
8553       // If the original argument was split and passed by reference (e.g. i128
8554       // on RV32), we need to load all parts of it here (using the same
8555       // address). Vectors may be partly split to registers and partly to the
8556       // stack, in which case the base address is partly offset and subsequent
8557       // stores are relative to that.
8558       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8559                                    MachinePointerInfo()));
8560       unsigned ArgIndex = Ins[i].OrigArgIndex;
8561       unsigned ArgPartOffset = Ins[i].PartOffset;
8562       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8563       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8564         CCValAssign &PartVA = ArgLocs[i + 1];
8565         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8566         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8567         if (PartVA.getValVT().isScalableVector())
8568           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8569         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8570         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8571                                      MachinePointerInfo()));
8572         ++i;
8573       }
8574       continue;
8575     }
8576     InVals.push_back(ArgValue);
8577   }
8578 
8579   if (IsVarArg) {
8580     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8581     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8582     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8583     MachineFrameInfo &MFI = MF.getFrameInfo();
8584     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8585     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8586 
8587     // Offset of the first variable argument from stack pointer, and size of
8588     // the vararg save area. For now, the varargs save area is either zero or
8589     // large enough to hold a0-a7.
8590     int VaArgOffset, VarArgsSaveSize;
8591 
8592     // If all registers are allocated, then all varargs must be passed on the
8593     // stack and we don't need to save any argregs.
8594     if (ArgRegs.size() == Idx) {
8595       VaArgOffset = CCInfo.getNextStackOffset();
8596       VarArgsSaveSize = 0;
8597     } else {
8598       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8599       VaArgOffset = -VarArgsSaveSize;
8600     }
8601 
8602     // Record the frame index of the first variable argument
8603     // which is a value necessary to VASTART.
8604     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8605     RVFI->setVarArgsFrameIndex(FI);
8606 
8607     // If saving an odd number of registers then create an extra stack slot to
8608     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8609     // offsets to even-numbered registered remain 2*XLEN-aligned.
8610     if (Idx % 2) {
8611       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8612       VarArgsSaveSize += XLenInBytes;
8613     }
8614 
8615     // Copy the integer registers that may have been used for passing varargs
8616     // to the vararg save area.
8617     for (unsigned I = Idx; I < ArgRegs.size();
8618          ++I, VaArgOffset += XLenInBytes) {
8619       const Register Reg = RegInfo.createVirtualRegister(RC);
8620       RegInfo.addLiveIn(ArgRegs[I], Reg);
8621       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8622       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8623       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8624       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8625                                    MachinePointerInfo::getFixedStack(MF, FI));
8626       cast<StoreSDNode>(Store.getNode())
8627           ->getMemOperand()
8628           ->setValue((Value *)nullptr);
8629       OutChains.push_back(Store);
8630     }
8631     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8632   }
8633 
8634   // All stores are grouped in one node to allow the matching between
8635   // the size of Ins and InVals. This only happens for vararg functions.
8636   if (!OutChains.empty()) {
8637     OutChains.push_back(Chain);
8638     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8639   }
8640 
8641   return Chain;
8642 }
8643 
8644 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8645 /// for tail call optimization.
8646 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8647 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8648     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8649     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8650 
8651   auto &Callee = CLI.Callee;
8652   auto CalleeCC = CLI.CallConv;
8653   auto &Outs = CLI.Outs;
8654   auto &Caller = MF.getFunction();
8655   auto CallerCC = Caller.getCallingConv();
8656 
8657   // Exception-handling functions need a special set of instructions to
8658   // indicate a return to the hardware. Tail-calling another function would
8659   // probably break this.
8660   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8661   // should be expanded as new function attributes are introduced.
8662   if (Caller.hasFnAttribute("interrupt"))
8663     return false;
8664 
8665   // Do not tail call opt if the stack is used to pass parameters.
8666   if (CCInfo.getNextStackOffset() != 0)
8667     return false;
8668 
8669   // Do not tail call opt if any parameters need to be passed indirectly.
8670   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8671   // passed indirectly. So the address of the value will be passed in a
8672   // register, or if not available, then the address is put on the stack. In
8673   // order to pass indirectly, space on the stack often needs to be allocated
8674   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8675   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8676   // are passed CCValAssign::Indirect.
8677   for (auto &VA : ArgLocs)
8678     if (VA.getLocInfo() == CCValAssign::Indirect)
8679       return false;
8680 
8681   // Do not tail call opt if either caller or callee uses struct return
8682   // semantics.
8683   auto IsCallerStructRet = Caller.hasStructRetAttr();
8684   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8685   if (IsCallerStructRet || IsCalleeStructRet)
8686     return false;
8687 
8688   // Externally-defined functions with weak linkage should not be
8689   // tail-called. The behaviour of branch instructions in this situation (as
8690   // used for tail calls) is implementation-defined, so we cannot rely on the
8691   // linker replacing the tail call with a return.
8692   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8693     const GlobalValue *GV = G->getGlobal();
8694     if (GV->hasExternalWeakLinkage())
8695       return false;
8696   }
8697 
8698   // The callee has to preserve all registers the caller needs to preserve.
8699   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8700   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8701   if (CalleeCC != CallerCC) {
8702     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8703     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8704       return false;
8705   }
8706 
8707   // Byval parameters hand the function a pointer directly into the stack area
8708   // we want to reuse during a tail call. Working around this *is* possible
8709   // but less efficient and uglier in LowerCall.
8710   for (auto &Arg : Outs)
8711     if (Arg.Flags.isByVal())
8712       return false;
8713 
8714   return true;
8715 }
8716 
8717 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8718   return DAG.getDataLayout().getPrefTypeAlign(
8719       VT.getTypeForEVT(*DAG.getContext()));
8720 }
8721 
8722 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8723 // and output parameter nodes.
8724 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8725                                        SmallVectorImpl<SDValue> &InVals) const {
8726   SelectionDAG &DAG = CLI.DAG;
8727   SDLoc &DL = CLI.DL;
8728   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8729   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8730   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8731   SDValue Chain = CLI.Chain;
8732   SDValue Callee = CLI.Callee;
8733   bool &IsTailCall = CLI.IsTailCall;
8734   CallingConv::ID CallConv = CLI.CallConv;
8735   bool IsVarArg = CLI.IsVarArg;
8736   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8737   MVT XLenVT = Subtarget.getXLenVT();
8738 
8739   MachineFunction &MF = DAG.getMachineFunction();
8740 
8741   // Analyze the operands of the call, assigning locations to each operand.
8742   SmallVector<CCValAssign, 16> ArgLocs;
8743   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8744 
8745   if (CallConv == CallingConv::GHC)
8746     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8747   else
8748     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8749                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8750                                                     : CC_RISCV);
8751 
8752   // Check if it's really possible to do a tail call.
8753   if (IsTailCall)
8754     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8755 
8756   if (IsTailCall)
8757     ++NumTailCalls;
8758   else if (CLI.CB && CLI.CB->isMustTailCall())
8759     report_fatal_error("failed to perform tail call elimination on a call "
8760                        "site marked musttail");
8761 
8762   // Get a count of how many bytes are to be pushed on the stack.
8763   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8764 
8765   // Create local copies for byval args
8766   SmallVector<SDValue, 8> ByValArgs;
8767   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8768     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8769     if (!Flags.isByVal())
8770       continue;
8771 
8772     SDValue Arg = OutVals[i];
8773     unsigned Size = Flags.getByValSize();
8774     Align Alignment = Flags.getNonZeroByValAlign();
8775 
8776     int FI =
8777         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8778     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8779     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8780 
8781     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8782                           /*IsVolatile=*/false,
8783                           /*AlwaysInline=*/false, IsTailCall,
8784                           MachinePointerInfo(), MachinePointerInfo());
8785     ByValArgs.push_back(FIPtr);
8786   }
8787 
8788   if (!IsTailCall)
8789     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8790 
8791   // Copy argument values to their designated locations.
8792   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8793   SmallVector<SDValue, 8> MemOpChains;
8794   SDValue StackPtr;
8795   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8796     CCValAssign &VA = ArgLocs[i];
8797     SDValue ArgValue = OutVals[i];
8798     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8799 
8800     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8801     bool IsF64OnRV32DSoftABI =
8802         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8803     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8804       SDValue SplitF64 = DAG.getNode(
8805           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8806       SDValue Lo = SplitF64.getValue(0);
8807       SDValue Hi = SplitF64.getValue(1);
8808 
8809       Register RegLo = VA.getLocReg();
8810       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8811 
8812       if (RegLo == RISCV::X17) {
8813         // Second half of f64 is passed on the stack.
8814         // Work out the address of the stack slot.
8815         if (!StackPtr.getNode())
8816           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8817         // Emit the store.
8818         MemOpChains.push_back(
8819             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8820       } else {
8821         // Second half of f64 is passed in another GPR.
8822         assert(RegLo < RISCV::X31 && "Invalid register pair");
8823         Register RegHigh = RegLo + 1;
8824         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8825       }
8826       continue;
8827     }
8828 
8829     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8830     // as any other MemLoc.
8831 
8832     // Promote the value if needed.
8833     // For now, only handle fully promoted and indirect arguments.
8834     if (VA.getLocInfo() == CCValAssign::Indirect) {
8835       // Store the argument in a stack slot and pass its address.
8836       Align StackAlign =
8837           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8838                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8839       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8840       // If the original argument was split (e.g. i128), we need
8841       // to store the required parts of it here (and pass just one address).
8842       // Vectors may be partly split to registers and partly to the stack, in
8843       // which case the base address is partly offset and subsequent stores are
8844       // relative to that.
8845       unsigned ArgIndex = Outs[i].OrigArgIndex;
8846       unsigned ArgPartOffset = Outs[i].PartOffset;
8847       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8848       // Calculate the total size to store. We don't have access to what we're
8849       // actually storing other than performing the loop and collecting the
8850       // info.
8851       SmallVector<std::pair<SDValue, SDValue>> Parts;
8852       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8853         SDValue PartValue = OutVals[i + 1];
8854         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8855         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8856         EVT PartVT = PartValue.getValueType();
8857         if (PartVT.isScalableVector())
8858           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8859         StoredSize += PartVT.getStoreSize();
8860         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8861         Parts.push_back(std::make_pair(PartValue, Offset));
8862         ++i;
8863       }
8864       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8865       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8866       MemOpChains.push_back(
8867           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8868                        MachinePointerInfo::getFixedStack(MF, FI)));
8869       for (const auto &Part : Parts) {
8870         SDValue PartValue = Part.first;
8871         SDValue PartOffset = Part.second;
8872         SDValue Address =
8873             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8874         MemOpChains.push_back(
8875             DAG.getStore(Chain, DL, PartValue, Address,
8876                          MachinePointerInfo::getFixedStack(MF, FI)));
8877       }
8878       ArgValue = SpillSlot;
8879     } else {
8880       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8881     }
8882 
8883     // Use local copy if it is a byval arg.
8884     if (Flags.isByVal())
8885       ArgValue = ByValArgs[j++];
8886 
8887     if (VA.isRegLoc()) {
8888       // Queue up the argument copies and emit them at the end.
8889       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8890     } else {
8891       assert(VA.isMemLoc() && "Argument not register or memory");
8892       assert(!IsTailCall && "Tail call not allowed if stack is used "
8893                             "for passing parameters");
8894 
8895       // Work out the address of the stack slot.
8896       if (!StackPtr.getNode())
8897         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8898       SDValue Address =
8899           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8900                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8901 
8902       // Emit the store.
8903       MemOpChains.push_back(
8904           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8905     }
8906   }
8907 
8908   // Join the stores, which are independent of one another.
8909   if (!MemOpChains.empty())
8910     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8911 
8912   SDValue Glue;
8913 
8914   // Build a sequence of copy-to-reg nodes, chained and glued together.
8915   for (auto &Reg : RegsToPass) {
8916     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8917     Glue = Chain.getValue(1);
8918   }
8919 
8920   // Validate that none of the argument registers have been marked as
8921   // reserved, if so report an error. Do the same for the return address if this
8922   // is not a tailcall.
8923   validateCCReservedRegs(RegsToPass, MF);
8924   if (!IsTailCall &&
8925       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8926     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8927         MF.getFunction(),
8928         "Return address register required, but has been reserved."});
8929 
8930   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8931   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8932   // split it and then direct call can be matched by PseudoCALL.
8933   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8934     const GlobalValue *GV = S->getGlobal();
8935 
8936     unsigned OpFlags = RISCVII::MO_CALL;
8937     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8938       OpFlags = RISCVII::MO_PLT;
8939 
8940     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8941   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8942     unsigned OpFlags = RISCVII::MO_CALL;
8943 
8944     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8945                                                  nullptr))
8946       OpFlags = RISCVII::MO_PLT;
8947 
8948     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8949   }
8950 
8951   // The first call operand is the chain and the second is the target address.
8952   SmallVector<SDValue, 8> Ops;
8953   Ops.push_back(Chain);
8954   Ops.push_back(Callee);
8955 
8956   // Add argument registers to the end of the list so that they are
8957   // known live into the call.
8958   for (auto &Reg : RegsToPass)
8959     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8960 
8961   if (!IsTailCall) {
8962     // Add a register mask operand representing the call-preserved registers.
8963     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8964     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8965     assert(Mask && "Missing call preserved mask for calling convention");
8966     Ops.push_back(DAG.getRegisterMask(Mask));
8967   }
8968 
8969   // Glue the call to the argument copies, if any.
8970   if (Glue.getNode())
8971     Ops.push_back(Glue);
8972 
8973   // Emit the call.
8974   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8975 
8976   if (IsTailCall) {
8977     MF.getFrameInfo().setHasTailCall();
8978     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8979   }
8980 
8981   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8982   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8983   Glue = Chain.getValue(1);
8984 
8985   // Mark the end of the call, which is glued to the call itself.
8986   Chain = DAG.getCALLSEQ_END(Chain,
8987                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8988                              DAG.getConstant(0, DL, PtrVT, true),
8989                              Glue, DL);
8990   Glue = Chain.getValue(1);
8991 
8992   // Assign locations to each value returned by this call.
8993   SmallVector<CCValAssign, 16> RVLocs;
8994   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8995   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8996 
8997   // Copy all of the result registers out of their specified physreg.
8998   for (auto &VA : RVLocs) {
8999     // Copy the value out
9000     SDValue RetValue =
9001         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9002     // Glue the RetValue to the end of the call sequence
9003     Chain = RetValue.getValue(1);
9004     Glue = RetValue.getValue(2);
9005 
9006     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9007       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9008       SDValue RetValue2 =
9009           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9010       Chain = RetValue2.getValue(1);
9011       Glue = RetValue2.getValue(2);
9012       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9013                              RetValue2);
9014     }
9015 
9016     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9017 
9018     InVals.push_back(RetValue);
9019   }
9020 
9021   return Chain;
9022 }
9023 
9024 bool RISCVTargetLowering::CanLowerReturn(
9025     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9026     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9027   SmallVector<CCValAssign, 16> RVLocs;
9028   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9029 
9030   Optional<unsigned> FirstMaskArgument;
9031   if (Subtarget.hasVInstructions())
9032     FirstMaskArgument = preAssignMask(Outs);
9033 
9034   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9035     MVT VT = Outs[i].VT;
9036     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9037     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9038     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9039                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9040                  *this, FirstMaskArgument))
9041       return false;
9042   }
9043   return true;
9044 }
9045 
9046 SDValue
9047 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9048                                  bool IsVarArg,
9049                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9050                                  const SmallVectorImpl<SDValue> &OutVals,
9051                                  const SDLoc &DL, SelectionDAG &DAG) const {
9052   const MachineFunction &MF = DAG.getMachineFunction();
9053   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9054 
9055   // Stores the assignment of the return value to a location.
9056   SmallVector<CCValAssign, 16> RVLocs;
9057 
9058   // Info about the registers and stack slot.
9059   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9060                  *DAG.getContext());
9061 
9062   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9063                     nullptr, CC_RISCV);
9064 
9065   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9066     report_fatal_error("GHC functions return void only");
9067 
9068   SDValue Glue;
9069   SmallVector<SDValue, 4> RetOps(1, Chain);
9070 
9071   // Copy the result values into the output registers.
9072   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9073     SDValue Val = OutVals[i];
9074     CCValAssign &VA = RVLocs[i];
9075     assert(VA.isRegLoc() && "Can only return in registers!");
9076 
9077     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9078       // Handle returning f64 on RV32D with a soft float ABI.
9079       assert(VA.isRegLoc() && "Expected return via registers");
9080       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9081                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9082       SDValue Lo = SplitF64.getValue(0);
9083       SDValue Hi = SplitF64.getValue(1);
9084       Register RegLo = VA.getLocReg();
9085       assert(RegLo < RISCV::X31 && "Invalid register pair");
9086       Register RegHi = RegLo + 1;
9087 
9088       if (STI.isRegisterReservedByUser(RegLo) ||
9089           STI.isRegisterReservedByUser(RegHi))
9090         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9091             MF.getFunction(),
9092             "Return value register required, but has been reserved."});
9093 
9094       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9095       Glue = Chain.getValue(1);
9096       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9097       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9098       Glue = Chain.getValue(1);
9099       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9100     } else {
9101       // Handle a 'normal' return.
9102       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9103       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9104 
9105       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9106         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9107             MF.getFunction(),
9108             "Return value register required, but has been reserved."});
9109 
9110       // Guarantee that all emitted copies are stuck together.
9111       Glue = Chain.getValue(1);
9112       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9113     }
9114   }
9115 
9116   RetOps[0] = Chain; // Update chain.
9117 
9118   // Add the glue node if we have it.
9119   if (Glue.getNode()) {
9120     RetOps.push_back(Glue);
9121   }
9122 
9123   unsigned RetOpc = RISCVISD::RET_FLAG;
9124   // Interrupt service routines use different return instructions.
9125   const Function &Func = DAG.getMachineFunction().getFunction();
9126   if (Func.hasFnAttribute("interrupt")) {
9127     if (!Func.getReturnType()->isVoidTy())
9128       report_fatal_error(
9129           "Functions with the interrupt attribute must have void return type!");
9130 
9131     MachineFunction &MF = DAG.getMachineFunction();
9132     StringRef Kind =
9133       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9134 
9135     if (Kind == "user")
9136       RetOpc = RISCVISD::URET_FLAG;
9137     else if (Kind == "supervisor")
9138       RetOpc = RISCVISD::SRET_FLAG;
9139     else
9140       RetOpc = RISCVISD::MRET_FLAG;
9141   }
9142 
9143   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9144 }
9145 
9146 void RISCVTargetLowering::validateCCReservedRegs(
9147     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9148     MachineFunction &MF) const {
9149   const Function &F = MF.getFunction();
9150   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9151 
9152   if (llvm::any_of(Regs, [&STI](auto Reg) {
9153         return STI.isRegisterReservedByUser(Reg.first);
9154       }))
9155     F.getContext().diagnose(DiagnosticInfoUnsupported{
9156         F, "Argument register required, but has been reserved."});
9157 }
9158 
9159 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9160   return CI->isTailCall();
9161 }
9162 
9163 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9164 #define NODE_NAME_CASE(NODE)                                                   \
9165   case RISCVISD::NODE:                                                         \
9166     return "RISCVISD::" #NODE;
9167   // clang-format off
9168   switch ((RISCVISD::NodeType)Opcode) {
9169   case RISCVISD::FIRST_NUMBER:
9170     break;
9171   NODE_NAME_CASE(RET_FLAG)
9172   NODE_NAME_CASE(URET_FLAG)
9173   NODE_NAME_CASE(SRET_FLAG)
9174   NODE_NAME_CASE(MRET_FLAG)
9175   NODE_NAME_CASE(CALL)
9176   NODE_NAME_CASE(SELECT_CC)
9177   NODE_NAME_CASE(BR_CC)
9178   NODE_NAME_CASE(BuildPairF64)
9179   NODE_NAME_CASE(SplitF64)
9180   NODE_NAME_CASE(TAIL)
9181   NODE_NAME_CASE(MULHSU)
9182   NODE_NAME_CASE(SLLW)
9183   NODE_NAME_CASE(SRAW)
9184   NODE_NAME_CASE(SRLW)
9185   NODE_NAME_CASE(DIVW)
9186   NODE_NAME_CASE(DIVUW)
9187   NODE_NAME_CASE(REMUW)
9188   NODE_NAME_CASE(ROLW)
9189   NODE_NAME_CASE(RORW)
9190   NODE_NAME_CASE(CLZW)
9191   NODE_NAME_CASE(CTZW)
9192   NODE_NAME_CASE(FSLW)
9193   NODE_NAME_CASE(FSRW)
9194   NODE_NAME_CASE(FSL)
9195   NODE_NAME_CASE(FSR)
9196   NODE_NAME_CASE(FMV_H_X)
9197   NODE_NAME_CASE(FMV_X_ANYEXTH)
9198   NODE_NAME_CASE(FMV_W_X_RV64)
9199   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9200   NODE_NAME_CASE(FCVT_X_RTZ)
9201   NODE_NAME_CASE(FCVT_XU_RTZ)
9202   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9203   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9204   NODE_NAME_CASE(READ_CYCLE_WIDE)
9205   NODE_NAME_CASE(GREV)
9206   NODE_NAME_CASE(GREVW)
9207   NODE_NAME_CASE(GORC)
9208   NODE_NAME_CASE(GORCW)
9209   NODE_NAME_CASE(SHFL)
9210   NODE_NAME_CASE(SHFLW)
9211   NODE_NAME_CASE(UNSHFL)
9212   NODE_NAME_CASE(UNSHFLW)
9213   NODE_NAME_CASE(BCOMPRESS)
9214   NODE_NAME_CASE(BCOMPRESSW)
9215   NODE_NAME_CASE(BDECOMPRESS)
9216   NODE_NAME_CASE(BDECOMPRESSW)
9217   NODE_NAME_CASE(VMV_V_X_VL)
9218   NODE_NAME_CASE(VFMV_V_F_VL)
9219   NODE_NAME_CASE(VMV_X_S)
9220   NODE_NAME_CASE(VMV_S_X_VL)
9221   NODE_NAME_CASE(VFMV_S_F_VL)
9222   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9223   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9224   NODE_NAME_CASE(READ_VLENB)
9225   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9226   NODE_NAME_CASE(VSLIDEUP_VL)
9227   NODE_NAME_CASE(VSLIDE1UP_VL)
9228   NODE_NAME_CASE(VSLIDEDOWN_VL)
9229   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9230   NODE_NAME_CASE(VID_VL)
9231   NODE_NAME_CASE(VFNCVT_ROD_VL)
9232   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9233   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9234   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9235   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9236   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9237   NODE_NAME_CASE(VECREDUCE_AND_VL)
9238   NODE_NAME_CASE(VECREDUCE_OR_VL)
9239   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9240   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9241   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9242   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9243   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9244   NODE_NAME_CASE(ADD_VL)
9245   NODE_NAME_CASE(AND_VL)
9246   NODE_NAME_CASE(MUL_VL)
9247   NODE_NAME_CASE(OR_VL)
9248   NODE_NAME_CASE(SDIV_VL)
9249   NODE_NAME_CASE(SHL_VL)
9250   NODE_NAME_CASE(SREM_VL)
9251   NODE_NAME_CASE(SRA_VL)
9252   NODE_NAME_CASE(SRL_VL)
9253   NODE_NAME_CASE(SUB_VL)
9254   NODE_NAME_CASE(UDIV_VL)
9255   NODE_NAME_CASE(UREM_VL)
9256   NODE_NAME_CASE(XOR_VL)
9257   NODE_NAME_CASE(SADDSAT_VL)
9258   NODE_NAME_CASE(UADDSAT_VL)
9259   NODE_NAME_CASE(SSUBSAT_VL)
9260   NODE_NAME_CASE(USUBSAT_VL)
9261   NODE_NAME_CASE(FADD_VL)
9262   NODE_NAME_CASE(FSUB_VL)
9263   NODE_NAME_CASE(FMUL_VL)
9264   NODE_NAME_CASE(FDIV_VL)
9265   NODE_NAME_CASE(FNEG_VL)
9266   NODE_NAME_CASE(FABS_VL)
9267   NODE_NAME_CASE(FSQRT_VL)
9268   NODE_NAME_CASE(FMA_VL)
9269   NODE_NAME_CASE(FCOPYSIGN_VL)
9270   NODE_NAME_CASE(SMIN_VL)
9271   NODE_NAME_CASE(SMAX_VL)
9272   NODE_NAME_CASE(UMIN_VL)
9273   NODE_NAME_CASE(UMAX_VL)
9274   NODE_NAME_CASE(FMINNUM_VL)
9275   NODE_NAME_CASE(FMAXNUM_VL)
9276   NODE_NAME_CASE(MULHS_VL)
9277   NODE_NAME_CASE(MULHU_VL)
9278   NODE_NAME_CASE(FP_TO_SINT_VL)
9279   NODE_NAME_CASE(FP_TO_UINT_VL)
9280   NODE_NAME_CASE(SINT_TO_FP_VL)
9281   NODE_NAME_CASE(UINT_TO_FP_VL)
9282   NODE_NAME_CASE(FP_EXTEND_VL)
9283   NODE_NAME_CASE(FP_ROUND_VL)
9284   NODE_NAME_CASE(VWMUL_VL)
9285   NODE_NAME_CASE(VWMULU_VL)
9286   NODE_NAME_CASE(SETCC_VL)
9287   NODE_NAME_CASE(VSELECT_VL)
9288   NODE_NAME_CASE(VMAND_VL)
9289   NODE_NAME_CASE(VMOR_VL)
9290   NODE_NAME_CASE(VMXOR_VL)
9291   NODE_NAME_CASE(VMCLR_VL)
9292   NODE_NAME_CASE(VMSET_VL)
9293   NODE_NAME_CASE(VRGATHER_VX_VL)
9294   NODE_NAME_CASE(VRGATHER_VV_VL)
9295   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9296   NODE_NAME_CASE(VSEXT_VL)
9297   NODE_NAME_CASE(VZEXT_VL)
9298   NODE_NAME_CASE(VCPOP_VL)
9299   NODE_NAME_CASE(VLE_VL)
9300   NODE_NAME_CASE(VSE_VL)
9301   NODE_NAME_CASE(READ_CSR)
9302   NODE_NAME_CASE(WRITE_CSR)
9303   NODE_NAME_CASE(SWAP_CSR)
9304   }
9305   // clang-format on
9306   return nullptr;
9307 #undef NODE_NAME_CASE
9308 }
9309 
9310 /// getConstraintType - Given a constraint letter, return the type of
9311 /// constraint it is for this target.
9312 RISCVTargetLowering::ConstraintType
9313 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9314   if (Constraint.size() == 1) {
9315     switch (Constraint[0]) {
9316     default:
9317       break;
9318     case 'f':
9319       return C_RegisterClass;
9320     case 'I':
9321     case 'J':
9322     case 'K':
9323       return C_Immediate;
9324     case 'A':
9325       return C_Memory;
9326     case 'S': // A symbolic address
9327       return C_Other;
9328     }
9329   } else {
9330     if (Constraint == "vr" || Constraint == "vm")
9331       return C_RegisterClass;
9332   }
9333   return TargetLowering::getConstraintType(Constraint);
9334 }
9335 
9336 std::pair<unsigned, const TargetRegisterClass *>
9337 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9338                                                   StringRef Constraint,
9339                                                   MVT VT) const {
9340   // First, see if this is a constraint that directly corresponds to a
9341   // RISCV register class.
9342   if (Constraint.size() == 1) {
9343     switch (Constraint[0]) {
9344     case 'r':
9345       return std::make_pair(0U, &RISCV::GPRRegClass);
9346     case 'f':
9347       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9348         return std::make_pair(0U, &RISCV::FPR16RegClass);
9349       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9350         return std::make_pair(0U, &RISCV::FPR32RegClass);
9351       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9352         return std::make_pair(0U, &RISCV::FPR64RegClass);
9353       break;
9354     default:
9355       break;
9356     }
9357   } else {
9358     if (Constraint == "vr") {
9359       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9360                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9361         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9362           return std::make_pair(0U, RC);
9363       }
9364     } else if (Constraint == "vm") {
9365       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9366         return std::make_pair(0U, &RISCV::VMRegClass);
9367     }
9368   }
9369 
9370   // Clang will correctly decode the usage of register name aliases into their
9371   // official names. However, other frontends like `rustc` do not. This allows
9372   // users of these frontends to use the ABI names for registers in LLVM-style
9373   // register constraints.
9374   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9375                                .Case("{zero}", RISCV::X0)
9376                                .Case("{ra}", RISCV::X1)
9377                                .Case("{sp}", RISCV::X2)
9378                                .Case("{gp}", RISCV::X3)
9379                                .Case("{tp}", RISCV::X4)
9380                                .Case("{t0}", RISCV::X5)
9381                                .Case("{t1}", RISCV::X6)
9382                                .Case("{t2}", RISCV::X7)
9383                                .Cases("{s0}", "{fp}", RISCV::X8)
9384                                .Case("{s1}", RISCV::X9)
9385                                .Case("{a0}", RISCV::X10)
9386                                .Case("{a1}", RISCV::X11)
9387                                .Case("{a2}", RISCV::X12)
9388                                .Case("{a3}", RISCV::X13)
9389                                .Case("{a4}", RISCV::X14)
9390                                .Case("{a5}", RISCV::X15)
9391                                .Case("{a6}", RISCV::X16)
9392                                .Case("{a7}", RISCV::X17)
9393                                .Case("{s2}", RISCV::X18)
9394                                .Case("{s3}", RISCV::X19)
9395                                .Case("{s4}", RISCV::X20)
9396                                .Case("{s5}", RISCV::X21)
9397                                .Case("{s6}", RISCV::X22)
9398                                .Case("{s7}", RISCV::X23)
9399                                .Case("{s8}", RISCV::X24)
9400                                .Case("{s9}", RISCV::X25)
9401                                .Case("{s10}", RISCV::X26)
9402                                .Case("{s11}", RISCV::X27)
9403                                .Case("{t3}", RISCV::X28)
9404                                .Case("{t4}", RISCV::X29)
9405                                .Case("{t5}", RISCV::X30)
9406                                .Case("{t6}", RISCV::X31)
9407                                .Default(RISCV::NoRegister);
9408   if (XRegFromAlias != RISCV::NoRegister)
9409     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9410 
9411   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9412   // TableGen record rather than the AsmName to choose registers for InlineAsm
9413   // constraints, plus we want to match those names to the widest floating point
9414   // register type available, manually select floating point registers here.
9415   //
9416   // The second case is the ABI name of the register, so that frontends can also
9417   // use the ABI names in register constraint lists.
9418   if (Subtarget.hasStdExtF()) {
9419     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9420                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9421                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9422                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9423                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9424                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9425                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9426                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9427                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9428                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9429                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9430                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9431                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9432                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9433                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9434                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9435                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9436                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9437                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9438                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9439                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9440                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9441                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9442                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9443                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9444                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9445                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9446                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9447                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9448                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9449                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9450                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9451                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9452                         .Default(RISCV::NoRegister);
9453     if (FReg != RISCV::NoRegister) {
9454       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9455       if (Subtarget.hasStdExtD()) {
9456         unsigned RegNo = FReg - RISCV::F0_F;
9457         unsigned DReg = RISCV::F0_D + RegNo;
9458         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9459       }
9460       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9461     }
9462   }
9463 
9464   if (Subtarget.hasVInstructions()) {
9465     Register VReg = StringSwitch<Register>(Constraint.lower())
9466                         .Case("{v0}", RISCV::V0)
9467                         .Case("{v1}", RISCV::V1)
9468                         .Case("{v2}", RISCV::V2)
9469                         .Case("{v3}", RISCV::V3)
9470                         .Case("{v4}", RISCV::V4)
9471                         .Case("{v5}", RISCV::V5)
9472                         .Case("{v6}", RISCV::V6)
9473                         .Case("{v7}", RISCV::V7)
9474                         .Case("{v8}", RISCV::V8)
9475                         .Case("{v9}", RISCV::V9)
9476                         .Case("{v10}", RISCV::V10)
9477                         .Case("{v11}", RISCV::V11)
9478                         .Case("{v12}", RISCV::V12)
9479                         .Case("{v13}", RISCV::V13)
9480                         .Case("{v14}", RISCV::V14)
9481                         .Case("{v15}", RISCV::V15)
9482                         .Case("{v16}", RISCV::V16)
9483                         .Case("{v17}", RISCV::V17)
9484                         .Case("{v18}", RISCV::V18)
9485                         .Case("{v19}", RISCV::V19)
9486                         .Case("{v20}", RISCV::V20)
9487                         .Case("{v21}", RISCV::V21)
9488                         .Case("{v22}", RISCV::V22)
9489                         .Case("{v23}", RISCV::V23)
9490                         .Case("{v24}", RISCV::V24)
9491                         .Case("{v25}", RISCV::V25)
9492                         .Case("{v26}", RISCV::V26)
9493                         .Case("{v27}", RISCV::V27)
9494                         .Case("{v28}", RISCV::V28)
9495                         .Case("{v29}", RISCV::V29)
9496                         .Case("{v30}", RISCV::V30)
9497                         .Case("{v31}", RISCV::V31)
9498                         .Default(RISCV::NoRegister);
9499     if (VReg != RISCV::NoRegister) {
9500       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9501         return std::make_pair(VReg, &RISCV::VMRegClass);
9502       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9503         return std::make_pair(VReg, &RISCV::VRRegClass);
9504       for (const auto *RC :
9505            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9506         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9507           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9508           return std::make_pair(VReg, RC);
9509         }
9510       }
9511     }
9512   }
9513 
9514   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9515 }
9516 
9517 unsigned
9518 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9519   // Currently only support length 1 constraints.
9520   if (ConstraintCode.size() == 1) {
9521     switch (ConstraintCode[0]) {
9522     case 'A':
9523       return InlineAsm::Constraint_A;
9524     default:
9525       break;
9526     }
9527   }
9528 
9529   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9530 }
9531 
9532 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9533     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9534     SelectionDAG &DAG) const {
9535   // Currently only support length 1 constraints.
9536   if (Constraint.length() == 1) {
9537     switch (Constraint[0]) {
9538     case 'I':
9539       // Validate & create a 12-bit signed immediate operand.
9540       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9541         uint64_t CVal = C->getSExtValue();
9542         if (isInt<12>(CVal))
9543           Ops.push_back(
9544               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9545       }
9546       return;
9547     case 'J':
9548       // Validate & create an integer zero operand.
9549       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9550         if (C->getZExtValue() == 0)
9551           Ops.push_back(
9552               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9553       return;
9554     case 'K':
9555       // Validate & create a 5-bit unsigned immediate operand.
9556       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9557         uint64_t CVal = C->getZExtValue();
9558         if (isUInt<5>(CVal))
9559           Ops.push_back(
9560               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9561       }
9562       return;
9563     case 'S':
9564       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9565         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9566                                                  GA->getValueType(0)));
9567       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9568         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9569                                                 BA->getValueType(0)));
9570       }
9571       return;
9572     default:
9573       break;
9574     }
9575   }
9576   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9577 }
9578 
9579 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9580                                                    Instruction *Inst,
9581                                                    AtomicOrdering Ord) const {
9582   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9583     return Builder.CreateFence(Ord);
9584   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9585     return Builder.CreateFence(AtomicOrdering::Release);
9586   return nullptr;
9587 }
9588 
9589 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9590                                                     Instruction *Inst,
9591                                                     AtomicOrdering Ord) const {
9592   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9593     return Builder.CreateFence(AtomicOrdering::Acquire);
9594   return nullptr;
9595 }
9596 
9597 TargetLowering::AtomicExpansionKind
9598 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9599   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9600   // point operations can't be used in an lr/sc sequence without breaking the
9601   // forward-progress guarantee.
9602   if (AI->isFloatingPointOperation())
9603     return AtomicExpansionKind::CmpXChg;
9604 
9605   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9606   if (Size == 8 || Size == 16)
9607     return AtomicExpansionKind::MaskedIntrinsic;
9608   return AtomicExpansionKind::None;
9609 }
9610 
9611 static Intrinsic::ID
9612 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9613   if (XLen == 32) {
9614     switch (BinOp) {
9615     default:
9616       llvm_unreachable("Unexpected AtomicRMW BinOp");
9617     case AtomicRMWInst::Xchg:
9618       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9619     case AtomicRMWInst::Add:
9620       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9621     case AtomicRMWInst::Sub:
9622       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9623     case AtomicRMWInst::Nand:
9624       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9625     case AtomicRMWInst::Max:
9626       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9627     case AtomicRMWInst::Min:
9628       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9629     case AtomicRMWInst::UMax:
9630       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9631     case AtomicRMWInst::UMin:
9632       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9633     }
9634   }
9635 
9636   if (XLen == 64) {
9637     switch (BinOp) {
9638     default:
9639       llvm_unreachable("Unexpected AtomicRMW BinOp");
9640     case AtomicRMWInst::Xchg:
9641       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9642     case AtomicRMWInst::Add:
9643       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9644     case AtomicRMWInst::Sub:
9645       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9646     case AtomicRMWInst::Nand:
9647       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9648     case AtomicRMWInst::Max:
9649       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9650     case AtomicRMWInst::Min:
9651       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9652     case AtomicRMWInst::UMax:
9653       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9654     case AtomicRMWInst::UMin:
9655       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9656     }
9657   }
9658 
9659   llvm_unreachable("Unexpected XLen\n");
9660 }
9661 
9662 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9663     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9664     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9665   unsigned XLen = Subtarget.getXLen();
9666   Value *Ordering =
9667       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9668   Type *Tys[] = {AlignedAddr->getType()};
9669   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9670       AI->getModule(),
9671       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9672 
9673   if (XLen == 64) {
9674     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9675     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9676     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9677   }
9678 
9679   Value *Result;
9680 
9681   // Must pass the shift amount needed to sign extend the loaded value prior
9682   // to performing a signed comparison for min/max. ShiftAmt is the number of
9683   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9684   // is the number of bits to left+right shift the value in order to
9685   // sign-extend.
9686   if (AI->getOperation() == AtomicRMWInst::Min ||
9687       AI->getOperation() == AtomicRMWInst::Max) {
9688     const DataLayout &DL = AI->getModule()->getDataLayout();
9689     unsigned ValWidth =
9690         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9691     Value *SextShamt =
9692         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9693     Result = Builder.CreateCall(LrwOpScwLoop,
9694                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9695   } else {
9696     Result =
9697         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9698   }
9699 
9700   if (XLen == 64)
9701     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9702   return Result;
9703 }
9704 
9705 TargetLowering::AtomicExpansionKind
9706 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9707     AtomicCmpXchgInst *CI) const {
9708   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9709   if (Size == 8 || Size == 16)
9710     return AtomicExpansionKind::MaskedIntrinsic;
9711   return AtomicExpansionKind::None;
9712 }
9713 
9714 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9715     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9716     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9717   unsigned XLen = Subtarget.getXLen();
9718   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9719   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9720   if (XLen == 64) {
9721     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9722     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9723     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9724     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9725   }
9726   Type *Tys[] = {AlignedAddr->getType()};
9727   Function *MaskedCmpXchg =
9728       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9729   Value *Result = Builder.CreateCall(
9730       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9731   if (XLen == 64)
9732     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9733   return Result;
9734 }
9735 
9736 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9737   return false;
9738 }
9739 
9740 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9741                                                      EVT VT) const {
9742   VT = VT.getScalarType();
9743 
9744   if (!VT.isSimple())
9745     return false;
9746 
9747   switch (VT.getSimpleVT().SimpleTy) {
9748   case MVT::f16:
9749     return Subtarget.hasStdExtZfh();
9750   case MVT::f32:
9751     return Subtarget.hasStdExtF();
9752   case MVT::f64:
9753     return Subtarget.hasStdExtD();
9754   default:
9755     break;
9756   }
9757 
9758   return false;
9759 }
9760 
9761 Register RISCVTargetLowering::getExceptionPointerRegister(
9762     const Constant *PersonalityFn) const {
9763   return RISCV::X10;
9764 }
9765 
9766 Register RISCVTargetLowering::getExceptionSelectorRegister(
9767     const Constant *PersonalityFn) const {
9768   return RISCV::X11;
9769 }
9770 
9771 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9772   // Return false to suppress the unnecessary extensions if the LibCall
9773   // arguments or return value is f32 type for LP64 ABI.
9774   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9775   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9776     return false;
9777 
9778   return true;
9779 }
9780 
9781 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9782   if (Subtarget.is64Bit() && Type == MVT::i32)
9783     return true;
9784 
9785   return IsSigned;
9786 }
9787 
9788 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9789                                                  SDValue C) const {
9790   // Check integral scalar types.
9791   if (VT.isScalarInteger()) {
9792     // Omit the optimization if the sub target has the M extension and the data
9793     // size exceeds XLen.
9794     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9795       return false;
9796     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9797       // Break the MUL to a SLLI and an ADD/SUB.
9798       const APInt &Imm = ConstNode->getAPIntValue();
9799       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9800           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9801         return true;
9802       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9803       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9804           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9805            (Imm - 8).isPowerOf2()))
9806         return true;
9807       // Omit the following optimization if the sub target has the M extension
9808       // and the data size >= XLen.
9809       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9810         return false;
9811       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9812       // a pair of LUI/ADDI.
9813       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9814         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9815         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9816             (1 - ImmS).isPowerOf2())
9817         return true;
9818       }
9819     }
9820   }
9821 
9822   return false;
9823 }
9824 
9825 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9826     const SDValue &AddNode, const SDValue &ConstNode) const {
9827   // Let the DAGCombiner decide for vectors.
9828   EVT VT = AddNode.getValueType();
9829   if (VT.isVector())
9830     return true;
9831 
9832   // Let the DAGCombiner decide for larger types.
9833   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9834     return true;
9835 
9836   // It is worse if c1 is simm12 while c1*c2 is not.
9837   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9838   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9839   const APInt &C1 = C1Node->getAPIntValue();
9840   const APInt &C2 = C2Node->getAPIntValue();
9841   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9842     return false;
9843 
9844   // Default to true and let the DAGCombiner decide.
9845   return true;
9846 }
9847 
9848 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9849     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9850     bool *Fast) const {
9851   if (!VT.isVector())
9852     return false;
9853 
9854   EVT ElemVT = VT.getVectorElementType();
9855   if (Alignment >= ElemVT.getStoreSize()) {
9856     if (Fast)
9857       *Fast = true;
9858     return true;
9859   }
9860 
9861   return false;
9862 }
9863 
9864 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9865     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9866     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9867   bool IsABIRegCopy = CC.hasValue();
9868   EVT ValueVT = Val.getValueType();
9869   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9870     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9871     // and cast to f32.
9872     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9873     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9874     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9875                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9876     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9877     Parts[0] = Val;
9878     return true;
9879   }
9880 
9881   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9882     LLVMContext &Context = *DAG.getContext();
9883     EVT ValueEltVT = ValueVT.getVectorElementType();
9884     EVT PartEltVT = PartVT.getVectorElementType();
9885     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9886     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9887     if (PartVTBitSize % ValueVTBitSize == 0) {
9888       // If the element types are different, bitcast to the same element type of
9889       // PartVT first.
9890       if (ValueEltVT != PartEltVT) {
9891         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9892         assert(Count != 0 && "The number of element should not be zero.");
9893         EVT SameEltTypeVT =
9894             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9895         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9896       }
9897       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9898                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9899       Parts[0] = Val;
9900       return true;
9901     }
9902   }
9903   return false;
9904 }
9905 
9906 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9907     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9908     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9909   bool IsABIRegCopy = CC.hasValue();
9910   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9911     SDValue Val = Parts[0];
9912 
9913     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9914     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9915     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9916     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9917     return Val;
9918   }
9919 
9920   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9921     LLVMContext &Context = *DAG.getContext();
9922     SDValue Val = Parts[0];
9923     EVT ValueEltVT = ValueVT.getVectorElementType();
9924     EVT PartEltVT = PartVT.getVectorElementType();
9925     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9926     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9927     if (PartVTBitSize % ValueVTBitSize == 0) {
9928       EVT SameEltTypeVT = ValueVT;
9929       // If the element types are different, convert it to the same element type
9930       // of PartVT.
9931       if (ValueEltVT != PartEltVT) {
9932         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9933         assert(Count != 0 && "The number of element should not be zero.");
9934         SameEltTypeVT =
9935             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9936       }
9937       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9938                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9939       if (ValueEltVT != PartEltVT)
9940         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9941       return Val;
9942     }
9943   }
9944   return SDValue();
9945 }
9946 
9947 #define GET_REGISTER_MATCHER
9948 #include "RISCVGenAsmMatcher.inc"
9949 
9950 Register
9951 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9952                                        const MachineFunction &MF) const {
9953   Register Reg = MatchRegisterAltName(RegName);
9954   if (Reg == RISCV::NoRegister)
9955     Reg = MatchRegisterName(RegName);
9956   if (Reg == RISCV::NoRegister)
9957     report_fatal_error(
9958         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9959   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9960   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9961     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9962                              StringRef(RegName) + "\"."));
9963   return Reg;
9964 }
9965 
9966 namespace llvm {
9967 namespace RISCVVIntrinsicsTable {
9968 
9969 #define GET_RISCVVIntrinsicsTable_IMPL
9970 #include "RISCVGenSearchableTables.inc"
9971 
9972 } // namespace RISCVVIntrinsicsTable
9973 
9974 } // namespace llvm
9975