1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasStdExtV()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs)
132       addRegClassForRVV(VT);
133 
134     if (Subtarget.hasStdExtZfh())
135       for (MVT VT : F16VecVTs)
136         addRegClassForRVV(VT);
137 
138     if (Subtarget.hasStdExtF())
139       for (MVT VT : F32VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasStdExtD())
143       for (MVT VT : F64VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.useRVVForFixedLengthVectors()) {
147       auto addRegClassForFixedVectors = [this](MVT VT) {
148         MVT ContainerVT = getContainerForFixedLengthVector(VT);
149         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
150         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
151         addRegisterClass(VT, TRI.getRegClass(RCID));
152       };
153       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
154         if (useRVVForFixedLengthVectorVT(VT))
155           addRegClassForFixedVectors(VT);
156 
157       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160     }
161   }
162 
163   // Compute derived properties from the register classes.
164   computeRegisterProperties(STI.getRegisterInfo());
165 
166   setStackPointerRegisterToSaveRestore(RISCV::X2);
167 
168   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
169     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
170 
171   // TODO: add all necessary setOperationAction calls.
172   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
173 
174   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
175   setOperationAction(ISD::BR_CC, XLenVT, Expand);
176   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
177   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
178 
179   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
180   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
181 
182   setOperationAction(ISD::VASTART, MVT::Other, Custom);
183   setOperationAction(ISD::VAARG, MVT::Other, Expand);
184   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
185   setOperationAction(ISD::VAEND, MVT::Other, Expand);
186 
187   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
188   if (!Subtarget.hasStdExtZbb()) {
189     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
190     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
191   }
192 
193   if (Subtarget.is64Bit()) {
194     setOperationAction(ISD::ADD, MVT::i32, Custom);
195     setOperationAction(ISD::SUB, MVT::i32, Custom);
196     setOperationAction(ISD::SHL, MVT::i32, Custom);
197     setOperationAction(ISD::SRA, MVT::i32, Custom);
198     setOperationAction(ISD::SRL, MVT::i32, Custom);
199 
200     setOperationAction(ISD::UADDO, MVT::i32, Custom);
201     setOperationAction(ISD::USUBO, MVT::i32, Custom);
202     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
203     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
204   } else {
205     setLibcallName(RTLIB::SHL_I128, nullptr);
206     setLibcallName(RTLIB::SRL_I128, nullptr);
207     setLibcallName(RTLIB::SRA_I128, nullptr);
208     setLibcallName(RTLIB::MUL_I128, nullptr);
209     setLibcallName(RTLIB::MULO_I64, nullptr);
210   }
211 
212   if (!Subtarget.hasStdExtM()) {
213     setOperationAction(ISD::MUL, XLenVT, Expand);
214     setOperationAction(ISD::MULHS, XLenVT, Expand);
215     setOperationAction(ISD::MULHU, XLenVT, Expand);
216     setOperationAction(ISD::SDIV, XLenVT, Expand);
217     setOperationAction(ISD::UDIV, XLenVT, Expand);
218     setOperationAction(ISD::SREM, XLenVT, Expand);
219     setOperationAction(ISD::UREM, XLenVT, Expand);
220   } else {
221     if (Subtarget.is64Bit()) {
222       setOperationAction(ISD::MUL, MVT::i32, Custom);
223       setOperationAction(ISD::MUL, MVT::i128, Custom);
224 
225       setOperationAction(ISD::SDIV, MVT::i8, Custom);
226       setOperationAction(ISD::UDIV, MVT::i8, Custom);
227       setOperationAction(ISD::UREM, MVT::i8, Custom);
228       setOperationAction(ISD::SDIV, MVT::i16, Custom);
229       setOperationAction(ISD::UDIV, MVT::i16, Custom);
230       setOperationAction(ISD::UREM, MVT::i16, Custom);
231       setOperationAction(ISD::SDIV, MVT::i32, Custom);
232       setOperationAction(ISD::UDIV, MVT::i32, Custom);
233       setOperationAction(ISD::UREM, MVT::i32, Custom);
234     } else {
235       setOperationAction(ISD::MUL, MVT::i64, Custom);
236     }
237   }
238 
239   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
240   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
241   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
242   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
243 
244   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
245   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
246   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
247 
248   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
249     if (Subtarget.is64Bit()) {
250       setOperationAction(ISD::ROTL, MVT::i32, Custom);
251       setOperationAction(ISD::ROTR, MVT::i32, Custom);
252     }
253   } else {
254     setOperationAction(ISD::ROTL, XLenVT, Expand);
255     setOperationAction(ISD::ROTR, XLenVT, Expand);
256   }
257 
258   if (Subtarget.hasStdExtZbp()) {
259     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
260     // more combining.
261     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
262     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
263     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
264     // BSWAP i8 doesn't exist.
265     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
266     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
267 
268     if (Subtarget.is64Bit()) {
269       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
270       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
271     }
272   } else {
273     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
274     // pattern match it directly in isel.
275     setOperationAction(ISD::BSWAP, XLenVT,
276                        Subtarget.hasStdExtZbb() ? Legal : Expand);
277   }
278 
279   if (Subtarget.hasStdExtZbb()) {
280     setOperationAction(ISD::SMIN, XLenVT, Legal);
281     setOperationAction(ISD::SMAX, XLenVT, Legal);
282     setOperationAction(ISD::UMIN, XLenVT, Legal);
283     setOperationAction(ISD::UMAX, XLenVT, Legal);
284 
285     if (Subtarget.is64Bit()) {
286       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
287       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
288       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
289       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
290     }
291   } else {
292     setOperationAction(ISD::CTTZ, XLenVT, Expand);
293     setOperationAction(ISD::CTLZ, XLenVT, Expand);
294     setOperationAction(ISD::CTPOP, XLenVT, Expand);
295   }
296 
297   if (Subtarget.hasStdExtZbt()) {
298     setOperationAction(ISD::FSHL, XLenVT, Custom);
299     setOperationAction(ISD::FSHR, XLenVT, Custom);
300     setOperationAction(ISD::SELECT, XLenVT, Legal);
301 
302     if (Subtarget.is64Bit()) {
303       setOperationAction(ISD::FSHL, MVT::i32, Custom);
304       setOperationAction(ISD::FSHR, MVT::i32, Custom);
305     }
306   } else {
307     setOperationAction(ISD::SELECT, XLenVT, Custom);
308   }
309 
310   static const ISD::CondCode FPCCToExpand[] = {
311       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
312       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
313       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
314 
315   static const ISD::NodeType FPOpToExpand[] = {
316       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
317       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
318 
319   if (Subtarget.hasStdExtZfh())
320     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
321 
322   if (Subtarget.hasStdExtZfh()) {
323     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
324     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
325     setOperationAction(ISD::LRINT, MVT::f16, Legal);
326     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
327     setOperationAction(ISD::LROUND, MVT::f16, Legal);
328     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
329     for (auto CC : FPCCToExpand)
330       setCondCodeAction(CC, MVT::f16, Expand);
331     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
332     setOperationAction(ISD::SELECT, MVT::f16, Custom);
333     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
334     for (auto Op : FPOpToExpand)
335       setOperationAction(Op, MVT::f16, Expand);
336   }
337 
338   if (Subtarget.hasStdExtF()) {
339     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
340     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
341     setOperationAction(ISD::LRINT, MVT::f32, Legal);
342     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
343     setOperationAction(ISD::LROUND, MVT::f32, Legal);
344     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
345     for (auto CC : FPCCToExpand)
346       setCondCodeAction(CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
348     setOperationAction(ISD::SELECT, MVT::f32, Custom);
349     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
350     for (auto Op : FPOpToExpand)
351       setOperationAction(Op, MVT::f32, Expand);
352     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
353     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
354   }
355 
356   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
357     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
358 
359   if (Subtarget.hasStdExtD()) {
360     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
361     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
362     setOperationAction(ISD::LRINT, MVT::f64, Legal);
363     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
364     setOperationAction(ISD::LROUND, MVT::f64, Legal);
365     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
366     for (auto CC : FPCCToExpand)
367       setCondCodeAction(CC, MVT::f64, Expand);
368     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
369     setOperationAction(ISD::SELECT, MVT::f64, Custom);
370     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
373     for (auto Op : FPOpToExpand)
374       setOperationAction(Op, MVT::f64, Expand);
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
376     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   }
378 
379   if (Subtarget.is64Bit()) {
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
383     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
384   }
385 
386   if (Subtarget.hasStdExtF()) {
387     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
388     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
389 
390     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
391     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
392   }
393 
394   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
395   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
396   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
397   setOperationAction(ISD::JumpTable, XLenVT, Custom);
398 
399   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction(ISD::TRAP, MVT::Other, Legal);
407   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
408   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409   if (Subtarget.is64Bit())
410     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
411 
412   if (Subtarget.hasStdExtA()) {
413     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
414     setMinCmpXchgSizeInBits(32);
415   } else {
416     setMaxAtomicSizeInBitsSupported(0);
417   }
418 
419   setBooleanContents(ZeroOrOneBooleanContent);
420 
421   if (Subtarget.hasStdExtV()) {
422     setBooleanVectorContents(ZeroOrOneBooleanContent);
423 
424     setOperationAction(ISD::VSCALE, XLenVT, Custom);
425 
426     // RVV intrinsics may have illegal operands.
427     // We also need to custom legalize vmv.x.s.
428     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
429     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
430     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
431     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
432     if (Subtarget.is64Bit()) {
433       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
434     } else {
435       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
436       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
437     }
438 
439     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
440     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
441 
442     static const unsigned IntegerVPOps[] = {
443         ISD::VP_ADD,  ISD::VP_SUB,  ISD::VP_MUL, ISD::VP_SDIV, ISD::VP_UDIV,
444         ISD::VP_SREM, ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR,   ISD::VP_XOR,
445         ISD::VP_ASHR, ISD::VP_LSHR, ISD::VP_SHL};
446 
447     static const unsigned FloatingPointVPOps[] = {ISD::VP_FADD, ISD::VP_FSUB,
448                                                   ISD::VP_FMUL, ISD::VP_FDIV};
449 
450     if (!Subtarget.is64Bit()) {
451       // We must custom-lower certain vXi64 operations on RV32 due to the vector
452       // element type being illegal.
453       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
454       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
455 
456       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
457       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
458       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
459       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
460       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
461       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
462       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
463       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
464     }
465 
466     for (MVT VT : BoolVecVTs) {
467       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
468 
469       // Mask VTs are custom-expanded into a series of standard nodes
470       setOperationAction(ISD::TRUNCATE, VT, Custom);
471       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
472       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
473       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
474 
475       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
476       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
477 
478       setOperationAction(ISD::SELECT, VT, Custom);
479       setOperationAction(ISD::SELECT_CC, VT, Expand);
480       setOperationAction(ISD::VSELECT, VT, Expand);
481 
482       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
483       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
484       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
485 
486       // RVV has native int->float & float->int conversions where the
487       // element type sizes are within one power-of-two of each other. Any
488       // wider distances between type sizes have to be lowered as sequences
489       // which progressively narrow the gap in stages.
490       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
491       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
492       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
493       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
494 
495       // Expand all extending loads to types larger than this, and truncating
496       // stores from types larger than this.
497       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
498         setTruncStoreAction(OtherVT, VT, Expand);
499         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
500         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
501         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
502       }
503     }
504 
505     for (MVT VT : IntVecVTs) {
506       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
507       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
508 
509       setOperationAction(ISD::SMIN, VT, Legal);
510       setOperationAction(ISD::SMAX, VT, Legal);
511       setOperationAction(ISD::UMIN, VT, Legal);
512       setOperationAction(ISD::UMAX, VT, Legal);
513 
514       setOperationAction(ISD::ROTL, VT, Expand);
515       setOperationAction(ISD::ROTR, VT, Expand);
516 
517       // Custom-lower extensions and truncations from/to mask types.
518       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
519       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
520       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
521 
522       // RVV has native int->float & float->int conversions where the
523       // element type sizes are within one power-of-two of each other. Any
524       // wider distances between type sizes have to be lowered as sequences
525       // which progressively narrow the gap in stages.
526       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
527       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
528       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
529       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
530 
531       setOperationAction(ISD::SADDSAT, VT, Legal);
532       setOperationAction(ISD::UADDSAT, VT, Legal);
533       setOperationAction(ISD::SSUBSAT, VT, Legal);
534       setOperationAction(ISD::USUBSAT, VT, Legal);
535 
536       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
537       // nodes which truncate by one power of two at a time.
538       setOperationAction(ISD::TRUNCATE, VT, Custom);
539 
540       // Custom-lower insert/extract operations to simplify patterns.
541       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
543 
544       // Custom-lower reduction operations to set up the corresponding custom
545       // nodes' operands.
546       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
547       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
548       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
551       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
552       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
553       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
554 
555       for (unsigned VPOpc : IntegerVPOps)
556         setOperationAction(VPOpc, VT, Custom);
557 
558       setOperationAction(ISD::LOAD, VT, Custom);
559       setOperationAction(ISD::STORE, VT, Custom);
560 
561       setOperationAction(ISD::MLOAD, VT, Custom);
562       setOperationAction(ISD::MSTORE, VT, Custom);
563       setOperationAction(ISD::MGATHER, VT, Custom);
564       setOperationAction(ISD::MSCATTER, VT, Custom);
565 
566       setOperationAction(ISD::VP_LOAD, VT, Custom);
567       setOperationAction(ISD::VP_STORE, VT, Custom);
568       setOperationAction(ISD::VP_GATHER, VT, Custom);
569       setOperationAction(ISD::VP_SCATTER, VT, Custom);
570 
571       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
572       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
573       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
574 
575       setOperationAction(ISD::SELECT, VT, Custom);
576       setOperationAction(ISD::SELECT_CC, VT, Expand);
577 
578       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
579       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
580 
581       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
582         setTruncStoreAction(VT, OtherVT, Expand);
583         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
584         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
585         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
586       }
587     }
588 
589     // Expand various CCs to best match the RVV ISA, which natively supports UNE
590     // but no other unordered comparisons, and supports all ordered comparisons
591     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
592     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
593     // and we pattern-match those back to the "original", swapping operands once
594     // more. This way we catch both operations and both "vf" and "fv" forms with
595     // fewer patterns.
596     static const ISD::CondCode VFPCCToExpand[] = {
597         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
598         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
599         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
600     };
601 
602     // Sets common operation actions on RVV floating-point vector types.
603     const auto SetCommonVFPActions = [&](MVT VT) {
604       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
605       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
606       // sizes are within one power-of-two of each other. Therefore conversions
607       // between vXf16 and vXf64 must be lowered as sequences which convert via
608       // vXf32.
609       setOperationAction(ISD::FP_ROUND, VT, Custom);
610       setOperationAction(ISD::FP_EXTEND, VT, Custom);
611       // Custom-lower insert/extract operations to simplify patterns.
612       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
613       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
614       // Expand various condition codes (explained above).
615       for (auto CC : VFPCCToExpand)
616         setCondCodeAction(CC, VT, Expand);
617 
618       setOperationAction(ISD::FMINNUM, VT, Legal);
619       setOperationAction(ISD::FMAXNUM, VT, Legal);
620 
621       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
622       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
623       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
624       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
625       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
626 
627       setOperationAction(ISD::LOAD, VT, Custom);
628       setOperationAction(ISD::STORE, VT, Custom);
629 
630       setOperationAction(ISD::MLOAD, VT, Custom);
631       setOperationAction(ISD::MSTORE, VT, Custom);
632       setOperationAction(ISD::MGATHER, VT, Custom);
633       setOperationAction(ISD::MSCATTER, VT, Custom);
634 
635       setOperationAction(ISD::VP_LOAD, VT, Custom);
636       setOperationAction(ISD::VP_STORE, VT, Custom);
637       setOperationAction(ISD::VP_GATHER, VT, Custom);
638       setOperationAction(ISD::VP_SCATTER, VT, Custom);
639 
640       setOperationAction(ISD::SELECT, VT, Custom);
641       setOperationAction(ISD::SELECT_CC, VT, Expand);
642 
643       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
644       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
645       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
646 
647       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
648 
649       for (unsigned VPOpc : FloatingPointVPOps)
650         setOperationAction(VPOpc, VT, Custom);
651     };
652 
653     // Sets common extload/truncstore actions on RVV floating-point vector
654     // types.
655     const auto SetCommonVFPExtLoadTruncStoreActions =
656         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
657           for (auto SmallVT : SmallerVTs) {
658             setTruncStoreAction(VT, SmallVT, Expand);
659             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
660           }
661         };
662 
663     if (Subtarget.hasStdExtZfh())
664       for (MVT VT : F16VecVTs)
665         SetCommonVFPActions(VT);
666 
667     for (MVT VT : F32VecVTs) {
668       if (Subtarget.hasStdExtF())
669         SetCommonVFPActions(VT);
670       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
671     }
672 
673     for (MVT VT : F64VecVTs) {
674       if (Subtarget.hasStdExtD())
675         SetCommonVFPActions(VT);
676       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
677       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
678     }
679 
680     if (Subtarget.useRVVForFixedLengthVectors()) {
681       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
682         if (!useRVVForFixedLengthVectorVT(VT))
683           continue;
684 
685         // By default everything must be expanded.
686         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
687           setOperationAction(Op, VT, Expand);
688         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
689           setTruncStoreAction(VT, OtherVT, Expand);
690           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
691           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
692           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
693         }
694 
695         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
696         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
697         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
698 
699         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
700         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
701 
702         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
703         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
704 
705         setOperationAction(ISD::LOAD, VT, Custom);
706         setOperationAction(ISD::STORE, VT, Custom);
707 
708         setOperationAction(ISD::SETCC, VT, Custom);
709 
710         setOperationAction(ISD::SELECT, VT, Custom);
711 
712         setOperationAction(ISD::TRUNCATE, VT, Custom);
713 
714         setOperationAction(ISD::BITCAST, VT, Custom);
715 
716         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
717         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
718         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
719 
720         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
721         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
722         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
723         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
724 
725         // Operations below are different for between masks and other vectors.
726         if (VT.getVectorElementType() == MVT::i1) {
727           setOperationAction(ISD::AND, VT, Custom);
728           setOperationAction(ISD::OR, VT, Custom);
729           setOperationAction(ISD::XOR, VT, Custom);
730           continue;
731         }
732 
733         // Use SPLAT_VECTOR to prevent type legalization from destroying the
734         // splats when type legalizing i64 scalar on RV32.
735         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
736         // improvements first.
737         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
738           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
739           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
740         }
741 
742         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
743         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
744 
745         setOperationAction(ISD::MLOAD, VT, Custom);
746         setOperationAction(ISD::MSTORE, VT, Custom);
747         setOperationAction(ISD::MGATHER, VT, Custom);
748         setOperationAction(ISD::MSCATTER, VT, Custom);
749 
750         setOperationAction(ISD::VP_LOAD, VT, Custom);
751         setOperationAction(ISD::VP_STORE, VT, Custom);
752         setOperationAction(ISD::VP_GATHER, VT, Custom);
753         setOperationAction(ISD::VP_SCATTER, VT, Custom);
754 
755         setOperationAction(ISD::ADD, VT, Custom);
756         setOperationAction(ISD::MUL, VT, Custom);
757         setOperationAction(ISD::SUB, VT, Custom);
758         setOperationAction(ISD::AND, VT, Custom);
759         setOperationAction(ISD::OR, VT, Custom);
760         setOperationAction(ISD::XOR, VT, Custom);
761         setOperationAction(ISD::SDIV, VT, Custom);
762         setOperationAction(ISD::SREM, VT, Custom);
763         setOperationAction(ISD::UDIV, VT, Custom);
764         setOperationAction(ISD::UREM, VT, Custom);
765         setOperationAction(ISD::SHL, VT, Custom);
766         setOperationAction(ISD::SRA, VT, Custom);
767         setOperationAction(ISD::SRL, VT, Custom);
768 
769         setOperationAction(ISD::SMIN, VT, Custom);
770         setOperationAction(ISD::SMAX, VT, Custom);
771         setOperationAction(ISD::UMIN, VT, Custom);
772         setOperationAction(ISD::UMAX, VT, Custom);
773         setOperationAction(ISD::ABS,  VT, Custom);
774 
775         setOperationAction(ISD::MULHS, VT, Custom);
776         setOperationAction(ISD::MULHU, VT, Custom);
777 
778         setOperationAction(ISD::SADDSAT, VT, Custom);
779         setOperationAction(ISD::UADDSAT, VT, Custom);
780         setOperationAction(ISD::SSUBSAT, VT, Custom);
781         setOperationAction(ISD::USUBSAT, VT, Custom);
782 
783         setOperationAction(ISD::VSELECT, VT, Custom);
784         setOperationAction(ISD::SELECT_CC, VT, Expand);
785 
786         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
787         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
788         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
789 
790         // Custom-lower reduction operations to set up the corresponding custom
791         // nodes' operands.
792         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
793         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
794         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
795         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
796         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
797 
798         for (unsigned VPOpc : IntegerVPOps)
799           setOperationAction(VPOpc, VT, Custom);
800       }
801 
802       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
803         if (!useRVVForFixedLengthVectorVT(VT))
804           continue;
805 
806         // By default everything must be expanded.
807         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
808           setOperationAction(Op, VT, Expand);
809         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
810           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
811           setTruncStoreAction(VT, OtherVT, Expand);
812         }
813 
814         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
815         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
816         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
817 
818         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
819         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
820         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
821         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
822         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
823 
824         setOperationAction(ISD::LOAD, VT, Custom);
825         setOperationAction(ISD::STORE, VT, Custom);
826         setOperationAction(ISD::MLOAD, VT, Custom);
827         setOperationAction(ISD::MSTORE, VT, Custom);
828         setOperationAction(ISD::MGATHER, VT, Custom);
829         setOperationAction(ISD::MSCATTER, VT, Custom);
830 
831         setOperationAction(ISD::VP_LOAD, VT, Custom);
832         setOperationAction(ISD::VP_STORE, VT, Custom);
833         setOperationAction(ISD::VP_GATHER, VT, Custom);
834         setOperationAction(ISD::VP_SCATTER, VT, Custom);
835 
836         setOperationAction(ISD::FADD, VT, Custom);
837         setOperationAction(ISD::FSUB, VT, Custom);
838         setOperationAction(ISD::FMUL, VT, Custom);
839         setOperationAction(ISD::FDIV, VT, Custom);
840         setOperationAction(ISD::FNEG, VT, Custom);
841         setOperationAction(ISD::FABS, VT, Custom);
842         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
843         setOperationAction(ISD::FSQRT, VT, Custom);
844         setOperationAction(ISD::FMA, VT, Custom);
845         setOperationAction(ISD::FMINNUM, VT, Custom);
846         setOperationAction(ISD::FMAXNUM, VT, Custom);
847 
848         setOperationAction(ISD::FP_ROUND, VT, Custom);
849         setOperationAction(ISD::FP_EXTEND, VT, Custom);
850 
851         for (auto CC : VFPCCToExpand)
852           setCondCodeAction(CC, VT, Expand);
853 
854         setOperationAction(ISD::VSELECT, VT, Custom);
855         setOperationAction(ISD::SELECT, VT, Custom);
856         setOperationAction(ISD::SELECT_CC, VT, Expand);
857 
858         setOperationAction(ISD::BITCAST, VT, Custom);
859 
860         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
861         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
862         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
863         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
864 
865         for (unsigned VPOpc : FloatingPointVPOps)
866           setOperationAction(VPOpc, VT, Custom);
867       }
868 
869       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
870       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
871       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
872       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
873       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
874       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
875       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
876       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
877     }
878   }
879 
880   // Function alignments.
881   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
882   setMinFunctionAlignment(FunctionAlignment);
883   setPrefFunctionAlignment(FunctionAlignment);
884 
885   setMinimumJumpTableEntries(5);
886 
887   // Jumps are expensive, compared to logic
888   setJumpIsExpensive();
889 
890   // We can use any register for comparisons
891   setHasMultipleConditionRegisters();
892 
893   setTargetDAGCombine(ISD::ADD);
894   setTargetDAGCombine(ISD::SUB);
895   setTargetDAGCombine(ISD::AND);
896   setTargetDAGCombine(ISD::OR);
897   setTargetDAGCombine(ISD::XOR);
898   setTargetDAGCombine(ISD::ANY_EXTEND);
899   setTargetDAGCombine(ISD::ZERO_EXTEND);
900   if (Subtarget.hasStdExtV()) {
901     setTargetDAGCombine(ISD::FCOPYSIGN);
902     setTargetDAGCombine(ISD::MGATHER);
903     setTargetDAGCombine(ISD::MSCATTER);
904     setTargetDAGCombine(ISD::VP_GATHER);
905     setTargetDAGCombine(ISD::VP_SCATTER);
906     setTargetDAGCombine(ISD::SRA);
907     setTargetDAGCombine(ISD::SRL);
908     setTargetDAGCombine(ISD::SHL);
909   }
910 }
911 
912 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
913                                             LLVMContext &Context,
914                                             EVT VT) const {
915   if (!VT.isVector())
916     return getPointerTy(DL);
917   if (Subtarget.hasStdExtV() &&
918       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
919     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
920   return VT.changeVectorElementTypeToInteger();
921 }
922 
923 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
924   return Subtarget.getXLenVT();
925 }
926 
927 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
928                                              const CallInst &I,
929                                              MachineFunction &MF,
930                                              unsigned Intrinsic) const {
931   switch (Intrinsic) {
932   default:
933     return false;
934   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
935   case Intrinsic::riscv_masked_atomicrmw_add_i32:
936   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
937   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
938   case Intrinsic::riscv_masked_atomicrmw_max_i32:
939   case Intrinsic::riscv_masked_atomicrmw_min_i32:
940   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
941   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
942   case Intrinsic::riscv_masked_cmpxchg_i32: {
943     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
944     Info.opc = ISD::INTRINSIC_W_CHAIN;
945     Info.memVT = MVT::getVT(PtrTy->getElementType());
946     Info.ptrVal = I.getArgOperand(0);
947     Info.offset = 0;
948     Info.align = Align(4);
949     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
950                  MachineMemOperand::MOVolatile;
951     return true;
952   }
953   case Intrinsic::riscv_masked_strided_load:
954     Info.opc = ISD::INTRINSIC_W_CHAIN;
955     Info.ptrVal = I.getArgOperand(1);
956     Info.memVT = MVT::getVT(I.getType()->getScalarType());
957     Info.align = Align(I.getType()->getScalarSizeInBits() / 8);
958     Info.size = MemoryLocation::UnknownSize;
959     Info.flags |= MachineMemOperand::MOLoad;
960     return true;
961   case Intrinsic::riscv_masked_strided_store:
962     Info.opc = ISD::INTRINSIC_VOID;
963     Info.ptrVal = I.getArgOperand(1);
964     Info.memVT = MVT::getVT(I.getArgOperand(0)->getType()->getScalarType());
965     Info.align =
966         Align(I.getArgOperand(0)->getType()->getScalarSizeInBits() / 8);
967     Info.size = MemoryLocation::UnknownSize;
968     Info.flags |= MachineMemOperand::MOStore;
969     return true;
970   }
971 }
972 
973 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
974                                                 const AddrMode &AM, Type *Ty,
975                                                 unsigned AS,
976                                                 Instruction *I) const {
977   // No global is ever allowed as a base.
978   if (AM.BaseGV)
979     return false;
980 
981   // Require a 12-bit signed offset.
982   if (!isInt<12>(AM.BaseOffs))
983     return false;
984 
985   switch (AM.Scale) {
986   case 0: // "r+i" or just "i", depending on HasBaseReg.
987     break;
988   case 1:
989     if (!AM.HasBaseReg) // allow "r+i".
990       break;
991     return false; // disallow "r+r" or "r+r+i".
992   default:
993     return false;
994   }
995 
996   return true;
997 }
998 
999 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1000   return isInt<12>(Imm);
1001 }
1002 
1003 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1004   return isInt<12>(Imm);
1005 }
1006 
1007 // On RV32, 64-bit integers are split into their high and low parts and held
1008 // in two different registers, so the trunc is free since the low register can
1009 // just be used.
1010 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1011   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1012     return false;
1013   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1014   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1015   return (SrcBits == 64 && DestBits == 32);
1016 }
1017 
1018 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1019   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1020       !SrcVT.isInteger() || !DstVT.isInteger())
1021     return false;
1022   unsigned SrcBits = SrcVT.getSizeInBits();
1023   unsigned DestBits = DstVT.getSizeInBits();
1024   return (SrcBits == 64 && DestBits == 32);
1025 }
1026 
1027 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1028   // Zexts are free if they can be combined with a load.
1029   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1030     EVT MemVT = LD->getMemoryVT();
1031     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1032          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1033         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1034          LD->getExtensionType() == ISD::ZEXTLOAD))
1035       return true;
1036   }
1037 
1038   return TargetLowering::isZExtFree(Val, VT2);
1039 }
1040 
1041 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1042   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1043 }
1044 
1045 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1046   return Subtarget.hasStdExtZbb();
1047 }
1048 
1049 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1050   return Subtarget.hasStdExtZbb();
1051 }
1052 
1053 /// Check if sinking \p I's operands to I's basic block is profitable, because
1054 /// the operands can be folded into a target instruction, e.g.
1055 /// splats of scalars can fold into vector instructions.
1056 bool RISCVTargetLowering::shouldSinkOperands(
1057     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1058   using namespace llvm::PatternMatch;
1059 
1060   if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV())
1061     return false;
1062 
1063   auto IsSinker = [&](Instruction *I, int Operand) {
1064     switch (I->getOpcode()) {
1065     case Instruction::Add:
1066     case Instruction::Sub:
1067     case Instruction::Mul:
1068     case Instruction::And:
1069     case Instruction::Or:
1070     case Instruction::Xor:
1071     case Instruction::FAdd:
1072     case Instruction::FSub:
1073     case Instruction::FMul:
1074     case Instruction::FDiv:
1075       return true;
1076     case Instruction::Shl:
1077     case Instruction::LShr:
1078     case Instruction::AShr:
1079       return Operand == 1;
1080     case Instruction::Call:
1081       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1082         switch (II->getIntrinsicID()) {
1083         case Intrinsic::fma:
1084           return Operand == 0 || Operand == 1;
1085         default:
1086           return false;
1087         }
1088       }
1089       return false;
1090     default:
1091       return false;
1092     }
1093   };
1094 
1095   for (auto OpIdx : enumerate(I->operands())) {
1096     if (!IsSinker(I, OpIdx.index()))
1097       continue;
1098 
1099     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1100     // Make sure we are not already sinking this operand
1101     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1102       continue;
1103 
1104     // We are looking for a splat that can be sunk.
1105     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1106                              m_Undef(), m_ZeroMask())))
1107       continue;
1108 
1109     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1110     // and vector registers
1111     for (Use &U : Op->uses()) {
1112       Instruction *Insn = cast<Instruction>(U.getUser());
1113       if (!IsSinker(Insn, U.getOperandNo()))
1114         return false;
1115     }
1116 
1117     Ops.push_back(&Op->getOperandUse(0));
1118     Ops.push_back(&OpIdx.value());
1119   }
1120   return true;
1121 }
1122 
1123 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1124                                        bool ForCodeSize) const {
1125   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1126     return false;
1127   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1128     return false;
1129   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1130     return false;
1131   if (Imm.isNegZero())
1132     return false;
1133   return Imm.isZero();
1134 }
1135 
1136 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1137   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1138          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1139          (VT == MVT::f64 && Subtarget.hasStdExtD());
1140 }
1141 
1142 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1143                                                       CallingConv::ID CC,
1144                                                       EVT VT) const {
1145   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1146   // end up using a GPR but that will be decided based on ABI.
1147   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1148     return MVT::f32;
1149 
1150   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1151 }
1152 
1153 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1154                                                            CallingConv::ID CC,
1155                                                            EVT VT) const {
1156   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1157   // end up using a GPR but that will be decided based on ABI.
1158   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1159     return 1;
1160 
1161   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1162 }
1163 
1164 // Changes the condition code and swaps operands if necessary, so the SetCC
1165 // operation matches one of the comparisons supported directly by branches
1166 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1167 // with 1/-1.
1168 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1169                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1170   // Convert X > -1 to X >= 0.
1171   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1172     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1173     CC = ISD::SETGE;
1174     return;
1175   }
1176   // Convert X < 1 to 0 >= X.
1177   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1178     RHS = LHS;
1179     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1180     CC = ISD::SETGE;
1181     return;
1182   }
1183 
1184   switch (CC) {
1185   default:
1186     break;
1187   case ISD::SETGT:
1188   case ISD::SETLE:
1189   case ISD::SETUGT:
1190   case ISD::SETULE:
1191     CC = ISD::getSetCCSwappedOperands(CC);
1192     std::swap(LHS, RHS);
1193     break;
1194   }
1195 }
1196 
1197 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1198   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1199   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1200   if (VT.getVectorElementType() == MVT::i1)
1201     KnownSize *= 8;
1202 
1203   switch (KnownSize) {
1204   default:
1205     llvm_unreachable("Invalid LMUL.");
1206   case 8:
1207     return RISCVII::VLMUL::LMUL_F8;
1208   case 16:
1209     return RISCVII::VLMUL::LMUL_F4;
1210   case 32:
1211     return RISCVII::VLMUL::LMUL_F2;
1212   case 64:
1213     return RISCVII::VLMUL::LMUL_1;
1214   case 128:
1215     return RISCVII::VLMUL::LMUL_2;
1216   case 256:
1217     return RISCVII::VLMUL::LMUL_4;
1218   case 512:
1219     return RISCVII::VLMUL::LMUL_8;
1220   }
1221 }
1222 
1223 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1224   switch (LMul) {
1225   default:
1226     llvm_unreachable("Invalid LMUL.");
1227   case RISCVII::VLMUL::LMUL_F8:
1228   case RISCVII::VLMUL::LMUL_F4:
1229   case RISCVII::VLMUL::LMUL_F2:
1230   case RISCVII::VLMUL::LMUL_1:
1231     return RISCV::VRRegClassID;
1232   case RISCVII::VLMUL::LMUL_2:
1233     return RISCV::VRM2RegClassID;
1234   case RISCVII::VLMUL::LMUL_4:
1235     return RISCV::VRM4RegClassID;
1236   case RISCVII::VLMUL::LMUL_8:
1237     return RISCV::VRM8RegClassID;
1238   }
1239 }
1240 
1241 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1242   RISCVII::VLMUL LMUL = getLMUL(VT);
1243   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1244       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1245       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1246       LMUL == RISCVII::VLMUL::LMUL_1) {
1247     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1248                   "Unexpected subreg numbering");
1249     return RISCV::sub_vrm1_0 + Index;
1250   }
1251   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1252     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1253                   "Unexpected subreg numbering");
1254     return RISCV::sub_vrm2_0 + Index;
1255   }
1256   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1257     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1258                   "Unexpected subreg numbering");
1259     return RISCV::sub_vrm4_0 + Index;
1260   }
1261   llvm_unreachable("Invalid vector type.");
1262 }
1263 
1264 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1265   if (VT.getVectorElementType() == MVT::i1)
1266     return RISCV::VRRegClassID;
1267   return getRegClassIDForLMUL(getLMUL(VT));
1268 }
1269 
1270 // Attempt to decompose a subvector insert/extract between VecVT and
1271 // SubVecVT via subregister indices. Returns the subregister index that
1272 // can perform the subvector insert/extract with the given element index, as
1273 // well as the index corresponding to any leftover subvectors that must be
1274 // further inserted/extracted within the register class for SubVecVT.
1275 std::pair<unsigned, unsigned>
1276 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1277     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1278     const RISCVRegisterInfo *TRI) {
1279   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1280                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1281                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1282                 "Register classes not ordered");
1283   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1284   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1285   // Try to compose a subregister index that takes us from the incoming
1286   // LMUL>1 register class down to the outgoing one. At each step we half
1287   // the LMUL:
1288   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1289   // Note that this is not guaranteed to find a subregister index, such as
1290   // when we are extracting from one VR type to another.
1291   unsigned SubRegIdx = RISCV::NoSubRegister;
1292   for (const unsigned RCID :
1293        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1294     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1295       VecVT = VecVT.getHalfNumVectorElementsVT();
1296       bool IsHi =
1297           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1298       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1299                                             getSubregIndexByMVT(VecVT, IsHi));
1300       if (IsHi)
1301         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1302     }
1303   return {SubRegIdx, InsertExtractIdx};
1304 }
1305 
1306 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1307 // stores for those types.
1308 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1309   return !Subtarget.useRVVForFixedLengthVectors() ||
1310          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1311 }
1312 
1313 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1314   if (ScalarTy->isPointerTy())
1315     return true;
1316 
1317   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1318       ScalarTy->isIntegerTy(32) || ScalarTy->isIntegerTy(64))
1319     return true;
1320 
1321   if (ScalarTy->isHalfTy())
1322     return Subtarget.hasStdExtZfh();
1323   if (ScalarTy->isFloatTy())
1324     return Subtarget.hasStdExtF();
1325   if (ScalarTy->isDoubleTy())
1326     return Subtarget.hasStdExtD();
1327 
1328   return false;
1329 }
1330 
1331 static bool useRVVForFixedLengthVectorVT(MVT VT,
1332                                          const RISCVSubtarget &Subtarget) {
1333   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1334   if (!Subtarget.useRVVForFixedLengthVectors())
1335     return false;
1336 
1337   // We only support a set of vector types with a consistent maximum fixed size
1338   // across all supported vector element types to avoid legalization issues.
1339   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1340   // fixed-length vector type we support is 1024 bytes.
1341   if (VT.getFixedSizeInBits() > 1024 * 8)
1342     return false;
1343 
1344   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1345 
1346   MVT EltVT = VT.getVectorElementType();
1347 
1348   // Don't use RVV for vectors we cannot scalarize if required.
1349   switch (EltVT.SimpleTy) {
1350   // i1 is supported but has different rules.
1351   default:
1352     return false;
1353   case MVT::i1:
1354     // Masks can only use a single register.
1355     if (VT.getVectorNumElements() > MinVLen)
1356       return false;
1357     MinVLen /= 8;
1358     break;
1359   case MVT::i8:
1360   case MVT::i16:
1361   case MVT::i32:
1362   case MVT::i64:
1363     break;
1364   case MVT::f16:
1365     if (!Subtarget.hasStdExtZfh())
1366       return false;
1367     break;
1368   case MVT::f32:
1369     if (!Subtarget.hasStdExtF())
1370       return false;
1371     break;
1372   case MVT::f64:
1373     if (!Subtarget.hasStdExtD())
1374       return false;
1375     break;
1376   }
1377 
1378   // Reject elements larger than ELEN.
1379   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1380     return false;
1381 
1382   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1383   // Don't use RVV for types that don't fit.
1384   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1385     return false;
1386 
1387   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1388   // the base fixed length RVV support in place.
1389   if (!VT.isPow2VectorType())
1390     return false;
1391 
1392   return true;
1393 }
1394 
1395 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1396   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1397 }
1398 
1399 // Return the largest legal scalable vector type that matches VT's element type.
1400 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1401                                             const RISCVSubtarget &Subtarget) {
1402   // This may be called before legal types are setup.
1403   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1404           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1405          "Expected legal fixed length vector!");
1406 
1407   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1408   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1409 
1410   MVT EltVT = VT.getVectorElementType();
1411   switch (EltVT.SimpleTy) {
1412   default:
1413     llvm_unreachable("unexpected element type for RVV container");
1414   case MVT::i1:
1415   case MVT::i8:
1416   case MVT::i16:
1417   case MVT::i32:
1418   case MVT::i64:
1419   case MVT::f16:
1420   case MVT::f32:
1421   case MVT::f64: {
1422     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1423     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1424     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1425     unsigned NumElts =
1426         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1427     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1428     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1429     return MVT::getScalableVectorVT(EltVT, NumElts);
1430   }
1431   }
1432 }
1433 
1434 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1435                                             const RISCVSubtarget &Subtarget) {
1436   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1437                                           Subtarget);
1438 }
1439 
1440 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1441   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1442 }
1443 
1444 // Grow V to consume an entire RVV register.
1445 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1446                                        const RISCVSubtarget &Subtarget) {
1447   assert(VT.isScalableVector() &&
1448          "Expected to convert into a scalable vector!");
1449   assert(V.getValueType().isFixedLengthVector() &&
1450          "Expected a fixed length vector operand!");
1451   SDLoc DL(V);
1452   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1453   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1454 }
1455 
1456 // Shrink V so it's just big enough to maintain a VT's worth of data.
1457 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1458                                          const RISCVSubtarget &Subtarget) {
1459   assert(VT.isFixedLengthVector() &&
1460          "Expected to convert into a fixed length vector!");
1461   assert(V.getValueType().isScalableVector() &&
1462          "Expected a scalable vector operand!");
1463   SDLoc DL(V);
1464   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1465   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1466 }
1467 
1468 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1469 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1470 // the vector type that it is contained in.
1471 static std::pair<SDValue, SDValue>
1472 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1473                 const RISCVSubtarget &Subtarget) {
1474   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1475   MVT XLenVT = Subtarget.getXLenVT();
1476   SDValue VL = VecVT.isFixedLengthVector()
1477                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1478                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1479   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1480   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1481   return {Mask, VL};
1482 }
1483 
1484 // As above but assuming the given type is a scalable vector type.
1485 static std::pair<SDValue, SDValue>
1486 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1487                         const RISCVSubtarget &Subtarget) {
1488   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1489   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1490 }
1491 
1492 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1493 // of either is (currently) supported. This can get us into an infinite loop
1494 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1495 // as a ..., etc.
1496 // Until either (or both) of these can reliably lower any node, reporting that
1497 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1498 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1499 // which is not desirable.
1500 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1501     EVT VT, unsigned DefinedValues) const {
1502   return false;
1503 }
1504 
1505 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1506   // Only splats are currently supported.
1507   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1508     return true;
1509 
1510   return false;
1511 }
1512 
1513 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1514   // RISCV FP-to-int conversions saturate to the destination register size, but
1515   // don't produce 0 for nan. We can use a conversion instruction and fix the
1516   // nan case with a compare and a select.
1517   SDValue Src = Op.getOperand(0);
1518 
1519   EVT DstVT = Op.getValueType();
1520   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1521 
1522   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1523   unsigned Opc;
1524   if (SatVT == DstVT)
1525     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1526   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1527     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1528   else
1529     return SDValue();
1530   // FIXME: Support other SatVTs by clamping before or after the conversion.
1531 
1532   SDLoc DL(Op);
1533   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1534 
1535   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1536   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1537 }
1538 
1539 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1540                                  const RISCVSubtarget &Subtarget) {
1541   MVT VT = Op.getSimpleValueType();
1542   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1543 
1544   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1545 
1546   SDLoc DL(Op);
1547   SDValue Mask, VL;
1548   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1549 
1550   unsigned Opc =
1551       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1552   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1553   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1554 }
1555 
1556 struct VIDSequence {
1557   int64_t StepNumerator;
1558   unsigned StepDenominator;
1559   int64_t Addend;
1560 };
1561 
1562 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1563 // to the (non-zero) step S and start value X. This can be then lowered as the
1564 // RVV sequence (VID * S) + X, for example.
1565 // The step S is represented as an integer numerator divided by a positive
1566 // denominator. Note that the implementation currently only identifies
1567 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1568 // cannot detect 2/3, for example.
1569 // Note that this method will also match potentially unappealing index
1570 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1571 // determine whether this is worth generating code for.
1572 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1573   unsigned NumElts = Op.getNumOperands();
1574   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1575   if (!Op.getValueType().isInteger())
1576     return None;
1577 
1578   Optional<unsigned> SeqStepDenom;
1579   Optional<int64_t> SeqStepNum, SeqAddend;
1580   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1581   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1582   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1583     // Assume undef elements match the sequence; we just have to be careful
1584     // when interpolating across them.
1585     if (Op.getOperand(Idx).isUndef())
1586       continue;
1587     // The BUILD_VECTOR must be all constants.
1588     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1589       return None;
1590 
1591     uint64_t Val = Op.getConstantOperandVal(Idx) &
1592                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1593 
1594     if (PrevElt) {
1595       // Calculate the step since the last non-undef element, and ensure
1596       // it's consistent across the entire sequence.
1597       unsigned IdxDiff = Idx - PrevElt->second;
1598       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1599 
1600       // A zero-value value difference means that we're somewhere in the middle
1601       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1602       // step change before evaluating the sequence.
1603       if (ValDiff != 0) {
1604         int64_t Remainder = ValDiff % IdxDiff;
1605         // Normalize the step if it's greater than 1.
1606         if (Remainder != ValDiff) {
1607           // The difference must cleanly divide the element span.
1608           if (Remainder != 0)
1609             return None;
1610           ValDiff /= IdxDiff;
1611           IdxDiff = 1;
1612         }
1613 
1614         if (!SeqStepNum)
1615           SeqStepNum = ValDiff;
1616         else if (ValDiff != SeqStepNum)
1617           return None;
1618 
1619         if (!SeqStepDenom)
1620           SeqStepDenom = IdxDiff;
1621         else if (IdxDiff != *SeqStepDenom)
1622           return None;
1623       }
1624     }
1625 
1626     // Record and/or check any addend.
1627     if (SeqStepNum && SeqStepDenom) {
1628       uint64_t ExpectedVal =
1629           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1630       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1631       if (!SeqAddend)
1632         SeqAddend = Addend;
1633       else if (SeqAddend != Addend)
1634         return None;
1635     }
1636 
1637     // Record this non-undef element for later.
1638     if (!PrevElt || PrevElt->first != Val)
1639       PrevElt = std::make_pair(Val, Idx);
1640   }
1641   // We need to have logged both a step and an addend for this to count as
1642   // a legal index sequence.
1643   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1644     return None;
1645 
1646   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1647 }
1648 
1649 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1650                                  const RISCVSubtarget &Subtarget) {
1651   MVT VT = Op.getSimpleValueType();
1652   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1653 
1654   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1655 
1656   SDLoc DL(Op);
1657   SDValue Mask, VL;
1658   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1659 
1660   MVT XLenVT = Subtarget.getXLenVT();
1661   unsigned NumElts = Op.getNumOperands();
1662 
1663   if (VT.getVectorElementType() == MVT::i1) {
1664     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1665       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1666       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1667     }
1668 
1669     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1670       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1671       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1672     }
1673 
1674     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1675     // scalar integer chunks whose bit-width depends on the number of mask
1676     // bits and XLEN.
1677     // First, determine the most appropriate scalar integer type to use. This
1678     // is at most XLenVT, but may be shrunk to a smaller vector element type
1679     // according to the size of the final vector - use i8 chunks rather than
1680     // XLenVT if we're producing a v8i1. This results in more consistent
1681     // codegen across RV32 and RV64.
1682     unsigned NumViaIntegerBits =
1683         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1684     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1685       // If we have to use more than one INSERT_VECTOR_ELT then this
1686       // optimization is likely to increase code size; avoid peforming it in
1687       // such a case. We can use a load from a constant pool in this case.
1688       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1689         return SDValue();
1690       // Now we can create our integer vector type. Note that it may be larger
1691       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1692       MVT IntegerViaVecVT =
1693           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1694                            divideCeil(NumElts, NumViaIntegerBits));
1695 
1696       uint64_t Bits = 0;
1697       unsigned BitPos = 0, IntegerEltIdx = 0;
1698       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1699 
1700       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1701         // Once we accumulate enough bits to fill our scalar type, insert into
1702         // our vector and clear our accumulated data.
1703         if (I != 0 && I % NumViaIntegerBits == 0) {
1704           if (NumViaIntegerBits <= 32)
1705             Bits = SignExtend64(Bits, 32);
1706           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1707           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1708                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1709           Bits = 0;
1710           BitPos = 0;
1711           IntegerEltIdx++;
1712         }
1713         SDValue V = Op.getOperand(I);
1714         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1715         Bits |= ((uint64_t)BitValue << BitPos);
1716       }
1717 
1718       // Insert the (remaining) scalar value into position in our integer
1719       // vector type.
1720       if (NumViaIntegerBits <= 32)
1721         Bits = SignExtend64(Bits, 32);
1722       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1723       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1724                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1725 
1726       if (NumElts < NumViaIntegerBits) {
1727         // If we're producing a smaller vector than our minimum legal integer
1728         // type, bitcast to the equivalent (known-legal) mask type, and extract
1729         // our final mask.
1730         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1731         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1732         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1733                           DAG.getConstant(0, DL, XLenVT));
1734       } else {
1735         // Else we must have produced an integer type with the same size as the
1736         // mask type; bitcast for the final result.
1737         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1738         Vec = DAG.getBitcast(VT, Vec);
1739       }
1740 
1741       return Vec;
1742     }
1743 
1744     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1745     // vector type, we have a legal equivalently-sized i8 type, so we can use
1746     // that.
1747     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1748     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1749 
1750     SDValue WideVec;
1751     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1752       // For a splat, perform a scalar truncate before creating the wider
1753       // vector.
1754       assert(Splat.getValueType() == XLenVT &&
1755              "Unexpected type for i1 splat value");
1756       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1757                           DAG.getConstant(1, DL, XLenVT));
1758       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1759     } else {
1760       SmallVector<SDValue, 8> Ops(Op->op_values());
1761       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1762       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1763       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1764     }
1765 
1766     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1767   }
1768 
1769   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1770     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1771                                         : RISCVISD::VMV_V_X_VL;
1772     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1773     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1774   }
1775 
1776   // Try and match index sequences, which we can lower to the vid instruction
1777   // with optional modifications. An all-undef vector is matched by
1778   // getSplatValue, above.
1779   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1780     int64_t StepNumerator = SimpleVID->StepNumerator;
1781     unsigned StepDenominator = SimpleVID->StepDenominator;
1782     int64_t Addend = SimpleVID->Addend;
1783     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1784     // threshold since it's the immediate value many RVV instructions accept.
1785     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1786         isInt<5>(Addend)) {
1787       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1788       // Convert right out of the scalable type so we can use standard ISD
1789       // nodes for the rest of the computation. If we used scalable types with
1790       // these, we'd lose the fixed-length vector info and generate worse
1791       // vsetvli code.
1792       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1793       assert(StepNumerator != 0 && "Invalid step");
1794       bool Negate = false;
1795       if (StepNumerator != 1) {
1796         int64_t SplatStepVal = StepNumerator;
1797         unsigned Opcode = ISD::MUL;
1798         if (isPowerOf2_64(std::abs(StepNumerator))) {
1799           Negate = StepNumerator < 0;
1800           Opcode = ISD::SHL;
1801           SplatStepVal = Log2_64(std::abs(StepNumerator));
1802         }
1803         SDValue SplatStep = DAG.getSplatVector(
1804             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1805         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1806       }
1807       if (StepDenominator != 1) {
1808         SDValue SplatStep = DAG.getSplatVector(
1809             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1810         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1811       }
1812       if (Addend != 0 || Negate) {
1813         SDValue SplatAddend =
1814             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1815         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1816       }
1817       return VID;
1818     }
1819   }
1820 
1821   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1822   // when re-interpreted as a vector with a larger element type. For example,
1823   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1824   // could be instead splat as
1825   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1826   // TODO: This optimization could also work on non-constant splats, but it
1827   // would require bit-manipulation instructions to construct the splat value.
1828   SmallVector<SDValue> Sequence;
1829   unsigned EltBitSize = VT.getScalarSizeInBits();
1830   const auto *BV = cast<BuildVectorSDNode>(Op);
1831   if (VT.isInteger() && EltBitSize < 64 &&
1832       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1833       BV->getRepeatedSequence(Sequence) &&
1834       (Sequence.size() * EltBitSize) <= 64) {
1835     unsigned SeqLen = Sequence.size();
1836     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1837     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1838     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1839             ViaIntVT == MVT::i64) &&
1840            "Unexpected sequence type");
1841 
1842     unsigned EltIdx = 0;
1843     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1844     uint64_t SplatValue = 0;
1845     // Construct the amalgamated value which can be splatted as this larger
1846     // vector type.
1847     for (const auto &SeqV : Sequence) {
1848       if (!SeqV.isUndef())
1849         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1850                        << (EltIdx * EltBitSize));
1851       EltIdx++;
1852     }
1853 
1854     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1855     // achieve better constant materializion.
1856     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1857       SplatValue = SignExtend64(SplatValue, 32);
1858 
1859     // Since we can't introduce illegal i64 types at this stage, we can only
1860     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1861     // way we can use RVV instructions to splat.
1862     assert((ViaIntVT.bitsLE(XLenVT) ||
1863             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1864            "Unexpected bitcast sequence");
1865     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1866       SDValue ViaVL =
1867           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1868       MVT ViaContainerVT =
1869           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1870       SDValue Splat =
1871           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1872                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1873       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1874       return DAG.getBitcast(VT, Splat);
1875     }
1876   }
1877 
1878   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1879   // which constitute a large proportion of the elements. In such cases we can
1880   // splat a vector with the dominant element and make up the shortfall with
1881   // INSERT_VECTOR_ELTs.
1882   // Note that this includes vectors of 2 elements by association. The
1883   // upper-most element is the "dominant" one, allowing us to use a splat to
1884   // "insert" the upper element, and an insert of the lower element at position
1885   // 0, which improves codegen.
1886   SDValue DominantValue;
1887   unsigned MostCommonCount = 0;
1888   DenseMap<SDValue, unsigned> ValueCounts;
1889   unsigned NumUndefElts =
1890       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1891 
1892   // Track the number of scalar loads we know we'd be inserting, estimated as
1893   // any non-zero floating-point constant. Other kinds of element are either
1894   // already in registers or are materialized on demand. The threshold at which
1895   // a vector load is more desirable than several scalar materializion and
1896   // vector-insertion instructions is not known.
1897   unsigned NumScalarLoads = 0;
1898 
1899   for (SDValue V : Op->op_values()) {
1900     if (V.isUndef())
1901       continue;
1902 
1903     ValueCounts.insert(std::make_pair(V, 0));
1904     unsigned &Count = ValueCounts[V];
1905 
1906     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1907       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1908 
1909     // Is this value dominant? In case of a tie, prefer the highest element as
1910     // it's cheaper to insert near the beginning of a vector than it is at the
1911     // end.
1912     if (++Count >= MostCommonCount) {
1913       DominantValue = V;
1914       MostCommonCount = Count;
1915     }
1916   }
1917 
1918   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1919   unsigned NumDefElts = NumElts - NumUndefElts;
1920   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1921 
1922   // Don't perform this optimization when optimizing for size, since
1923   // materializing elements and inserting them tends to cause code bloat.
1924   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1925       ((MostCommonCount > DominantValueCountThreshold) ||
1926        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1927     // Start by splatting the most common element.
1928     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1929 
1930     DenseSet<SDValue> Processed{DominantValue};
1931     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1932     for (const auto &OpIdx : enumerate(Op->ops())) {
1933       const SDValue &V = OpIdx.value();
1934       if (V.isUndef() || !Processed.insert(V).second)
1935         continue;
1936       if (ValueCounts[V] == 1) {
1937         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1938                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1939       } else {
1940         // Blend in all instances of this value using a VSELECT, using a
1941         // mask where each bit signals whether that element is the one
1942         // we're after.
1943         SmallVector<SDValue> Ops;
1944         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1945           return DAG.getConstant(V == V1, DL, XLenVT);
1946         });
1947         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1948                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1949                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1950       }
1951     }
1952 
1953     return Vec;
1954   }
1955 
1956   return SDValue();
1957 }
1958 
1959 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
1960                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
1961   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
1962     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
1963     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
1964     // If Hi constant is all the same sign bit as Lo, lower this as a custom
1965     // node in order to try and match RVV vector/scalar instructions.
1966     if ((LoC >> 31) == HiC)
1967       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
1968   }
1969 
1970   // Fall back to a stack store and stride x0 vector load.
1971   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
1972 }
1973 
1974 // Called by type legalization to handle splat of i64 on RV32.
1975 // FIXME: We can optimize this when the type has sign or zero bits in one
1976 // of the halves.
1977 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
1978                                    SDValue VL, SelectionDAG &DAG) {
1979   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
1980   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1981                            DAG.getConstant(0, DL, MVT::i32));
1982   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1983                            DAG.getConstant(1, DL, MVT::i32));
1984   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
1985 }
1986 
1987 // This function lowers a splat of a scalar operand Splat with the vector
1988 // length VL. It ensures the final sequence is type legal, which is useful when
1989 // lowering a splat after type legalization.
1990 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
1991                                 SelectionDAG &DAG,
1992                                 const RISCVSubtarget &Subtarget) {
1993   if (VT.isFloatingPoint())
1994     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
1995 
1996   MVT XLenVT = Subtarget.getXLenVT();
1997 
1998   // Simplest case is that the operand needs to be promoted to XLenVT.
1999   if (Scalar.getValueType().bitsLE(XLenVT)) {
2000     // If the operand is a constant, sign extend to increase our chances
2001     // of being able to use a .vi instruction. ANY_EXTEND would become a
2002     // a zero extend and the simm5 check in isel would fail.
2003     // FIXME: Should we ignore the upper bits in isel instead?
2004     unsigned ExtOpc =
2005         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2006     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2007     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2008   }
2009 
2010   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2011          "Unexpected scalar for splat lowering!");
2012 
2013   // Otherwise use the more complicated splatting algorithm.
2014   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2015 }
2016 
2017 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2018                                    const RISCVSubtarget &Subtarget) {
2019   SDValue V1 = Op.getOperand(0);
2020   SDValue V2 = Op.getOperand(1);
2021   SDLoc DL(Op);
2022   MVT XLenVT = Subtarget.getXLenVT();
2023   MVT VT = Op.getSimpleValueType();
2024   unsigned NumElts = VT.getVectorNumElements();
2025   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2026 
2027   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2028 
2029   SDValue TrueMask, VL;
2030   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2031 
2032   if (SVN->isSplat()) {
2033     const int Lane = SVN->getSplatIndex();
2034     if (Lane >= 0) {
2035       MVT SVT = VT.getVectorElementType();
2036 
2037       // Turn splatted vector load into a strided load with an X0 stride.
2038       SDValue V = V1;
2039       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2040       // with undef.
2041       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2042       int Offset = Lane;
2043       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2044         int OpElements =
2045             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2046         V = V.getOperand(Offset / OpElements);
2047         Offset %= OpElements;
2048       }
2049 
2050       // We need to ensure the load isn't atomic or volatile.
2051       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2052         auto *Ld = cast<LoadSDNode>(V);
2053         Offset *= SVT.getStoreSize();
2054         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2055                                                    TypeSize::Fixed(Offset), DL);
2056 
2057         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2058         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2059           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2060           SDValue IntID =
2061               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2062           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2063                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2064           SDValue NewLoad = DAG.getMemIntrinsicNode(
2065               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2066               DAG.getMachineFunction().getMachineMemOperand(
2067                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2068           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2069           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2070         }
2071 
2072         // Otherwise use a scalar load and splat. This will give the best
2073         // opportunity to fold a splat into the operation. ISel can turn it into
2074         // the x0 strided load if we aren't able to fold away the select.
2075         if (SVT.isFloatingPoint())
2076           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2077                           Ld->getPointerInfo().getWithOffset(Offset),
2078                           Ld->getOriginalAlign(),
2079                           Ld->getMemOperand()->getFlags());
2080         else
2081           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2082                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2083                              Ld->getOriginalAlign(),
2084                              Ld->getMemOperand()->getFlags());
2085         DAG.makeEquivalentMemoryOrdering(Ld, V);
2086 
2087         unsigned Opc =
2088             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2089         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2090         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2091       }
2092 
2093       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2094       assert(Lane < (int)NumElts && "Unexpected lane!");
2095       SDValue Gather =
2096           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2097                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2098       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2099     }
2100   }
2101 
2102   // Detect shuffles which can be re-expressed as vector selects; these are
2103   // shuffles in which each element in the destination is taken from an element
2104   // at the corresponding index in either source vectors.
2105   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2106     int MaskIndex = MaskIdx.value();
2107     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2108   });
2109 
2110   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2111 
2112   SmallVector<SDValue> MaskVals;
2113   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2114   // merged with a second vrgather.
2115   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2116 
2117   // By default we preserve the original operand order, and use a mask to
2118   // select LHS as true and RHS as false. However, since RVV vector selects may
2119   // feature splats but only on the LHS, we may choose to invert our mask and
2120   // instead select between RHS and LHS.
2121   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2122   bool InvertMask = IsSelect == SwapOps;
2123 
2124   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2125   // half.
2126   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2127 
2128   // Now construct the mask that will be used by the vselect or blended
2129   // vrgather operation. For vrgathers, construct the appropriate indices into
2130   // each vector.
2131   for (int MaskIndex : SVN->getMask()) {
2132     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2133     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2134     if (!IsSelect) {
2135       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2136       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2137                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2138                                      : DAG.getUNDEF(XLenVT));
2139       GatherIndicesRHS.push_back(
2140           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2141                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2142       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2143         ++LHSIndexCounts[MaskIndex];
2144       if (!IsLHSOrUndefIndex)
2145         ++RHSIndexCounts[MaskIndex - NumElts];
2146     }
2147   }
2148 
2149   if (SwapOps) {
2150     std::swap(V1, V2);
2151     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2152   }
2153 
2154   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2155   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2156   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2157 
2158   if (IsSelect)
2159     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2160 
2161   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2162     // On such a large vector we're unable to use i8 as the index type.
2163     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2164     // may involve vector splitting if we're already at LMUL=8, or our
2165     // user-supplied maximum fixed-length LMUL.
2166     return SDValue();
2167   }
2168 
2169   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2170   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2171   MVT IndexVT = VT.changeTypeToInteger();
2172   // Since we can't introduce illegal index types at this stage, use i16 and
2173   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2174   // than XLenVT.
2175   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2176     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2177     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2178   }
2179 
2180   MVT IndexContainerVT =
2181       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2182 
2183   SDValue Gather;
2184   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2185   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2186   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2187     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2188   } else {
2189     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2190     // If only one index is used, we can use a "splat" vrgather.
2191     // TODO: We can splat the most-common index and fix-up any stragglers, if
2192     // that's beneficial.
2193     if (LHSIndexCounts.size() == 1) {
2194       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2195       Gather =
2196           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2197                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2198     } else {
2199       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2200       LHSIndices =
2201           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2202 
2203       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2204                            TrueMask, VL);
2205     }
2206   }
2207 
2208   // If a second vector operand is used by this shuffle, blend it in with an
2209   // additional vrgather.
2210   if (!V2.isUndef()) {
2211     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2212     // If only one index is used, we can use a "splat" vrgather.
2213     // TODO: We can splat the most-common index and fix-up any stragglers, if
2214     // that's beneficial.
2215     if (RHSIndexCounts.size() == 1) {
2216       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2217       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2218                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2219     } else {
2220       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2221       RHSIndices =
2222           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2223       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2224                        VL);
2225     }
2226 
2227     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2228     SelectMask =
2229         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2230 
2231     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2232                          Gather, VL);
2233   }
2234 
2235   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2236 }
2237 
2238 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2239                                      SDLoc DL, SelectionDAG &DAG,
2240                                      const RISCVSubtarget &Subtarget) {
2241   if (VT.isScalableVector())
2242     return DAG.getFPExtendOrRound(Op, DL, VT);
2243   assert(VT.isFixedLengthVector() &&
2244          "Unexpected value type for RVV FP extend/round lowering");
2245   SDValue Mask, VL;
2246   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2247   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2248                         ? RISCVISD::FP_EXTEND_VL
2249                         : RISCVISD::FP_ROUND_VL;
2250   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2251 }
2252 
2253 // While RVV has alignment restrictions, we should always be able to load as a
2254 // legal equivalently-sized byte-typed vector instead. This method is
2255 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2256 // the load is already correctly-aligned, it returns SDValue().
2257 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2258                                                     SelectionDAG &DAG) const {
2259   auto *Load = cast<LoadSDNode>(Op);
2260   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2261 
2262   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2263                                      Load->getMemoryVT(),
2264                                      *Load->getMemOperand()))
2265     return SDValue();
2266 
2267   SDLoc DL(Op);
2268   MVT VT = Op.getSimpleValueType();
2269   unsigned EltSizeBits = VT.getScalarSizeInBits();
2270   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2271          "Unexpected unaligned RVV load type");
2272   MVT NewVT =
2273       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2274   assert(NewVT.isValid() &&
2275          "Expecting equally-sized RVV vector types to be legal");
2276   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2277                           Load->getPointerInfo(), Load->getOriginalAlign(),
2278                           Load->getMemOperand()->getFlags());
2279   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2280 }
2281 
2282 // While RVV has alignment restrictions, we should always be able to store as a
2283 // legal equivalently-sized byte-typed vector instead. This method is
2284 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2285 // returns SDValue() if the store is already correctly aligned.
2286 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2287                                                      SelectionDAG &DAG) const {
2288   auto *Store = cast<StoreSDNode>(Op);
2289   assert(Store && Store->getValue().getValueType().isVector() &&
2290          "Expected vector store");
2291 
2292   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2293                                      Store->getMemoryVT(),
2294                                      *Store->getMemOperand()))
2295     return SDValue();
2296 
2297   SDLoc DL(Op);
2298   SDValue StoredVal = Store->getValue();
2299   MVT VT = StoredVal.getSimpleValueType();
2300   unsigned EltSizeBits = VT.getScalarSizeInBits();
2301   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2302          "Unexpected unaligned RVV store type");
2303   MVT NewVT =
2304       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2305   assert(NewVT.isValid() &&
2306          "Expecting equally-sized RVV vector types to be legal");
2307   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2308   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2309                       Store->getPointerInfo(), Store->getOriginalAlign(),
2310                       Store->getMemOperand()->getFlags());
2311 }
2312 
2313 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2314                                             SelectionDAG &DAG) const {
2315   switch (Op.getOpcode()) {
2316   default:
2317     report_fatal_error("unimplemented operand");
2318   case ISD::GlobalAddress:
2319     return lowerGlobalAddress(Op, DAG);
2320   case ISD::BlockAddress:
2321     return lowerBlockAddress(Op, DAG);
2322   case ISD::ConstantPool:
2323     return lowerConstantPool(Op, DAG);
2324   case ISD::JumpTable:
2325     return lowerJumpTable(Op, DAG);
2326   case ISD::GlobalTLSAddress:
2327     return lowerGlobalTLSAddress(Op, DAG);
2328   case ISD::SELECT:
2329     return lowerSELECT(Op, DAG);
2330   case ISD::BRCOND:
2331     return lowerBRCOND(Op, DAG);
2332   case ISD::VASTART:
2333     return lowerVASTART(Op, DAG);
2334   case ISD::FRAMEADDR:
2335     return lowerFRAMEADDR(Op, DAG);
2336   case ISD::RETURNADDR:
2337     return lowerRETURNADDR(Op, DAG);
2338   case ISD::SHL_PARTS:
2339     return lowerShiftLeftParts(Op, DAG);
2340   case ISD::SRA_PARTS:
2341     return lowerShiftRightParts(Op, DAG, true);
2342   case ISD::SRL_PARTS:
2343     return lowerShiftRightParts(Op, DAG, false);
2344   case ISD::BITCAST: {
2345     SDLoc DL(Op);
2346     EVT VT = Op.getValueType();
2347     SDValue Op0 = Op.getOperand(0);
2348     EVT Op0VT = Op0.getValueType();
2349     MVT XLenVT = Subtarget.getXLenVT();
2350     if (VT.isFixedLengthVector()) {
2351       // We can handle fixed length vector bitcasts with a simple replacement
2352       // in isel.
2353       if (Op0VT.isFixedLengthVector())
2354         return Op;
2355       // When bitcasting from scalar to fixed-length vector, insert the scalar
2356       // into a one-element vector of the result type, and perform a vector
2357       // bitcast.
2358       if (!Op0VT.isVector()) {
2359         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2360         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2361                                               DAG.getUNDEF(BVT), Op0,
2362                                               DAG.getConstant(0, DL, XLenVT)));
2363       }
2364       return SDValue();
2365     }
2366     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2367     // thus: bitcast the vector to a one-element vector type whose element type
2368     // is the same as the result type, and extract the first element.
2369     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2370       LLVMContext &Context = *DAG.getContext();
2371       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2372       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2373                          DAG.getConstant(0, DL, XLenVT));
2374     }
2375     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2376       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2377       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2378       return FPConv;
2379     }
2380     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2381         Subtarget.hasStdExtF()) {
2382       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2383       SDValue FPConv =
2384           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2385       return FPConv;
2386     }
2387     return SDValue();
2388   }
2389   case ISD::INTRINSIC_WO_CHAIN:
2390     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2391   case ISD::INTRINSIC_W_CHAIN:
2392     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2393   case ISD::INTRINSIC_VOID:
2394     return LowerINTRINSIC_VOID(Op, DAG);
2395   case ISD::BSWAP:
2396   case ISD::BITREVERSE: {
2397     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2398     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2399     MVT VT = Op.getSimpleValueType();
2400     SDLoc DL(Op);
2401     // Start with the maximum immediate value which is the bitwidth - 1.
2402     unsigned Imm = VT.getSizeInBits() - 1;
2403     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2404     if (Op.getOpcode() == ISD::BSWAP)
2405       Imm &= ~0x7U;
2406     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2407                        DAG.getConstant(Imm, DL, VT));
2408   }
2409   case ISD::FSHL:
2410   case ISD::FSHR: {
2411     MVT VT = Op.getSimpleValueType();
2412     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2413     SDLoc DL(Op);
2414     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2415       return Op;
2416     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2417     // use log(XLen) bits. Mask the shift amount accordingly.
2418     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2419     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2420                                 DAG.getConstant(ShAmtWidth, DL, VT));
2421     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2422     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2423   }
2424   case ISD::TRUNCATE: {
2425     SDLoc DL(Op);
2426     MVT VT = Op.getSimpleValueType();
2427     // Only custom-lower vector truncates
2428     if (!VT.isVector())
2429       return Op;
2430 
2431     // Truncates to mask types are handled differently
2432     if (VT.getVectorElementType() == MVT::i1)
2433       return lowerVectorMaskTrunc(Op, DAG);
2434 
2435     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2436     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2437     // truncate by one power of two at a time.
2438     MVT DstEltVT = VT.getVectorElementType();
2439 
2440     SDValue Src = Op.getOperand(0);
2441     MVT SrcVT = Src.getSimpleValueType();
2442     MVT SrcEltVT = SrcVT.getVectorElementType();
2443 
2444     assert(DstEltVT.bitsLT(SrcEltVT) &&
2445            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2446            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2447            "Unexpected vector truncate lowering");
2448 
2449     MVT ContainerVT = SrcVT;
2450     if (SrcVT.isFixedLengthVector()) {
2451       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2452       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2453     }
2454 
2455     SDValue Result = Src;
2456     SDValue Mask, VL;
2457     std::tie(Mask, VL) =
2458         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2459     LLVMContext &Context = *DAG.getContext();
2460     const ElementCount Count = ContainerVT.getVectorElementCount();
2461     do {
2462       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2463       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2464       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2465                            Mask, VL);
2466     } while (SrcEltVT != DstEltVT);
2467 
2468     if (SrcVT.isFixedLengthVector())
2469       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2470 
2471     return Result;
2472   }
2473   case ISD::ANY_EXTEND:
2474   case ISD::ZERO_EXTEND:
2475     if (Op.getOperand(0).getValueType().isVector() &&
2476         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2477       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2478     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2479   case ISD::SIGN_EXTEND:
2480     if (Op.getOperand(0).getValueType().isVector() &&
2481         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2482       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2483     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2484   case ISD::SPLAT_VECTOR_PARTS:
2485     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2486   case ISD::INSERT_VECTOR_ELT:
2487     return lowerINSERT_VECTOR_ELT(Op, DAG);
2488   case ISD::EXTRACT_VECTOR_ELT:
2489     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2490   case ISD::VSCALE: {
2491     MVT VT = Op.getSimpleValueType();
2492     SDLoc DL(Op);
2493     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2494     // We define our scalable vector types for lmul=1 to use a 64 bit known
2495     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2496     // vscale as VLENB / 8.
2497     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2498     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2499       // We assume VLENB is a multiple of 8. We manually choose the best shift
2500       // here because SimplifyDemandedBits isn't always able to simplify it.
2501       uint64_t Val = Op.getConstantOperandVal(0);
2502       if (isPowerOf2_64(Val)) {
2503         uint64_t Log2 = Log2_64(Val);
2504         if (Log2 < 3)
2505           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2506                              DAG.getConstant(3 - Log2, DL, VT));
2507         if (Log2 > 3)
2508           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2509                              DAG.getConstant(Log2 - 3, DL, VT));
2510         return VLENB;
2511       }
2512       // If the multiplier is a multiple of 8, scale it down to avoid needing
2513       // to shift the VLENB value.
2514       if ((Val % 8) == 0)
2515         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2516                            DAG.getConstant(Val / 8, DL, VT));
2517     }
2518 
2519     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2520                                  DAG.getConstant(3, DL, VT));
2521     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2522   }
2523   case ISD::FP_EXTEND: {
2524     // RVV can only do fp_extend to types double the size as the source. We
2525     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2526     // via f32.
2527     SDLoc DL(Op);
2528     MVT VT = Op.getSimpleValueType();
2529     SDValue Src = Op.getOperand(0);
2530     MVT SrcVT = Src.getSimpleValueType();
2531 
2532     // Prepare any fixed-length vector operands.
2533     MVT ContainerVT = VT;
2534     if (SrcVT.isFixedLengthVector()) {
2535       ContainerVT = getContainerForFixedLengthVector(VT);
2536       MVT SrcContainerVT =
2537           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2538       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2539     }
2540 
2541     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2542         SrcVT.getVectorElementType() != MVT::f16) {
2543       // For scalable vectors, we only need to close the gap between
2544       // vXf16->vXf64.
2545       if (!VT.isFixedLengthVector())
2546         return Op;
2547       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2548       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2549       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2550     }
2551 
2552     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2553     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2554     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2555         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2556 
2557     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2558                                            DL, DAG, Subtarget);
2559     if (VT.isFixedLengthVector())
2560       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2561     return Extend;
2562   }
2563   case ISD::FP_ROUND: {
2564     // RVV can only do fp_round to types half the size as the source. We
2565     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2566     // conversion instruction.
2567     SDLoc DL(Op);
2568     MVT VT = Op.getSimpleValueType();
2569     SDValue Src = Op.getOperand(0);
2570     MVT SrcVT = Src.getSimpleValueType();
2571 
2572     // Prepare any fixed-length vector operands.
2573     MVT ContainerVT = VT;
2574     if (VT.isFixedLengthVector()) {
2575       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2576       ContainerVT =
2577           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2578       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2579     }
2580 
2581     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2582         SrcVT.getVectorElementType() != MVT::f64) {
2583       // For scalable vectors, we only need to close the gap between
2584       // vXf64<->vXf16.
2585       if (!VT.isFixedLengthVector())
2586         return Op;
2587       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2588       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2589       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2590     }
2591 
2592     SDValue Mask, VL;
2593     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2594 
2595     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2596     SDValue IntermediateRound =
2597         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2598     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2599                                           DL, DAG, Subtarget);
2600 
2601     if (VT.isFixedLengthVector())
2602       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2603     return Round;
2604   }
2605   case ISD::FP_TO_SINT:
2606   case ISD::FP_TO_UINT:
2607   case ISD::SINT_TO_FP:
2608   case ISD::UINT_TO_FP: {
2609     // RVV can only do fp<->int conversions to types half/double the size as
2610     // the source. We custom-lower any conversions that do two hops into
2611     // sequences.
2612     MVT VT = Op.getSimpleValueType();
2613     if (!VT.isVector())
2614       return Op;
2615     SDLoc DL(Op);
2616     SDValue Src = Op.getOperand(0);
2617     MVT EltVT = VT.getVectorElementType();
2618     MVT SrcVT = Src.getSimpleValueType();
2619     MVT SrcEltVT = SrcVT.getVectorElementType();
2620     unsigned EltSize = EltVT.getSizeInBits();
2621     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2622     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2623            "Unexpected vector element types");
2624 
2625     bool IsInt2FP = SrcEltVT.isInteger();
2626     // Widening conversions
2627     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2628       if (IsInt2FP) {
2629         // Do a regular integer sign/zero extension then convert to float.
2630         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2631                                       VT.getVectorElementCount());
2632         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2633                                  ? ISD::ZERO_EXTEND
2634                                  : ISD::SIGN_EXTEND;
2635         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2636         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2637       }
2638       // FP2Int
2639       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2640       // Do one doubling fp_extend then complete the operation by converting
2641       // to int.
2642       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2643       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2644       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2645     }
2646 
2647     // Narrowing conversions
2648     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2649       if (IsInt2FP) {
2650         // One narrowing int_to_fp, then an fp_round.
2651         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2652         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2653         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2654         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2655       }
2656       // FP2Int
2657       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2658       // representable by the integer, the result is poison.
2659       MVT IVecVT =
2660           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2661                            VT.getVectorElementCount());
2662       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2663       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2664     }
2665 
2666     // Scalable vectors can exit here. Patterns will handle equally-sized
2667     // conversions halving/doubling ones.
2668     if (!VT.isFixedLengthVector())
2669       return Op;
2670 
2671     // For fixed-length vectors we lower to a custom "VL" node.
2672     unsigned RVVOpc = 0;
2673     switch (Op.getOpcode()) {
2674     default:
2675       llvm_unreachable("Impossible opcode");
2676     case ISD::FP_TO_SINT:
2677       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2678       break;
2679     case ISD::FP_TO_UINT:
2680       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2681       break;
2682     case ISD::SINT_TO_FP:
2683       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2684       break;
2685     case ISD::UINT_TO_FP:
2686       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2687       break;
2688     }
2689 
2690     MVT ContainerVT, SrcContainerVT;
2691     // Derive the reference container type from the larger vector type.
2692     if (SrcEltSize > EltSize) {
2693       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2694       ContainerVT =
2695           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2696     } else {
2697       ContainerVT = getContainerForFixedLengthVector(VT);
2698       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2699     }
2700 
2701     SDValue Mask, VL;
2702     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2703 
2704     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2705     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2706     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2707   }
2708   case ISD::FP_TO_SINT_SAT:
2709   case ISD::FP_TO_UINT_SAT:
2710     return lowerFP_TO_INT_SAT(Op, DAG);
2711   case ISD::VECREDUCE_ADD:
2712   case ISD::VECREDUCE_UMAX:
2713   case ISD::VECREDUCE_SMAX:
2714   case ISD::VECREDUCE_UMIN:
2715   case ISD::VECREDUCE_SMIN:
2716     return lowerVECREDUCE(Op, DAG);
2717   case ISD::VECREDUCE_AND:
2718   case ISD::VECREDUCE_OR:
2719   case ISD::VECREDUCE_XOR:
2720     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2721       return lowerVectorMaskVECREDUCE(Op, DAG);
2722     return lowerVECREDUCE(Op, DAG);
2723   case ISD::VECREDUCE_FADD:
2724   case ISD::VECREDUCE_SEQ_FADD:
2725   case ISD::VECREDUCE_FMIN:
2726   case ISD::VECREDUCE_FMAX:
2727     return lowerFPVECREDUCE(Op, DAG);
2728   case ISD::INSERT_SUBVECTOR:
2729     return lowerINSERT_SUBVECTOR(Op, DAG);
2730   case ISD::EXTRACT_SUBVECTOR:
2731     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2732   case ISD::STEP_VECTOR:
2733     return lowerSTEP_VECTOR(Op, DAG);
2734   case ISD::VECTOR_REVERSE:
2735     return lowerVECTOR_REVERSE(Op, DAG);
2736   case ISD::BUILD_VECTOR:
2737     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2738   case ISD::SPLAT_VECTOR:
2739     if (Op.getValueType().getVectorElementType() == MVT::i1)
2740       return lowerVectorMaskSplat(Op, DAG);
2741     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2742   case ISD::VECTOR_SHUFFLE:
2743     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2744   case ISD::CONCAT_VECTORS: {
2745     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2746     // better than going through the stack, as the default expansion does.
2747     SDLoc DL(Op);
2748     MVT VT = Op.getSimpleValueType();
2749     unsigned NumOpElts =
2750         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2751     SDValue Vec = DAG.getUNDEF(VT);
2752     for (const auto &OpIdx : enumerate(Op->ops()))
2753       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2754                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2755     return Vec;
2756   }
2757   case ISD::LOAD:
2758     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2759       return V;
2760     if (Op.getValueType().isFixedLengthVector())
2761       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2762     return Op;
2763   case ISD::STORE:
2764     if (auto V = expandUnalignedRVVStore(Op, DAG))
2765       return V;
2766     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2767       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2768     return Op;
2769   case ISD::MLOAD:
2770   case ISD::VP_LOAD:
2771     return lowerMaskedLoad(Op, DAG);
2772   case ISD::MSTORE:
2773   case ISD::VP_STORE:
2774     return lowerMaskedStore(Op, DAG);
2775   case ISD::SETCC:
2776     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2777   case ISD::ADD:
2778     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2779   case ISD::SUB:
2780     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2781   case ISD::MUL:
2782     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2783   case ISD::MULHS:
2784     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2785   case ISD::MULHU:
2786     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2787   case ISD::AND:
2788     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2789                                               RISCVISD::AND_VL);
2790   case ISD::OR:
2791     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2792                                               RISCVISD::OR_VL);
2793   case ISD::XOR:
2794     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2795                                               RISCVISD::XOR_VL);
2796   case ISD::SDIV:
2797     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2798   case ISD::SREM:
2799     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2800   case ISD::UDIV:
2801     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2802   case ISD::UREM:
2803     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2804   case ISD::SHL:
2805   case ISD::SRA:
2806   case ISD::SRL:
2807     if (Op.getSimpleValueType().isFixedLengthVector())
2808       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2809     // This can be called for an i32 shift amount that needs to be promoted.
2810     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2811            "Unexpected custom legalisation");
2812     return SDValue();
2813   case ISD::SADDSAT:
2814     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2815   case ISD::UADDSAT:
2816     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2817   case ISD::SSUBSAT:
2818     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2819   case ISD::USUBSAT:
2820     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2821   case ISD::FADD:
2822     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2823   case ISD::FSUB:
2824     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2825   case ISD::FMUL:
2826     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2827   case ISD::FDIV:
2828     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2829   case ISD::FNEG:
2830     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2831   case ISD::FABS:
2832     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2833   case ISD::FSQRT:
2834     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2835   case ISD::FMA:
2836     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2837   case ISD::SMIN:
2838     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2839   case ISD::SMAX:
2840     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2841   case ISD::UMIN:
2842     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2843   case ISD::UMAX:
2844     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2845   case ISD::FMINNUM:
2846     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2847   case ISD::FMAXNUM:
2848     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2849   case ISD::ABS:
2850     return lowerABS(Op, DAG);
2851   case ISD::VSELECT:
2852     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2853   case ISD::FCOPYSIGN:
2854     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2855   case ISD::MGATHER:
2856   case ISD::VP_GATHER:
2857     return lowerMaskedGather(Op, DAG);
2858   case ISD::MSCATTER:
2859   case ISD::VP_SCATTER:
2860     return lowerMaskedScatter(Op, DAG);
2861   case ISD::FLT_ROUNDS_:
2862     return lowerGET_ROUNDING(Op, DAG);
2863   case ISD::SET_ROUNDING:
2864     return lowerSET_ROUNDING(Op, DAG);
2865   case ISD::VP_ADD:
2866     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2867   case ISD::VP_SUB:
2868     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2869   case ISD::VP_MUL:
2870     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2871   case ISD::VP_SDIV:
2872     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2873   case ISD::VP_UDIV:
2874     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2875   case ISD::VP_SREM:
2876     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2877   case ISD::VP_UREM:
2878     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2879   case ISD::VP_AND:
2880     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2881   case ISD::VP_OR:
2882     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2883   case ISD::VP_XOR:
2884     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2885   case ISD::VP_ASHR:
2886     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2887   case ISD::VP_LSHR:
2888     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2889   case ISD::VP_SHL:
2890     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2891   case ISD::VP_FADD:
2892     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2893   case ISD::VP_FSUB:
2894     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2895   case ISD::VP_FMUL:
2896     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2897   case ISD::VP_FDIV:
2898     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2899   }
2900 }
2901 
2902 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2903                              SelectionDAG &DAG, unsigned Flags) {
2904   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2905 }
2906 
2907 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2908                              SelectionDAG &DAG, unsigned Flags) {
2909   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2910                                    Flags);
2911 }
2912 
2913 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2914                              SelectionDAG &DAG, unsigned Flags) {
2915   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2916                                    N->getOffset(), Flags);
2917 }
2918 
2919 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2920                              SelectionDAG &DAG, unsigned Flags) {
2921   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2922 }
2923 
2924 template <class NodeTy>
2925 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2926                                      bool IsLocal) const {
2927   SDLoc DL(N);
2928   EVT Ty = getPointerTy(DAG.getDataLayout());
2929 
2930   if (isPositionIndependent()) {
2931     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2932     if (IsLocal)
2933       // Use PC-relative addressing to access the symbol. This generates the
2934       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2935       // %pcrel_lo(auipc)).
2936       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2937 
2938     // Use PC-relative addressing to access the GOT for this symbol, then load
2939     // the address from the GOT. This generates the pattern (PseudoLA sym),
2940     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2941     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2942   }
2943 
2944   switch (getTargetMachine().getCodeModel()) {
2945   default:
2946     report_fatal_error("Unsupported code model for lowering");
2947   case CodeModel::Small: {
2948     // Generate a sequence for accessing addresses within the first 2 GiB of
2949     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
2950     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
2951     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
2952     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2953     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
2954   }
2955   case CodeModel::Medium: {
2956     // Generate a sequence for accessing addresses within any 2GiB range within
2957     // the address space. This generates the pattern (PseudoLLA sym), which
2958     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2959     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2960     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2961   }
2962   }
2963 }
2964 
2965 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
2966                                                 SelectionDAG &DAG) const {
2967   SDLoc DL(Op);
2968   EVT Ty = Op.getValueType();
2969   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2970   int64_t Offset = N->getOffset();
2971   MVT XLenVT = Subtarget.getXLenVT();
2972 
2973   const GlobalValue *GV = N->getGlobal();
2974   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2975   SDValue Addr = getAddr(N, DAG, IsLocal);
2976 
2977   // In order to maximise the opportunity for common subexpression elimination,
2978   // emit a separate ADD node for the global address offset instead of folding
2979   // it in the global address node. Later peephole optimisations may choose to
2980   // fold it back in when profitable.
2981   if (Offset != 0)
2982     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2983                        DAG.getConstant(Offset, DL, XLenVT));
2984   return Addr;
2985 }
2986 
2987 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
2988                                                SelectionDAG &DAG) const {
2989   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2990 
2991   return getAddr(N, DAG);
2992 }
2993 
2994 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
2995                                                SelectionDAG &DAG) const {
2996   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2997 
2998   return getAddr(N, DAG);
2999 }
3000 
3001 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3002                                             SelectionDAG &DAG) const {
3003   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3004 
3005   return getAddr(N, DAG);
3006 }
3007 
3008 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3009                                               SelectionDAG &DAG,
3010                                               bool UseGOT) const {
3011   SDLoc DL(N);
3012   EVT Ty = getPointerTy(DAG.getDataLayout());
3013   const GlobalValue *GV = N->getGlobal();
3014   MVT XLenVT = Subtarget.getXLenVT();
3015 
3016   if (UseGOT) {
3017     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3018     // load the address from the GOT and add the thread pointer. This generates
3019     // the pattern (PseudoLA_TLS_IE sym), which expands to
3020     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3021     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3022     SDValue Load =
3023         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3024 
3025     // Add the thread pointer.
3026     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3027     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3028   }
3029 
3030   // Generate a sequence for accessing the address relative to the thread
3031   // pointer, with the appropriate adjustment for the thread pointer offset.
3032   // This generates the pattern
3033   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3034   SDValue AddrHi =
3035       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3036   SDValue AddrAdd =
3037       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3038   SDValue AddrLo =
3039       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3040 
3041   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3042   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3043   SDValue MNAdd = SDValue(
3044       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3045       0);
3046   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3047 }
3048 
3049 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3050                                                SelectionDAG &DAG) const {
3051   SDLoc DL(N);
3052   EVT Ty = getPointerTy(DAG.getDataLayout());
3053   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3054   const GlobalValue *GV = N->getGlobal();
3055 
3056   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3057   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3058   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3059   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3060   SDValue Load =
3061       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3062 
3063   // Prepare argument list to generate call.
3064   ArgListTy Args;
3065   ArgListEntry Entry;
3066   Entry.Node = Load;
3067   Entry.Ty = CallTy;
3068   Args.push_back(Entry);
3069 
3070   // Setup call to __tls_get_addr.
3071   TargetLowering::CallLoweringInfo CLI(DAG);
3072   CLI.setDebugLoc(DL)
3073       .setChain(DAG.getEntryNode())
3074       .setLibCallee(CallingConv::C, CallTy,
3075                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3076                     std::move(Args));
3077 
3078   return LowerCallTo(CLI).first;
3079 }
3080 
3081 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3082                                                    SelectionDAG &DAG) const {
3083   SDLoc DL(Op);
3084   EVT Ty = Op.getValueType();
3085   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3086   int64_t Offset = N->getOffset();
3087   MVT XLenVT = Subtarget.getXLenVT();
3088 
3089   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3090 
3091   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3092       CallingConv::GHC)
3093     report_fatal_error("In GHC calling convention TLS is not supported");
3094 
3095   SDValue Addr;
3096   switch (Model) {
3097   case TLSModel::LocalExec:
3098     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3099     break;
3100   case TLSModel::InitialExec:
3101     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3102     break;
3103   case TLSModel::LocalDynamic:
3104   case TLSModel::GeneralDynamic:
3105     Addr = getDynamicTLSAddr(N, DAG);
3106     break;
3107   }
3108 
3109   // In order to maximise the opportunity for common subexpression elimination,
3110   // emit a separate ADD node for the global address offset instead of folding
3111   // it in the global address node. Later peephole optimisations may choose to
3112   // fold it back in when profitable.
3113   if (Offset != 0)
3114     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3115                        DAG.getConstant(Offset, DL, XLenVT));
3116   return Addr;
3117 }
3118 
3119 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3120   SDValue CondV = Op.getOperand(0);
3121   SDValue TrueV = Op.getOperand(1);
3122   SDValue FalseV = Op.getOperand(2);
3123   SDLoc DL(Op);
3124   MVT VT = Op.getSimpleValueType();
3125   MVT XLenVT = Subtarget.getXLenVT();
3126 
3127   // Lower vector SELECTs to VSELECTs by splatting the condition.
3128   if (VT.isVector()) {
3129     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3130     SDValue CondSplat = VT.isScalableVector()
3131                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3132                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3133     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3134   }
3135 
3136   // If the result type is XLenVT and CondV is the output of a SETCC node
3137   // which also operated on XLenVT inputs, then merge the SETCC node into the
3138   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3139   // compare+branch instructions. i.e.:
3140   // (select (setcc lhs, rhs, cc), truev, falsev)
3141   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3142   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3143       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3144     SDValue LHS = CondV.getOperand(0);
3145     SDValue RHS = CondV.getOperand(1);
3146     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3147     ISD::CondCode CCVal = CC->get();
3148 
3149     // Special case for a select of 2 constants that have a diffence of 1.
3150     // Normally this is done by DAGCombine, but if the select is introduced by
3151     // type legalization or op legalization, we miss it. Restricting to SETLT
3152     // case for now because that is what signed saturating add/sub need.
3153     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3154     // but we would probably want to swap the true/false values if the condition
3155     // is SETGE/SETLE to avoid an XORI.
3156     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3157         CCVal == ISD::SETLT) {
3158       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3159       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3160       if (TrueVal - 1 == FalseVal)
3161         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3162       if (TrueVal + 1 == FalseVal)
3163         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3164     }
3165 
3166     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3167 
3168     SDValue TargetCC = DAG.getCondCode(CCVal);
3169     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3170     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3171   }
3172 
3173   // Otherwise:
3174   // (select condv, truev, falsev)
3175   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3176   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3177   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3178 
3179   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3180 
3181   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3182 }
3183 
3184 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3185   SDValue CondV = Op.getOperand(1);
3186   SDLoc DL(Op);
3187   MVT XLenVT = Subtarget.getXLenVT();
3188 
3189   if (CondV.getOpcode() == ISD::SETCC &&
3190       CondV.getOperand(0).getValueType() == XLenVT) {
3191     SDValue LHS = CondV.getOperand(0);
3192     SDValue RHS = CondV.getOperand(1);
3193     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3194 
3195     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3196 
3197     SDValue TargetCC = DAG.getCondCode(CCVal);
3198     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3199                        LHS, RHS, TargetCC, Op.getOperand(2));
3200   }
3201 
3202   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3203                      CondV, DAG.getConstant(0, DL, XLenVT),
3204                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3205 }
3206 
3207 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3208   MachineFunction &MF = DAG.getMachineFunction();
3209   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3210 
3211   SDLoc DL(Op);
3212   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3213                                  getPointerTy(MF.getDataLayout()));
3214 
3215   // vastart just stores the address of the VarArgsFrameIndex slot into the
3216   // memory location argument.
3217   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3218   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3219                       MachinePointerInfo(SV));
3220 }
3221 
3222 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3223                                             SelectionDAG &DAG) const {
3224   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3225   MachineFunction &MF = DAG.getMachineFunction();
3226   MachineFrameInfo &MFI = MF.getFrameInfo();
3227   MFI.setFrameAddressIsTaken(true);
3228   Register FrameReg = RI.getFrameRegister(MF);
3229   int XLenInBytes = Subtarget.getXLen() / 8;
3230 
3231   EVT VT = Op.getValueType();
3232   SDLoc DL(Op);
3233   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3234   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3235   while (Depth--) {
3236     int Offset = -(XLenInBytes * 2);
3237     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3238                               DAG.getIntPtrConstant(Offset, DL));
3239     FrameAddr =
3240         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3241   }
3242   return FrameAddr;
3243 }
3244 
3245 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3246                                              SelectionDAG &DAG) const {
3247   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3248   MachineFunction &MF = DAG.getMachineFunction();
3249   MachineFrameInfo &MFI = MF.getFrameInfo();
3250   MFI.setReturnAddressIsTaken(true);
3251   MVT XLenVT = Subtarget.getXLenVT();
3252   int XLenInBytes = Subtarget.getXLen() / 8;
3253 
3254   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3255     return SDValue();
3256 
3257   EVT VT = Op.getValueType();
3258   SDLoc DL(Op);
3259   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3260   if (Depth) {
3261     int Off = -XLenInBytes;
3262     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3263     SDValue Offset = DAG.getConstant(Off, DL, VT);
3264     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3265                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3266                        MachinePointerInfo());
3267   }
3268 
3269   // Return the value of the return address register, marking it an implicit
3270   // live-in.
3271   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3272   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3273 }
3274 
3275 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3276                                                  SelectionDAG &DAG) const {
3277   SDLoc DL(Op);
3278   SDValue Lo = Op.getOperand(0);
3279   SDValue Hi = Op.getOperand(1);
3280   SDValue Shamt = Op.getOperand(2);
3281   EVT VT = Lo.getValueType();
3282 
3283   // if Shamt-XLEN < 0: // Shamt < XLEN
3284   //   Lo = Lo << Shamt
3285   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3286   // else:
3287   //   Lo = 0
3288   //   Hi = Lo << (Shamt-XLEN)
3289 
3290   SDValue Zero = DAG.getConstant(0, DL, VT);
3291   SDValue One = DAG.getConstant(1, DL, VT);
3292   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3293   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3294   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3295   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3296 
3297   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3298   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3299   SDValue ShiftRightLo =
3300       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3301   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3302   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3303   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3304 
3305   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3306 
3307   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3308   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3309 
3310   SDValue Parts[2] = {Lo, Hi};
3311   return DAG.getMergeValues(Parts, DL);
3312 }
3313 
3314 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3315                                                   bool IsSRA) const {
3316   SDLoc DL(Op);
3317   SDValue Lo = Op.getOperand(0);
3318   SDValue Hi = Op.getOperand(1);
3319   SDValue Shamt = Op.getOperand(2);
3320   EVT VT = Lo.getValueType();
3321 
3322   // SRA expansion:
3323   //   if Shamt-XLEN < 0: // Shamt < XLEN
3324   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3325   //     Hi = Hi >>s Shamt
3326   //   else:
3327   //     Lo = Hi >>s (Shamt-XLEN);
3328   //     Hi = Hi >>s (XLEN-1)
3329   //
3330   // SRL expansion:
3331   //   if Shamt-XLEN < 0: // Shamt < XLEN
3332   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3333   //     Hi = Hi >>u Shamt
3334   //   else:
3335   //     Lo = Hi >>u (Shamt-XLEN);
3336   //     Hi = 0;
3337 
3338   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3339 
3340   SDValue Zero = DAG.getConstant(0, DL, VT);
3341   SDValue One = DAG.getConstant(1, DL, VT);
3342   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3343   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3344   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3345   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3346 
3347   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3348   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3349   SDValue ShiftLeftHi =
3350       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3351   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3352   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3353   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3354   SDValue HiFalse =
3355       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3356 
3357   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3358 
3359   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3360   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3361 
3362   SDValue Parts[2] = {Lo, Hi};
3363   return DAG.getMergeValues(Parts, DL);
3364 }
3365 
3366 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3367 // legal equivalently-sized i8 type, so we can use that as a go-between.
3368 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3369                                                   SelectionDAG &DAG) const {
3370   SDLoc DL(Op);
3371   MVT VT = Op.getSimpleValueType();
3372   SDValue SplatVal = Op.getOperand(0);
3373   // All-zeros or all-ones splats are handled specially.
3374   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3375     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3376     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3377   }
3378   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3379     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3380     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3381   }
3382   MVT XLenVT = Subtarget.getXLenVT();
3383   assert(SplatVal.getValueType() == XLenVT &&
3384          "Unexpected type for i1 splat value");
3385   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3386   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3387                          DAG.getConstant(1, DL, XLenVT));
3388   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3389   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3390   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3391 }
3392 
3393 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3394 // illegal (currently only vXi64 RV32).
3395 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3396 // them to SPLAT_VECTOR_I64
3397 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3398                                                      SelectionDAG &DAG) const {
3399   SDLoc DL(Op);
3400   MVT VecVT = Op.getSimpleValueType();
3401   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3402          "Unexpected SPLAT_VECTOR_PARTS lowering");
3403 
3404   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3405   SDValue Lo = Op.getOperand(0);
3406   SDValue Hi = Op.getOperand(1);
3407 
3408   if (VecVT.isFixedLengthVector()) {
3409     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3410     SDLoc DL(Op);
3411     SDValue Mask, VL;
3412     std::tie(Mask, VL) =
3413         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3414 
3415     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3416     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3417   }
3418 
3419   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3420     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3421     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3422     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3423     // node in order to try and match RVV vector/scalar instructions.
3424     if ((LoC >> 31) == HiC)
3425       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3426   }
3427 
3428   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3429   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3430       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3431       Hi.getConstantOperandVal(1) == 31)
3432     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3433 
3434   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3435   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3436                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3437 }
3438 
3439 // Custom-lower extensions from mask vectors by using a vselect either with 1
3440 // for zero/any-extension or -1 for sign-extension:
3441 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3442 // Note that any-extension is lowered identically to zero-extension.
3443 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3444                                                 int64_t ExtTrueVal) const {
3445   SDLoc DL(Op);
3446   MVT VecVT = Op.getSimpleValueType();
3447   SDValue Src = Op.getOperand(0);
3448   // Only custom-lower extensions from mask types
3449   assert(Src.getValueType().isVector() &&
3450          Src.getValueType().getVectorElementType() == MVT::i1);
3451 
3452   MVT XLenVT = Subtarget.getXLenVT();
3453   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3454   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3455 
3456   if (VecVT.isScalableVector()) {
3457     // Be careful not to introduce illegal scalar types at this stage, and be
3458     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3459     // illegal and must be expanded. Since we know that the constants are
3460     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3461     bool IsRV32E64 =
3462         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3463 
3464     if (!IsRV32E64) {
3465       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3466       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3467     } else {
3468       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3469       SplatTrueVal =
3470           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3471     }
3472 
3473     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3474   }
3475 
3476   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3477   MVT I1ContainerVT =
3478       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3479 
3480   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3481 
3482   SDValue Mask, VL;
3483   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3484 
3485   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3486   SplatTrueVal =
3487       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3488   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3489                                SplatTrueVal, SplatZero, VL);
3490 
3491   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3492 }
3493 
3494 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3495     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3496   MVT ExtVT = Op.getSimpleValueType();
3497   // Only custom-lower extensions from fixed-length vector types.
3498   if (!ExtVT.isFixedLengthVector())
3499     return Op;
3500   MVT VT = Op.getOperand(0).getSimpleValueType();
3501   // Grab the canonical container type for the extended type. Infer the smaller
3502   // type from that to ensure the same number of vector elements, as we know
3503   // the LMUL will be sufficient to hold the smaller type.
3504   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3505   // Get the extended container type manually to ensure the same number of
3506   // vector elements between source and dest.
3507   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3508                                      ContainerExtVT.getVectorElementCount());
3509 
3510   SDValue Op1 =
3511       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3512 
3513   SDLoc DL(Op);
3514   SDValue Mask, VL;
3515   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3516 
3517   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3518 
3519   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3520 }
3521 
3522 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3523 // setcc operation:
3524 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3525 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3526                                                   SelectionDAG &DAG) const {
3527   SDLoc DL(Op);
3528   EVT MaskVT = Op.getValueType();
3529   // Only expect to custom-lower truncations to mask types
3530   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3531          "Unexpected type for vector mask lowering");
3532   SDValue Src = Op.getOperand(0);
3533   MVT VecVT = Src.getSimpleValueType();
3534 
3535   // If this is a fixed vector, we need to convert it to a scalable vector.
3536   MVT ContainerVT = VecVT;
3537   if (VecVT.isFixedLengthVector()) {
3538     ContainerVT = getContainerForFixedLengthVector(VecVT);
3539     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3540   }
3541 
3542   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3543   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3544 
3545   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3546   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3547 
3548   if (VecVT.isScalableVector()) {
3549     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3550     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3551   }
3552 
3553   SDValue Mask, VL;
3554   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3555 
3556   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3557   SDValue Trunc =
3558       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3559   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3560                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3561   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3562 }
3563 
3564 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3565 // first position of a vector, and that vector is slid up to the insert index.
3566 // By limiting the active vector length to index+1 and merging with the
3567 // original vector (with an undisturbed tail policy for elements >= VL), we
3568 // achieve the desired result of leaving all elements untouched except the one
3569 // at VL-1, which is replaced with the desired value.
3570 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3571                                                     SelectionDAG &DAG) const {
3572   SDLoc DL(Op);
3573   MVT VecVT = Op.getSimpleValueType();
3574   SDValue Vec = Op.getOperand(0);
3575   SDValue Val = Op.getOperand(1);
3576   SDValue Idx = Op.getOperand(2);
3577 
3578   if (VecVT.getVectorElementType() == MVT::i1) {
3579     // FIXME: For now we just promote to an i8 vector and insert into that,
3580     // but this is probably not optimal.
3581     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3582     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3583     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3584     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3585   }
3586 
3587   MVT ContainerVT = VecVT;
3588   // If the operand is a fixed-length vector, convert to a scalable one.
3589   if (VecVT.isFixedLengthVector()) {
3590     ContainerVT = getContainerForFixedLengthVector(VecVT);
3591     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3592   }
3593 
3594   MVT XLenVT = Subtarget.getXLenVT();
3595 
3596   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3597   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3598   // Even i64-element vectors on RV32 can be lowered without scalar
3599   // legalization if the most-significant 32 bits of the value are not affected
3600   // by the sign-extension of the lower 32 bits.
3601   // TODO: We could also catch sign extensions of a 32-bit value.
3602   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3603     const auto *CVal = cast<ConstantSDNode>(Val);
3604     if (isInt<32>(CVal->getSExtValue())) {
3605       IsLegalInsert = true;
3606       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3607     }
3608   }
3609 
3610   SDValue Mask, VL;
3611   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3612 
3613   SDValue ValInVec;
3614 
3615   if (IsLegalInsert) {
3616     unsigned Opc =
3617         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3618     if (isNullConstant(Idx)) {
3619       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3620       if (!VecVT.isFixedLengthVector())
3621         return Vec;
3622       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3623     }
3624     ValInVec =
3625         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3626   } else {
3627     // On RV32, i64-element vectors must be specially handled to place the
3628     // value at element 0, by using two vslide1up instructions in sequence on
3629     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3630     // this.
3631     SDValue One = DAG.getConstant(1, DL, XLenVT);
3632     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3633     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3634     MVT I32ContainerVT =
3635         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3636     SDValue I32Mask =
3637         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3638     // Limit the active VL to two.
3639     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3640     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3641     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3642     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3643                            InsertI64VL);
3644     // First slide in the hi value, then the lo in underneath it.
3645     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3646                            ValHi, I32Mask, InsertI64VL);
3647     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3648                            ValLo, I32Mask, InsertI64VL);
3649     // Bitcast back to the right container type.
3650     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3651   }
3652 
3653   // Now that the value is in a vector, slide it into position.
3654   SDValue InsertVL =
3655       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3656   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3657                                 ValInVec, Idx, Mask, InsertVL);
3658   if (!VecVT.isFixedLengthVector())
3659     return Slideup;
3660   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3661 }
3662 
3663 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3664 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3665 // types this is done using VMV_X_S to allow us to glean information about the
3666 // sign bits of the result.
3667 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3668                                                      SelectionDAG &DAG) const {
3669   SDLoc DL(Op);
3670   SDValue Idx = Op.getOperand(1);
3671   SDValue Vec = Op.getOperand(0);
3672   EVT EltVT = Op.getValueType();
3673   MVT VecVT = Vec.getSimpleValueType();
3674   MVT XLenVT = Subtarget.getXLenVT();
3675 
3676   if (VecVT.getVectorElementType() == MVT::i1) {
3677     // FIXME: For now we just promote to an i8 vector and extract from that,
3678     // but this is probably not optimal.
3679     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3680     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3681     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3682   }
3683 
3684   // If this is a fixed vector, we need to convert it to a scalable vector.
3685   MVT ContainerVT = VecVT;
3686   if (VecVT.isFixedLengthVector()) {
3687     ContainerVT = getContainerForFixedLengthVector(VecVT);
3688     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3689   }
3690 
3691   // If the index is 0, the vector is already in the right position.
3692   if (!isNullConstant(Idx)) {
3693     // Use a VL of 1 to avoid processing more elements than we need.
3694     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3695     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3696     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3697     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3698                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3699   }
3700 
3701   if (!EltVT.isInteger()) {
3702     // Floating-point extracts are handled in TableGen.
3703     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3704                        DAG.getConstant(0, DL, XLenVT));
3705   }
3706 
3707   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3708   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3709 }
3710 
3711 // Some RVV intrinsics may claim that they want an integer operand to be
3712 // promoted or expanded.
3713 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3714                                           const RISCVSubtarget &Subtarget) {
3715   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3716           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3717          "Unexpected opcode");
3718 
3719   if (!Subtarget.hasStdExtV())
3720     return SDValue();
3721 
3722   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3723   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3724   SDLoc DL(Op);
3725 
3726   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3727       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3728   if (!II || !II->SplatOperand)
3729     return SDValue();
3730 
3731   unsigned SplatOp = II->SplatOperand + HasChain;
3732   assert(SplatOp < Op.getNumOperands());
3733 
3734   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3735   SDValue &ScalarOp = Operands[SplatOp];
3736   MVT OpVT = ScalarOp.getSimpleValueType();
3737   MVT XLenVT = Subtarget.getXLenVT();
3738 
3739   // If this isn't a scalar, or its type is XLenVT we're done.
3740   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3741     return SDValue();
3742 
3743   // Simplest case is that the operand needs to be promoted to XLenVT.
3744   if (OpVT.bitsLT(XLenVT)) {
3745     // If the operand is a constant, sign extend to increase our chances
3746     // of being able to use a .vi instruction. ANY_EXTEND would become a
3747     // a zero extend and the simm5 check in isel would fail.
3748     // FIXME: Should we ignore the upper bits in isel instead?
3749     unsigned ExtOpc =
3750         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3751     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3752     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3753   }
3754 
3755   // Use the previous operand to get the vXi64 VT. The result might be a mask
3756   // VT for compares. Using the previous operand assumes that the previous
3757   // operand will never have a smaller element size than a scalar operand and
3758   // that a widening operation never uses SEW=64.
3759   // NOTE: If this fails the below assert, we can probably just find the
3760   // element count from any operand or result and use it to construct the VT.
3761   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3762   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3763 
3764   // The more complex case is when the scalar is larger than XLenVT.
3765   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3766          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3767 
3768   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3769   // on the instruction to sign-extend since SEW>XLEN.
3770   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3771     if (isInt<32>(CVal->getSExtValue())) {
3772       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3773       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3774     }
3775   }
3776 
3777   // We need to convert the scalar to a splat vector.
3778   // FIXME: Can we implicitly truncate the scalar if it is known to
3779   // be sign extended?
3780   // VL should be the last operand.
3781   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3782   assert(VL.getValueType() == XLenVT);
3783   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3784   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3785 }
3786 
3787 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3788                                                      SelectionDAG &DAG) const {
3789   unsigned IntNo = Op.getConstantOperandVal(0);
3790   SDLoc DL(Op);
3791   MVT XLenVT = Subtarget.getXLenVT();
3792 
3793   switch (IntNo) {
3794   default:
3795     break; // Don't custom lower most intrinsics.
3796   case Intrinsic::thread_pointer: {
3797     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3798     return DAG.getRegister(RISCV::X4, PtrVT);
3799   }
3800   case Intrinsic::riscv_orc_b:
3801     // Lower to the GORCI encoding for orc.b.
3802     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3803                        DAG.getConstant(7, DL, XLenVT));
3804   case Intrinsic::riscv_grev:
3805   case Intrinsic::riscv_gorc: {
3806     unsigned Opc =
3807         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3808     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3809   }
3810   case Intrinsic::riscv_shfl:
3811   case Intrinsic::riscv_unshfl: {
3812     unsigned Opc =
3813         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3814     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3815   }
3816   case Intrinsic::riscv_bcompress:
3817   case Intrinsic::riscv_bdecompress: {
3818     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3819                                                        : RISCVISD::BDECOMPRESS;
3820     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3821   }
3822   case Intrinsic::riscv_vmv_x_s:
3823     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3824     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3825                        Op.getOperand(1));
3826   case Intrinsic::riscv_vmv_v_x:
3827     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3828                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3829   case Intrinsic::riscv_vfmv_v_f:
3830     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3831                        Op.getOperand(1), Op.getOperand(2));
3832   case Intrinsic::riscv_vmv_s_x: {
3833     SDValue Scalar = Op.getOperand(2);
3834 
3835     if (Scalar.getValueType().bitsLE(XLenVT)) {
3836       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3837       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3838                          Op.getOperand(1), Scalar, Op.getOperand(3));
3839     }
3840 
3841     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3842 
3843     // This is an i64 value that lives in two scalar registers. We have to
3844     // insert this in a convoluted way. First we build vXi64 splat containing
3845     // the/ two values that we assemble using some bit math. Next we'll use
3846     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3847     // to merge element 0 from our splat into the source vector.
3848     // FIXME: This is probably not the best way to do this, but it is
3849     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3850     // point.
3851     //   sw lo, (a0)
3852     //   sw hi, 4(a0)
3853     //   vlse vX, (a0)
3854     //
3855     //   vid.v      vVid
3856     //   vmseq.vx   mMask, vVid, 0
3857     //   vmerge.vvm vDest, vSrc, vVal, mMask
3858     MVT VT = Op.getSimpleValueType();
3859     SDValue Vec = Op.getOperand(1);
3860     SDValue VL = Op.getOperand(3);
3861 
3862     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3863     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3864                                       DAG.getConstant(0, DL, MVT::i32), VL);
3865 
3866     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3867     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3868     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3869     SDValue SelectCond =
3870         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3871                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3872     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3873                        Vec, VL);
3874   }
3875   case Intrinsic::riscv_vslide1up:
3876   case Intrinsic::riscv_vslide1down:
3877   case Intrinsic::riscv_vslide1up_mask:
3878   case Intrinsic::riscv_vslide1down_mask: {
3879     // We need to special case these when the scalar is larger than XLen.
3880     unsigned NumOps = Op.getNumOperands();
3881     bool IsMasked = NumOps == 6;
3882     unsigned OpOffset = IsMasked ? 1 : 0;
3883     SDValue Scalar = Op.getOperand(2 + OpOffset);
3884     if (Scalar.getValueType().bitsLE(XLenVT))
3885       break;
3886 
3887     // Splatting a sign extended constant is fine.
3888     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3889       if (isInt<32>(CVal->getSExtValue()))
3890         break;
3891 
3892     MVT VT = Op.getSimpleValueType();
3893     assert(VT.getVectorElementType() == MVT::i64 &&
3894            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3895 
3896     // Convert the vector source to the equivalent nxvXi32 vector.
3897     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3898     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3899 
3900     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3901                                    DAG.getConstant(0, DL, XLenVT));
3902     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3903                                    DAG.getConstant(1, DL, XLenVT));
3904 
3905     // Double the VL since we halved SEW.
3906     SDValue VL = Op.getOperand(NumOps - 1);
3907     SDValue I32VL =
3908         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3909 
3910     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3911     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3912 
3913     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3914     // instructions.
3915     if (IntNo == Intrinsic::riscv_vslide1up ||
3916         IntNo == Intrinsic::riscv_vslide1up_mask) {
3917       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3918                         I32Mask, I32VL);
3919       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3920                         I32Mask, I32VL);
3921     } else {
3922       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3923                         I32Mask, I32VL);
3924       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3925                         I32Mask, I32VL);
3926     }
3927 
3928     // Convert back to nxvXi64.
3929     Vec = DAG.getBitcast(VT, Vec);
3930 
3931     if (!IsMasked)
3932       return Vec;
3933 
3934     // Apply mask after the operation.
3935     SDValue Mask = Op.getOperand(NumOps - 2);
3936     SDValue MaskedOff = Op.getOperand(1);
3937     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3938   }
3939   }
3940 
3941   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3942 }
3943 
3944 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3945                                                     SelectionDAG &DAG) const {
3946   unsigned IntNo = Op.getConstantOperandVal(1);
3947   switch (IntNo) {
3948   default:
3949     break;
3950   case Intrinsic::riscv_masked_strided_load: {
3951     SDLoc DL(Op);
3952     MVT XLenVT = Subtarget.getXLenVT();
3953 
3954     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
3955     // the selection of the masked intrinsics doesn't do this for us.
3956     SDValue Mask = Op.getOperand(5);
3957     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
3958 
3959     MVT VT = Op->getSimpleValueType(0);
3960     MVT ContainerVT = getContainerForFixedLengthVector(VT);
3961 
3962     SDValue PassThru = Op.getOperand(2);
3963     if (!IsUnmasked) {
3964       MVT MaskVT =
3965           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3966       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
3967       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
3968     }
3969 
3970     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
3971 
3972     SDValue IntID = DAG.getTargetConstant(
3973         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
3974         XLenVT);
3975 
3976     auto *Load = cast<MemIntrinsicSDNode>(Op);
3977     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
3978     if (!IsUnmasked)
3979       Ops.push_back(PassThru);
3980     Ops.push_back(Op.getOperand(3)); // Ptr
3981     Ops.push_back(Op.getOperand(4)); // Stride
3982     if (!IsUnmasked)
3983       Ops.push_back(Mask);
3984     Ops.push_back(VL);
3985 
3986     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
3987     SDValue Result =
3988         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
3989                                 Load->getMemoryVT(), Load->getMemOperand());
3990     SDValue Chain = Result.getValue(1);
3991     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3992     return DAG.getMergeValues({Result, Chain}, DL);
3993   }
3994   }
3995 
3996   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3997 }
3998 
3999 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4000                                                  SelectionDAG &DAG) const {
4001   unsigned IntNo = Op.getConstantOperandVal(1);
4002   switch (IntNo) {
4003   default:
4004     break;
4005   case Intrinsic::riscv_masked_strided_store: {
4006     SDLoc DL(Op);
4007     MVT XLenVT = Subtarget.getXLenVT();
4008 
4009     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4010     // the selection of the masked intrinsics doesn't do this for us.
4011     SDValue Mask = Op.getOperand(5);
4012     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4013 
4014     SDValue Val = Op.getOperand(2);
4015     MVT VT = Val.getSimpleValueType();
4016     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4017 
4018     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4019     if (!IsUnmasked) {
4020       MVT MaskVT =
4021           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4022       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4023     }
4024 
4025     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4026 
4027     SDValue IntID = DAG.getTargetConstant(
4028         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4029         XLenVT);
4030 
4031     auto *Store = cast<MemIntrinsicSDNode>(Op);
4032     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4033     Ops.push_back(Val);
4034     Ops.push_back(Op.getOperand(3)); // Ptr
4035     Ops.push_back(Op.getOperand(4)); // Stride
4036     if (!IsUnmasked)
4037       Ops.push_back(Mask);
4038     Ops.push_back(VL);
4039 
4040     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4041                                    Ops, Store->getMemoryVT(),
4042                                    Store->getMemOperand());
4043   }
4044   }
4045 
4046   return SDValue();
4047 }
4048 
4049 static MVT getLMUL1VT(MVT VT) {
4050   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4051          "Unexpected vector MVT");
4052   return MVT::getScalableVectorVT(
4053       VT.getVectorElementType(),
4054       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4055 }
4056 
4057 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4058   switch (ISDOpcode) {
4059   default:
4060     llvm_unreachable("Unhandled reduction");
4061   case ISD::VECREDUCE_ADD:
4062     return RISCVISD::VECREDUCE_ADD_VL;
4063   case ISD::VECREDUCE_UMAX:
4064     return RISCVISD::VECREDUCE_UMAX_VL;
4065   case ISD::VECREDUCE_SMAX:
4066     return RISCVISD::VECREDUCE_SMAX_VL;
4067   case ISD::VECREDUCE_UMIN:
4068     return RISCVISD::VECREDUCE_UMIN_VL;
4069   case ISD::VECREDUCE_SMIN:
4070     return RISCVISD::VECREDUCE_SMIN_VL;
4071   case ISD::VECREDUCE_AND:
4072     return RISCVISD::VECREDUCE_AND_VL;
4073   case ISD::VECREDUCE_OR:
4074     return RISCVISD::VECREDUCE_OR_VL;
4075   case ISD::VECREDUCE_XOR:
4076     return RISCVISD::VECREDUCE_XOR_VL;
4077   }
4078 }
4079 
4080 SDValue RISCVTargetLowering::lowerVectorMaskVECREDUCE(SDValue Op,
4081                                                       SelectionDAG &DAG) const {
4082   SDLoc DL(Op);
4083   SDValue Vec = Op.getOperand(0);
4084   MVT VecVT = Vec.getSimpleValueType();
4085   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4086           Op.getOpcode() == ISD::VECREDUCE_OR ||
4087           Op.getOpcode() == ISD::VECREDUCE_XOR) &&
4088          "Unexpected reduction lowering");
4089 
4090   MVT XLenVT = Subtarget.getXLenVT();
4091   assert(Op.getValueType() == XLenVT &&
4092          "Expected reduction output to be legalized to XLenVT");
4093 
4094   MVT ContainerVT = VecVT;
4095   if (VecVT.isFixedLengthVector()) {
4096     ContainerVT = getContainerForFixedLengthVector(VecVT);
4097     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4098   }
4099 
4100   SDValue Mask, VL;
4101   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4102   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4103 
4104   switch (Op.getOpcode()) {
4105   default:
4106     llvm_unreachable("Unhandled reduction");
4107   case ISD::VECREDUCE_AND:
4108     // vpopc ~x == 0
4109     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, Mask, VL);
4110     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4111     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETEQ);
4112   case ISD::VECREDUCE_OR:
4113     // vpopc x != 0
4114     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4115     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
4116   case ISD::VECREDUCE_XOR: {
4117     // ((vpopc x) & 1) != 0
4118     SDValue One = DAG.getConstant(1, DL, XLenVT);
4119     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4120     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4121     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
4122   }
4123   }
4124 }
4125 
4126 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4127                                             SelectionDAG &DAG) const {
4128   SDLoc DL(Op);
4129   SDValue Vec = Op.getOperand(0);
4130   EVT VecEVT = Vec.getValueType();
4131 
4132   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4133 
4134   // Due to ordering in legalize types we may have a vector type that needs to
4135   // be split. Do that manually so we can get down to a legal type.
4136   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4137          TargetLowering::TypeSplitVector) {
4138     SDValue Lo, Hi;
4139     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4140     VecEVT = Lo.getValueType();
4141     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4142   }
4143 
4144   // TODO: The type may need to be widened rather than split. Or widened before
4145   // it can be split.
4146   if (!isTypeLegal(VecEVT))
4147     return SDValue();
4148 
4149   MVT VecVT = VecEVT.getSimpleVT();
4150   MVT VecEltVT = VecVT.getVectorElementType();
4151   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4152 
4153   MVT ContainerVT = VecVT;
4154   if (VecVT.isFixedLengthVector()) {
4155     ContainerVT = getContainerForFixedLengthVector(VecVT);
4156     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4157   }
4158 
4159   MVT M1VT = getLMUL1VT(ContainerVT);
4160 
4161   SDValue Mask, VL;
4162   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4163 
4164   // FIXME: This is a VLMAX splat which might be too large and can prevent
4165   // vsetvli removal.
4166   SDValue NeutralElem =
4167       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4168   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4169   SDValue Reduction =
4170       DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL);
4171   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4172                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4173   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4174 }
4175 
4176 // Given a reduction op, this function returns the matching reduction opcode,
4177 // the vector SDValue and the scalar SDValue required to lower this to a
4178 // RISCVISD node.
4179 static std::tuple<unsigned, SDValue, SDValue>
4180 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4181   SDLoc DL(Op);
4182   auto Flags = Op->getFlags();
4183   unsigned Opcode = Op.getOpcode();
4184   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4185   switch (Opcode) {
4186   default:
4187     llvm_unreachable("Unhandled reduction");
4188   case ISD::VECREDUCE_FADD:
4189     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4190                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4191   case ISD::VECREDUCE_SEQ_FADD:
4192     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4193                            Op.getOperand(0));
4194   case ISD::VECREDUCE_FMIN:
4195     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4196                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4197   case ISD::VECREDUCE_FMAX:
4198     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4199                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4200   }
4201 }
4202 
4203 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4204                                               SelectionDAG &DAG) const {
4205   SDLoc DL(Op);
4206   MVT VecEltVT = Op.getSimpleValueType();
4207 
4208   unsigned RVVOpcode;
4209   SDValue VectorVal, ScalarVal;
4210   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4211       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4212   MVT VecVT = VectorVal.getSimpleValueType();
4213 
4214   MVT ContainerVT = VecVT;
4215   if (VecVT.isFixedLengthVector()) {
4216     ContainerVT = getContainerForFixedLengthVector(VecVT);
4217     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4218   }
4219 
4220   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4221 
4222   SDValue Mask, VL;
4223   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4224 
4225   // FIXME: This is a VLMAX splat which might be too large and can prevent
4226   // vsetvli removal.
4227   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4228   SDValue Reduction =
4229       DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL);
4230   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4231                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4232 }
4233 
4234 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4235                                                    SelectionDAG &DAG) const {
4236   SDValue Vec = Op.getOperand(0);
4237   SDValue SubVec = Op.getOperand(1);
4238   MVT VecVT = Vec.getSimpleValueType();
4239   MVT SubVecVT = SubVec.getSimpleValueType();
4240 
4241   SDLoc DL(Op);
4242   MVT XLenVT = Subtarget.getXLenVT();
4243   unsigned OrigIdx = Op.getConstantOperandVal(2);
4244   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4245 
4246   // We don't have the ability to slide mask vectors up indexed by their i1
4247   // elements; the smallest we can do is i8. Often we are able to bitcast to
4248   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4249   // into a scalable one, we might not necessarily have enough scalable
4250   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4251   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4252       (OrigIdx != 0 || !Vec.isUndef())) {
4253     if (VecVT.getVectorMinNumElements() >= 8 &&
4254         SubVecVT.getVectorMinNumElements() >= 8) {
4255       assert(OrigIdx % 8 == 0 && "Invalid index");
4256       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4257              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4258              "Unexpected mask vector lowering");
4259       OrigIdx /= 8;
4260       SubVecVT =
4261           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4262                            SubVecVT.isScalableVector());
4263       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4264                                VecVT.isScalableVector());
4265       Vec = DAG.getBitcast(VecVT, Vec);
4266       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4267     } else {
4268       // We can't slide this mask vector up indexed by its i1 elements.
4269       // This poses a problem when we wish to insert a scalable vector which
4270       // can't be re-expressed as a larger type. Just choose the slow path and
4271       // extend to a larger type, then truncate back down.
4272       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4273       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4274       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4275       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4276       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4277                         Op.getOperand(2));
4278       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4279       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4280     }
4281   }
4282 
4283   // If the subvector vector is a fixed-length type, we cannot use subregister
4284   // manipulation to simplify the codegen; we don't know which register of a
4285   // LMUL group contains the specific subvector as we only know the minimum
4286   // register size. Therefore we must slide the vector group up the full
4287   // amount.
4288   if (SubVecVT.isFixedLengthVector()) {
4289     if (OrigIdx == 0 && Vec.isUndef())
4290       return Op;
4291     MVT ContainerVT = VecVT;
4292     if (VecVT.isFixedLengthVector()) {
4293       ContainerVT = getContainerForFixedLengthVector(VecVT);
4294       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4295     }
4296     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4297                          DAG.getUNDEF(ContainerVT), SubVec,
4298                          DAG.getConstant(0, DL, XLenVT));
4299     SDValue Mask =
4300         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4301     // Set the vector length to only the number of elements we care about. Note
4302     // that for slideup this includes the offset.
4303     SDValue VL =
4304         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4305     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4306     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4307                                   SubVec, SlideupAmt, Mask, VL);
4308     if (VecVT.isFixedLengthVector())
4309       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4310     return DAG.getBitcast(Op.getValueType(), Slideup);
4311   }
4312 
4313   unsigned SubRegIdx, RemIdx;
4314   std::tie(SubRegIdx, RemIdx) =
4315       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4316           VecVT, SubVecVT, OrigIdx, TRI);
4317 
4318   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4319   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4320                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4321                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4322 
4323   // 1. If the Idx has been completely eliminated and this subvector's size is
4324   // a vector register or a multiple thereof, or the surrounding elements are
4325   // undef, then this is a subvector insert which naturally aligns to a vector
4326   // register. These can easily be handled using subregister manipulation.
4327   // 2. If the subvector is smaller than a vector register, then the insertion
4328   // must preserve the undisturbed elements of the register. We do this by
4329   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4330   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4331   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4332   // LMUL=1 type back into the larger vector (resolving to another subregister
4333   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4334   // to avoid allocating a large register group to hold our subvector.
4335   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4336     return Op;
4337 
4338   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4339   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4340   // (in our case undisturbed). This means we can set up a subvector insertion
4341   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4342   // size of the subvector.
4343   MVT InterSubVT = VecVT;
4344   SDValue AlignedExtract = Vec;
4345   unsigned AlignedIdx = OrigIdx - RemIdx;
4346   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4347     InterSubVT = getLMUL1VT(VecVT);
4348     // Extract a subvector equal to the nearest full vector register type. This
4349     // should resolve to a EXTRACT_SUBREG instruction.
4350     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4351                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4352   }
4353 
4354   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4355   // For scalable vectors this must be further multiplied by vscale.
4356   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4357 
4358   SDValue Mask, VL;
4359   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4360 
4361   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4362   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4363   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4364   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4365 
4366   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4367                        DAG.getUNDEF(InterSubVT), SubVec,
4368                        DAG.getConstant(0, DL, XLenVT));
4369 
4370   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4371                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4372 
4373   // If required, insert this subvector back into the correct vector register.
4374   // This should resolve to an INSERT_SUBREG instruction.
4375   if (VecVT.bitsGT(InterSubVT))
4376     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4377                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4378 
4379   // We might have bitcast from a mask type: cast back to the original type if
4380   // required.
4381   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4382 }
4383 
4384 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4385                                                     SelectionDAG &DAG) const {
4386   SDValue Vec = Op.getOperand(0);
4387   MVT SubVecVT = Op.getSimpleValueType();
4388   MVT VecVT = Vec.getSimpleValueType();
4389 
4390   SDLoc DL(Op);
4391   MVT XLenVT = Subtarget.getXLenVT();
4392   unsigned OrigIdx = Op.getConstantOperandVal(1);
4393   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4394 
4395   // We don't have the ability to slide mask vectors down indexed by their i1
4396   // elements; the smallest we can do is i8. Often we are able to bitcast to
4397   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4398   // from a scalable one, we might not necessarily have enough scalable
4399   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4400   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4401     if (VecVT.getVectorMinNumElements() >= 8 &&
4402         SubVecVT.getVectorMinNumElements() >= 8) {
4403       assert(OrigIdx % 8 == 0 && "Invalid index");
4404       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4405              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4406              "Unexpected mask vector lowering");
4407       OrigIdx /= 8;
4408       SubVecVT =
4409           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4410                            SubVecVT.isScalableVector());
4411       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4412                                VecVT.isScalableVector());
4413       Vec = DAG.getBitcast(VecVT, Vec);
4414     } else {
4415       // We can't slide this mask vector down, indexed by its i1 elements.
4416       // This poses a problem when we wish to extract a scalable vector which
4417       // can't be re-expressed as a larger type. Just choose the slow path and
4418       // extend to a larger type, then truncate back down.
4419       // TODO: We could probably improve this when extracting certain fixed
4420       // from fixed, where we can extract as i8 and shift the correct element
4421       // right to reach the desired subvector?
4422       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4423       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4424       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4425       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4426                         Op.getOperand(1));
4427       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4428       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4429     }
4430   }
4431 
4432   // If the subvector vector is a fixed-length type, we cannot use subregister
4433   // manipulation to simplify the codegen; we don't know which register of a
4434   // LMUL group contains the specific subvector as we only know the minimum
4435   // register size. Therefore we must slide the vector group down the full
4436   // amount.
4437   if (SubVecVT.isFixedLengthVector()) {
4438     // With an index of 0 this is a cast-like subvector, which can be performed
4439     // with subregister operations.
4440     if (OrigIdx == 0)
4441       return Op;
4442     MVT ContainerVT = VecVT;
4443     if (VecVT.isFixedLengthVector()) {
4444       ContainerVT = getContainerForFixedLengthVector(VecVT);
4445       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4446     }
4447     SDValue Mask =
4448         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4449     // Set the vector length to only the number of elements we care about. This
4450     // avoids sliding down elements we're going to discard straight away.
4451     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4452     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4453     SDValue Slidedown =
4454         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4455                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4456     // Now we can use a cast-like subvector extract to get the result.
4457     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4458                             DAG.getConstant(0, DL, XLenVT));
4459     return DAG.getBitcast(Op.getValueType(), Slidedown);
4460   }
4461 
4462   unsigned SubRegIdx, RemIdx;
4463   std::tie(SubRegIdx, RemIdx) =
4464       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4465           VecVT, SubVecVT, OrigIdx, TRI);
4466 
4467   // If the Idx has been completely eliminated then this is a subvector extract
4468   // which naturally aligns to a vector register. These can easily be handled
4469   // using subregister manipulation.
4470   if (RemIdx == 0)
4471     return Op;
4472 
4473   // Else we must shift our vector register directly to extract the subvector.
4474   // Do this using VSLIDEDOWN.
4475 
4476   // If the vector type is an LMUL-group type, extract a subvector equal to the
4477   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4478   // instruction.
4479   MVT InterSubVT = VecVT;
4480   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4481     InterSubVT = getLMUL1VT(VecVT);
4482     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4483                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4484   }
4485 
4486   // Slide this vector register down by the desired number of elements in order
4487   // to place the desired subvector starting at element 0.
4488   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4489   // For scalable vectors this must be further multiplied by vscale.
4490   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4491 
4492   SDValue Mask, VL;
4493   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4494   SDValue Slidedown =
4495       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4496                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4497 
4498   // Now the vector is in the right position, extract our final subvector. This
4499   // should resolve to a COPY.
4500   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4501                           DAG.getConstant(0, DL, XLenVT));
4502 
4503   // We might have bitcast from a mask type: cast back to the original type if
4504   // required.
4505   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4506 }
4507 
4508 // Lower step_vector to the vid instruction. Any non-identity step value must
4509 // be accounted for my manual expansion.
4510 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4511                                               SelectionDAG &DAG) const {
4512   SDLoc DL(Op);
4513   MVT VT = Op.getSimpleValueType();
4514   MVT XLenVT = Subtarget.getXLenVT();
4515   SDValue Mask, VL;
4516   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4517   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4518   uint64_t StepValImm = Op.getConstantOperandVal(0);
4519   if (StepValImm != 1) {
4520     if (isPowerOf2_64(StepValImm)) {
4521       SDValue StepVal =
4522           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4523                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4524       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4525     } else {
4526       SDValue StepVal = lowerScalarSplat(
4527           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4528           DL, DAG, Subtarget);
4529       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4530     }
4531   }
4532   return StepVec;
4533 }
4534 
4535 // Implement vector_reverse using vrgather.vv with indices determined by
4536 // subtracting the id of each element from (VLMAX-1). This will convert
4537 // the indices like so:
4538 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4539 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4540 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4541                                                  SelectionDAG &DAG) const {
4542   SDLoc DL(Op);
4543   MVT VecVT = Op.getSimpleValueType();
4544   unsigned EltSize = VecVT.getScalarSizeInBits();
4545   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4546 
4547   unsigned MaxVLMAX = 0;
4548   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4549   if (VectorBitsMax != 0)
4550     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4551 
4552   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4553   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4554 
4555   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4556   // to use vrgatherei16.vv.
4557   // TODO: It's also possible to use vrgatherei16.vv for other types to
4558   // decrease register width for the index calculation.
4559   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4560     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4561     // Reverse each half, then reassemble them in reverse order.
4562     // NOTE: It's also possible that after splitting that VLMAX no longer
4563     // requires vrgatherei16.vv.
4564     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4565       SDValue Lo, Hi;
4566       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4567       EVT LoVT, HiVT;
4568       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4569       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4570       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4571       // Reassemble the low and high pieces reversed.
4572       // FIXME: This is a CONCAT_VECTORS.
4573       SDValue Res =
4574           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4575                       DAG.getIntPtrConstant(0, DL));
4576       return DAG.getNode(
4577           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4578           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4579     }
4580 
4581     // Just promote the int type to i16 which will double the LMUL.
4582     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4583     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4584   }
4585 
4586   MVT XLenVT = Subtarget.getXLenVT();
4587   SDValue Mask, VL;
4588   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4589 
4590   // Calculate VLMAX-1 for the desired SEW.
4591   unsigned MinElts = VecVT.getVectorMinNumElements();
4592   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4593                               DAG.getConstant(MinElts, DL, XLenVT));
4594   SDValue VLMinus1 =
4595       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4596 
4597   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4598   bool IsRV32E64 =
4599       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4600   SDValue SplatVL;
4601   if (!IsRV32E64)
4602     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4603   else
4604     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4605 
4606   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4607   SDValue Indices =
4608       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4609 
4610   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4611 }
4612 
4613 SDValue
4614 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4615                                                      SelectionDAG &DAG) const {
4616   SDLoc DL(Op);
4617   auto *Load = cast<LoadSDNode>(Op);
4618 
4619   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4620                                         Load->getMemoryVT(),
4621                                         *Load->getMemOperand()) &&
4622          "Expecting a correctly-aligned load");
4623 
4624   MVT VT = Op.getSimpleValueType();
4625   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4626 
4627   SDValue VL =
4628       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4629 
4630   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4631   SDValue NewLoad = DAG.getMemIntrinsicNode(
4632       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4633       Load->getMemoryVT(), Load->getMemOperand());
4634 
4635   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4636   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4637 }
4638 
4639 SDValue
4640 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4641                                                       SelectionDAG &DAG) const {
4642   SDLoc DL(Op);
4643   auto *Store = cast<StoreSDNode>(Op);
4644 
4645   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4646                                         Store->getMemoryVT(),
4647                                         *Store->getMemOperand()) &&
4648          "Expecting a correctly-aligned store");
4649 
4650   SDValue StoreVal = Store->getValue();
4651   MVT VT = StoreVal.getSimpleValueType();
4652 
4653   // If the size less than a byte, we need to pad with zeros to make a byte.
4654   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4655     VT = MVT::v8i1;
4656     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4657                            DAG.getConstant(0, DL, VT), StoreVal,
4658                            DAG.getIntPtrConstant(0, DL));
4659   }
4660 
4661   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4662 
4663   SDValue VL =
4664       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4665 
4666   SDValue NewValue =
4667       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4668   return DAG.getMemIntrinsicNode(
4669       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4670       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4671       Store->getMemoryVT(), Store->getMemOperand());
4672 }
4673 
4674 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4675                                              SelectionDAG &DAG) const {
4676   SDLoc DL(Op);
4677   MVT VT = Op.getSimpleValueType();
4678 
4679   const auto *MemSD = cast<MemSDNode>(Op);
4680   EVT MemVT = MemSD->getMemoryVT();
4681   MachineMemOperand *MMO = MemSD->getMemOperand();
4682   SDValue Chain = MemSD->getChain();
4683   SDValue BasePtr = MemSD->getBasePtr();
4684 
4685   SDValue Mask, PassThru, VL;
4686   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4687     Mask = VPLoad->getMask();
4688     PassThru = DAG.getUNDEF(VT);
4689     VL = VPLoad->getVectorLength();
4690   } else {
4691     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4692     Mask = MLoad->getMask();
4693     PassThru = MLoad->getPassThru();
4694   }
4695 
4696   MVT XLenVT = Subtarget.getXLenVT();
4697 
4698   MVT ContainerVT = VT;
4699   if (VT.isFixedLengthVector()) {
4700     ContainerVT = getContainerForFixedLengthVector(VT);
4701     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4702 
4703     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4704     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4705   }
4706 
4707   if (!VL)
4708     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4709 
4710   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4711   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
4712   SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL};
4713   SDValue Result =
4714       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4715   Chain = Result.getValue(1);
4716 
4717   if (VT.isFixedLengthVector())
4718     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4719 
4720   return DAG.getMergeValues({Result, Chain}, DL);
4721 }
4722 
4723 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4724                                               SelectionDAG &DAG) const {
4725   SDLoc DL(Op);
4726 
4727   const auto *MemSD = cast<MemSDNode>(Op);
4728   EVT MemVT = MemSD->getMemoryVT();
4729   MachineMemOperand *MMO = MemSD->getMemOperand();
4730   SDValue Chain = MemSD->getChain();
4731   SDValue BasePtr = MemSD->getBasePtr();
4732   SDValue Val, Mask, VL;
4733 
4734   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4735     Val = VPStore->getValue();
4736     Mask = VPStore->getMask();
4737     VL = VPStore->getVectorLength();
4738   } else {
4739     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4740     Val = MStore->getValue();
4741     Mask = MStore->getMask();
4742   }
4743 
4744   MVT VT = Val.getSimpleValueType();
4745   MVT XLenVT = Subtarget.getXLenVT();
4746 
4747   MVT ContainerVT = VT;
4748   if (VT.isFixedLengthVector()) {
4749     ContainerVT = getContainerForFixedLengthVector(VT);
4750     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4751 
4752     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4753     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4754   }
4755 
4756   if (!VL)
4757     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4758 
4759   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT);
4760   return DAG.getMemIntrinsicNode(
4761       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
4762       {Chain, IntID, Val, BasePtr, Mask, VL}, MemVT, MMO);
4763 }
4764 
4765 SDValue
4766 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4767                                                       SelectionDAG &DAG) const {
4768   MVT InVT = Op.getOperand(0).getSimpleValueType();
4769   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4770 
4771   MVT VT = Op.getSimpleValueType();
4772 
4773   SDValue Op1 =
4774       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4775   SDValue Op2 =
4776       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4777 
4778   SDLoc DL(Op);
4779   SDValue VL =
4780       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4781 
4782   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4783   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4784 
4785   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4786                             Op.getOperand(2), Mask, VL);
4787 
4788   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4789 }
4790 
4791 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4792     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4793   MVT VT = Op.getSimpleValueType();
4794 
4795   if (VT.getVectorElementType() == MVT::i1)
4796     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4797 
4798   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4799 }
4800 
4801 SDValue
4802 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4803                                                       SelectionDAG &DAG) const {
4804   unsigned Opc;
4805   switch (Op.getOpcode()) {
4806   default: llvm_unreachable("Unexpected opcode!");
4807   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4808   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4809   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4810   }
4811 
4812   return lowerToScalableOp(Op, DAG, Opc);
4813 }
4814 
4815 // Lower vector ABS to smax(X, sub(0, X)).
4816 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4817   SDLoc DL(Op);
4818   MVT VT = Op.getSimpleValueType();
4819   SDValue X = Op.getOperand(0);
4820 
4821   assert(VT.isFixedLengthVector() && "Unexpected type");
4822 
4823   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4824   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
4825 
4826   SDValue Mask, VL;
4827   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4828 
4829   SDValue SplatZero =
4830       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4831                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4832   SDValue NegX =
4833       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
4834   SDValue Max =
4835       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
4836 
4837   return convertFromScalableVector(VT, Max, DAG, Subtarget);
4838 }
4839 
4840 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
4841     SDValue Op, SelectionDAG &DAG) const {
4842   SDLoc DL(Op);
4843   MVT VT = Op.getSimpleValueType();
4844   SDValue Mag = Op.getOperand(0);
4845   SDValue Sign = Op.getOperand(1);
4846   assert(Mag.getValueType() == Sign.getValueType() &&
4847          "Can only handle COPYSIGN with matching types.");
4848 
4849   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4850   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
4851   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
4852 
4853   SDValue Mask, VL;
4854   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4855 
4856   SDValue CopySign =
4857       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
4858 
4859   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
4860 }
4861 
4862 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
4863     SDValue Op, SelectionDAG &DAG) const {
4864   MVT VT = Op.getSimpleValueType();
4865   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4866 
4867   MVT I1ContainerVT =
4868       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4869 
4870   SDValue CC =
4871       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
4872   SDValue Op1 =
4873       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4874   SDValue Op2 =
4875       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
4876 
4877   SDLoc DL(Op);
4878   SDValue Mask, VL;
4879   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4880 
4881   SDValue Select =
4882       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
4883 
4884   return convertFromScalableVector(VT, Select, DAG, Subtarget);
4885 }
4886 
4887 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
4888                                                unsigned NewOpc,
4889                                                bool HasMask) const {
4890   MVT VT = Op.getSimpleValueType();
4891   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4892 
4893   // Create list of operands by converting existing ones to scalable types.
4894   SmallVector<SDValue, 6> Ops;
4895   for (const SDValue &V : Op->op_values()) {
4896     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4897 
4898     // Pass through non-vector operands.
4899     if (!V.getValueType().isVector()) {
4900       Ops.push_back(V);
4901       continue;
4902     }
4903 
4904     // "cast" fixed length vector to a scalable vector.
4905     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
4906            "Only fixed length vectors are supported!");
4907     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4908   }
4909 
4910   SDLoc DL(Op);
4911   SDValue Mask, VL;
4912   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4913   if (HasMask)
4914     Ops.push_back(Mask);
4915   Ops.push_back(VL);
4916 
4917   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
4918   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
4919 }
4920 
4921 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
4922 // * Operands of each node are assumed to be in the same order.
4923 // * The EVL operand is promoted from i32 to i64 on RV64.
4924 // * Fixed-length vectors are converted to their scalable-vector container
4925 //   types.
4926 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
4927                                        unsigned RISCVISDOpc) const {
4928   SDLoc DL(Op);
4929   MVT VT = Op.getSimpleValueType();
4930   SmallVector<SDValue, 4> Ops;
4931 
4932   for (const auto &OpIdx : enumerate(Op->ops())) {
4933     SDValue V = OpIdx.value();
4934     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4935     // Pass through operands which aren't fixed-length vectors.
4936     if (!V.getValueType().isFixedLengthVector()) {
4937       Ops.push_back(V);
4938       continue;
4939     }
4940     // "cast" fixed length vector to a scalable vector.
4941     MVT OpVT = V.getSimpleValueType();
4942     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
4943     assert(useRVVForFixedLengthVectorVT(OpVT) &&
4944            "Only fixed length vectors are supported!");
4945     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4946   }
4947 
4948   if (!VT.isFixedLengthVector())
4949     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
4950 
4951   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4952 
4953   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
4954 
4955   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
4956 }
4957 
4958 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
4959 // matched to a RVV indexed load. The RVV indexed load instructions only
4960 // support the "unsigned unscaled" addressing mode; indices are implicitly
4961 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
4962 // signed or scaled indexing is extended to the XLEN value type and scaled
4963 // accordingly.
4964 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
4965                                                SelectionDAG &DAG) const {
4966   SDLoc DL(Op);
4967   MVT VT = Op.getSimpleValueType();
4968 
4969   const auto *MemSD = cast<MemSDNode>(Op.getNode());
4970   EVT MemVT = MemSD->getMemoryVT();
4971   MachineMemOperand *MMO = MemSD->getMemOperand();
4972   SDValue Chain = MemSD->getChain();
4973   SDValue BasePtr = MemSD->getBasePtr();
4974 
4975   ISD::LoadExtType LoadExtType;
4976   SDValue Index, Mask, PassThru, VL;
4977 
4978   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
4979     Index = VPGN->getIndex();
4980     Mask = VPGN->getMask();
4981     PassThru = DAG.getUNDEF(VT);
4982     VL = VPGN->getVectorLength();
4983     // VP doesn't support extending loads.
4984     LoadExtType = ISD::NON_EXTLOAD;
4985   } else {
4986     // Else it must be a MGATHER.
4987     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
4988     Index = MGN->getIndex();
4989     Mask = MGN->getMask();
4990     PassThru = MGN->getPassThru();
4991     LoadExtType = MGN->getExtensionType();
4992   }
4993 
4994   MVT IndexVT = Index.getSimpleValueType();
4995   MVT XLenVT = Subtarget.getXLenVT();
4996 
4997   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4998          "Unexpected VTs!");
4999   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5000   // Targets have to explicitly opt-in for extending vector loads.
5001   assert(LoadExtType == ISD::NON_EXTLOAD &&
5002          "Unexpected extending MGATHER/VP_GATHER");
5003   (void)LoadExtType;
5004 
5005   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5006   // the selection of the masked intrinsics doesn't do this for us.
5007   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5008 
5009   MVT ContainerVT = VT;
5010   if (VT.isFixedLengthVector()) {
5011     // We need to use the larger of the result and index type to determine the
5012     // scalable type to use so we don't increase LMUL for any operand/result.
5013     if (VT.bitsGE(IndexVT)) {
5014       ContainerVT = getContainerForFixedLengthVector(VT);
5015       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5016                                  ContainerVT.getVectorElementCount());
5017     } else {
5018       IndexVT = getContainerForFixedLengthVector(IndexVT);
5019       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5020                                      IndexVT.getVectorElementCount());
5021     }
5022 
5023     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5024 
5025     if (!IsUnmasked) {
5026       MVT MaskVT =
5027           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5028       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5029       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5030     }
5031   }
5032 
5033   if (!VL)
5034     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5035 
5036   unsigned IntID =
5037       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5038   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5039   if (!IsUnmasked)
5040     Ops.push_back(PassThru);
5041   Ops.push_back(BasePtr);
5042   Ops.push_back(Index);
5043   if (!IsUnmasked)
5044     Ops.push_back(Mask);
5045   Ops.push_back(VL);
5046 
5047   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5048   SDValue Result =
5049       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5050   Chain = Result.getValue(1);
5051 
5052   if (VT.isFixedLengthVector())
5053     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5054 
5055   return DAG.getMergeValues({Result, Chain}, DL);
5056 }
5057 
5058 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5059 // matched to a RVV indexed store. The RVV indexed store instructions only
5060 // support the "unsigned unscaled" addressing mode; indices are implicitly
5061 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5062 // signed or scaled indexing is extended to the XLEN value type and scaled
5063 // accordingly.
5064 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5065                                                 SelectionDAG &DAG) const {
5066   SDLoc DL(Op);
5067   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5068   EVT MemVT = MemSD->getMemoryVT();
5069   MachineMemOperand *MMO = MemSD->getMemOperand();
5070   SDValue Chain = MemSD->getChain();
5071   SDValue BasePtr = MemSD->getBasePtr();
5072 
5073   bool IsTruncatingStore = false;
5074   SDValue Index, Mask, Val, VL;
5075 
5076   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5077     Index = VPSN->getIndex();
5078     Mask = VPSN->getMask();
5079     Val = VPSN->getValue();
5080     VL = VPSN->getVectorLength();
5081     // VP doesn't support truncating stores.
5082     IsTruncatingStore = false;
5083   } else {
5084     // Else it must be a MSCATTER.
5085     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5086     Index = MSN->getIndex();
5087     Mask = MSN->getMask();
5088     Val = MSN->getValue();
5089     IsTruncatingStore = MSN->isTruncatingStore();
5090   }
5091 
5092   MVT VT = Val.getSimpleValueType();
5093   MVT IndexVT = Index.getSimpleValueType();
5094   MVT XLenVT = Subtarget.getXLenVT();
5095 
5096   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5097          "Unexpected VTs!");
5098   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5099   // Targets have to explicitly opt-in for extending vector loads and
5100   // truncating vector stores.
5101   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5102   (void)IsTruncatingStore;
5103 
5104   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5105   // the selection of the masked intrinsics doesn't do this for us.
5106   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5107 
5108   MVT ContainerVT = VT;
5109   if (VT.isFixedLengthVector()) {
5110     // We need to use the larger of the value and index type to determine the
5111     // scalable type to use so we don't increase LMUL for any operand/result.
5112     if (VT.bitsGE(IndexVT)) {
5113       ContainerVT = getContainerForFixedLengthVector(VT);
5114       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5115                                  ContainerVT.getVectorElementCount());
5116     } else {
5117       IndexVT = getContainerForFixedLengthVector(IndexVT);
5118       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5119                                      IndexVT.getVectorElementCount());
5120     }
5121 
5122     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5123     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5124 
5125     if (!IsUnmasked) {
5126       MVT MaskVT =
5127           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5128       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5129     }
5130   }
5131 
5132   if (!VL)
5133     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5134 
5135   unsigned IntID =
5136       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5137   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5138   Ops.push_back(Val);
5139   Ops.push_back(BasePtr);
5140   Ops.push_back(Index);
5141   if (!IsUnmasked)
5142     Ops.push_back(Mask);
5143   Ops.push_back(VL);
5144 
5145   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5146                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5147 }
5148 
5149 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5150                                                SelectionDAG &DAG) const {
5151   const MVT XLenVT = Subtarget.getXLenVT();
5152   SDLoc DL(Op);
5153   SDValue Chain = Op->getOperand(0);
5154   SDValue SysRegNo = DAG.getConstant(
5155       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5156   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5157   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5158 
5159   // Encoding used for rounding mode in RISCV differs from that used in
5160   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5161   // table, which consists of a sequence of 4-bit fields, each representing
5162   // corresponding FLT_ROUNDS mode.
5163   static const int Table =
5164       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5165       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5166       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5167       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5168       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5169 
5170   SDValue Shift =
5171       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5172   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5173                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5174   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5175                                DAG.getConstant(7, DL, XLenVT));
5176 
5177   return DAG.getMergeValues({Masked, Chain}, DL);
5178 }
5179 
5180 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5181                                                SelectionDAG &DAG) const {
5182   const MVT XLenVT = Subtarget.getXLenVT();
5183   SDLoc DL(Op);
5184   SDValue Chain = Op->getOperand(0);
5185   SDValue RMValue = Op->getOperand(1);
5186   SDValue SysRegNo = DAG.getConstant(
5187       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5188 
5189   // Encoding used for rounding mode in RISCV differs from that used in
5190   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5191   // a table, which consists of a sequence of 4-bit fields, each representing
5192   // corresponding RISCV mode.
5193   static const unsigned Table =
5194       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5195       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5196       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5197       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5198       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5199 
5200   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5201                               DAG.getConstant(2, DL, XLenVT));
5202   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5203                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5204   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5205                         DAG.getConstant(0x7, DL, XLenVT));
5206   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5207                      RMValue);
5208 }
5209 
5210 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5211 // form of the given Opcode.
5212 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5213   switch (Opcode) {
5214   default:
5215     llvm_unreachable("Unexpected opcode");
5216   case ISD::SHL:
5217     return RISCVISD::SLLW;
5218   case ISD::SRA:
5219     return RISCVISD::SRAW;
5220   case ISD::SRL:
5221     return RISCVISD::SRLW;
5222   case ISD::SDIV:
5223     return RISCVISD::DIVW;
5224   case ISD::UDIV:
5225     return RISCVISD::DIVUW;
5226   case ISD::UREM:
5227     return RISCVISD::REMUW;
5228   case ISD::ROTL:
5229     return RISCVISD::ROLW;
5230   case ISD::ROTR:
5231     return RISCVISD::RORW;
5232   case RISCVISD::GREV:
5233     return RISCVISD::GREVW;
5234   case RISCVISD::GORC:
5235     return RISCVISD::GORCW;
5236   }
5237 }
5238 
5239 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5240 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5241 // otherwise be promoted to i64, making it difficult to select the
5242 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5243 // type i8/i16/i32 is lost.
5244 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5245                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5246   SDLoc DL(N);
5247   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5248   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5249   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5250   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5251   // ReplaceNodeResults requires we maintain the same type for the return value.
5252   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5253 }
5254 
5255 // Converts the given 32-bit operation to a i64 operation with signed extension
5256 // semantic to reduce the signed extension instructions.
5257 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5258   SDLoc DL(N);
5259   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5260   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5261   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5262   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5263                                DAG.getValueType(MVT::i32));
5264   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5265 }
5266 
5267 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5268                                              SmallVectorImpl<SDValue> &Results,
5269                                              SelectionDAG &DAG) const {
5270   SDLoc DL(N);
5271   switch (N->getOpcode()) {
5272   default:
5273     llvm_unreachable("Don't know how to custom type legalize this operation!");
5274   case ISD::STRICT_FP_TO_SINT:
5275   case ISD::STRICT_FP_TO_UINT:
5276   case ISD::FP_TO_SINT:
5277   case ISD::FP_TO_UINT: {
5278     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5279            "Unexpected custom legalisation");
5280     bool IsStrict = N->isStrictFPOpcode();
5281     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5282                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5283     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5284     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5285         TargetLowering::TypeSoftenFloat) {
5286       // FIXME: Support strict FP.
5287       if (IsStrict)
5288         return;
5289       if (!isTypeLegal(Op0.getValueType()))
5290         return;
5291       unsigned Opc =
5292           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5293       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5294       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5295       return;
5296     }
5297     // If the FP type needs to be softened, emit a library call using the 'si'
5298     // version. If we left it to default legalization we'd end up with 'di'. If
5299     // the FP type doesn't need to be softened just let generic type
5300     // legalization promote the result type.
5301     RTLIB::Libcall LC;
5302     if (IsSigned)
5303       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5304     else
5305       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5306     MakeLibCallOptions CallOptions;
5307     EVT OpVT = Op0.getValueType();
5308     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5309     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5310     SDValue Result;
5311     std::tie(Result, Chain) =
5312         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5313     Results.push_back(Result);
5314     if (IsStrict)
5315       Results.push_back(Chain);
5316     break;
5317   }
5318   case ISD::READCYCLECOUNTER: {
5319     assert(!Subtarget.is64Bit() &&
5320            "READCYCLECOUNTER only has custom type legalization on riscv32");
5321 
5322     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5323     SDValue RCW =
5324         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5325 
5326     Results.push_back(
5327         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5328     Results.push_back(RCW.getValue(2));
5329     break;
5330   }
5331   case ISD::MUL: {
5332     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5333     unsigned XLen = Subtarget.getXLen();
5334     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5335     if (Size > XLen) {
5336       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5337       SDValue LHS = N->getOperand(0);
5338       SDValue RHS = N->getOperand(1);
5339       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5340 
5341       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5342       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5343       // We need exactly one side to be unsigned.
5344       if (LHSIsU == RHSIsU)
5345         return;
5346 
5347       auto MakeMULPair = [&](SDValue S, SDValue U) {
5348         MVT XLenVT = Subtarget.getXLenVT();
5349         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5350         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5351         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5352         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5353         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5354       };
5355 
5356       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5357       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5358 
5359       // The other operand should be signed, but still prefer MULH when
5360       // possible.
5361       if (RHSIsU && LHSIsS && !RHSIsS)
5362         Results.push_back(MakeMULPair(LHS, RHS));
5363       else if (LHSIsU && RHSIsS && !LHSIsS)
5364         Results.push_back(MakeMULPair(RHS, LHS));
5365 
5366       return;
5367     }
5368     LLVM_FALLTHROUGH;
5369   }
5370   case ISD::ADD:
5371   case ISD::SUB:
5372     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5373            "Unexpected custom legalisation");
5374     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5375     break;
5376   case ISD::SHL:
5377   case ISD::SRA:
5378   case ISD::SRL:
5379     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5380            "Unexpected custom legalisation");
5381     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5382       Results.push_back(customLegalizeToWOp(N, DAG));
5383       break;
5384     }
5385 
5386     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5387     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5388     // shift amount.
5389     if (N->getOpcode() == ISD::SHL) {
5390       SDLoc DL(N);
5391       SDValue NewOp0 =
5392           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5393       SDValue NewOp1 =
5394           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5395       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5396       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5397                                    DAG.getValueType(MVT::i32));
5398       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5399     }
5400 
5401     break;
5402   case ISD::ROTL:
5403   case ISD::ROTR:
5404     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5405            "Unexpected custom legalisation");
5406     Results.push_back(customLegalizeToWOp(N, DAG));
5407     break;
5408   case ISD::CTTZ:
5409   case ISD::CTTZ_ZERO_UNDEF:
5410   case ISD::CTLZ:
5411   case ISD::CTLZ_ZERO_UNDEF: {
5412     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5413            "Unexpected custom legalisation");
5414 
5415     SDValue NewOp0 =
5416         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5417     bool IsCTZ =
5418         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5419     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5420     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5421     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5422     return;
5423   }
5424   case ISD::SDIV:
5425   case ISD::UDIV:
5426   case ISD::UREM: {
5427     MVT VT = N->getSimpleValueType(0);
5428     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5429            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5430            "Unexpected custom legalisation");
5431     // Don't promote division/remainder by constant since we should expand those
5432     // to multiply by magic constant.
5433     // FIXME: What if the expansion is disabled for minsize.
5434     if (N->getOperand(1).getOpcode() == ISD::Constant)
5435       return;
5436 
5437     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5438     // the upper 32 bits. For other types we need to sign or zero extend
5439     // based on the opcode.
5440     unsigned ExtOpc = ISD::ANY_EXTEND;
5441     if (VT != MVT::i32)
5442       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5443                                            : ISD::ZERO_EXTEND;
5444 
5445     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5446     break;
5447   }
5448   case ISD::UADDO:
5449   case ISD::USUBO: {
5450     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5451            "Unexpected custom legalisation");
5452     bool IsAdd = N->getOpcode() == ISD::UADDO;
5453     // Create an ADDW or SUBW.
5454     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5455     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5456     SDValue Res =
5457         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5458     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5459                       DAG.getValueType(MVT::i32));
5460 
5461     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5462     // Since the inputs are sign extended from i32, this is equivalent to
5463     // comparing the lower 32 bits.
5464     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5465     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5466                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5467 
5468     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5469     Results.push_back(Overflow);
5470     return;
5471   }
5472   case ISD::UADDSAT:
5473   case ISD::USUBSAT: {
5474     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5475            "Unexpected custom legalisation");
5476     if (Subtarget.hasStdExtZbb()) {
5477       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5478       // sign extend allows overflow of the lower 32 bits to be detected on
5479       // the promoted size.
5480       SDValue LHS =
5481           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5482       SDValue RHS =
5483           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5484       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5485       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5486       return;
5487     }
5488 
5489     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5490     // promotion for UADDO/USUBO.
5491     Results.push_back(expandAddSubSat(N, DAG));
5492     return;
5493   }
5494   case ISD::BITCAST: {
5495     EVT VT = N->getValueType(0);
5496     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5497     SDValue Op0 = N->getOperand(0);
5498     EVT Op0VT = Op0.getValueType();
5499     MVT XLenVT = Subtarget.getXLenVT();
5500     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5501       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5502       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5503     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5504                Subtarget.hasStdExtF()) {
5505       SDValue FPConv =
5506           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5507       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5508     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5509                isTypeLegal(Op0VT)) {
5510       // Custom-legalize bitcasts from fixed-length vector types to illegal
5511       // scalar types in order to improve codegen. Bitcast the vector to a
5512       // one-element vector type whose element type is the same as the result
5513       // type, and extract the first element.
5514       LLVMContext &Context = *DAG.getContext();
5515       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5516       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5517                                     DAG.getConstant(0, DL, XLenVT)));
5518     }
5519     break;
5520   }
5521   case RISCVISD::GREV:
5522   case RISCVISD::GORC: {
5523     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5524            "Unexpected custom legalisation");
5525     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5526     // This is similar to customLegalizeToWOp, except that we pass the second
5527     // operand (a TargetConstant) straight through: it is already of type
5528     // XLenVT.
5529     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5530     SDValue NewOp0 =
5531         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5532     SDValue NewOp1 =
5533         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5534     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5535     // ReplaceNodeResults requires we maintain the same type for the return
5536     // value.
5537     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5538     break;
5539   }
5540   case RISCVISD::SHFL: {
5541     // There is no SHFLIW instruction, but we can just promote the operation.
5542     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5543            "Unexpected custom legalisation");
5544     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5545     SDValue NewOp0 =
5546         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5547     SDValue NewOp1 =
5548         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5549     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5550     // ReplaceNodeResults requires we maintain the same type for the return
5551     // value.
5552     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5553     break;
5554   }
5555   case ISD::BSWAP:
5556   case ISD::BITREVERSE: {
5557     MVT VT = N->getSimpleValueType(0);
5558     MVT XLenVT = Subtarget.getXLenVT();
5559     assert((VT == MVT::i8 || VT == MVT::i16 ||
5560             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5561            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5562     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5563     unsigned Imm = VT.getSizeInBits() - 1;
5564     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5565     if (N->getOpcode() == ISD::BSWAP)
5566       Imm &= ~0x7U;
5567     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5568     SDValue GREVI =
5569         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5570     // ReplaceNodeResults requires we maintain the same type for the return
5571     // value.
5572     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5573     break;
5574   }
5575   case ISD::FSHL:
5576   case ISD::FSHR: {
5577     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5578            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5579     SDValue NewOp0 =
5580         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5581     SDValue NewOp1 =
5582         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5583     SDValue NewOp2 =
5584         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5585     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5586     // Mask the shift amount to 5 bits.
5587     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5588                          DAG.getConstant(0x1f, DL, MVT::i64));
5589     unsigned Opc =
5590         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5591     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5592     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5593     break;
5594   }
5595   case ISD::EXTRACT_VECTOR_ELT: {
5596     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5597     // type is illegal (currently only vXi64 RV32).
5598     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5599     // transferred to the destination register. We issue two of these from the
5600     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5601     // first element.
5602     SDValue Vec = N->getOperand(0);
5603     SDValue Idx = N->getOperand(1);
5604 
5605     // The vector type hasn't been legalized yet so we can't issue target
5606     // specific nodes if it needs legalization.
5607     // FIXME: We would manually legalize if it's important.
5608     if (!isTypeLegal(Vec.getValueType()))
5609       return;
5610 
5611     MVT VecVT = Vec.getSimpleValueType();
5612 
5613     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5614            VecVT.getVectorElementType() == MVT::i64 &&
5615            "Unexpected EXTRACT_VECTOR_ELT legalization");
5616 
5617     // If this is a fixed vector, we need to convert it to a scalable vector.
5618     MVT ContainerVT = VecVT;
5619     if (VecVT.isFixedLengthVector()) {
5620       ContainerVT = getContainerForFixedLengthVector(VecVT);
5621       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5622     }
5623 
5624     MVT XLenVT = Subtarget.getXLenVT();
5625 
5626     // Use a VL of 1 to avoid processing more elements than we need.
5627     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5628     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5629     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5630 
5631     // Unless the index is known to be 0, we must slide the vector down to get
5632     // the desired element into index 0.
5633     if (!isNullConstant(Idx)) {
5634       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5635                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5636     }
5637 
5638     // Extract the lower XLEN bits of the correct vector element.
5639     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5640 
5641     // To extract the upper XLEN bits of the vector element, shift the first
5642     // element right by 32 bits and re-extract the lower XLEN bits.
5643     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5644                                      DAG.getConstant(32, DL, XLenVT), VL);
5645     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5646                                  ThirtyTwoV, Mask, VL);
5647 
5648     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5649 
5650     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5651     break;
5652   }
5653   case ISD::INTRINSIC_WO_CHAIN: {
5654     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5655     switch (IntNo) {
5656     default:
5657       llvm_unreachable(
5658           "Don't know how to custom type legalize this intrinsic!");
5659     case Intrinsic::riscv_orc_b: {
5660       // Lower to the GORCI encoding for orc.b with the operand extended.
5661       SDValue NewOp =
5662           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5663       // If Zbp is enabled, use GORCIW which will sign extend the result.
5664       unsigned Opc =
5665           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5666       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5667                                 DAG.getConstant(7, DL, MVT::i64));
5668       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5669       return;
5670     }
5671     case Intrinsic::riscv_grev:
5672     case Intrinsic::riscv_gorc: {
5673       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5674              "Unexpected custom legalisation");
5675       SDValue NewOp1 =
5676           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5677       SDValue NewOp2 =
5678           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5679       unsigned Opc =
5680           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5681       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5682       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5683       break;
5684     }
5685     case Intrinsic::riscv_shfl:
5686     case Intrinsic::riscv_unshfl: {
5687       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5688              "Unexpected custom legalisation");
5689       SDValue NewOp1 =
5690           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5691       SDValue NewOp2 =
5692           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5693       unsigned Opc =
5694           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5695       if (isa<ConstantSDNode>(N->getOperand(2))) {
5696         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5697                              DAG.getConstant(0xf, DL, MVT::i64));
5698         Opc =
5699             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5700       }
5701       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5702       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5703       break;
5704     }
5705     case Intrinsic::riscv_bcompress:
5706     case Intrinsic::riscv_bdecompress: {
5707       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5708              "Unexpected custom legalisation");
5709       SDValue NewOp1 =
5710           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5711       SDValue NewOp2 =
5712           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5713       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5714                          ? RISCVISD::BCOMPRESSW
5715                          : RISCVISD::BDECOMPRESSW;
5716       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5717       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5718       break;
5719     }
5720     case Intrinsic::riscv_vmv_x_s: {
5721       EVT VT = N->getValueType(0);
5722       MVT XLenVT = Subtarget.getXLenVT();
5723       if (VT.bitsLT(XLenVT)) {
5724         // Simple case just extract using vmv.x.s and truncate.
5725         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5726                                       Subtarget.getXLenVT(), N->getOperand(1));
5727         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5728         return;
5729       }
5730 
5731       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5732              "Unexpected custom legalization");
5733 
5734       // We need to do the move in two steps.
5735       SDValue Vec = N->getOperand(1);
5736       MVT VecVT = Vec.getSimpleValueType();
5737 
5738       // First extract the lower XLEN bits of the element.
5739       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5740 
5741       // To extract the upper XLEN bits of the vector element, shift the first
5742       // element right by 32 bits and re-extract the lower XLEN bits.
5743       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5744       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5745       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5746       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5747                                        DAG.getConstant(32, DL, XLenVT), VL);
5748       SDValue LShr32 =
5749           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5750       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5751 
5752       Results.push_back(
5753           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5754       break;
5755     }
5756     }
5757     break;
5758   }
5759   case ISD::VECREDUCE_ADD:
5760   case ISD::VECREDUCE_AND:
5761   case ISD::VECREDUCE_OR:
5762   case ISD::VECREDUCE_XOR:
5763   case ISD::VECREDUCE_SMAX:
5764   case ISD::VECREDUCE_UMAX:
5765   case ISD::VECREDUCE_SMIN:
5766   case ISD::VECREDUCE_UMIN:
5767     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5768       Results.push_back(V);
5769     break;
5770   case ISD::FLT_ROUNDS_: {
5771     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5772     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5773     Results.push_back(Res.getValue(0));
5774     Results.push_back(Res.getValue(1));
5775     break;
5776   }
5777   }
5778 }
5779 
5780 // A structure to hold one of the bit-manipulation patterns below. Together, a
5781 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5782 //   (or (and (shl x, 1), 0xAAAAAAAA),
5783 //       (and (srl x, 1), 0x55555555))
5784 struct RISCVBitmanipPat {
5785   SDValue Op;
5786   unsigned ShAmt;
5787   bool IsSHL;
5788 
5789   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5790     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5791   }
5792 };
5793 
5794 // Matches patterns of the form
5795 //   (and (shl x, C2), (C1 << C2))
5796 //   (and (srl x, C2), C1)
5797 //   (shl (and x, C1), C2)
5798 //   (srl (and x, (C1 << C2)), C2)
5799 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5800 // The expected masks for each shift amount are specified in BitmanipMasks where
5801 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5802 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5803 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5804 // XLen is 64.
5805 static Optional<RISCVBitmanipPat>
5806 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5807   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5808          "Unexpected number of masks");
5809   Optional<uint64_t> Mask;
5810   // Optionally consume a mask around the shift operation.
5811   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5812     Mask = Op.getConstantOperandVal(1);
5813     Op = Op.getOperand(0);
5814   }
5815   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5816     return None;
5817   bool IsSHL = Op.getOpcode() == ISD::SHL;
5818 
5819   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5820     return None;
5821   uint64_t ShAmt = Op.getConstantOperandVal(1);
5822 
5823   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5824   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
5825     return None;
5826   // If we don't have enough masks for 64 bit, then we must be trying to
5827   // match SHFL so we're only allowed to shift 1/4 of the width.
5828   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
5829     return None;
5830 
5831   SDValue Src = Op.getOperand(0);
5832 
5833   // The expected mask is shifted left when the AND is found around SHL
5834   // patterns.
5835   //   ((x >> 1) & 0x55555555)
5836   //   ((x << 1) & 0xAAAAAAAA)
5837   bool SHLExpMask = IsSHL;
5838 
5839   if (!Mask) {
5840     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
5841     // the mask is all ones: consume that now.
5842     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
5843       Mask = Src.getConstantOperandVal(1);
5844       Src = Src.getOperand(0);
5845       // The expected mask is now in fact shifted left for SRL, so reverse the
5846       // decision.
5847       //   ((x & 0xAAAAAAAA) >> 1)
5848       //   ((x & 0x55555555) << 1)
5849       SHLExpMask = !SHLExpMask;
5850     } else {
5851       // Use a default shifted mask of all-ones if there's no AND, truncated
5852       // down to the expected width. This simplifies the logic later on.
5853       Mask = maskTrailingOnes<uint64_t>(Width);
5854       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
5855     }
5856   }
5857 
5858   unsigned MaskIdx = Log2_32(ShAmt);
5859   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5860 
5861   if (SHLExpMask)
5862     ExpMask <<= ShAmt;
5863 
5864   if (Mask != ExpMask)
5865     return None;
5866 
5867   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
5868 }
5869 
5870 // Matches any of the following bit-manipulation patterns:
5871 //   (and (shl x, 1), (0x55555555 << 1))
5872 //   (and (srl x, 1), 0x55555555)
5873 //   (shl (and x, 0x55555555), 1)
5874 //   (srl (and x, (0x55555555 << 1)), 1)
5875 // where the shift amount and mask may vary thus:
5876 //   [1]  = 0x55555555 / 0xAAAAAAAA
5877 //   [2]  = 0x33333333 / 0xCCCCCCCC
5878 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
5879 //   [8]  = 0x00FF00FF / 0xFF00FF00
5880 //   [16] = 0x0000FFFF / 0xFFFFFFFF
5881 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
5882 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
5883   // These are the unshifted masks which we use to match bit-manipulation
5884   // patterns. They may be shifted left in certain circumstances.
5885   static const uint64_t BitmanipMasks[] = {
5886       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
5887       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
5888 
5889   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5890 }
5891 
5892 // Match the following pattern as a GREVI(W) operation
5893 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
5894 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
5895                                const RISCVSubtarget &Subtarget) {
5896   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5897   EVT VT = Op.getValueType();
5898 
5899   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5900     auto LHS = matchGREVIPat(Op.getOperand(0));
5901     auto RHS = matchGREVIPat(Op.getOperand(1));
5902     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
5903       SDLoc DL(Op);
5904       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
5905                          DAG.getConstant(LHS->ShAmt, DL, VT));
5906     }
5907   }
5908   return SDValue();
5909 }
5910 
5911 // Matches any the following pattern as a GORCI(W) operation
5912 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
5913 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
5914 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
5915 // Note that with the variant of 3.,
5916 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
5917 // the inner pattern will first be matched as GREVI and then the outer
5918 // pattern will be matched to GORC via the first rule above.
5919 // 4.  (or (rotl/rotr x, bitwidth/2), x)
5920 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
5921                                const RISCVSubtarget &Subtarget) {
5922   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5923   EVT VT = Op.getValueType();
5924 
5925   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5926     SDLoc DL(Op);
5927     SDValue Op0 = Op.getOperand(0);
5928     SDValue Op1 = Op.getOperand(1);
5929 
5930     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
5931       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
5932           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
5933           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
5934         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
5935       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
5936       if ((Reverse.getOpcode() == ISD::ROTL ||
5937            Reverse.getOpcode() == ISD::ROTR) &&
5938           Reverse.getOperand(0) == X &&
5939           isa<ConstantSDNode>(Reverse.getOperand(1))) {
5940         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
5941         if (RotAmt == (VT.getSizeInBits() / 2))
5942           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
5943                              DAG.getConstant(RotAmt, DL, VT));
5944       }
5945       return SDValue();
5946     };
5947 
5948     // Check for either commutable permutation of (or (GREVI x, shamt), x)
5949     if (SDValue V = MatchOROfReverse(Op0, Op1))
5950       return V;
5951     if (SDValue V = MatchOROfReverse(Op1, Op0))
5952       return V;
5953 
5954     // OR is commutable so canonicalize its OR operand to the left
5955     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
5956       std::swap(Op0, Op1);
5957     if (Op0.getOpcode() != ISD::OR)
5958       return SDValue();
5959     SDValue OrOp0 = Op0.getOperand(0);
5960     SDValue OrOp1 = Op0.getOperand(1);
5961     auto LHS = matchGREVIPat(OrOp0);
5962     // OR is commutable so swap the operands and try again: x might have been
5963     // on the left
5964     if (!LHS) {
5965       std::swap(OrOp0, OrOp1);
5966       LHS = matchGREVIPat(OrOp0);
5967     }
5968     auto RHS = matchGREVIPat(Op1);
5969     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
5970       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
5971                          DAG.getConstant(LHS->ShAmt, DL, VT));
5972     }
5973   }
5974   return SDValue();
5975 }
5976 
5977 // Matches any of the following bit-manipulation patterns:
5978 //   (and (shl x, 1), (0x22222222 << 1))
5979 //   (and (srl x, 1), 0x22222222)
5980 //   (shl (and x, 0x22222222), 1)
5981 //   (srl (and x, (0x22222222 << 1)), 1)
5982 // where the shift amount and mask may vary thus:
5983 //   [1]  = 0x22222222 / 0x44444444
5984 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
5985 //   [4]  = 0x00F000F0 / 0x0F000F00
5986 //   [8]  = 0x0000FF00 / 0x00FF0000
5987 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
5988 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
5989   // These are the unshifted masks which we use to match bit-manipulation
5990   // patterns. They may be shifted left in certain circumstances.
5991   static const uint64_t BitmanipMasks[] = {
5992       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
5993       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
5994 
5995   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5996 }
5997 
5998 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
5999 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6000                                const RISCVSubtarget &Subtarget) {
6001   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6002   EVT VT = Op.getValueType();
6003 
6004   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6005     return SDValue();
6006 
6007   SDValue Op0 = Op.getOperand(0);
6008   SDValue Op1 = Op.getOperand(1);
6009 
6010   // Or is commutable so canonicalize the second OR to the LHS.
6011   if (Op0.getOpcode() != ISD::OR)
6012     std::swap(Op0, Op1);
6013   if (Op0.getOpcode() != ISD::OR)
6014     return SDValue();
6015 
6016   // We found an inner OR, so our operands are the operands of the inner OR
6017   // and the other operand of the outer OR.
6018   SDValue A = Op0.getOperand(0);
6019   SDValue B = Op0.getOperand(1);
6020   SDValue C = Op1;
6021 
6022   auto Match1 = matchSHFLPat(A);
6023   auto Match2 = matchSHFLPat(B);
6024 
6025   // If neither matched, we failed.
6026   if (!Match1 && !Match2)
6027     return SDValue();
6028 
6029   // We had at least one match. if one failed, try the remaining C operand.
6030   if (!Match1) {
6031     std::swap(A, C);
6032     Match1 = matchSHFLPat(A);
6033     if (!Match1)
6034       return SDValue();
6035   } else if (!Match2) {
6036     std::swap(B, C);
6037     Match2 = matchSHFLPat(B);
6038     if (!Match2)
6039       return SDValue();
6040   }
6041   assert(Match1 && Match2);
6042 
6043   // Make sure our matches pair up.
6044   if (!Match1->formsPairWith(*Match2))
6045     return SDValue();
6046 
6047   // All the remains is to make sure C is an AND with the same input, that masks
6048   // out the bits that are being shuffled.
6049   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6050       C.getOperand(0) != Match1->Op)
6051     return SDValue();
6052 
6053   uint64_t Mask = C.getConstantOperandVal(1);
6054 
6055   static const uint64_t BitmanipMasks[] = {
6056       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6057       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6058   };
6059 
6060   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6061   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6062   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6063 
6064   if (Mask != ExpMask)
6065     return SDValue();
6066 
6067   SDLoc DL(Op);
6068   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6069                      DAG.getConstant(Match1->ShAmt, DL, VT));
6070 }
6071 
6072 // Optimize (add (shl x, c0), (shl y, c1)) ->
6073 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6074 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6075                                   const RISCVSubtarget &Subtarget) {
6076   // Perform this optimization only in the zba extension.
6077   if (!Subtarget.hasStdExtZba())
6078     return SDValue();
6079 
6080   // Skip for vector types and larger types.
6081   EVT VT = N->getValueType(0);
6082   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6083     return SDValue();
6084 
6085   // The two operand nodes must be SHL and have no other use.
6086   SDValue N0 = N->getOperand(0);
6087   SDValue N1 = N->getOperand(1);
6088   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6089       !N0->hasOneUse() || !N1->hasOneUse())
6090     return SDValue();
6091 
6092   // Check c0 and c1.
6093   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6094   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6095   if (!N0C || !N1C)
6096     return SDValue();
6097   int64_t C0 = N0C->getSExtValue();
6098   int64_t C1 = N1C->getSExtValue();
6099   if (C0 <= 0 || C1 <= 0)
6100     return SDValue();
6101 
6102   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6103   int64_t Bits = std::min(C0, C1);
6104   int64_t Diff = std::abs(C0 - C1);
6105   if (Diff != 1 && Diff != 2 && Diff != 3)
6106     return SDValue();
6107 
6108   // Build nodes.
6109   SDLoc DL(N);
6110   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6111   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6112   SDValue NA0 =
6113       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6114   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6115   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6116 }
6117 
6118 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6119 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6120 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6121 // not undo itself, but they are redundant.
6122 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6123   SDValue Src = N->getOperand(0);
6124 
6125   if (Src.getOpcode() != N->getOpcode())
6126     return SDValue();
6127 
6128   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6129       !isa<ConstantSDNode>(Src.getOperand(1)))
6130     return SDValue();
6131 
6132   unsigned ShAmt1 = N->getConstantOperandVal(1);
6133   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6134   Src = Src.getOperand(0);
6135 
6136   unsigned CombinedShAmt;
6137   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6138     CombinedShAmt = ShAmt1 | ShAmt2;
6139   else
6140     CombinedShAmt = ShAmt1 ^ ShAmt2;
6141 
6142   if (CombinedShAmt == 0)
6143     return Src;
6144 
6145   SDLoc DL(N);
6146   return DAG.getNode(
6147       N->getOpcode(), DL, N->getValueType(0), Src,
6148       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6149 }
6150 
6151 // Combine a constant select operand into its use:
6152 //
6153 // (and (select cond, -1, c), x)
6154 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6155 // (or  (select cond, 0, c), x)
6156 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6157 // (xor (select cond, 0, c), x)
6158 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6159 // (add (select cond, 0, c), x)
6160 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6161 // (sub x, (select cond, 0, c))
6162 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6163 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6164                                    SelectionDAG &DAG, bool AllOnes) {
6165   EVT VT = N->getValueType(0);
6166 
6167   // Skip vectors.
6168   if (VT.isVector())
6169     return SDValue();
6170 
6171   if ((Slct.getOpcode() != ISD::SELECT &&
6172        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6173       !Slct.hasOneUse())
6174     return SDValue();
6175 
6176   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6177     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6178   };
6179 
6180   bool SwapSelectOps;
6181   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6182   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6183   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6184   SDValue NonConstantVal;
6185   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6186     SwapSelectOps = false;
6187     NonConstantVal = FalseVal;
6188   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6189     SwapSelectOps = true;
6190     NonConstantVal = TrueVal;
6191   } else
6192     return SDValue();
6193 
6194   // Slct is now know to be the desired identity constant when CC is true.
6195   TrueVal = OtherOp;
6196   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6197   // Unless SwapSelectOps says the condition should be false.
6198   if (SwapSelectOps)
6199     std::swap(TrueVal, FalseVal);
6200 
6201   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6202     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6203                        {Slct.getOperand(0), Slct.getOperand(1),
6204                         Slct.getOperand(2), TrueVal, FalseVal});
6205 
6206   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6207                      {Slct.getOperand(0), TrueVal, FalseVal});
6208 }
6209 
6210 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6211 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6212                                               bool AllOnes) {
6213   SDValue N0 = N->getOperand(0);
6214   SDValue N1 = N->getOperand(1);
6215   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6216     return Result;
6217   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6218     return Result;
6219   return SDValue();
6220 }
6221 
6222 // Transform (add (mul x, c0), c1) ->
6223 //           (add (mul (add x, c1/c0), c0), c1%c0).
6224 // if c1/c0 and c1%c0 are simm12, while c1 is not.
6225 // Or transform (add (mul x, c0), c1) ->
6226 //              (mul (add x, c1/c0), c0).
6227 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6228 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6229                                      const RISCVSubtarget &Subtarget) {
6230   // Skip for vector types and larger types.
6231   EVT VT = N->getValueType(0);
6232   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6233     return SDValue();
6234   // The first operand node must be a MUL and has no other use.
6235   SDValue N0 = N->getOperand(0);
6236   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6237     return SDValue();
6238   // Check if c0 and c1 match above conditions.
6239   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6240   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6241   if (!N0C || !N1C)
6242     return SDValue();
6243   int64_t C0 = N0C->getSExtValue();
6244   int64_t C1 = N1C->getSExtValue();
6245   if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) ||
6246       !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0))
6247     return SDValue();
6248   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6249   SDLoc DL(N);
6250   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6251                              DAG.getConstant(C1 / C0, DL, VT));
6252   SDValue New1 =
6253       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6254   if ((C1 % C0) == 0)
6255     return New1;
6256   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT));
6257 }
6258 
6259 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6260                                  const RISCVSubtarget &Subtarget) {
6261   // Transform (add (mul x, c0), c1) ->
6262   //           (add (mul (add x, c1/c0), c0), c1%c0).
6263   // if c1/c0 and c1%c0 are simm12, while c1 is not.
6264   // Or transform (add (mul x, c0), c1) ->
6265   //              (mul (add x, c1/c0), c0).
6266   // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6267   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6268     return V;
6269   // Fold (add (shl x, c0), (shl y, c1)) ->
6270   //      (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6271   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6272     return V;
6273   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6274   //      (select lhs, rhs, cc, x, (add x, y))
6275   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6276 }
6277 
6278 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6279   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6280   //      (select lhs, rhs, cc, x, (sub x, y))
6281   SDValue N0 = N->getOperand(0);
6282   SDValue N1 = N->getOperand(1);
6283   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6284 }
6285 
6286 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6287   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6288   //      (select lhs, rhs, cc, x, (and x, y))
6289   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6290 }
6291 
6292 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6293                                 const RISCVSubtarget &Subtarget) {
6294   if (Subtarget.hasStdExtZbp()) {
6295     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6296       return GREV;
6297     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6298       return GORC;
6299     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6300       return SHFL;
6301   }
6302 
6303   // fold (or (select cond, 0, y), x) ->
6304   //      (select cond, x, (or x, y))
6305   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6306 }
6307 
6308 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6309   // fold (xor (select cond, 0, y), x) ->
6310   //      (select cond, x, (xor x, y))
6311   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6312 }
6313 
6314 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6315 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6316 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6317 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6318 // ADDW/SUBW/MULW.
6319 static SDValue performANY_EXTENDCombine(SDNode *N,
6320                                         TargetLowering::DAGCombinerInfo &DCI,
6321                                         const RISCVSubtarget &Subtarget) {
6322   if (!Subtarget.is64Bit())
6323     return SDValue();
6324 
6325   SelectionDAG &DAG = DCI.DAG;
6326 
6327   SDValue Src = N->getOperand(0);
6328   EVT VT = N->getValueType(0);
6329   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6330     return SDValue();
6331 
6332   // The opcode must be one that can implicitly sign_extend.
6333   // FIXME: Additional opcodes.
6334   switch (Src.getOpcode()) {
6335   default:
6336     return SDValue();
6337   case ISD::MUL:
6338     if (!Subtarget.hasStdExtM())
6339       return SDValue();
6340     LLVM_FALLTHROUGH;
6341   case ISD::ADD:
6342   case ISD::SUB:
6343     break;
6344   }
6345 
6346   // Only handle cases where the result is used by a CopyToReg. That likely
6347   // means the value is a liveout of the basic block. This helps prevent
6348   // infinite combine loops like PR51206.
6349   if (none_of(N->uses(),
6350               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6351     return SDValue();
6352 
6353   SmallVector<SDNode *, 4> SetCCs;
6354   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6355                             UE = Src.getNode()->use_end();
6356        UI != UE; ++UI) {
6357     SDNode *User = *UI;
6358     if (User == N)
6359       continue;
6360     if (UI.getUse().getResNo() != Src.getResNo())
6361       continue;
6362     // All i32 setccs are legalized by sign extending operands.
6363     if (User->getOpcode() == ISD::SETCC) {
6364       SetCCs.push_back(User);
6365       continue;
6366     }
6367     // We don't know if we can extend this user.
6368     break;
6369   }
6370 
6371   // If we don't have any SetCCs, this isn't worthwhile.
6372   if (SetCCs.empty())
6373     return SDValue();
6374 
6375   SDLoc DL(N);
6376   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6377   DCI.CombineTo(N, SExt);
6378 
6379   // Promote all the setccs.
6380   for (SDNode *SetCC : SetCCs) {
6381     SmallVector<SDValue, 4> Ops;
6382 
6383     for (unsigned j = 0; j != 2; ++j) {
6384       SDValue SOp = SetCC->getOperand(j);
6385       if (SOp == Src)
6386         Ops.push_back(SExt);
6387       else
6388         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6389     }
6390 
6391     Ops.push_back(SetCC->getOperand(2));
6392     DCI.CombineTo(SetCC,
6393                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6394   }
6395   return SDValue(N, 0);
6396 }
6397 
6398 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6399                                                DAGCombinerInfo &DCI) const {
6400   SelectionDAG &DAG = DCI.DAG;
6401 
6402   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6403   // bits are demanded. N will be added to the Worklist if it was not deleted.
6404   // Caller should return SDValue(N, 0) if this returns true.
6405   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6406     SDValue Op = N->getOperand(OpNo);
6407     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6408     if (!SimplifyDemandedBits(Op, Mask, DCI))
6409       return false;
6410 
6411     if (N->getOpcode() != ISD::DELETED_NODE)
6412       DCI.AddToWorklist(N);
6413     return true;
6414   };
6415 
6416   switch (N->getOpcode()) {
6417   default:
6418     break;
6419   case RISCVISD::SplitF64: {
6420     SDValue Op0 = N->getOperand(0);
6421     // If the input to SplitF64 is just BuildPairF64 then the operation is
6422     // redundant. Instead, use BuildPairF64's operands directly.
6423     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6424       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6425 
6426     SDLoc DL(N);
6427 
6428     // It's cheaper to materialise two 32-bit integers than to load a double
6429     // from the constant pool and transfer it to integer registers through the
6430     // stack.
6431     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6432       APInt V = C->getValueAPF().bitcastToAPInt();
6433       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6434       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6435       return DCI.CombineTo(N, Lo, Hi);
6436     }
6437 
6438     // This is a target-specific version of a DAGCombine performed in
6439     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6440     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6441     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6442     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6443         !Op0.getNode()->hasOneUse())
6444       break;
6445     SDValue NewSplitF64 =
6446         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6447                     Op0.getOperand(0));
6448     SDValue Lo = NewSplitF64.getValue(0);
6449     SDValue Hi = NewSplitF64.getValue(1);
6450     APInt SignBit = APInt::getSignMask(32);
6451     if (Op0.getOpcode() == ISD::FNEG) {
6452       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6453                                   DAG.getConstant(SignBit, DL, MVT::i32));
6454       return DCI.CombineTo(N, Lo, NewHi);
6455     }
6456     assert(Op0.getOpcode() == ISD::FABS);
6457     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6458                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6459     return DCI.CombineTo(N, Lo, NewHi);
6460   }
6461   case RISCVISD::SLLW:
6462   case RISCVISD::SRAW:
6463   case RISCVISD::SRLW:
6464   case RISCVISD::ROLW:
6465   case RISCVISD::RORW: {
6466     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6467     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6468         SimplifyDemandedLowBitsHelper(1, 5))
6469       return SDValue(N, 0);
6470     break;
6471   }
6472   case RISCVISD::CLZW:
6473   case RISCVISD::CTZW: {
6474     // Only the lower 32 bits of the first operand are read
6475     if (SimplifyDemandedLowBitsHelper(0, 32))
6476       return SDValue(N, 0);
6477     break;
6478   }
6479   case RISCVISD::FSL:
6480   case RISCVISD::FSR: {
6481     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6482     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6483     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6484     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6485       return SDValue(N, 0);
6486     break;
6487   }
6488   case RISCVISD::FSLW:
6489   case RISCVISD::FSRW: {
6490     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6491     // read.
6492     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6493         SimplifyDemandedLowBitsHelper(1, 32) ||
6494         SimplifyDemandedLowBitsHelper(2, 6))
6495       return SDValue(N, 0);
6496     break;
6497   }
6498   case RISCVISD::GREV:
6499   case RISCVISD::GORC: {
6500     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6501     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6502     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6503     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6504       return SDValue(N, 0);
6505 
6506     return combineGREVI_GORCI(N, DCI.DAG);
6507   }
6508   case RISCVISD::GREVW:
6509   case RISCVISD::GORCW: {
6510     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6511     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6512         SimplifyDemandedLowBitsHelper(1, 5))
6513       return SDValue(N, 0);
6514 
6515     return combineGREVI_GORCI(N, DCI.DAG);
6516   }
6517   case RISCVISD::SHFL:
6518   case RISCVISD::UNSHFL: {
6519     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6520     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6521     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6522     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6523       return SDValue(N, 0);
6524 
6525     break;
6526   }
6527   case RISCVISD::SHFLW:
6528   case RISCVISD::UNSHFLW: {
6529     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6530     SDValue LHS = N->getOperand(0);
6531     SDValue RHS = N->getOperand(1);
6532     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6533     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6534     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6535         SimplifyDemandedLowBitsHelper(1, 4))
6536       return SDValue(N, 0);
6537 
6538     break;
6539   }
6540   case RISCVISD::BCOMPRESSW:
6541   case RISCVISD::BDECOMPRESSW: {
6542     // Only the lower 32 bits of LHS and RHS are read.
6543     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6544         SimplifyDemandedLowBitsHelper(1, 32))
6545       return SDValue(N, 0);
6546 
6547     break;
6548   }
6549   case RISCVISD::FMV_X_ANYEXTH:
6550   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6551     SDLoc DL(N);
6552     SDValue Op0 = N->getOperand(0);
6553     MVT VT = N->getSimpleValueType(0);
6554     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6555     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6556     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6557     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6558          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6559         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6560          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6561       assert(Op0.getOperand(0).getValueType() == VT &&
6562              "Unexpected value type!");
6563       return Op0.getOperand(0);
6564     }
6565 
6566     // This is a target-specific version of a DAGCombine performed in
6567     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6568     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6569     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6570     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6571         !Op0.getNode()->hasOneUse())
6572       break;
6573     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6574     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6575     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6576     if (Op0.getOpcode() == ISD::FNEG)
6577       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6578                          DAG.getConstant(SignBit, DL, VT));
6579 
6580     assert(Op0.getOpcode() == ISD::FABS);
6581     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6582                        DAG.getConstant(~SignBit, DL, VT));
6583   }
6584   case ISD::ADD:
6585     return performADDCombine(N, DAG, Subtarget);
6586   case ISD::SUB:
6587     return performSUBCombine(N, DAG);
6588   case ISD::AND:
6589     return performANDCombine(N, DAG);
6590   case ISD::OR:
6591     return performORCombine(N, DAG, Subtarget);
6592   case ISD::XOR:
6593     return performXORCombine(N, DAG);
6594   case ISD::ANY_EXTEND:
6595     return performANY_EXTENDCombine(N, DCI, Subtarget);
6596   case ISD::ZERO_EXTEND:
6597     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6598     // type legalization. This is safe because fp_to_uint produces poison if
6599     // it overflows.
6600     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6601         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6602         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6603       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6604                          N->getOperand(0).getOperand(0));
6605     return SDValue();
6606   case RISCVISD::SELECT_CC: {
6607     // Transform
6608     SDValue LHS = N->getOperand(0);
6609     SDValue RHS = N->getOperand(1);
6610     SDValue TrueV = N->getOperand(3);
6611     SDValue FalseV = N->getOperand(4);
6612 
6613     // If the True and False values are the same, we don't need a select_cc.
6614     if (TrueV == FalseV)
6615       return TrueV;
6616 
6617     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6618     if (!ISD::isIntEqualitySetCC(CCVal))
6619       break;
6620 
6621     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6622     //      (select_cc X, Y, lt, trueV, falseV)
6623     // Sometimes the setcc is introduced after select_cc has been formed.
6624     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6625         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6626       // If we're looking for eq 0 instead of ne 0, we need to invert the
6627       // condition.
6628       bool Invert = CCVal == ISD::SETEQ;
6629       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6630       if (Invert)
6631         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6632 
6633       SDLoc DL(N);
6634       RHS = LHS.getOperand(1);
6635       LHS = LHS.getOperand(0);
6636       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6637 
6638       SDValue TargetCC = DAG.getCondCode(CCVal);
6639       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6640                          {LHS, RHS, TargetCC, TrueV, FalseV});
6641     }
6642 
6643     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6644     //      (select_cc X, Y, eq/ne, trueV, falseV)
6645     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6646       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6647                          {LHS.getOperand(0), LHS.getOperand(1),
6648                           N->getOperand(2), TrueV, FalseV});
6649     // (select_cc X, 1, setne, trueV, falseV) ->
6650     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6651     // This can occur when legalizing some floating point comparisons.
6652     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6653     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6654       SDLoc DL(N);
6655       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6656       SDValue TargetCC = DAG.getCondCode(CCVal);
6657       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6658       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6659                          {LHS, RHS, TargetCC, TrueV, FalseV});
6660     }
6661 
6662     break;
6663   }
6664   case RISCVISD::BR_CC: {
6665     SDValue LHS = N->getOperand(1);
6666     SDValue RHS = N->getOperand(2);
6667     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6668     if (!ISD::isIntEqualitySetCC(CCVal))
6669       break;
6670 
6671     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6672     //      (br_cc X, Y, lt, dest)
6673     // Sometimes the setcc is introduced after br_cc has been formed.
6674     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6675         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6676       // If we're looking for eq 0 instead of ne 0, we need to invert the
6677       // condition.
6678       bool Invert = CCVal == ISD::SETEQ;
6679       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6680       if (Invert)
6681         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6682 
6683       SDLoc DL(N);
6684       RHS = LHS.getOperand(1);
6685       LHS = LHS.getOperand(0);
6686       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6687 
6688       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6689                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6690                          N->getOperand(4));
6691     }
6692 
6693     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6694     //      (br_cc X, Y, eq/ne, trueV, falseV)
6695     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6696       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6697                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6698                          N->getOperand(3), N->getOperand(4));
6699 
6700     // (br_cc X, 1, setne, br_cc) ->
6701     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6702     // This can occur when legalizing some floating point comparisons.
6703     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6704     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6705       SDLoc DL(N);
6706       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6707       SDValue TargetCC = DAG.getCondCode(CCVal);
6708       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6709       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6710                          N->getOperand(0), LHS, RHS, TargetCC,
6711                          N->getOperand(4));
6712     }
6713     break;
6714   }
6715   case ISD::FCOPYSIGN: {
6716     EVT VT = N->getValueType(0);
6717     if (!VT.isVector())
6718       break;
6719     // There is a form of VFSGNJ which injects the negated sign of its second
6720     // operand. Try and bubble any FNEG up after the extend/round to produce
6721     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6722     // TRUNC=1.
6723     SDValue In2 = N->getOperand(1);
6724     // Avoid cases where the extend/round has multiple uses, as duplicating
6725     // those is typically more expensive than removing a fneg.
6726     if (!In2.hasOneUse())
6727       break;
6728     if (In2.getOpcode() != ISD::FP_EXTEND &&
6729         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6730       break;
6731     In2 = In2.getOperand(0);
6732     if (In2.getOpcode() != ISD::FNEG)
6733       break;
6734     SDLoc DL(N);
6735     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6736     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6737                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6738   }
6739   case ISD::MGATHER:
6740   case ISD::MSCATTER:
6741   case ISD::VP_GATHER:
6742   case ISD::VP_SCATTER: {
6743     if (!DCI.isBeforeLegalize())
6744       break;
6745     SDValue Index, ScaleOp;
6746     bool IsIndexScaled = false;
6747     bool IsIndexSigned = false;
6748     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
6749       Index = VPGSN->getIndex();
6750       ScaleOp = VPGSN->getScale();
6751       IsIndexScaled = VPGSN->isIndexScaled();
6752       IsIndexSigned = VPGSN->isIndexSigned();
6753     } else {
6754       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
6755       Index = MGSN->getIndex();
6756       ScaleOp = MGSN->getScale();
6757       IsIndexScaled = MGSN->isIndexScaled();
6758       IsIndexSigned = MGSN->isIndexSigned();
6759     }
6760     EVT IndexVT = Index.getValueType();
6761     MVT XLenVT = Subtarget.getXLenVT();
6762     // RISCV indexed loads only support the "unsigned unscaled" addressing
6763     // mode, so anything else must be manually legalized.
6764     bool NeedsIdxLegalization =
6765         IsIndexScaled ||
6766         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
6767     if (!NeedsIdxLegalization)
6768       break;
6769 
6770     SDLoc DL(N);
6771 
6772     // Any index legalization should first promote to XLenVT, so we don't lose
6773     // bits when scaling. This may create an illegal index type so we let
6774     // LLVM's legalization take care of the splitting.
6775     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
6776     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6777       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6778       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6779                           DL, IndexVT, Index);
6780     }
6781 
6782     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
6783     if (IsIndexScaled && Scale != 1) {
6784       // Manually scale the indices by the element size.
6785       // TODO: Sanitize the scale operand here?
6786       // TODO: For VP nodes, should we use VP_SHL here?
6787       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6788       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6789       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6790     }
6791 
6792     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6793     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
6794       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
6795                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
6796                               VPGN->getScale(), VPGN->getMask(),
6797                               VPGN->getVectorLength()},
6798                              VPGN->getMemOperand(), NewIndexTy);
6799     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
6800       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
6801                               {VPSN->getChain(), VPSN->getValue(),
6802                                VPSN->getBasePtr(), Index, VPSN->getScale(),
6803                                VPSN->getMask(), VPSN->getVectorLength()},
6804                               VPSN->getMemOperand(), NewIndexTy);
6805     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
6806       return DAG.getMaskedGather(
6807           N->getVTList(), MGN->getMemoryVT(), DL,
6808           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
6809            MGN->getBasePtr(), Index, MGN->getScale()},
6810           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6811     const auto *MSN = cast<MaskedScatterSDNode>(N);
6812     return DAG.getMaskedScatter(
6813         N->getVTList(), MSN->getMemoryVT(), DL,
6814         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
6815          Index, MSN->getScale()},
6816         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6817   }
6818   case RISCVISD::SRA_VL:
6819   case RISCVISD::SRL_VL:
6820   case RISCVISD::SHL_VL: {
6821     SDValue ShAmt = N->getOperand(1);
6822     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6823       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6824       SDLoc DL(N);
6825       SDValue VL = N->getOperand(3);
6826       EVT VT = N->getValueType(0);
6827       ShAmt =
6828           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
6829       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
6830                          N->getOperand(2), N->getOperand(3));
6831     }
6832     break;
6833   }
6834   case ISD::SRA:
6835   case ISD::SRL:
6836   case ISD::SHL: {
6837     SDValue ShAmt = N->getOperand(1);
6838     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6839       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6840       SDLoc DL(N);
6841       EVT VT = N->getValueType(0);
6842       ShAmt =
6843           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
6844       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
6845     }
6846     break;
6847   }
6848   case RISCVISD::MUL_VL: {
6849     // Try to form VWMUL or VWMULU.
6850     // FIXME: Look for splat of extended scalar as well.
6851     // FIXME: Support VWMULSU.
6852     SDValue Op0 = N->getOperand(0);
6853     SDValue Op1 = N->getOperand(1);
6854     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6855     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6856     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
6857       return SDValue();
6858 
6859     // Make sure the extends have a single use.
6860     if (!Op0.hasOneUse() || !Op1.hasOneUse())
6861       return SDValue();
6862 
6863     SDValue Mask = N->getOperand(2);
6864     SDValue VL = N->getOperand(3);
6865     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
6866         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
6867       return SDValue();
6868 
6869     Op0 = Op0.getOperand(0);
6870     Op1 = Op1.getOperand(0);
6871 
6872     MVT VT = N->getSimpleValueType(0);
6873     MVT NarrowVT =
6874         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
6875                          VT.getVectorElementCount());
6876 
6877     SDLoc DL(N);
6878 
6879     // Re-introduce narrower extends if needed.
6880     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6881     if (Op0.getValueType() != NarrowVT)
6882       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6883     if (Op1.getValueType() != NarrowVT)
6884       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6885 
6886     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6887     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6888   }
6889   }
6890 
6891   return SDValue();
6892 }
6893 
6894 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
6895     const SDNode *N, CombineLevel Level) const {
6896   // The following folds are only desirable if `(OP _, c1 << c2)` can be
6897   // materialised in fewer instructions than `(OP _, c1)`:
6898   //
6899   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6900   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6901   SDValue N0 = N->getOperand(0);
6902   EVT Ty = N0.getValueType();
6903   if (Ty.isScalarInteger() &&
6904       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
6905     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6906     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
6907     if (C1 && C2) {
6908       const APInt &C1Int = C1->getAPIntValue();
6909       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
6910 
6911       // We can materialise `c1 << c2` into an add immediate, so it's "free",
6912       // and the combine should happen, to potentially allow further combines
6913       // later.
6914       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
6915           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
6916         return true;
6917 
6918       // We can materialise `c1` in an add immediate, so it's "free", and the
6919       // combine should be prevented.
6920       if (C1Int.getMinSignedBits() <= 64 &&
6921           isLegalAddImmediate(C1Int.getSExtValue()))
6922         return false;
6923 
6924       // Neither constant will fit into an immediate, so find materialisation
6925       // costs.
6926       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
6927                                               Subtarget.getFeatureBits(),
6928                                               /*CompressionCost*/true);
6929       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
6930           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
6931           /*CompressionCost*/true);
6932 
6933       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
6934       // combine should be prevented.
6935       if (C1Cost < ShiftedC1Cost)
6936         return false;
6937     }
6938   }
6939   return true;
6940 }
6941 
6942 bool RISCVTargetLowering::targetShrinkDemandedConstant(
6943     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
6944     TargetLoweringOpt &TLO) const {
6945   // Delay this optimization as late as possible.
6946   if (!TLO.LegalOps)
6947     return false;
6948 
6949   EVT VT = Op.getValueType();
6950   if (VT.isVector())
6951     return false;
6952 
6953   // Only handle AND for now.
6954   if (Op.getOpcode() != ISD::AND)
6955     return false;
6956 
6957   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6958   if (!C)
6959     return false;
6960 
6961   const APInt &Mask = C->getAPIntValue();
6962 
6963   // Clear all non-demanded bits initially.
6964   APInt ShrunkMask = Mask & DemandedBits;
6965 
6966   // Try to make a smaller immediate by setting undemanded bits.
6967 
6968   APInt ExpandedMask = Mask | ~DemandedBits;
6969 
6970   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
6971     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
6972   };
6973   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
6974     if (NewMask == Mask)
6975       return true;
6976     SDLoc DL(Op);
6977     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
6978     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
6979     return TLO.CombineTo(Op, NewOp);
6980   };
6981 
6982   // If the shrunk mask fits in sign extended 12 bits, let the target
6983   // independent code apply it.
6984   if (ShrunkMask.isSignedIntN(12))
6985     return false;
6986 
6987   // Preserve (and X, 0xffff) when zext.h is supported.
6988   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
6989     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
6990     if (IsLegalMask(NewMask))
6991       return UseMask(NewMask);
6992   }
6993 
6994   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
6995   if (VT == MVT::i64) {
6996     APInt NewMask = APInt(64, 0xffffffff);
6997     if (IsLegalMask(NewMask))
6998       return UseMask(NewMask);
6999   }
7000 
7001   // For the remaining optimizations, we need to be able to make a negative
7002   // number through a combination of mask and undemanded bits.
7003   if (!ExpandedMask.isNegative())
7004     return false;
7005 
7006   // What is the fewest number of bits we need to represent the negative number.
7007   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7008 
7009   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7010   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7011   APInt NewMask = ShrunkMask;
7012   if (MinSignedBits <= 12)
7013     NewMask.setBitsFrom(11);
7014   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7015     NewMask.setBitsFrom(31);
7016   else
7017     return false;
7018 
7019   // Sanity check that our new mask is a subset of the demanded mask.
7020   assert(IsLegalMask(NewMask));
7021   return UseMask(NewMask);
7022 }
7023 
7024 static void computeGREV(APInt &Src, unsigned ShAmt) {
7025   ShAmt &= Src.getBitWidth() - 1;
7026   uint64_t x = Src.getZExtValue();
7027   if (ShAmt & 1)
7028     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7029   if (ShAmt & 2)
7030     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7031   if (ShAmt & 4)
7032     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7033   if (ShAmt & 8)
7034     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7035   if (ShAmt & 16)
7036     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7037   if (ShAmt & 32)
7038     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7039   Src = x;
7040 }
7041 
7042 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7043                                                         KnownBits &Known,
7044                                                         const APInt &DemandedElts,
7045                                                         const SelectionDAG &DAG,
7046                                                         unsigned Depth) const {
7047   unsigned BitWidth = Known.getBitWidth();
7048   unsigned Opc = Op.getOpcode();
7049   assert((Opc >= ISD::BUILTIN_OP_END ||
7050           Opc == ISD::INTRINSIC_WO_CHAIN ||
7051           Opc == ISD::INTRINSIC_W_CHAIN ||
7052           Opc == ISD::INTRINSIC_VOID) &&
7053          "Should use MaskedValueIsZero if you don't know whether Op"
7054          " is a target node!");
7055 
7056   Known.resetAll();
7057   switch (Opc) {
7058   default: break;
7059   case RISCVISD::SELECT_CC: {
7060     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7061     // If we don't know any bits, early out.
7062     if (Known.isUnknown())
7063       break;
7064     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7065 
7066     // Only known if known in both the LHS and RHS.
7067     Known = KnownBits::commonBits(Known, Known2);
7068     break;
7069   }
7070   case RISCVISD::REMUW: {
7071     KnownBits Known2;
7072     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7073     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7074     // We only care about the lower 32 bits.
7075     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7076     // Restore the original width by sign extending.
7077     Known = Known.sext(BitWidth);
7078     break;
7079   }
7080   case RISCVISD::DIVUW: {
7081     KnownBits Known2;
7082     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7083     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7084     // We only care about the lower 32 bits.
7085     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7086     // Restore the original width by sign extending.
7087     Known = Known.sext(BitWidth);
7088     break;
7089   }
7090   case RISCVISD::CTZW: {
7091     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7092     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7093     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7094     Known.Zero.setBitsFrom(LowBits);
7095     break;
7096   }
7097   case RISCVISD::CLZW: {
7098     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7099     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7100     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7101     Known.Zero.setBitsFrom(LowBits);
7102     break;
7103   }
7104   case RISCVISD::GREV:
7105   case RISCVISD::GREVW: {
7106     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7107       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7108       if (Opc == RISCVISD::GREVW)
7109         Known = Known.trunc(32);
7110       unsigned ShAmt = C->getZExtValue();
7111       computeGREV(Known.Zero, ShAmt);
7112       computeGREV(Known.One, ShAmt);
7113       if (Opc == RISCVISD::GREVW)
7114         Known = Known.sext(BitWidth);
7115     }
7116     break;
7117   }
7118   case RISCVISD::READ_VLENB:
7119     // We assume VLENB is at least 16 bytes.
7120     Known.Zero.setLowBits(4);
7121     // We assume VLENB is no more than 65536 / 8 bytes.
7122     Known.Zero.setBitsFrom(14);
7123     break;
7124   case ISD::INTRINSIC_W_CHAIN: {
7125     unsigned IntNo = Op.getConstantOperandVal(1);
7126     switch (IntNo) {
7127     default:
7128       // We can't do anything for most intrinsics.
7129       break;
7130     case Intrinsic::riscv_vsetvli:
7131     case Intrinsic::riscv_vsetvlimax:
7132       // Assume that VL output is positive and would fit in an int32_t.
7133       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7134       if (BitWidth >= 32)
7135         Known.Zero.setBitsFrom(31);
7136       break;
7137     }
7138     break;
7139   }
7140   }
7141 }
7142 
7143 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7144     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7145     unsigned Depth) const {
7146   switch (Op.getOpcode()) {
7147   default:
7148     break;
7149   case RISCVISD::SELECT_CC: {
7150     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7151     if (Tmp == 1) return 1;  // Early out.
7152     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7153     return std::min(Tmp, Tmp2);
7154   }
7155   case RISCVISD::SLLW:
7156   case RISCVISD::SRAW:
7157   case RISCVISD::SRLW:
7158   case RISCVISD::DIVW:
7159   case RISCVISD::DIVUW:
7160   case RISCVISD::REMUW:
7161   case RISCVISD::ROLW:
7162   case RISCVISD::RORW:
7163   case RISCVISD::GREVW:
7164   case RISCVISD::GORCW:
7165   case RISCVISD::FSLW:
7166   case RISCVISD::FSRW:
7167   case RISCVISD::SHFLW:
7168   case RISCVISD::UNSHFLW:
7169   case RISCVISD::BCOMPRESSW:
7170   case RISCVISD::BDECOMPRESSW:
7171   case RISCVISD::FCVT_W_RTZ_RV64:
7172   case RISCVISD::FCVT_WU_RTZ_RV64:
7173     // TODO: As the result is sign-extended, this is conservatively correct. A
7174     // more precise answer could be calculated for SRAW depending on known
7175     // bits in the shift amount.
7176     return 33;
7177   case RISCVISD::SHFL:
7178   case RISCVISD::UNSHFL: {
7179     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7180     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7181     // will stay within the upper 32 bits. If there were more than 32 sign bits
7182     // before there will be at least 33 sign bits after.
7183     if (Op.getValueType() == MVT::i64 &&
7184         isa<ConstantSDNode>(Op.getOperand(1)) &&
7185         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7186       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7187       if (Tmp > 32)
7188         return 33;
7189     }
7190     break;
7191   }
7192   case RISCVISD::VMV_X_S:
7193     // The number of sign bits of the scalar result is computed by obtaining the
7194     // element type of the input vector operand, subtracting its width from the
7195     // XLEN, and then adding one (sign bit within the element type). If the
7196     // element type is wider than XLen, the least-significant XLEN bits are
7197     // taken.
7198     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7199       return 1;
7200     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7201   }
7202 
7203   return 1;
7204 }
7205 
7206 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7207                                                   MachineBasicBlock *BB) {
7208   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7209 
7210   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7211   // Should the count have wrapped while it was being read, we need to try
7212   // again.
7213   // ...
7214   // read:
7215   // rdcycleh x3 # load high word of cycle
7216   // rdcycle  x2 # load low word of cycle
7217   // rdcycleh x4 # load high word of cycle
7218   // bne x3, x4, read # check if high word reads match, otherwise try again
7219   // ...
7220 
7221   MachineFunction &MF = *BB->getParent();
7222   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7223   MachineFunction::iterator It = ++BB->getIterator();
7224 
7225   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7226   MF.insert(It, LoopMBB);
7227 
7228   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7229   MF.insert(It, DoneMBB);
7230 
7231   // Transfer the remainder of BB and its successor edges to DoneMBB.
7232   DoneMBB->splice(DoneMBB->begin(), BB,
7233                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7234   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7235 
7236   BB->addSuccessor(LoopMBB);
7237 
7238   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7239   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7240   Register LoReg = MI.getOperand(0).getReg();
7241   Register HiReg = MI.getOperand(1).getReg();
7242   DebugLoc DL = MI.getDebugLoc();
7243 
7244   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7245   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7246       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7247       .addReg(RISCV::X0);
7248   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7249       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7250       .addReg(RISCV::X0);
7251   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7252       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7253       .addReg(RISCV::X0);
7254 
7255   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7256       .addReg(HiReg)
7257       .addReg(ReadAgainReg)
7258       .addMBB(LoopMBB);
7259 
7260   LoopMBB->addSuccessor(LoopMBB);
7261   LoopMBB->addSuccessor(DoneMBB);
7262 
7263   MI.eraseFromParent();
7264 
7265   return DoneMBB;
7266 }
7267 
7268 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7269                                              MachineBasicBlock *BB) {
7270   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7271 
7272   MachineFunction &MF = *BB->getParent();
7273   DebugLoc DL = MI.getDebugLoc();
7274   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7275   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7276   Register LoReg = MI.getOperand(0).getReg();
7277   Register HiReg = MI.getOperand(1).getReg();
7278   Register SrcReg = MI.getOperand(2).getReg();
7279   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7280   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7281 
7282   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7283                           RI);
7284   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7285   MachineMemOperand *MMOLo =
7286       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7287   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7288       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7289   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7290       .addFrameIndex(FI)
7291       .addImm(0)
7292       .addMemOperand(MMOLo);
7293   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7294       .addFrameIndex(FI)
7295       .addImm(4)
7296       .addMemOperand(MMOHi);
7297   MI.eraseFromParent(); // The pseudo instruction is gone now.
7298   return BB;
7299 }
7300 
7301 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7302                                                  MachineBasicBlock *BB) {
7303   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7304          "Unexpected instruction");
7305 
7306   MachineFunction &MF = *BB->getParent();
7307   DebugLoc DL = MI.getDebugLoc();
7308   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7309   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7310   Register DstReg = MI.getOperand(0).getReg();
7311   Register LoReg = MI.getOperand(1).getReg();
7312   Register HiReg = MI.getOperand(2).getReg();
7313   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7314   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7315 
7316   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7317   MachineMemOperand *MMOLo =
7318       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7319   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7320       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7321   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7322       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7323       .addFrameIndex(FI)
7324       .addImm(0)
7325       .addMemOperand(MMOLo);
7326   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7327       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7328       .addFrameIndex(FI)
7329       .addImm(4)
7330       .addMemOperand(MMOHi);
7331   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7332   MI.eraseFromParent(); // The pseudo instruction is gone now.
7333   return BB;
7334 }
7335 
7336 static bool isSelectPseudo(MachineInstr &MI) {
7337   switch (MI.getOpcode()) {
7338   default:
7339     return false;
7340   case RISCV::Select_GPR_Using_CC_GPR:
7341   case RISCV::Select_FPR16_Using_CC_GPR:
7342   case RISCV::Select_FPR32_Using_CC_GPR:
7343   case RISCV::Select_FPR64_Using_CC_GPR:
7344     return true;
7345   }
7346 }
7347 
7348 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7349                                            MachineBasicBlock *BB,
7350                                            const RISCVSubtarget &Subtarget) {
7351   // To "insert" Select_* instructions, we actually have to insert the triangle
7352   // control-flow pattern.  The incoming instructions know the destination vreg
7353   // to set, the condition code register to branch on, the true/false values to
7354   // select between, and the condcode to use to select the appropriate branch.
7355   //
7356   // We produce the following control flow:
7357   //     HeadMBB
7358   //     |  \
7359   //     |  IfFalseMBB
7360   //     | /
7361   //    TailMBB
7362   //
7363   // When we find a sequence of selects we attempt to optimize their emission
7364   // by sharing the control flow. Currently we only handle cases where we have
7365   // multiple selects with the exact same condition (same LHS, RHS and CC).
7366   // The selects may be interleaved with other instructions if the other
7367   // instructions meet some requirements we deem safe:
7368   // - They are debug instructions. Otherwise,
7369   // - They do not have side-effects, do not access memory and their inputs do
7370   //   not depend on the results of the select pseudo-instructions.
7371   // The TrueV/FalseV operands of the selects cannot depend on the result of
7372   // previous selects in the sequence.
7373   // These conditions could be further relaxed. See the X86 target for a
7374   // related approach and more information.
7375   Register LHS = MI.getOperand(1).getReg();
7376   Register RHS = MI.getOperand(2).getReg();
7377   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7378 
7379   SmallVector<MachineInstr *, 4> SelectDebugValues;
7380   SmallSet<Register, 4> SelectDests;
7381   SelectDests.insert(MI.getOperand(0).getReg());
7382 
7383   MachineInstr *LastSelectPseudo = &MI;
7384 
7385   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7386        SequenceMBBI != E; ++SequenceMBBI) {
7387     if (SequenceMBBI->isDebugInstr())
7388       continue;
7389     else if (isSelectPseudo(*SequenceMBBI)) {
7390       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7391           SequenceMBBI->getOperand(2).getReg() != RHS ||
7392           SequenceMBBI->getOperand(3).getImm() != CC ||
7393           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7394           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7395         break;
7396       LastSelectPseudo = &*SequenceMBBI;
7397       SequenceMBBI->collectDebugValues(SelectDebugValues);
7398       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7399     } else {
7400       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7401           SequenceMBBI->mayLoadOrStore())
7402         break;
7403       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7404             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7405           }))
7406         break;
7407     }
7408   }
7409 
7410   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7411   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7412   DebugLoc DL = MI.getDebugLoc();
7413   MachineFunction::iterator I = ++BB->getIterator();
7414 
7415   MachineBasicBlock *HeadMBB = BB;
7416   MachineFunction *F = BB->getParent();
7417   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7418   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7419 
7420   F->insert(I, IfFalseMBB);
7421   F->insert(I, TailMBB);
7422 
7423   // Transfer debug instructions associated with the selects to TailMBB.
7424   for (MachineInstr *DebugInstr : SelectDebugValues) {
7425     TailMBB->push_back(DebugInstr->removeFromParent());
7426   }
7427 
7428   // Move all instructions after the sequence to TailMBB.
7429   TailMBB->splice(TailMBB->end(), HeadMBB,
7430                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7431   // Update machine-CFG edges by transferring all successors of the current
7432   // block to the new block which will contain the Phi nodes for the selects.
7433   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7434   // Set the successors for HeadMBB.
7435   HeadMBB->addSuccessor(IfFalseMBB);
7436   HeadMBB->addSuccessor(TailMBB);
7437 
7438   // Insert appropriate branch.
7439   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7440     .addReg(LHS)
7441     .addReg(RHS)
7442     .addMBB(TailMBB);
7443 
7444   // IfFalseMBB just falls through to TailMBB.
7445   IfFalseMBB->addSuccessor(TailMBB);
7446 
7447   // Create PHIs for all of the select pseudo-instructions.
7448   auto SelectMBBI = MI.getIterator();
7449   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7450   auto InsertionPoint = TailMBB->begin();
7451   while (SelectMBBI != SelectEnd) {
7452     auto Next = std::next(SelectMBBI);
7453     if (isSelectPseudo(*SelectMBBI)) {
7454       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7455       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7456               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7457           .addReg(SelectMBBI->getOperand(4).getReg())
7458           .addMBB(HeadMBB)
7459           .addReg(SelectMBBI->getOperand(5).getReg())
7460           .addMBB(IfFalseMBB);
7461       SelectMBBI->eraseFromParent();
7462     }
7463     SelectMBBI = Next;
7464   }
7465 
7466   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7467   return TailMBB;
7468 }
7469 
7470 MachineBasicBlock *
7471 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7472                                                  MachineBasicBlock *BB) const {
7473   switch (MI.getOpcode()) {
7474   default:
7475     llvm_unreachable("Unexpected instr type to insert");
7476   case RISCV::ReadCycleWide:
7477     assert(!Subtarget.is64Bit() &&
7478            "ReadCycleWrite is only to be used on riscv32");
7479     return emitReadCycleWidePseudo(MI, BB);
7480   case RISCV::Select_GPR_Using_CC_GPR:
7481   case RISCV::Select_FPR16_Using_CC_GPR:
7482   case RISCV::Select_FPR32_Using_CC_GPR:
7483   case RISCV::Select_FPR64_Using_CC_GPR:
7484     return emitSelectPseudo(MI, BB, Subtarget);
7485   case RISCV::BuildPairF64Pseudo:
7486     return emitBuildPairF64Pseudo(MI, BB);
7487   case RISCV::SplitF64Pseudo:
7488     return emitSplitF64Pseudo(MI, BB);
7489   }
7490 }
7491 
7492 // Calling Convention Implementation.
7493 // The expectations for frontend ABI lowering vary from target to target.
7494 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7495 // details, but this is a longer term goal. For now, we simply try to keep the
7496 // role of the frontend as simple and well-defined as possible. The rules can
7497 // be summarised as:
7498 // * Never split up large scalar arguments. We handle them here.
7499 // * If a hardfloat calling convention is being used, and the struct may be
7500 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7501 // available, then pass as two separate arguments. If either the GPRs or FPRs
7502 // are exhausted, then pass according to the rule below.
7503 // * If a struct could never be passed in registers or directly in a stack
7504 // slot (as it is larger than 2*XLEN and the floating point rules don't
7505 // apply), then pass it using a pointer with the byval attribute.
7506 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7507 // word-sized array or a 2*XLEN scalar (depending on alignment).
7508 // * The frontend can determine whether a struct is returned by reference or
7509 // not based on its size and fields. If it will be returned by reference, the
7510 // frontend must modify the prototype so a pointer with the sret annotation is
7511 // passed as the first argument. This is not necessary for large scalar
7512 // returns.
7513 // * Struct return values and varargs should be coerced to structs containing
7514 // register-size fields in the same situations they would be for fixed
7515 // arguments.
7516 
7517 static const MCPhysReg ArgGPRs[] = {
7518   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7519   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7520 };
7521 static const MCPhysReg ArgFPR16s[] = {
7522   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7523   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7524 };
7525 static const MCPhysReg ArgFPR32s[] = {
7526   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7527   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7528 };
7529 static const MCPhysReg ArgFPR64s[] = {
7530   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7531   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7532 };
7533 // This is an interim calling convention and it may be changed in the future.
7534 static const MCPhysReg ArgVRs[] = {
7535     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7536     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7537     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7538 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7539                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7540                                      RISCV::V20M2, RISCV::V22M2};
7541 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7542                                      RISCV::V20M4};
7543 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7544 
7545 // Pass a 2*XLEN argument that has been split into two XLEN values through
7546 // registers or the stack as necessary.
7547 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7548                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7549                                 MVT ValVT2, MVT LocVT2,
7550                                 ISD::ArgFlagsTy ArgFlags2) {
7551   unsigned XLenInBytes = XLen / 8;
7552   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7553     // At least one half can be passed via register.
7554     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7555                                      VA1.getLocVT(), CCValAssign::Full));
7556   } else {
7557     // Both halves must be passed on the stack, with proper alignment.
7558     Align StackAlign =
7559         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7560     State.addLoc(
7561         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7562                             State.AllocateStack(XLenInBytes, StackAlign),
7563                             VA1.getLocVT(), CCValAssign::Full));
7564     State.addLoc(CCValAssign::getMem(
7565         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7566         LocVT2, CCValAssign::Full));
7567     return false;
7568   }
7569 
7570   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7571     // The second half can also be passed via register.
7572     State.addLoc(
7573         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7574   } else {
7575     // The second half is passed via the stack, without additional alignment.
7576     State.addLoc(CCValAssign::getMem(
7577         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7578         LocVT2, CCValAssign::Full));
7579   }
7580 
7581   return false;
7582 }
7583 
7584 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7585                                Optional<unsigned> FirstMaskArgument,
7586                                CCState &State, const RISCVTargetLowering &TLI) {
7587   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7588   if (RC == &RISCV::VRRegClass) {
7589     // Assign the first mask argument to V0.
7590     // This is an interim calling convention and it may be changed in the
7591     // future.
7592     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7593       return State.AllocateReg(RISCV::V0);
7594     return State.AllocateReg(ArgVRs);
7595   }
7596   if (RC == &RISCV::VRM2RegClass)
7597     return State.AllocateReg(ArgVRM2s);
7598   if (RC == &RISCV::VRM4RegClass)
7599     return State.AllocateReg(ArgVRM4s);
7600   if (RC == &RISCV::VRM8RegClass)
7601     return State.AllocateReg(ArgVRM8s);
7602   llvm_unreachable("Unhandled register class for ValueType");
7603 }
7604 
7605 // Implements the RISC-V calling convention. Returns true upon failure.
7606 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7607                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7608                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7609                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7610                      Optional<unsigned> FirstMaskArgument) {
7611   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7612   assert(XLen == 32 || XLen == 64);
7613   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7614 
7615   // Any return value split in to more than two values can't be returned
7616   // directly. Vectors are returned via the available vector registers.
7617   if (!LocVT.isVector() && IsRet && ValNo > 1)
7618     return true;
7619 
7620   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7621   // variadic argument, or if no F16/F32 argument registers are available.
7622   bool UseGPRForF16_F32 = true;
7623   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7624   // variadic argument, or if no F64 argument registers are available.
7625   bool UseGPRForF64 = true;
7626 
7627   switch (ABI) {
7628   default:
7629     llvm_unreachable("Unexpected ABI");
7630   case RISCVABI::ABI_ILP32:
7631   case RISCVABI::ABI_LP64:
7632     break;
7633   case RISCVABI::ABI_ILP32F:
7634   case RISCVABI::ABI_LP64F:
7635     UseGPRForF16_F32 = !IsFixed;
7636     break;
7637   case RISCVABI::ABI_ILP32D:
7638   case RISCVABI::ABI_LP64D:
7639     UseGPRForF16_F32 = !IsFixed;
7640     UseGPRForF64 = !IsFixed;
7641     break;
7642   }
7643 
7644   // FPR16, FPR32, and FPR64 alias each other.
7645   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7646     UseGPRForF16_F32 = true;
7647     UseGPRForF64 = true;
7648   }
7649 
7650   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7651   // similar local variables rather than directly checking against the target
7652   // ABI.
7653 
7654   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7655     LocVT = XLenVT;
7656     LocInfo = CCValAssign::BCvt;
7657   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7658     LocVT = MVT::i64;
7659     LocInfo = CCValAssign::BCvt;
7660   }
7661 
7662   // If this is a variadic argument, the RISC-V calling convention requires
7663   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7664   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7665   // be used regardless of whether the original argument was split during
7666   // legalisation or not. The argument will not be passed by registers if the
7667   // original type is larger than 2*XLEN, so the register alignment rule does
7668   // not apply.
7669   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7670   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7671       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7672     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7673     // Skip 'odd' register if necessary.
7674     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7675       State.AllocateReg(ArgGPRs);
7676   }
7677 
7678   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7679   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7680       State.getPendingArgFlags();
7681 
7682   assert(PendingLocs.size() == PendingArgFlags.size() &&
7683          "PendingLocs and PendingArgFlags out of sync");
7684 
7685   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7686   // registers are exhausted.
7687   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7688     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7689            "Can't lower f64 if it is split");
7690     // Depending on available argument GPRS, f64 may be passed in a pair of
7691     // GPRs, split between a GPR and the stack, or passed completely on the
7692     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7693     // cases.
7694     Register Reg = State.AllocateReg(ArgGPRs);
7695     LocVT = MVT::i32;
7696     if (!Reg) {
7697       unsigned StackOffset = State.AllocateStack(8, Align(8));
7698       State.addLoc(
7699           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7700       return false;
7701     }
7702     if (!State.AllocateReg(ArgGPRs))
7703       State.AllocateStack(4, Align(4));
7704     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7705     return false;
7706   }
7707 
7708   // Fixed-length vectors are located in the corresponding scalable-vector
7709   // container types.
7710   if (ValVT.isFixedLengthVector())
7711     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7712 
7713   // Split arguments might be passed indirectly, so keep track of the pending
7714   // values. Split vectors are passed via a mix of registers and indirectly, so
7715   // treat them as we would any other argument.
7716   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7717     LocVT = XLenVT;
7718     LocInfo = CCValAssign::Indirect;
7719     PendingLocs.push_back(
7720         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7721     PendingArgFlags.push_back(ArgFlags);
7722     if (!ArgFlags.isSplitEnd()) {
7723       return false;
7724     }
7725   }
7726 
7727   // If the split argument only had two elements, it should be passed directly
7728   // in registers or on the stack.
7729   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7730       PendingLocs.size() <= 2) {
7731     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7732     // Apply the normal calling convention rules to the first half of the
7733     // split argument.
7734     CCValAssign VA = PendingLocs[0];
7735     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7736     PendingLocs.clear();
7737     PendingArgFlags.clear();
7738     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7739                                ArgFlags);
7740   }
7741 
7742   // Allocate to a register if possible, or else a stack slot.
7743   Register Reg;
7744   unsigned StoreSizeBytes = XLen / 8;
7745   Align StackAlign = Align(XLen / 8);
7746 
7747   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7748     Reg = State.AllocateReg(ArgFPR16s);
7749   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7750     Reg = State.AllocateReg(ArgFPR32s);
7751   else if (ValVT == MVT::f64 && !UseGPRForF64)
7752     Reg = State.AllocateReg(ArgFPR64s);
7753   else if (ValVT.isVector()) {
7754     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7755     if (!Reg) {
7756       // For return values, the vector must be passed fully via registers or
7757       // via the stack.
7758       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7759       // but we're using all of them.
7760       if (IsRet)
7761         return true;
7762       // Try using a GPR to pass the address
7763       if ((Reg = State.AllocateReg(ArgGPRs))) {
7764         LocVT = XLenVT;
7765         LocInfo = CCValAssign::Indirect;
7766       } else if (ValVT.isScalableVector()) {
7767         report_fatal_error("Unable to pass scalable vector types on the stack");
7768       } else {
7769         // Pass fixed-length vectors on the stack.
7770         LocVT = ValVT;
7771         StoreSizeBytes = ValVT.getStoreSize();
7772         // Align vectors to their element sizes, being careful for vXi1
7773         // vectors.
7774         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7775       }
7776     }
7777   } else {
7778     Reg = State.AllocateReg(ArgGPRs);
7779   }
7780 
7781   unsigned StackOffset =
7782       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7783 
7784   // If we reach this point and PendingLocs is non-empty, we must be at the
7785   // end of a split argument that must be passed indirectly.
7786   if (!PendingLocs.empty()) {
7787     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7788     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7789 
7790     for (auto &It : PendingLocs) {
7791       if (Reg)
7792         It.convertToReg(Reg);
7793       else
7794         It.convertToMem(StackOffset);
7795       State.addLoc(It);
7796     }
7797     PendingLocs.clear();
7798     PendingArgFlags.clear();
7799     return false;
7800   }
7801 
7802   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7803           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7804          "Expected an XLenVT or vector types at this stage");
7805 
7806   if (Reg) {
7807     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7808     return false;
7809   }
7810 
7811   // When a floating-point value is passed on the stack, no bit-conversion is
7812   // needed.
7813   if (ValVT.isFloatingPoint()) {
7814     LocVT = ValVT;
7815     LocInfo = CCValAssign::Full;
7816   }
7817   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7818   return false;
7819 }
7820 
7821 template <typename ArgTy>
7822 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
7823   for (const auto &ArgIdx : enumerate(Args)) {
7824     MVT ArgVT = ArgIdx.value().VT;
7825     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
7826       return ArgIdx.index();
7827   }
7828   return None;
7829 }
7830 
7831 void RISCVTargetLowering::analyzeInputArgs(
7832     MachineFunction &MF, CCState &CCInfo,
7833     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
7834     RISCVCCAssignFn Fn) const {
7835   unsigned NumArgs = Ins.size();
7836   FunctionType *FType = MF.getFunction().getFunctionType();
7837 
7838   Optional<unsigned> FirstMaskArgument;
7839   if (Subtarget.hasStdExtV())
7840     FirstMaskArgument = preAssignMask(Ins);
7841 
7842   for (unsigned i = 0; i != NumArgs; ++i) {
7843     MVT ArgVT = Ins[i].VT;
7844     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
7845 
7846     Type *ArgTy = nullptr;
7847     if (IsRet)
7848       ArgTy = FType->getReturnType();
7849     else if (Ins[i].isOrigArg())
7850       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
7851 
7852     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7853     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7854            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
7855            FirstMaskArgument)) {
7856       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
7857                         << EVT(ArgVT).getEVTString() << '\n');
7858       llvm_unreachable(nullptr);
7859     }
7860   }
7861 }
7862 
7863 void RISCVTargetLowering::analyzeOutputArgs(
7864     MachineFunction &MF, CCState &CCInfo,
7865     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
7866     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
7867   unsigned NumArgs = Outs.size();
7868 
7869   Optional<unsigned> FirstMaskArgument;
7870   if (Subtarget.hasStdExtV())
7871     FirstMaskArgument = preAssignMask(Outs);
7872 
7873   for (unsigned i = 0; i != NumArgs; i++) {
7874     MVT ArgVT = Outs[i].VT;
7875     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7876     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
7877 
7878     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7879     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7880            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
7881            FirstMaskArgument)) {
7882       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
7883                         << EVT(ArgVT).getEVTString() << "\n");
7884       llvm_unreachable(nullptr);
7885     }
7886   }
7887 }
7888 
7889 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
7890 // values.
7891 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
7892                                    const CCValAssign &VA, const SDLoc &DL,
7893                                    const RISCVSubtarget &Subtarget) {
7894   switch (VA.getLocInfo()) {
7895   default:
7896     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7897   case CCValAssign::Full:
7898     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
7899       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
7900     break;
7901   case CCValAssign::BCvt:
7902     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7903       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
7904     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7905       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
7906     else
7907       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
7908     break;
7909   }
7910   return Val;
7911 }
7912 
7913 // The caller is responsible for loading the full value if the argument is
7914 // passed with CCValAssign::Indirect.
7915 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
7916                                 const CCValAssign &VA, const SDLoc &DL,
7917                                 const RISCVTargetLowering &TLI) {
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7920   EVT LocVT = VA.getLocVT();
7921   SDValue Val;
7922   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
7923   Register VReg = RegInfo.createVirtualRegister(RC);
7924   RegInfo.addLiveIn(VA.getLocReg(), VReg);
7925   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
7926 
7927   if (VA.getLocInfo() == CCValAssign::Indirect)
7928     return Val;
7929 
7930   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
7931 }
7932 
7933 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
7934                                    const CCValAssign &VA, const SDLoc &DL,
7935                                    const RISCVSubtarget &Subtarget) {
7936   EVT LocVT = VA.getLocVT();
7937 
7938   switch (VA.getLocInfo()) {
7939   default:
7940     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7941   case CCValAssign::Full:
7942     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
7943       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
7944     break;
7945   case CCValAssign::BCvt:
7946     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7947       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
7948     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7949       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
7950     else
7951       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
7952     break;
7953   }
7954   return Val;
7955 }
7956 
7957 // The caller is responsible for loading the full value if the argument is
7958 // passed with CCValAssign::Indirect.
7959 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
7960                                 const CCValAssign &VA, const SDLoc &DL) {
7961   MachineFunction &MF = DAG.getMachineFunction();
7962   MachineFrameInfo &MFI = MF.getFrameInfo();
7963   EVT LocVT = VA.getLocVT();
7964   EVT ValVT = VA.getValVT();
7965   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
7966   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
7967                                  /*Immutable=*/true);
7968   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7969   SDValue Val;
7970 
7971   ISD::LoadExtType ExtType;
7972   switch (VA.getLocInfo()) {
7973   default:
7974     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7975   case CCValAssign::Full:
7976   case CCValAssign::Indirect:
7977   case CCValAssign::BCvt:
7978     ExtType = ISD::NON_EXTLOAD;
7979     break;
7980   }
7981   Val = DAG.getExtLoad(
7982       ExtType, DL, LocVT, Chain, FIN,
7983       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
7984   return Val;
7985 }
7986 
7987 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
7988                                        const CCValAssign &VA, const SDLoc &DL) {
7989   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
7990          "Unexpected VA");
7991   MachineFunction &MF = DAG.getMachineFunction();
7992   MachineFrameInfo &MFI = MF.getFrameInfo();
7993   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7994 
7995   if (VA.isMemLoc()) {
7996     // f64 is passed on the stack.
7997     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
7998     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7999     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8000                        MachinePointerInfo::getFixedStack(MF, FI));
8001   }
8002 
8003   assert(VA.isRegLoc() && "Expected register VA assignment");
8004 
8005   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8006   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8007   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8008   SDValue Hi;
8009   if (VA.getLocReg() == RISCV::X17) {
8010     // Second half of f64 is passed on the stack.
8011     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8012     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8013     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8014                      MachinePointerInfo::getFixedStack(MF, FI));
8015   } else {
8016     // Second half of f64 is passed in another GPR.
8017     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8018     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8019     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8020   }
8021   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8022 }
8023 
8024 // FastCC has less than 1% performance improvement for some particular
8025 // benchmark. But theoretically, it may has benenfit for some cases.
8026 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8027                             unsigned ValNo, MVT ValVT, MVT LocVT,
8028                             CCValAssign::LocInfo LocInfo,
8029                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8030                             bool IsFixed, bool IsRet, Type *OrigTy,
8031                             const RISCVTargetLowering &TLI,
8032                             Optional<unsigned> FirstMaskArgument) {
8033 
8034   // X5 and X6 might be used for save-restore libcall.
8035   static const MCPhysReg GPRList[] = {
8036       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8037       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8038       RISCV::X29, RISCV::X30, RISCV::X31};
8039 
8040   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8041     if (unsigned Reg = State.AllocateReg(GPRList)) {
8042       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8043       return false;
8044     }
8045   }
8046 
8047   if (LocVT == MVT::f16) {
8048     static const MCPhysReg FPR16List[] = {
8049         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8050         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8051         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8052         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8053     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8054       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8055       return false;
8056     }
8057   }
8058 
8059   if (LocVT == MVT::f32) {
8060     static const MCPhysReg FPR32List[] = {
8061         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8062         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8063         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8064         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8065     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8066       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8067       return false;
8068     }
8069   }
8070 
8071   if (LocVT == MVT::f64) {
8072     static const MCPhysReg FPR64List[] = {
8073         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8074         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8075         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8076         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8077     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8078       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8079       return false;
8080     }
8081   }
8082 
8083   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8084     unsigned Offset4 = State.AllocateStack(4, Align(4));
8085     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8086     return false;
8087   }
8088 
8089   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8090     unsigned Offset5 = State.AllocateStack(8, Align(8));
8091     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8092     return false;
8093   }
8094 
8095   if (LocVT.isVector()) {
8096     if (unsigned Reg =
8097             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8098       // Fixed-length vectors are located in the corresponding scalable-vector
8099       // container types.
8100       if (ValVT.isFixedLengthVector())
8101         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8102       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8103     } else {
8104       // Try and pass the address via a "fast" GPR.
8105       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8106         LocInfo = CCValAssign::Indirect;
8107         LocVT = TLI.getSubtarget().getXLenVT();
8108         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8109       } else if (ValVT.isFixedLengthVector()) {
8110         auto StackAlign =
8111             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8112         unsigned StackOffset =
8113             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8114         State.addLoc(
8115             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8116       } else {
8117         // Can't pass scalable vectors on the stack.
8118         return true;
8119       }
8120     }
8121 
8122     return false;
8123   }
8124 
8125   return true; // CC didn't match.
8126 }
8127 
8128 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8129                          CCValAssign::LocInfo LocInfo,
8130                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8131 
8132   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8133     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8134     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8135     static const MCPhysReg GPRList[] = {
8136         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8137         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8138     if (unsigned Reg = State.AllocateReg(GPRList)) {
8139       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8140       return false;
8141     }
8142   }
8143 
8144   if (LocVT == MVT::f32) {
8145     // Pass in STG registers: F1, ..., F6
8146     //                        fs0 ... fs5
8147     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8148                                           RISCV::F18_F, RISCV::F19_F,
8149                                           RISCV::F20_F, RISCV::F21_F};
8150     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8151       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8152       return false;
8153     }
8154   }
8155 
8156   if (LocVT == MVT::f64) {
8157     // Pass in STG registers: D1, ..., D6
8158     //                        fs6 ... fs11
8159     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8160                                           RISCV::F24_D, RISCV::F25_D,
8161                                           RISCV::F26_D, RISCV::F27_D};
8162     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8163       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8164       return false;
8165     }
8166   }
8167 
8168   report_fatal_error("No registers left in GHC calling convention");
8169   return true;
8170 }
8171 
8172 // Transform physical registers into virtual registers.
8173 SDValue RISCVTargetLowering::LowerFormalArguments(
8174     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8175     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8176     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8177 
8178   MachineFunction &MF = DAG.getMachineFunction();
8179 
8180   switch (CallConv) {
8181   default:
8182     report_fatal_error("Unsupported calling convention");
8183   case CallingConv::C:
8184   case CallingConv::Fast:
8185     break;
8186   case CallingConv::GHC:
8187     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8188         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8189       report_fatal_error(
8190         "GHC calling convention requires the F and D instruction set extensions");
8191   }
8192 
8193   const Function &Func = MF.getFunction();
8194   if (Func.hasFnAttribute("interrupt")) {
8195     if (!Func.arg_empty())
8196       report_fatal_error(
8197         "Functions with the interrupt attribute cannot have arguments!");
8198 
8199     StringRef Kind =
8200       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8201 
8202     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8203       report_fatal_error(
8204         "Function interrupt attribute argument not supported!");
8205   }
8206 
8207   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8208   MVT XLenVT = Subtarget.getXLenVT();
8209   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8210   // Used with vargs to acumulate store chains.
8211   std::vector<SDValue> OutChains;
8212 
8213   // Assign locations to all of the incoming arguments.
8214   SmallVector<CCValAssign, 16> ArgLocs;
8215   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8216 
8217   if (CallConv == CallingConv::GHC)
8218     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8219   else
8220     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8221                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8222                                                    : CC_RISCV);
8223 
8224   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8225     CCValAssign &VA = ArgLocs[i];
8226     SDValue ArgValue;
8227     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8228     // case.
8229     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8230       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8231     else if (VA.isRegLoc())
8232       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8233     else
8234       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8235 
8236     if (VA.getLocInfo() == CCValAssign::Indirect) {
8237       // If the original argument was split and passed by reference (e.g. i128
8238       // on RV32), we need to load all parts of it here (using the same
8239       // address). Vectors may be partly split to registers and partly to the
8240       // stack, in which case the base address is partly offset and subsequent
8241       // stores are relative to that.
8242       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8243                                    MachinePointerInfo()));
8244       unsigned ArgIndex = Ins[i].OrigArgIndex;
8245       unsigned ArgPartOffset = Ins[i].PartOffset;
8246       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8247       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8248         CCValAssign &PartVA = ArgLocs[i + 1];
8249         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8250         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8251         if (PartVA.getValVT().isScalableVector())
8252           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8253         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8254         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8255                                      MachinePointerInfo()));
8256         ++i;
8257       }
8258       continue;
8259     }
8260     InVals.push_back(ArgValue);
8261   }
8262 
8263   if (IsVarArg) {
8264     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8265     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8266     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8267     MachineFrameInfo &MFI = MF.getFrameInfo();
8268     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8269     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8270 
8271     // Offset of the first variable argument from stack pointer, and size of
8272     // the vararg save area. For now, the varargs save area is either zero or
8273     // large enough to hold a0-a7.
8274     int VaArgOffset, VarArgsSaveSize;
8275 
8276     // If all registers are allocated, then all varargs must be passed on the
8277     // stack and we don't need to save any argregs.
8278     if (ArgRegs.size() == Idx) {
8279       VaArgOffset = CCInfo.getNextStackOffset();
8280       VarArgsSaveSize = 0;
8281     } else {
8282       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8283       VaArgOffset = -VarArgsSaveSize;
8284     }
8285 
8286     // Record the frame index of the first variable argument
8287     // which is a value necessary to VASTART.
8288     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8289     RVFI->setVarArgsFrameIndex(FI);
8290 
8291     // If saving an odd number of registers then create an extra stack slot to
8292     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8293     // offsets to even-numbered registered remain 2*XLEN-aligned.
8294     if (Idx % 2) {
8295       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8296       VarArgsSaveSize += XLenInBytes;
8297     }
8298 
8299     // Copy the integer registers that may have been used for passing varargs
8300     // to the vararg save area.
8301     for (unsigned I = Idx; I < ArgRegs.size();
8302          ++I, VaArgOffset += XLenInBytes) {
8303       const Register Reg = RegInfo.createVirtualRegister(RC);
8304       RegInfo.addLiveIn(ArgRegs[I], Reg);
8305       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8306       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8307       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8308       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8309                                    MachinePointerInfo::getFixedStack(MF, FI));
8310       cast<StoreSDNode>(Store.getNode())
8311           ->getMemOperand()
8312           ->setValue((Value *)nullptr);
8313       OutChains.push_back(Store);
8314     }
8315     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8316   }
8317 
8318   // All stores are grouped in one node to allow the matching between
8319   // the size of Ins and InVals. This only happens for vararg functions.
8320   if (!OutChains.empty()) {
8321     OutChains.push_back(Chain);
8322     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8323   }
8324 
8325   return Chain;
8326 }
8327 
8328 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8329 /// for tail call optimization.
8330 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8331 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8332     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8333     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8334 
8335   auto &Callee = CLI.Callee;
8336   auto CalleeCC = CLI.CallConv;
8337   auto &Outs = CLI.Outs;
8338   auto &Caller = MF.getFunction();
8339   auto CallerCC = Caller.getCallingConv();
8340 
8341   // Exception-handling functions need a special set of instructions to
8342   // indicate a return to the hardware. Tail-calling another function would
8343   // probably break this.
8344   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8345   // should be expanded as new function attributes are introduced.
8346   if (Caller.hasFnAttribute("interrupt"))
8347     return false;
8348 
8349   // Do not tail call opt if the stack is used to pass parameters.
8350   if (CCInfo.getNextStackOffset() != 0)
8351     return false;
8352 
8353   // Do not tail call opt if any parameters need to be passed indirectly.
8354   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8355   // passed indirectly. So the address of the value will be passed in a
8356   // register, or if not available, then the address is put on the stack. In
8357   // order to pass indirectly, space on the stack often needs to be allocated
8358   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8359   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8360   // are passed CCValAssign::Indirect.
8361   for (auto &VA : ArgLocs)
8362     if (VA.getLocInfo() == CCValAssign::Indirect)
8363       return false;
8364 
8365   // Do not tail call opt if either caller or callee uses struct return
8366   // semantics.
8367   auto IsCallerStructRet = Caller.hasStructRetAttr();
8368   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8369   if (IsCallerStructRet || IsCalleeStructRet)
8370     return false;
8371 
8372   // Externally-defined functions with weak linkage should not be
8373   // tail-called. The behaviour of branch instructions in this situation (as
8374   // used for tail calls) is implementation-defined, so we cannot rely on the
8375   // linker replacing the tail call with a return.
8376   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8377     const GlobalValue *GV = G->getGlobal();
8378     if (GV->hasExternalWeakLinkage())
8379       return false;
8380   }
8381 
8382   // The callee has to preserve all registers the caller needs to preserve.
8383   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8384   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8385   if (CalleeCC != CallerCC) {
8386     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8387     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8388       return false;
8389   }
8390 
8391   // Byval parameters hand the function a pointer directly into the stack area
8392   // we want to reuse during a tail call. Working around this *is* possible
8393   // but less efficient and uglier in LowerCall.
8394   for (auto &Arg : Outs)
8395     if (Arg.Flags.isByVal())
8396       return false;
8397 
8398   return true;
8399 }
8400 
8401 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8402   return DAG.getDataLayout().getPrefTypeAlign(
8403       VT.getTypeForEVT(*DAG.getContext()));
8404 }
8405 
8406 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8407 // and output parameter nodes.
8408 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8409                                        SmallVectorImpl<SDValue> &InVals) const {
8410   SelectionDAG &DAG = CLI.DAG;
8411   SDLoc &DL = CLI.DL;
8412   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8413   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8414   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8415   SDValue Chain = CLI.Chain;
8416   SDValue Callee = CLI.Callee;
8417   bool &IsTailCall = CLI.IsTailCall;
8418   CallingConv::ID CallConv = CLI.CallConv;
8419   bool IsVarArg = CLI.IsVarArg;
8420   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8421   MVT XLenVT = Subtarget.getXLenVT();
8422 
8423   MachineFunction &MF = DAG.getMachineFunction();
8424 
8425   // Analyze the operands of the call, assigning locations to each operand.
8426   SmallVector<CCValAssign, 16> ArgLocs;
8427   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8428 
8429   if (CallConv == CallingConv::GHC)
8430     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8431   else
8432     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8433                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8434                                                     : CC_RISCV);
8435 
8436   // Check if it's really possible to do a tail call.
8437   if (IsTailCall)
8438     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8439 
8440   if (IsTailCall)
8441     ++NumTailCalls;
8442   else if (CLI.CB && CLI.CB->isMustTailCall())
8443     report_fatal_error("failed to perform tail call elimination on a call "
8444                        "site marked musttail");
8445 
8446   // Get a count of how many bytes are to be pushed on the stack.
8447   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8448 
8449   // Create local copies for byval args
8450   SmallVector<SDValue, 8> ByValArgs;
8451   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8452     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8453     if (!Flags.isByVal())
8454       continue;
8455 
8456     SDValue Arg = OutVals[i];
8457     unsigned Size = Flags.getByValSize();
8458     Align Alignment = Flags.getNonZeroByValAlign();
8459 
8460     int FI =
8461         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8462     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8463     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8464 
8465     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8466                           /*IsVolatile=*/false,
8467                           /*AlwaysInline=*/false, IsTailCall,
8468                           MachinePointerInfo(), MachinePointerInfo());
8469     ByValArgs.push_back(FIPtr);
8470   }
8471 
8472   if (!IsTailCall)
8473     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8474 
8475   // Copy argument values to their designated locations.
8476   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8477   SmallVector<SDValue, 8> MemOpChains;
8478   SDValue StackPtr;
8479   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8480     CCValAssign &VA = ArgLocs[i];
8481     SDValue ArgValue = OutVals[i];
8482     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8483 
8484     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8485     bool IsF64OnRV32DSoftABI =
8486         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8487     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8488       SDValue SplitF64 = DAG.getNode(
8489           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8490       SDValue Lo = SplitF64.getValue(0);
8491       SDValue Hi = SplitF64.getValue(1);
8492 
8493       Register RegLo = VA.getLocReg();
8494       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8495 
8496       if (RegLo == RISCV::X17) {
8497         // Second half of f64 is passed on the stack.
8498         // Work out the address of the stack slot.
8499         if (!StackPtr.getNode())
8500           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8501         // Emit the store.
8502         MemOpChains.push_back(
8503             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8504       } else {
8505         // Second half of f64 is passed in another GPR.
8506         assert(RegLo < RISCV::X31 && "Invalid register pair");
8507         Register RegHigh = RegLo + 1;
8508         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8509       }
8510       continue;
8511     }
8512 
8513     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8514     // as any other MemLoc.
8515 
8516     // Promote the value if needed.
8517     // For now, only handle fully promoted and indirect arguments.
8518     if (VA.getLocInfo() == CCValAssign::Indirect) {
8519       // Store the argument in a stack slot and pass its address.
8520       Align StackAlign =
8521           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8522                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8523       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8524       // If the original argument was split (e.g. i128), we need
8525       // to store the required parts of it here (and pass just one address).
8526       // Vectors may be partly split to registers and partly to the stack, in
8527       // which case the base address is partly offset and subsequent stores are
8528       // relative to that.
8529       unsigned ArgIndex = Outs[i].OrigArgIndex;
8530       unsigned ArgPartOffset = Outs[i].PartOffset;
8531       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8532       // Calculate the total size to store. We don't have access to what we're
8533       // actually storing other than performing the loop and collecting the
8534       // info.
8535       SmallVector<std::pair<SDValue, SDValue>> Parts;
8536       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8537         SDValue PartValue = OutVals[i + 1];
8538         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8539         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8540         EVT PartVT = PartValue.getValueType();
8541         if (PartVT.isScalableVector())
8542           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8543         StoredSize += PartVT.getStoreSize();
8544         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8545         Parts.push_back(std::make_pair(PartValue, Offset));
8546         ++i;
8547       }
8548       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8549       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8550       MemOpChains.push_back(
8551           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8552                        MachinePointerInfo::getFixedStack(MF, FI)));
8553       for (const auto &Part : Parts) {
8554         SDValue PartValue = Part.first;
8555         SDValue PartOffset = Part.second;
8556         SDValue Address =
8557             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8558         MemOpChains.push_back(
8559             DAG.getStore(Chain, DL, PartValue, Address,
8560                          MachinePointerInfo::getFixedStack(MF, FI)));
8561       }
8562       ArgValue = SpillSlot;
8563     } else {
8564       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8565     }
8566 
8567     // Use local copy if it is a byval arg.
8568     if (Flags.isByVal())
8569       ArgValue = ByValArgs[j++];
8570 
8571     if (VA.isRegLoc()) {
8572       // Queue up the argument copies and emit them at the end.
8573       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8574     } else {
8575       assert(VA.isMemLoc() && "Argument not register or memory");
8576       assert(!IsTailCall && "Tail call not allowed if stack is used "
8577                             "for passing parameters");
8578 
8579       // Work out the address of the stack slot.
8580       if (!StackPtr.getNode())
8581         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8582       SDValue Address =
8583           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8584                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8585 
8586       // Emit the store.
8587       MemOpChains.push_back(
8588           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8589     }
8590   }
8591 
8592   // Join the stores, which are independent of one another.
8593   if (!MemOpChains.empty())
8594     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8595 
8596   SDValue Glue;
8597 
8598   // Build a sequence of copy-to-reg nodes, chained and glued together.
8599   for (auto &Reg : RegsToPass) {
8600     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8601     Glue = Chain.getValue(1);
8602   }
8603 
8604   // Validate that none of the argument registers have been marked as
8605   // reserved, if so report an error. Do the same for the return address if this
8606   // is not a tailcall.
8607   validateCCReservedRegs(RegsToPass, MF);
8608   if (!IsTailCall &&
8609       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8610     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8611         MF.getFunction(),
8612         "Return address register required, but has been reserved."});
8613 
8614   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8615   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8616   // split it and then direct call can be matched by PseudoCALL.
8617   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8618     const GlobalValue *GV = S->getGlobal();
8619 
8620     unsigned OpFlags = RISCVII::MO_CALL;
8621     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8622       OpFlags = RISCVII::MO_PLT;
8623 
8624     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8625   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8626     unsigned OpFlags = RISCVII::MO_CALL;
8627 
8628     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8629                                                  nullptr))
8630       OpFlags = RISCVII::MO_PLT;
8631 
8632     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8633   }
8634 
8635   // The first call operand is the chain and the second is the target address.
8636   SmallVector<SDValue, 8> Ops;
8637   Ops.push_back(Chain);
8638   Ops.push_back(Callee);
8639 
8640   // Add argument registers to the end of the list so that they are
8641   // known live into the call.
8642   for (auto &Reg : RegsToPass)
8643     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8644 
8645   if (!IsTailCall) {
8646     // Add a register mask operand representing the call-preserved registers.
8647     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8648     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8649     assert(Mask && "Missing call preserved mask for calling convention");
8650     Ops.push_back(DAG.getRegisterMask(Mask));
8651   }
8652 
8653   // Glue the call to the argument copies, if any.
8654   if (Glue.getNode())
8655     Ops.push_back(Glue);
8656 
8657   // Emit the call.
8658   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8659 
8660   if (IsTailCall) {
8661     MF.getFrameInfo().setHasTailCall();
8662     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8663   }
8664 
8665   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8666   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8667   Glue = Chain.getValue(1);
8668 
8669   // Mark the end of the call, which is glued to the call itself.
8670   Chain = DAG.getCALLSEQ_END(Chain,
8671                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8672                              DAG.getConstant(0, DL, PtrVT, true),
8673                              Glue, DL);
8674   Glue = Chain.getValue(1);
8675 
8676   // Assign locations to each value returned by this call.
8677   SmallVector<CCValAssign, 16> RVLocs;
8678   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8679   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8680 
8681   // Copy all of the result registers out of their specified physreg.
8682   for (auto &VA : RVLocs) {
8683     // Copy the value out
8684     SDValue RetValue =
8685         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8686     // Glue the RetValue to the end of the call sequence
8687     Chain = RetValue.getValue(1);
8688     Glue = RetValue.getValue(2);
8689 
8690     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8691       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8692       SDValue RetValue2 =
8693           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8694       Chain = RetValue2.getValue(1);
8695       Glue = RetValue2.getValue(2);
8696       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8697                              RetValue2);
8698     }
8699 
8700     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8701 
8702     InVals.push_back(RetValue);
8703   }
8704 
8705   return Chain;
8706 }
8707 
8708 bool RISCVTargetLowering::CanLowerReturn(
8709     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8710     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8711   SmallVector<CCValAssign, 16> RVLocs;
8712   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8713 
8714   Optional<unsigned> FirstMaskArgument;
8715   if (Subtarget.hasStdExtV())
8716     FirstMaskArgument = preAssignMask(Outs);
8717 
8718   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8719     MVT VT = Outs[i].VT;
8720     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8721     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8722     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8723                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8724                  *this, FirstMaskArgument))
8725       return false;
8726   }
8727   return true;
8728 }
8729 
8730 SDValue
8731 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8732                                  bool IsVarArg,
8733                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8734                                  const SmallVectorImpl<SDValue> &OutVals,
8735                                  const SDLoc &DL, SelectionDAG &DAG) const {
8736   const MachineFunction &MF = DAG.getMachineFunction();
8737   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8738 
8739   // Stores the assignment of the return value to a location.
8740   SmallVector<CCValAssign, 16> RVLocs;
8741 
8742   // Info about the registers and stack slot.
8743   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8744                  *DAG.getContext());
8745 
8746   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8747                     nullptr, CC_RISCV);
8748 
8749   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8750     report_fatal_error("GHC functions return void only");
8751 
8752   SDValue Glue;
8753   SmallVector<SDValue, 4> RetOps(1, Chain);
8754 
8755   // Copy the result values into the output registers.
8756   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8757     SDValue Val = OutVals[i];
8758     CCValAssign &VA = RVLocs[i];
8759     assert(VA.isRegLoc() && "Can only return in registers!");
8760 
8761     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8762       // Handle returning f64 on RV32D with a soft float ABI.
8763       assert(VA.isRegLoc() && "Expected return via registers");
8764       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8765                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8766       SDValue Lo = SplitF64.getValue(0);
8767       SDValue Hi = SplitF64.getValue(1);
8768       Register RegLo = VA.getLocReg();
8769       assert(RegLo < RISCV::X31 && "Invalid register pair");
8770       Register RegHi = RegLo + 1;
8771 
8772       if (STI.isRegisterReservedByUser(RegLo) ||
8773           STI.isRegisterReservedByUser(RegHi))
8774         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8775             MF.getFunction(),
8776             "Return value register required, but has been reserved."});
8777 
8778       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8779       Glue = Chain.getValue(1);
8780       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8781       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8782       Glue = Chain.getValue(1);
8783       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8784     } else {
8785       // Handle a 'normal' return.
8786       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8787       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8788 
8789       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8790         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8791             MF.getFunction(),
8792             "Return value register required, but has been reserved."});
8793 
8794       // Guarantee that all emitted copies are stuck together.
8795       Glue = Chain.getValue(1);
8796       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8797     }
8798   }
8799 
8800   RetOps[0] = Chain; // Update chain.
8801 
8802   // Add the glue node if we have it.
8803   if (Glue.getNode()) {
8804     RetOps.push_back(Glue);
8805   }
8806 
8807   unsigned RetOpc = RISCVISD::RET_FLAG;
8808   // Interrupt service routines use different return instructions.
8809   const Function &Func = DAG.getMachineFunction().getFunction();
8810   if (Func.hasFnAttribute("interrupt")) {
8811     if (!Func.getReturnType()->isVoidTy())
8812       report_fatal_error(
8813           "Functions with the interrupt attribute must have void return type!");
8814 
8815     MachineFunction &MF = DAG.getMachineFunction();
8816     StringRef Kind =
8817       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8818 
8819     if (Kind == "user")
8820       RetOpc = RISCVISD::URET_FLAG;
8821     else if (Kind == "supervisor")
8822       RetOpc = RISCVISD::SRET_FLAG;
8823     else
8824       RetOpc = RISCVISD::MRET_FLAG;
8825   }
8826 
8827   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
8828 }
8829 
8830 void RISCVTargetLowering::validateCCReservedRegs(
8831     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
8832     MachineFunction &MF) const {
8833   const Function &F = MF.getFunction();
8834   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8835 
8836   if (llvm::any_of(Regs, [&STI](auto Reg) {
8837         return STI.isRegisterReservedByUser(Reg.first);
8838       }))
8839     F.getContext().diagnose(DiagnosticInfoUnsupported{
8840         F, "Argument register required, but has been reserved."});
8841 }
8842 
8843 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
8844   return CI->isTailCall();
8845 }
8846 
8847 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
8848 #define NODE_NAME_CASE(NODE)                                                   \
8849   case RISCVISD::NODE:                                                         \
8850     return "RISCVISD::" #NODE;
8851   // clang-format off
8852   switch ((RISCVISD::NodeType)Opcode) {
8853   case RISCVISD::FIRST_NUMBER:
8854     break;
8855   NODE_NAME_CASE(RET_FLAG)
8856   NODE_NAME_CASE(URET_FLAG)
8857   NODE_NAME_CASE(SRET_FLAG)
8858   NODE_NAME_CASE(MRET_FLAG)
8859   NODE_NAME_CASE(CALL)
8860   NODE_NAME_CASE(SELECT_CC)
8861   NODE_NAME_CASE(BR_CC)
8862   NODE_NAME_CASE(BuildPairF64)
8863   NODE_NAME_CASE(SplitF64)
8864   NODE_NAME_CASE(TAIL)
8865   NODE_NAME_CASE(MULHSU)
8866   NODE_NAME_CASE(SLLW)
8867   NODE_NAME_CASE(SRAW)
8868   NODE_NAME_CASE(SRLW)
8869   NODE_NAME_CASE(DIVW)
8870   NODE_NAME_CASE(DIVUW)
8871   NODE_NAME_CASE(REMUW)
8872   NODE_NAME_CASE(ROLW)
8873   NODE_NAME_CASE(RORW)
8874   NODE_NAME_CASE(CLZW)
8875   NODE_NAME_CASE(CTZW)
8876   NODE_NAME_CASE(FSLW)
8877   NODE_NAME_CASE(FSRW)
8878   NODE_NAME_CASE(FSL)
8879   NODE_NAME_CASE(FSR)
8880   NODE_NAME_CASE(FMV_H_X)
8881   NODE_NAME_CASE(FMV_X_ANYEXTH)
8882   NODE_NAME_CASE(FMV_W_X_RV64)
8883   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
8884   NODE_NAME_CASE(FCVT_X_RTZ)
8885   NODE_NAME_CASE(FCVT_XU_RTZ)
8886   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
8887   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
8888   NODE_NAME_CASE(READ_CYCLE_WIDE)
8889   NODE_NAME_CASE(GREV)
8890   NODE_NAME_CASE(GREVW)
8891   NODE_NAME_CASE(GORC)
8892   NODE_NAME_CASE(GORCW)
8893   NODE_NAME_CASE(SHFL)
8894   NODE_NAME_CASE(SHFLW)
8895   NODE_NAME_CASE(UNSHFL)
8896   NODE_NAME_CASE(UNSHFLW)
8897   NODE_NAME_CASE(BCOMPRESS)
8898   NODE_NAME_CASE(BCOMPRESSW)
8899   NODE_NAME_CASE(BDECOMPRESS)
8900   NODE_NAME_CASE(BDECOMPRESSW)
8901   NODE_NAME_CASE(VMV_V_X_VL)
8902   NODE_NAME_CASE(VFMV_V_F_VL)
8903   NODE_NAME_CASE(VMV_X_S)
8904   NODE_NAME_CASE(VMV_S_X_VL)
8905   NODE_NAME_CASE(VFMV_S_F_VL)
8906   NODE_NAME_CASE(SPLAT_VECTOR_I64)
8907   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
8908   NODE_NAME_CASE(READ_VLENB)
8909   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
8910   NODE_NAME_CASE(VSLIDEUP_VL)
8911   NODE_NAME_CASE(VSLIDE1UP_VL)
8912   NODE_NAME_CASE(VSLIDEDOWN_VL)
8913   NODE_NAME_CASE(VSLIDE1DOWN_VL)
8914   NODE_NAME_CASE(VID_VL)
8915   NODE_NAME_CASE(VFNCVT_ROD_VL)
8916   NODE_NAME_CASE(VECREDUCE_ADD_VL)
8917   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
8918   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
8919   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
8920   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
8921   NODE_NAME_CASE(VECREDUCE_AND_VL)
8922   NODE_NAME_CASE(VECREDUCE_OR_VL)
8923   NODE_NAME_CASE(VECREDUCE_XOR_VL)
8924   NODE_NAME_CASE(VECREDUCE_FADD_VL)
8925   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
8926   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
8927   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
8928   NODE_NAME_CASE(ADD_VL)
8929   NODE_NAME_CASE(AND_VL)
8930   NODE_NAME_CASE(MUL_VL)
8931   NODE_NAME_CASE(OR_VL)
8932   NODE_NAME_CASE(SDIV_VL)
8933   NODE_NAME_CASE(SHL_VL)
8934   NODE_NAME_CASE(SREM_VL)
8935   NODE_NAME_CASE(SRA_VL)
8936   NODE_NAME_CASE(SRL_VL)
8937   NODE_NAME_CASE(SUB_VL)
8938   NODE_NAME_CASE(UDIV_VL)
8939   NODE_NAME_CASE(UREM_VL)
8940   NODE_NAME_CASE(XOR_VL)
8941   NODE_NAME_CASE(SADDSAT_VL)
8942   NODE_NAME_CASE(UADDSAT_VL)
8943   NODE_NAME_CASE(SSUBSAT_VL)
8944   NODE_NAME_CASE(USUBSAT_VL)
8945   NODE_NAME_CASE(FADD_VL)
8946   NODE_NAME_CASE(FSUB_VL)
8947   NODE_NAME_CASE(FMUL_VL)
8948   NODE_NAME_CASE(FDIV_VL)
8949   NODE_NAME_CASE(FNEG_VL)
8950   NODE_NAME_CASE(FABS_VL)
8951   NODE_NAME_CASE(FSQRT_VL)
8952   NODE_NAME_CASE(FMA_VL)
8953   NODE_NAME_CASE(FCOPYSIGN_VL)
8954   NODE_NAME_CASE(SMIN_VL)
8955   NODE_NAME_CASE(SMAX_VL)
8956   NODE_NAME_CASE(UMIN_VL)
8957   NODE_NAME_CASE(UMAX_VL)
8958   NODE_NAME_CASE(FMINNUM_VL)
8959   NODE_NAME_CASE(FMAXNUM_VL)
8960   NODE_NAME_CASE(MULHS_VL)
8961   NODE_NAME_CASE(MULHU_VL)
8962   NODE_NAME_CASE(FP_TO_SINT_VL)
8963   NODE_NAME_CASE(FP_TO_UINT_VL)
8964   NODE_NAME_CASE(SINT_TO_FP_VL)
8965   NODE_NAME_CASE(UINT_TO_FP_VL)
8966   NODE_NAME_CASE(FP_EXTEND_VL)
8967   NODE_NAME_CASE(FP_ROUND_VL)
8968   NODE_NAME_CASE(VWMUL_VL)
8969   NODE_NAME_CASE(VWMULU_VL)
8970   NODE_NAME_CASE(SETCC_VL)
8971   NODE_NAME_CASE(VSELECT_VL)
8972   NODE_NAME_CASE(VMAND_VL)
8973   NODE_NAME_CASE(VMOR_VL)
8974   NODE_NAME_CASE(VMXOR_VL)
8975   NODE_NAME_CASE(VMCLR_VL)
8976   NODE_NAME_CASE(VMSET_VL)
8977   NODE_NAME_CASE(VRGATHER_VX_VL)
8978   NODE_NAME_CASE(VRGATHER_VV_VL)
8979   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
8980   NODE_NAME_CASE(VSEXT_VL)
8981   NODE_NAME_CASE(VZEXT_VL)
8982   NODE_NAME_CASE(VPOPC_VL)
8983   NODE_NAME_CASE(VLE_VL)
8984   NODE_NAME_CASE(VSE_VL)
8985   NODE_NAME_CASE(READ_CSR)
8986   NODE_NAME_CASE(WRITE_CSR)
8987   NODE_NAME_CASE(SWAP_CSR)
8988   }
8989   // clang-format on
8990   return nullptr;
8991 #undef NODE_NAME_CASE
8992 }
8993 
8994 /// getConstraintType - Given a constraint letter, return the type of
8995 /// constraint it is for this target.
8996 RISCVTargetLowering::ConstraintType
8997 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
8998   if (Constraint.size() == 1) {
8999     switch (Constraint[0]) {
9000     default:
9001       break;
9002     case 'f':
9003       return C_RegisterClass;
9004     case 'I':
9005     case 'J':
9006     case 'K':
9007       return C_Immediate;
9008     case 'A':
9009       return C_Memory;
9010     case 'S': // A symbolic address
9011       return C_Other;
9012     }
9013   } else {
9014     if (Constraint == "vr" || Constraint == "vm")
9015       return C_RegisterClass;
9016   }
9017   return TargetLowering::getConstraintType(Constraint);
9018 }
9019 
9020 std::pair<unsigned, const TargetRegisterClass *>
9021 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9022                                                   StringRef Constraint,
9023                                                   MVT VT) const {
9024   // First, see if this is a constraint that directly corresponds to a
9025   // RISCV register class.
9026   if (Constraint.size() == 1) {
9027     switch (Constraint[0]) {
9028     case 'r':
9029       return std::make_pair(0U, &RISCV::GPRRegClass);
9030     case 'f':
9031       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9032         return std::make_pair(0U, &RISCV::FPR16RegClass);
9033       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9034         return std::make_pair(0U, &RISCV::FPR32RegClass);
9035       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9036         return std::make_pair(0U, &RISCV::FPR64RegClass);
9037       break;
9038     default:
9039       break;
9040     }
9041   } else {
9042     if (Constraint == "vr") {
9043       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9044                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9045         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9046           return std::make_pair(0U, RC);
9047       }
9048     } else if (Constraint == "vm") {
9049       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9050         return std::make_pair(0U, &RISCV::VMRegClass);
9051     }
9052   }
9053 
9054   // Clang will correctly decode the usage of register name aliases into their
9055   // official names. However, other frontends like `rustc` do not. This allows
9056   // users of these frontends to use the ABI names for registers in LLVM-style
9057   // register constraints.
9058   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9059                                .Case("{zero}", RISCV::X0)
9060                                .Case("{ra}", RISCV::X1)
9061                                .Case("{sp}", RISCV::X2)
9062                                .Case("{gp}", RISCV::X3)
9063                                .Case("{tp}", RISCV::X4)
9064                                .Case("{t0}", RISCV::X5)
9065                                .Case("{t1}", RISCV::X6)
9066                                .Case("{t2}", RISCV::X7)
9067                                .Cases("{s0}", "{fp}", RISCV::X8)
9068                                .Case("{s1}", RISCV::X9)
9069                                .Case("{a0}", RISCV::X10)
9070                                .Case("{a1}", RISCV::X11)
9071                                .Case("{a2}", RISCV::X12)
9072                                .Case("{a3}", RISCV::X13)
9073                                .Case("{a4}", RISCV::X14)
9074                                .Case("{a5}", RISCV::X15)
9075                                .Case("{a6}", RISCV::X16)
9076                                .Case("{a7}", RISCV::X17)
9077                                .Case("{s2}", RISCV::X18)
9078                                .Case("{s3}", RISCV::X19)
9079                                .Case("{s4}", RISCV::X20)
9080                                .Case("{s5}", RISCV::X21)
9081                                .Case("{s6}", RISCV::X22)
9082                                .Case("{s7}", RISCV::X23)
9083                                .Case("{s8}", RISCV::X24)
9084                                .Case("{s9}", RISCV::X25)
9085                                .Case("{s10}", RISCV::X26)
9086                                .Case("{s11}", RISCV::X27)
9087                                .Case("{t3}", RISCV::X28)
9088                                .Case("{t4}", RISCV::X29)
9089                                .Case("{t5}", RISCV::X30)
9090                                .Case("{t6}", RISCV::X31)
9091                                .Default(RISCV::NoRegister);
9092   if (XRegFromAlias != RISCV::NoRegister)
9093     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9094 
9095   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9096   // TableGen record rather than the AsmName to choose registers for InlineAsm
9097   // constraints, plus we want to match those names to the widest floating point
9098   // register type available, manually select floating point registers here.
9099   //
9100   // The second case is the ABI name of the register, so that frontends can also
9101   // use the ABI names in register constraint lists.
9102   if (Subtarget.hasStdExtF()) {
9103     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9104                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9105                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9106                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9107                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9108                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9109                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9110                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9111                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9112                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9113                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9114                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9115                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9116                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9117                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9118                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9119                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9120                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9121                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9122                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9123                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9124                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9125                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9126                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9127                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9128                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9129                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9130                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9131                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9132                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9133                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9134                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9135                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9136                         .Default(RISCV::NoRegister);
9137     if (FReg != RISCV::NoRegister) {
9138       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9139       if (Subtarget.hasStdExtD()) {
9140         unsigned RegNo = FReg - RISCV::F0_F;
9141         unsigned DReg = RISCV::F0_D + RegNo;
9142         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9143       }
9144       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9145     }
9146   }
9147 
9148   if (Subtarget.hasStdExtV()) {
9149     Register VReg = StringSwitch<Register>(Constraint.lower())
9150                         .Case("{v0}", RISCV::V0)
9151                         .Case("{v1}", RISCV::V1)
9152                         .Case("{v2}", RISCV::V2)
9153                         .Case("{v3}", RISCV::V3)
9154                         .Case("{v4}", RISCV::V4)
9155                         .Case("{v5}", RISCV::V5)
9156                         .Case("{v6}", RISCV::V6)
9157                         .Case("{v7}", RISCV::V7)
9158                         .Case("{v8}", RISCV::V8)
9159                         .Case("{v9}", RISCV::V9)
9160                         .Case("{v10}", RISCV::V10)
9161                         .Case("{v11}", RISCV::V11)
9162                         .Case("{v12}", RISCV::V12)
9163                         .Case("{v13}", RISCV::V13)
9164                         .Case("{v14}", RISCV::V14)
9165                         .Case("{v15}", RISCV::V15)
9166                         .Case("{v16}", RISCV::V16)
9167                         .Case("{v17}", RISCV::V17)
9168                         .Case("{v18}", RISCV::V18)
9169                         .Case("{v19}", RISCV::V19)
9170                         .Case("{v20}", RISCV::V20)
9171                         .Case("{v21}", RISCV::V21)
9172                         .Case("{v22}", RISCV::V22)
9173                         .Case("{v23}", RISCV::V23)
9174                         .Case("{v24}", RISCV::V24)
9175                         .Case("{v25}", RISCV::V25)
9176                         .Case("{v26}", RISCV::V26)
9177                         .Case("{v27}", RISCV::V27)
9178                         .Case("{v28}", RISCV::V28)
9179                         .Case("{v29}", RISCV::V29)
9180                         .Case("{v30}", RISCV::V30)
9181                         .Case("{v31}", RISCV::V31)
9182                         .Default(RISCV::NoRegister);
9183     if (VReg != RISCV::NoRegister) {
9184       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9185         return std::make_pair(VReg, &RISCV::VMRegClass);
9186       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9187         return std::make_pair(VReg, &RISCV::VRRegClass);
9188       for (const auto *RC :
9189            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9190         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9191           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9192           return std::make_pair(VReg, RC);
9193         }
9194       }
9195     }
9196   }
9197 
9198   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9199 }
9200 
9201 unsigned
9202 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9203   // Currently only support length 1 constraints.
9204   if (ConstraintCode.size() == 1) {
9205     switch (ConstraintCode[0]) {
9206     case 'A':
9207       return InlineAsm::Constraint_A;
9208     default:
9209       break;
9210     }
9211   }
9212 
9213   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9214 }
9215 
9216 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9217     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9218     SelectionDAG &DAG) const {
9219   // Currently only support length 1 constraints.
9220   if (Constraint.length() == 1) {
9221     switch (Constraint[0]) {
9222     case 'I':
9223       // Validate & create a 12-bit signed immediate operand.
9224       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9225         uint64_t CVal = C->getSExtValue();
9226         if (isInt<12>(CVal))
9227           Ops.push_back(
9228               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9229       }
9230       return;
9231     case 'J':
9232       // Validate & create an integer zero operand.
9233       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9234         if (C->getZExtValue() == 0)
9235           Ops.push_back(
9236               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9237       return;
9238     case 'K':
9239       // Validate & create a 5-bit unsigned immediate operand.
9240       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9241         uint64_t CVal = C->getZExtValue();
9242         if (isUInt<5>(CVal))
9243           Ops.push_back(
9244               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9245       }
9246       return;
9247     case 'S':
9248       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9249         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9250                                                  GA->getValueType(0)));
9251       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9252         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9253                                                 BA->getValueType(0)));
9254       }
9255       return;
9256     default:
9257       break;
9258     }
9259   }
9260   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9261 }
9262 
9263 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9264                                                    Instruction *Inst,
9265                                                    AtomicOrdering Ord) const {
9266   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9267     return Builder.CreateFence(Ord);
9268   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9269     return Builder.CreateFence(AtomicOrdering::Release);
9270   return nullptr;
9271 }
9272 
9273 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9274                                                     Instruction *Inst,
9275                                                     AtomicOrdering Ord) const {
9276   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9277     return Builder.CreateFence(AtomicOrdering::Acquire);
9278   return nullptr;
9279 }
9280 
9281 TargetLowering::AtomicExpansionKind
9282 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9283   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9284   // point operations can't be used in an lr/sc sequence without breaking the
9285   // forward-progress guarantee.
9286   if (AI->isFloatingPointOperation())
9287     return AtomicExpansionKind::CmpXChg;
9288 
9289   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9290   if (Size == 8 || Size == 16)
9291     return AtomicExpansionKind::MaskedIntrinsic;
9292   return AtomicExpansionKind::None;
9293 }
9294 
9295 static Intrinsic::ID
9296 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9297   if (XLen == 32) {
9298     switch (BinOp) {
9299     default:
9300       llvm_unreachable("Unexpected AtomicRMW BinOp");
9301     case AtomicRMWInst::Xchg:
9302       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9303     case AtomicRMWInst::Add:
9304       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9305     case AtomicRMWInst::Sub:
9306       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9307     case AtomicRMWInst::Nand:
9308       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9309     case AtomicRMWInst::Max:
9310       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9311     case AtomicRMWInst::Min:
9312       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9313     case AtomicRMWInst::UMax:
9314       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9315     case AtomicRMWInst::UMin:
9316       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9317     }
9318   }
9319 
9320   if (XLen == 64) {
9321     switch (BinOp) {
9322     default:
9323       llvm_unreachable("Unexpected AtomicRMW BinOp");
9324     case AtomicRMWInst::Xchg:
9325       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9326     case AtomicRMWInst::Add:
9327       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9328     case AtomicRMWInst::Sub:
9329       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9330     case AtomicRMWInst::Nand:
9331       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9332     case AtomicRMWInst::Max:
9333       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9334     case AtomicRMWInst::Min:
9335       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9336     case AtomicRMWInst::UMax:
9337       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9338     case AtomicRMWInst::UMin:
9339       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9340     }
9341   }
9342 
9343   llvm_unreachable("Unexpected XLen\n");
9344 }
9345 
9346 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9347     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9348     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9349   unsigned XLen = Subtarget.getXLen();
9350   Value *Ordering =
9351       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9352   Type *Tys[] = {AlignedAddr->getType()};
9353   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9354       AI->getModule(),
9355       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9356 
9357   if (XLen == 64) {
9358     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9359     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9360     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9361   }
9362 
9363   Value *Result;
9364 
9365   // Must pass the shift amount needed to sign extend the loaded value prior
9366   // to performing a signed comparison for min/max. ShiftAmt is the number of
9367   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9368   // is the number of bits to left+right shift the value in order to
9369   // sign-extend.
9370   if (AI->getOperation() == AtomicRMWInst::Min ||
9371       AI->getOperation() == AtomicRMWInst::Max) {
9372     const DataLayout &DL = AI->getModule()->getDataLayout();
9373     unsigned ValWidth =
9374         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9375     Value *SextShamt =
9376         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9377     Result = Builder.CreateCall(LrwOpScwLoop,
9378                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9379   } else {
9380     Result =
9381         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9382   }
9383 
9384   if (XLen == 64)
9385     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9386   return Result;
9387 }
9388 
9389 TargetLowering::AtomicExpansionKind
9390 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9391     AtomicCmpXchgInst *CI) const {
9392   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9393   if (Size == 8 || Size == 16)
9394     return AtomicExpansionKind::MaskedIntrinsic;
9395   return AtomicExpansionKind::None;
9396 }
9397 
9398 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9399     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9400     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9401   unsigned XLen = Subtarget.getXLen();
9402   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9403   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9404   if (XLen == 64) {
9405     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9406     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9407     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9408     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9409   }
9410   Type *Tys[] = {AlignedAddr->getType()};
9411   Function *MaskedCmpXchg =
9412       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9413   Value *Result = Builder.CreateCall(
9414       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9415   if (XLen == 64)
9416     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9417   return Result;
9418 }
9419 
9420 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9421   return false;
9422 }
9423 
9424 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9425                                                      EVT VT) const {
9426   VT = VT.getScalarType();
9427 
9428   if (!VT.isSimple())
9429     return false;
9430 
9431   switch (VT.getSimpleVT().SimpleTy) {
9432   case MVT::f16:
9433     return Subtarget.hasStdExtZfh();
9434   case MVT::f32:
9435     return Subtarget.hasStdExtF();
9436   case MVT::f64:
9437     return Subtarget.hasStdExtD();
9438   default:
9439     break;
9440   }
9441 
9442   return false;
9443 }
9444 
9445 Register RISCVTargetLowering::getExceptionPointerRegister(
9446     const Constant *PersonalityFn) const {
9447   return RISCV::X10;
9448 }
9449 
9450 Register RISCVTargetLowering::getExceptionSelectorRegister(
9451     const Constant *PersonalityFn) const {
9452   return RISCV::X11;
9453 }
9454 
9455 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9456   // Return false to suppress the unnecessary extensions if the LibCall
9457   // arguments or return value is f32 type for LP64 ABI.
9458   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9459   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9460     return false;
9461 
9462   return true;
9463 }
9464 
9465 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9466   if (Subtarget.is64Bit() && Type == MVT::i32)
9467     return true;
9468 
9469   return IsSigned;
9470 }
9471 
9472 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9473                                                  SDValue C) const {
9474   // Check integral scalar types.
9475   if (VT.isScalarInteger()) {
9476     // Omit the optimization if the sub target has the M extension and the data
9477     // size exceeds XLen.
9478     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9479       return false;
9480     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9481       // Break the MUL to a SLLI and an ADD/SUB.
9482       const APInt &Imm = ConstNode->getAPIntValue();
9483       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9484           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9485         return true;
9486       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9487       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9488           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9489            (Imm - 8).isPowerOf2()))
9490         return true;
9491       // Omit the following optimization if the sub target has the M extension
9492       // and the data size >= XLen.
9493       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9494         return false;
9495       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9496       // a pair of LUI/ADDI.
9497       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9498         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9499         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9500             (1 - ImmS).isPowerOf2())
9501         return true;
9502       }
9503     }
9504   }
9505 
9506   return false;
9507 }
9508 
9509 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9510     const SDValue &AddNode, const SDValue &ConstNode) const {
9511   // Let the DAGCombiner decide for vectors.
9512   EVT VT = AddNode.getValueType();
9513   if (VT.isVector())
9514     return true;
9515 
9516   // Let the DAGCombiner decide for larger types.
9517   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9518     return true;
9519 
9520   // It is worse if c1 is simm12 while c1*c2 is not.
9521   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9522   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9523   const APInt &C1 = C1Node->getAPIntValue();
9524   const APInt &C2 = C2Node->getAPIntValue();
9525   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9526     return false;
9527 
9528   // Default to true and let the DAGCombiner decide.
9529   return true;
9530 }
9531 
9532 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9533     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9534     bool *Fast) const {
9535   if (!VT.isVector())
9536     return false;
9537 
9538   EVT ElemVT = VT.getVectorElementType();
9539   if (Alignment >= ElemVT.getStoreSize()) {
9540     if (Fast)
9541       *Fast = true;
9542     return true;
9543   }
9544 
9545   return false;
9546 }
9547 
9548 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9549     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9550     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9551   bool IsABIRegCopy = CC.hasValue();
9552   EVT ValueVT = Val.getValueType();
9553   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9554     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9555     // and cast to f32.
9556     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9557     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9558     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9559                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9560     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9561     Parts[0] = Val;
9562     return true;
9563   }
9564 
9565   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9566     LLVMContext &Context = *DAG.getContext();
9567     EVT ValueEltVT = ValueVT.getVectorElementType();
9568     EVT PartEltVT = PartVT.getVectorElementType();
9569     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9570     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9571     if (PartVTBitSize % ValueVTBitSize == 0) {
9572       // If the element types are different, bitcast to the same element type of
9573       // PartVT first.
9574       if (ValueEltVT != PartEltVT) {
9575         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9576         assert(Count != 0 && "The number of element should not be zero.");
9577         EVT SameEltTypeVT =
9578             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9579         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9580       }
9581       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9582                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9583       Parts[0] = Val;
9584       return true;
9585     }
9586   }
9587   return false;
9588 }
9589 
9590 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9591     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9592     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9593   bool IsABIRegCopy = CC.hasValue();
9594   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9595     SDValue Val = Parts[0];
9596 
9597     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9598     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9599     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9600     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9601     return Val;
9602   }
9603 
9604   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9605     LLVMContext &Context = *DAG.getContext();
9606     SDValue Val = Parts[0];
9607     EVT ValueEltVT = ValueVT.getVectorElementType();
9608     EVT PartEltVT = PartVT.getVectorElementType();
9609     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9610     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9611     if (PartVTBitSize % ValueVTBitSize == 0) {
9612       EVT SameEltTypeVT = ValueVT;
9613       // If the element types are different, convert it to the same element type
9614       // of PartVT.
9615       if (ValueEltVT != PartEltVT) {
9616         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9617         assert(Count != 0 && "The number of element should not be zero.");
9618         SameEltTypeVT =
9619             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9620       }
9621       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9622                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9623       if (ValueEltVT != PartEltVT)
9624         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9625       return Val;
9626     }
9627   }
9628   return SDValue();
9629 }
9630 
9631 #define GET_REGISTER_MATCHER
9632 #include "RISCVGenAsmMatcher.inc"
9633 
9634 Register
9635 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9636                                        const MachineFunction &MF) const {
9637   Register Reg = MatchRegisterAltName(RegName);
9638   if (Reg == RISCV::NoRegister)
9639     Reg = MatchRegisterName(RegName);
9640   if (Reg == RISCV::NoRegister)
9641     report_fatal_error(
9642         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9643   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9644   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9645     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9646                              StringRef(RegName) + "\"."));
9647   return Reg;
9648 }
9649 
9650 namespace llvm {
9651 namespace RISCVVIntrinsicsTable {
9652 
9653 #define GET_RISCVVIntrinsicsTable_IMPL
9654 #include "RISCVGenSearchableTables.inc"
9655 
9656 } // namespace RISCVVIntrinsicsTable
9657 
9658 } // namespace llvm
9659