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