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