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   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4745 
4746   MVT VT = Val.getSimpleValueType();
4747   MVT XLenVT = Subtarget.getXLenVT();
4748 
4749   MVT ContainerVT = VT;
4750   if (VT.isFixedLengthVector()) {
4751     ContainerVT = getContainerForFixedLengthVector(VT);
4752 
4753     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4754     if (!IsUnmasked) {
4755       MVT MaskVT =
4756           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4757       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4758     }
4759   }
4760 
4761   if (!VL)
4762     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4763 
4764   unsigned IntID =
4765       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4766   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4767   Ops.push_back(Val);
4768   Ops.push_back(BasePtr);
4769   if (!IsUnmasked)
4770     Ops.push_back(Mask);
4771   Ops.push_back(VL);
4772 
4773   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4774                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4775 }
4776 
4777 SDValue
4778 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4779                                                       SelectionDAG &DAG) const {
4780   MVT InVT = Op.getOperand(0).getSimpleValueType();
4781   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4782 
4783   MVT VT = Op.getSimpleValueType();
4784 
4785   SDValue Op1 =
4786       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4787   SDValue Op2 =
4788       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4789 
4790   SDLoc DL(Op);
4791   SDValue VL =
4792       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4793 
4794   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4795   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4796 
4797   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4798                             Op.getOperand(2), Mask, VL);
4799 
4800   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4801 }
4802 
4803 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4804     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4805   MVT VT = Op.getSimpleValueType();
4806 
4807   if (VT.getVectorElementType() == MVT::i1)
4808     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4809 
4810   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4811 }
4812 
4813 SDValue
4814 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4815                                                       SelectionDAG &DAG) const {
4816   unsigned Opc;
4817   switch (Op.getOpcode()) {
4818   default: llvm_unreachable("Unexpected opcode!");
4819   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4820   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4821   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4822   }
4823 
4824   return lowerToScalableOp(Op, DAG, Opc);
4825 }
4826 
4827 // Lower vector ABS to smax(X, sub(0, X)).
4828 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4829   SDLoc DL(Op);
4830   MVT VT = Op.getSimpleValueType();
4831   SDValue X = Op.getOperand(0);
4832 
4833   assert(VT.isFixedLengthVector() && "Unexpected type");
4834 
4835   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4836   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
4837 
4838   SDValue Mask, VL;
4839   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4840 
4841   SDValue SplatZero =
4842       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4843                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4844   SDValue NegX =
4845       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
4846   SDValue Max =
4847       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
4848 
4849   return convertFromScalableVector(VT, Max, DAG, Subtarget);
4850 }
4851 
4852 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
4853     SDValue Op, SelectionDAG &DAG) const {
4854   SDLoc DL(Op);
4855   MVT VT = Op.getSimpleValueType();
4856   SDValue Mag = Op.getOperand(0);
4857   SDValue Sign = Op.getOperand(1);
4858   assert(Mag.getValueType() == Sign.getValueType() &&
4859          "Can only handle COPYSIGN with matching types.");
4860 
4861   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4862   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
4863   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
4864 
4865   SDValue Mask, VL;
4866   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4867 
4868   SDValue CopySign =
4869       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
4870 
4871   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
4872 }
4873 
4874 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
4875     SDValue Op, SelectionDAG &DAG) const {
4876   MVT VT = Op.getSimpleValueType();
4877   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4878 
4879   MVT I1ContainerVT =
4880       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4881 
4882   SDValue CC =
4883       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
4884   SDValue Op1 =
4885       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4886   SDValue Op2 =
4887       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
4888 
4889   SDLoc DL(Op);
4890   SDValue Mask, VL;
4891   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4892 
4893   SDValue Select =
4894       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
4895 
4896   return convertFromScalableVector(VT, Select, DAG, Subtarget);
4897 }
4898 
4899 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
4900                                                unsigned NewOpc,
4901                                                bool HasMask) const {
4902   MVT VT = Op.getSimpleValueType();
4903   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4904 
4905   // Create list of operands by converting existing ones to scalable types.
4906   SmallVector<SDValue, 6> Ops;
4907   for (const SDValue &V : Op->op_values()) {
4908     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4909 
4910     // Pass through non-vector operands.
4911     if (!V.getValueType().isVector()) {
4912       Ops.push_back(V);
4913       continue;
4914     }
4915 
4916     // "cast" fixed length vector to a scalable vector.
4917     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
4918            "Only fixed length vectors are supported!");
4919     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4920   }
4921 
4922   SDLoc DL(Op);
4923   SDValue Mask, VL;
4924   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4925   if (HasMask)
4926     Ops.push_back(Mask);
4927   Ops.push_back(VL);
4928 
4929   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
4930   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
4931 }
4932 
4933 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
4934 // * Operands of each node are assumed to be in the same order.
4935 // * The EVL operand is promoted from i32 to i64 on RV64.
4936 // * Fixed-length vectors are converted to their scalable-vector container
4937 //   types.
4938 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
4939                                        unsigned RISCVISDOpc) const {
4940   SDLoc DL(Op);
4941   MVT VT = Op.getSimpleValueType();
4942   SmallVector<SDValue, 4> Ops;
4943 
4944   for (const auto &OpIdx : enumerate(Op->ops())) {
4945     SDValue V = OpIdx.value();
4946     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4947     // Pass through operands which aren't fixed-length vectors.
4948     if (!V.getValueType().isFixedLengthVector()) {
4949       Ops.push_back(V);
4950       continue;
4951     }
4952     // "cast" fixed length vector to a scalable vector.
4953     MVT OpVT = V.getSimpleValueType();
4954     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
4955     assert(useRVVForFixedLengthVectorVT(OpVT) &&
4956            "Only fixed length vectors are supported!");
4957     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4958   }
4959 
4960   if (!VT.isFixedLengthVector())
4961     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
4962 
4963   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4964 
4965   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
4966 
4967   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
4968 }
4969 
4970 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
4971 // matched to a RVV indexed load. The RVV indexed load instructions only
4972 // support the "unsigned unscaled" addressing mode; indices are implicitly
4973 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
4974 // signed or scaled indexing is extended to the XLEN value type and scaled
4975 // accordingly.
4976 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
4977                                                SelectionDAG &DAG) const {
4978   SDLoc DL(Op);
4979   MVT VT = Op.getSimpleValueType();
4980 
4981   const auto *MemSD = cast<MemSDNode>(Op.getNode());
4982   EVT MemVT = MemSD->getMemoryVT();
4983   MachineMemOperand *MMO = MemSD->getMemOperand();
4984   SDValue Chain = MemSD->getChain();
4985   SDValue BasePtr = MemSD->getBasePtr();
4986 
4987   ISD::LoadExtType LoadExtType;
4988   SDValue Index, Mask, PassThru, VL;
4989 
4990   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
4991     Index = VPGN->getIndex();
4992     Mask = VPGN->getMask();
4993     PassThru = DAG.getUNDEF(VT);
4994     VL = VPGN->getVectorLength();
4995     // VP doesn't support extending loads.
4996     LoadExtType = ISD::NON_EXTLOAD;
4997   } else {
4998     // Else it must be a MGATHER.
4999     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5000     Index = MGN->getIndex();
5001     Mask = MGN->getMask();
5002     PassThru = MGN->getPassThru();
5003     LoadExtType = MGN->getExtensionType();
5004   }
5005 
5006   MVT IndexVT = Index.getSimpleValueType();
5007   MVT XLenVT = Subtarget.getXLenVT();
5008 
5009   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5010          "Unexpected VTs!");
5011   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5012   // Targets have to explicitly opt-in for extending vector loads.
5013   assert(LoadExtType == ISD::NON_EXTLOAD &&
5014          "Unexpected extending MGATHER/VP_GATHER");
5015   (void)LoadExtType;
5016 
5017   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5018   // the selection of the masked intrinsics doesn't do this for us.
5019   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5020 
5021   MVT ContainerVT = VT;
5022   if (VT.isFixedLengthVector()) {
5023     // We need to use the larger of the result and index type to determine the
5024     // scalable type to use so we don't increase LMUL for any operand/result.
5025     if (VT.bitsGE(IndexVT)) {
5026       ContainerVT = getContainerForFixedLengthVector(VT);
5027       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5028                                  ContainerVT.getVectorElementCount());
5029     } else {
5030       IndexVT = getContainerForFixedLengthVector(IndexVT);
5031       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5032                                      IndexVT.getVectorElementCount());
5033     }
5034 
5035     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5036 
5037     if (!IsUnmasked) {
5038       MVT MaskVT =
5039           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5040       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5041       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5042     }
5043   }
5044 
5045   if (!VL)
5046     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5047 
5048   unsigned IntID =
5049       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5050   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5051   if (!IsUnmasked)
5052     Ops.push_back(PassThru);
5053   Ops.push_back(BasePtr);
5054   Ops.push_back(Index);
5055   if (!IsUnmasked)
5056     Ops.push_back(Mask);
5057   Ops.push_back(VL);
5058 
5059   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5060   SDValue Result =
5061       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5062   Chain = Result.getValue(1);
5063 
5064   if (VT.isFixedLengthVector())
5065     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5066 
5067   return DAG.getMergeValues({Result, Chain}, DL);
5068 }
5069 
5070 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5071 // matched to a RVV indexed store. The RVV indexed store instructions only
5072 // support the "unsigned unscaled" addressing mode; indices are implicitly
5073 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5074 // signed or scaled indexing is extended to the XLEN value type and scaled
5075 // accordingly.
5076 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5077                                                 SelectionDAG &DAG) const {
5078   SDLoc DL(Op);
5079   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5080   EVT MemVT = MemSD->getMemoryVT();
5081   MachineMemOperand *MMO = MemSD->getMemOperand();
5082   SDValue Chain = MemSD->getChain();
5083   SDValue BasePtr = MemSD->getBasePtr();
5084 
5085   bool IsTruncatingStore = false;
5086   SDValue Index, Mask, Val, VL;
5087 
5088   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5089     Index = VPSN->getIndex();
5090     Mask = VPSN->getMask();
5091     Val = VPSN->getValue();
5092     VL = VPSN->getVectorLength();
5093     // VP doesn't support truncating stores.
5094     IsTruncatingStore = false;
5095   } else {
5096     // Else it must be a MSCATTER.
5097     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5098     Index = MSN->getIndex();
5099     Mask = MSN->getMask();
5100     Val = MSN->getValue();
5101     IsTruncatingStore = MSN->isTruncatingStore();
5102   }
5103 
5104   MVT VT = Val.getSimpleValueType();
5105   MVT IndexVT = Index.getSimpleValueType();
5106   MVT XLenVT = Subtarget.getXLenVT();
5107 
5108   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5109          "Unexpected VTs!");
5110   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5111   // Targets have to explicitly opt-in for extending vector loads and
5112   // truncating vector stores.
5113   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5114   (void)IsTruncatingStore;
5115 
5116   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5117   // the selection of the masked intrinsics doesn't do this for us.
5118   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5119 
5120   MVT ContainerVT = VT;
5121   if (VT.isFixedLengthVector()) {
5122     // We need to use the larger of the value and index type to determine the
5123     // scalable type to use so we don't increase LMUL for any operand/result.
5124     if (VT.bitsGE(IndexVT)) {
5125       ContainerVT = getContainerForFixedLengthVector(VT);
5126       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5127                                  ContainerVT.getVectorElementCount());
5128     } else {
5129       IndexVT = getContainerForFixedLengthVector(IndexVT);
5130       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5131                                      IndexVT.getVectorElementCount());
5132     }
5133 
5134     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5135     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5136 
5137     if (!IsUnmasked) {
5138       MVT MaskVT =
5139           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5140       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5141     }
5142   }
5143 
5144   if (!VL)
5145     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5146 
5147   unsigned IntID =
5148       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5149   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5150   Ops.push_back(Val);
5151   Ops.push_back(BasePtr);
5152   Ops.push_back(Index);
5153   if (!IsUnmasked)
5154     Ops.push_back(Mask);
5155   Ops.push_back(VL);
5156 
5157   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5158                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5159 }
5160 
5161 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5162                                                SelectionDAG &DAG) const {
5163   const MVT XLenVT = Subtarget.getXLenVT();
5164   SDLoc DL(Op);
5165   SDValue Chain = Op->getOperand(0);
5166   SDValue SysRegNo = DAG.getConstant(
5167       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5168   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5169   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5170 
5171   // Encoding used for rounding mode in RISCV differs from that used in
5172   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5173   // table, which consists of a sequence of 4-bit fields, each representing
5174   // corresponding FLT_ROUNDS mode.
5175   static const int Table =
5176       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5177       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5178       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5179       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5180       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5181 
5182   SDValue Shift =
5183       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5184   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5185                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5186   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5187                                DAG.getConstant(7, DL, XLenVT));
5188 
5189   return DAG.getMergeValues({Masked, Chain}, DL);
5190 }
5191 
5192 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5193                                                SelectionDAG &DAG) const {
5194   const MVT XLenVT = Subtarget.getXLenVT();
5195   SDLoc DL(Op);
5196   SDValue Chain = Op->getOperand(0);
5197   SDValue RMValue = Op->getOperand(1);
5198   SDValue SysRegNo = DAG.getConstant(
5199       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5200 
5201   // Encoding used for rounding mode in RISCV differs from that used in
5202   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5203   // a table, which consists of a sequence of 4-bit fields, each representing
5204   // corresponding RISCV mode.
5205   static const unsigned Table =
5206       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5207       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5208       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5209       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5210       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5211 
5212   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5213                               DAG.getConstant(2, DL, XLenVT));
5214   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5215                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5216   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5217                         DAG.getConstant(0x7, DL, XLenVT));
5218   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5219                      RMValue);
5220 }
5221 
5222 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5223 // form of the given Opcode.
5224 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5225   switch (Opcode) {
5226   default:
5227     llvm_unreachable("Unexpected opcode");
5228   case ISD::SHL:
5229     return RISCVISD::SLLW;
5230   case ISD::SRA:
5231     return RISCVISD::SRAW;
5232   case ISD::SRL:
5233     return RISCVISD::SRLW;
5234   case ISD::SDIV:
5235     return RISCVISD::DIVW;
5236   case ISD::UDIV:
5237     return RISCVISD::DIVUW;
5238   case ISD::UREM:
5239     return RISCVISD::REMUW;
5240   case ISD::ROTL:
5241     return RISCVISD::ROLW;
5242   case ISD::ROTR:
5243     return RISCVISD::RORW;
5244   case RISCVISD::GREV:
5245     return RISCVISD::GREVW;
5246   case RISCVISD::GORC:
5247     return RISCVISD::GORCW;
5248   }
5249 }
5250 
5251 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5252 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5253 // otherwise be promoted to i64, making it difficult to select the
5254 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5255 // type i8/i16/i32 is lost.
5256 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5257                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5258   SDLoc DL(N);
5259   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5260   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5261   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5262   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5263   // ReplaceNodeResults requires we maintain the same type for the return value.
5264   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5265 }
5266 
5267 // Converts the given 32-bit operation to a i64 operation with signed extension
5268 // semantic to reduce the signed extension instructions.
5269 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5270   SDLoc DL(N);
5271   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5272   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5273   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5274   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5275                                DAG.getValueType(MVT::i32));
5276   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5277 }
5278 
5279 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5280                                              SmallVectorImpl<SDValue> &Results,
5281                                              SelectionDAG &DAG) const {
5282   SDLoc DL(N);
5283   switch (N->getOpcode()) {
5284   default:
5285     llvm_unreachable("Don't know how to custom type legalize this operation!");
5286   case ISD::STRICT_FP_TO_SINT:
5287   case ISD::STRICT_FP_TO_UINT:
5288   case ISD::FP_TO_SINT:
5289   case ISD::FP_TO_UINT: {
5290     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5291            "Unexpected custom legalisation");
5292     bool IsStrict = N->isStrictFPOpcode();
5293     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5294                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5295     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5296     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5297         TargetLowering::TypeSoftenFloat) {
5298       // FIXME: Support strict FP.
5299       if (IsStrict)
5300         return;
5301       if (!isTypeLegal(Op0.getValueType()))
5302         return;
5303       unsigned Opc =
5304           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5305       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5306       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5307       return;
5308     }
5309     // If the FP type needs to be softened, emit a library call using the 'si'
5310     // version. If we left it to default legalization we'd end up with 'di'. If
5311     // the FP type doesn't need to be softened just let generic type
5312     // legalization promote the result type.
5313     RTLIB::Libcall LC;
5314     if (IsSigned)
5315       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5316     else
5317       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5318     MakeLibCallOptions CallOptions;
5319     EVT OpVT = Op0.getValueType();
5320     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5321     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5322     SDValue Result;
5323     std::tie(Result, Chain) =
5324         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5325     Results.push_back(Result);
5326     if (IsStrict)
5327       Results.push_back(Chain);
5328     break;
5329   }
5330   case ISD::READCYCLECOUNTER: {
5331     assert(!Subtarget.is64Bit() &&
5332            "READCYCLECOUNTER only has custom type legalization on riscv32");
5333 
5334     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5335     SDValue RCW =
5336         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5337 
5338     Results.push_back(
5339         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5340     Results.push_back(RCW.getValue(2));
5341     break;
5342   }
5343   case ISD::MUL: {
5344     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5345     unsigned XLen = Subtarget.getXLen();
5346     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5347     if (Size > XLen) {
5348       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5349       SDValue LHS = N->getOperand(0);
5350       SDValue RHS = N->getOperand(1);
5351       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5352 
5353       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5354       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5355       // We need exactly one side to be unsigned.
5356       if (LHSIsU == RHSIsU)
5357         return;
5358 
5359       auto MakeMULPair = [&](SDValue S, SDValue U) {
5360         MVT XLenVT = Subtarget.getXLenVT();
5361         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5362         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5363         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5364         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5365         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5366       };
5367 
5368       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5369       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5370 
5371       // The other operand should be signed, but still prefer MULH when
5372       // possible.
5373       if (RHSIsU && LHSIsS && !RHSIsS)
5374         Results.push_back(MakeMULPair(LHS, RHS));
5375       else if (LHSIsU && RHSIsS && !LHSIsS)
5376         Results.push_back(MakeMULPair(RHS, LHS));
5377 
5378       return;
5379     }
5380     LLVM_FALLTHROUGH;
5381   }
5382   case ISD::ADD:
5383   case ISD::SUB:
5384     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5385            "Unexpected custom legalisation");
5386     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5387     break;
5388   case ISD::SHL:
5389   case ISD::SRA:
5390   case ISD::SRL:
5391     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5392            "Unexpected custom legalisation");
5393     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5394       Results.push_back(customLegalizeToWOp(N, DAG));
5395       break;
5396     }
5397 
5398     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5399     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5400     // shift amount.
5401     if (N->getOpcode() == ISD::SHL) {
5402       SDLoc DL(N);
5403       SDValue NewOp0 =
5404           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5405       SDValue NewOp1 =
5406           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5407       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5408       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5409                                    DAG.getValueType(MVT::i32));
5410       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5411     }
5412 
5413     break;
5414   case ISD::ROTL:
5415   case ISD::ROTR:
5416     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5417            "Unexpected custom legalisation");
5418     Results.push_back(customLegalizeToWOp(N, DAG));
5419     break;
5420   case ISD::CTTZ:
5421   case ISD::CTTZ_ZERO_UNDEF:
5422   case ISD::CTLZ:
5423   case ISD::CTLZ_ZERO_UNDEF: {
5424     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5425            "Unexpected custom legalisation");
5426 
5427     SDValue NewOp0 =
5428         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5429     bool IsCTZ =
5430         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5431     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5432     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5433     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5434     return;
5435   }
5436   case ISD::SDIV:
5437   case ISD::UDIV:
5438   case ISD::UREM: {
5439     MVT VT = N->getSimpleValueType(0);
5440     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5441            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5442            "Unexpected custom legalisation");
5443     // Don't promote division/remainder by constant since we should expand those
5444     // to multiply by magic constant.
5445     // FIXME: What if the expansion is disabled for minsize.
5446     if (N->getOperand(1).getOpcode() == ISD::Constant)
5447       return;
5448 
5449     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5450     // the upper 32 bits. For other types we need to sign or zero extend
5451     // based on the opcode.
5452     unsigned ExtOpc = ISD::ANY_EXTEND;
5453     if (VT != MVT::i32)
5454       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5455                                            : ISD::ZERO_EXTEND;
5456 
5457     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5458     break;
5459   }
5460   case ISD::UADDO:
5461   case ISD::USUBO: {
5462     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5463            "Unexpected custom legalisation");
5464     bool IsAdd = N->getOpcode() == ISD::UADDO;
5465     // Create an ADDW or SUBW.
5466     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5467     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5468     SDValue Res =
5469         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5470     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5471                       DAG.getValueType(MVT::i32));
5472 
5473     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5474     // Since the inputs are sign extended from i32, this is equivalent to
5475     // comparing the lower 32 bits.
5476     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5477     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5478                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5479 
5480     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5481     Results.push_back(Overflow);
5482     return;
5483   }
5484   case ISD::UADDSAT:
5485   case ISD::USUBSAT: {
5486     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5487            "Unexpected custom legalisation");
5488     if (Subtarget.hasStdExtZbb()) {
5489       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5490       // sign extend allows overflow of the lower 32 bits to be detected on
5491       // the promoted size.
5492       SDValue LHS =
5493           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5494       SDValue RHS =
5495           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5496       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5497       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5498       return;
5499     }
5500 
5501     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5502     // promotion for UADDO/USUBO.
5503     Results.push_back(expandAddSubSat(N, DAG));
5504     return;
5505   }
5506   case ISD::BITCAST: {
5507     EVT VT = N->getValueType(0);
5508     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5509     SDValue Op0 = N->getOperand(0);
5510     EVT Op0VT = Op0.getValueType();
5511     MVT XLenVT = Subtarget.getXLenVT();
5512     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5513       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5514       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5515     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5516                Subtarget.hasStdExtF()) {
5517       SDValue FPConv =
5518           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5519       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5520     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5521                isTypeLegal(Op0VT)) {
5522       // Custom-legalize bitcasts from fixed-length vector types to illegal
5523       // scalar types in order to improve codegen. Bitcast the vector to a
5524       // one-element vector type whose element type is the same as the result
5525       // type, and extract the first element.
5526       LLVMContext &Context = *DAG.getContext();
5527       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5528       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5529                                     DAG.getConstant(0, DL, XLenVT)));
5530     }
5531     break;
5532   }
5533   case RISCVISD::GREV:
5534   case RISCVISD::GORC: {
5535     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5536            "Unexpected custom legalisation");
5537     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5538     // This is similar to customLegalizeToWOp, except that we pass the second
5539     // operand (a TargetConstant) straight through: it is already of type
5540     // XLenVT.
5541     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5542     SDValue NewOp0 =
5543         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5544     SDValue NewOp1 =
5545         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5546     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5547     // ReplaceNodeResults requires we maintain the same type for the return
5548     // value.
5549     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5550     break;
5551   }
5552   case RISCVISD::SHFL: {
5553     // There is no SHFLIW instruction, but we can just promote the operation.
5554     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5555            "Unexpected custom legalisation");
5556     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5557     SDValue NewOp0 =
5558         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5559     SDValue NewOp1 =
5560         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5561     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5562     // ReplaceNodeResults requires we maintain the same type for the return
5563     // value.
5564     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5565     break;
5566   }
5567   case ISD::BSWAP:
5568   case ISD::BITREVERSE: {
5569     MVT VT = N->getSimpleValueType(0);
5570     MVT XLenVT = Subtarget.getXLenVT();
5571     assert((VT == MVT::i8 || VT == MVT::i16 ||
5572             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5573            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5574     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5575     unsigned Imm = VT.getSizeInBits() - 1;
5576     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5577     if (N->getOpcode() == ISD::BSWAP)
5578       Imm &= ~0x7U;
5579     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5580     SDValue GREVI =
5581         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5582     // ReplaceNodeResults requires we maintain the same type for the return
5583     // value.
5584     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5585     break;
5586   }
5587   case ISD::FSHL:
5588   case ISD::FSHR: {
5589     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5590            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5591     SDValue NewOp0 =
5592         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5593     SDValue NewOp1 =
5594         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5595     SDValue NewOp2 =
5596         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5597     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5598     // Mask the shift amount to 5 bits.
5599     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5600                          DAG.getConstant(0x1f, DL, MVT::i64));
5601     unsigned Opc =
5602         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5603     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5604     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5605     break;
5606   }
5607   case ISD::EXTRACT_VECTOR_ELT: {
5608     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5609     // type is illegal (currently only vXi64 RV32).
5610     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5611     // transferred to the destination register. We issue two of these from the
5612     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5613     // first element.
5614     SDValue Vec = N->getOperand(0);
5615     SDValue Idx = N->getOperand(1);
5616 
5617     // The vector type hasn't been legalized yet so we can't issue target
5618     // specific nodes if it needs legalization.
5619     // FIXME: We would manually legalize if it's important.
5620     if (!isTypeLegal(Vec.getValueType()))
5621       return;
5622 
5623     MVT VecVT = Vec.getSimpleValueType();
5624 
5625     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5626            VecVT.getVectorElementType() == MVT::i64 &&
5627            "Unexpected EXTRACT_VECTOR_ELT legalization");
5628 
5629     // If this is a fixed vector, we need to convert it to a scalable vector.
5630     MVT ContainerVT = VecVT;
5631     if (VecVT.isFixedLengthVector()) {
5632       ContainerVT = getContainerForFixedLengthVector(VecVT);
5633       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5634     }
5635 
5636     MVT XLenVT = Subtarget.getXLenVT();
5637 
5638     // Use a VL of 1 to avoid processing more elements than we need.
5639     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5640     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5641     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5642 
5643     // Unless the index is known to be 0, we must slide the vector down to get
5644     // the desired element into index 0.
5645     if (!isNullConstant(Idx)) {
5646       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5647                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5648     }
5649 
5650     // Extract the lower XLEN bits of the correct vector element.
5651     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5652 
5653     // To extract the upper XLEN bits of the vector element, shift the first
5654     // element right by 32 bits and re-extract the lower XLEN bits.
5655     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5656                                      DAG.getConstant(32, DL, XLenVT), VL);
5657     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5658                                  ThirtyTwoV, Mask, VL);
5659 
5660     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5661 
5662     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5663     break;
5664   }
5665   case ISD::INTRINSIC_WO_CHAIN: {
5666     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5667     switch (IntNo) {
5668     default:
5669       llvm_unreachable(
5670           "Don't know how to custom type legalize this intrinsic!");
5671     case Intrinsic::riscv_orc_b: {
5672       // Lower to the GORCI encoding for orc.b with the operand extended.
5673       SDValue NewOp =
5674           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5675       // If Zbp is enabled, use GORCIW which will sign extend the result.
5676       unsigned Opc =
5677           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5678       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5679                                 DAG.getConstant(7, DL, MVT::i64));
5680       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5681       return;
5682     }
5683     case Intrinsic::riscv_grev:
5684     case Intrinsic::riscv_gorc: {
5685       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5686              "Unexpected custom legalisation");
5687       SDValue NewOp1 =
5688           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5689       SDValue NewOp2 =
5690           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5691       unsigned Opc =
5692           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5693       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5694       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5695       break;
5696     }
5697     case Intrinsic::riscv_shfl:
5698     case Intrinsic::riscv_unshfl: {
5699       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5700              "Unexpected custom legalisation");
5701       SDValue NewOp1 =
5702           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5703       SDValue NewOp2 =
5704           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5705       unsigned Opc =
5706           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5707       if (isa<ConstantSDNode>(N->getOperand(2))) {
5708         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5709                              DAG.getConstant(0xf, DL, MVT::i64));
5710         Opc =
5711             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5712       }
5713       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5714       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5715       break;
5716     }
5717     case Intrinsic::riscv_bcompress:
5718     case Intrinsic::riscv_bdecompress: {
5719       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5720              "Unexpected custom legalisation");
5721       SDValue NewOp1 =
5722           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5723       SDValue NewOp2 =
5724           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5725       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5726                          ? RISCVISD::BCOMPRESSW
5727                          : RISCVISD::BDECOMPRESSW;
5728       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5729       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5730       break;
5731     }
5732     case Intrinsic::riscv_vmv_x_s: {
5733       EVT VT = N->getValueType(0);
5734       MVT XLenVT = Subtarget.getXLenVT();
5735       if (VT.bitsLT(XLenVT)) {
5736         // Simple case just extract using vmv.x.s and truncate.
5737         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5738                                       Subtarget.getXLenVT(), N->getOperand(1));
5739         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5740         return;
5741       }
5742 
5743       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5744              "Unexpected custom legalization");
5745 
5746       // We need to do the move in two steps.
5747       SDValue Vec = N->getOperand(1);
5748       MVT VecVT = Vec.getSimpleValueType();
5749 
5750       // First extract the lower XLEN bits of the element.
5751       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5752 
5753       // To extract the upper XLEN bits of the vector element, shift the first
5754       // element right by 32 bits and re-extract the lower XLEN bits.
5755       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5756       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5757       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5758       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5759                                        DAG.getConstant(32, DL, XLenVT), VL);
5760       SDValue LShr32 =
5761           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5762       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5763 
5764       Results.push_back(
5765           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5766       break;
5767     }
5768     }
5769     break;
5770   }
5771   case ISD::VECREDUCE_ADD:
5772   case ISD::VECREDUCE_AND:
5773   case ISD::VECREDUCE_OR:
5774   case ISD::VECREDUCE_XOR:
5775   case ISD::VECREDUCE_SMAX:
5776   case ISD::VECREDUCE_UMAX:
5777   case ISD::VECREDUCE_SMIN:
5778   case ISD::VECREDUCE_UMIN:
5779     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5780       Results.push_back(V);
5781     break;
5782   case ISD::FLT_ROUNDS_: {
5783     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5784     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5785     Results.push_back(Res.getValue(0));
5786     Results.push_back(Res.getValue(1));
5787     break;
5788   }
5789   }
5790 }
5791 
5792 // A structure to hold one of the bit-manipulation patterns below. Together, a
5793 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5794 //   (or (and (shl x, 1), 0xAAAAAAAA),
5795 //       (and (srl x, 1), 0x55555555))
5796 struct RISCVBitmanipPat {
5797   SDValue Op;
5798   unsigned ShAmt;
5799   bool IsSHL;
5800 
5801   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5802     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5803   }
5804 };
5805 
5806 // Matches patterns of the form
5807 //   (and (shl x, C2), (C1 << C2))
5808 //   (and (srl x, C2), C1)
5809 //   (shl (and x, C1), C2)
5810 //   (srl (and x, (C1 << C2)), C2)
5811 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5812 // The expected masks for each shift amount are specified in BitmanipMasks where
5813 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5814 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5815 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5816 // XLen is 64.
5817 static Optional<RISCVBitmanipPat>
5818 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5819   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5820          "Unexpected number of masks");
5821   Optional<uint64_t> Mask;
5822   // Optionally consume a mask around the shift operation.
5823   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5824     Mask = Op.getConstantOperandVal(1);
5825     Op = Op.getOperand(0);
5826   }
5827   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5828     return None;
5829   bool IsSHL = Op.getOpcode() == ISD::SHL;
5830 
5831   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5832     return None;
5833   uint64_t ShAmt = Op.getConstantOperandVal(1);
5834 
5835   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5836   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
5837     return None;
5838   // If we don't have enough masks for 64 bit, then we must be trying to
5839   // match SHFL so we're only allowed to shift 1/4 of the width.
5840   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
5841     return None;
5842 
5843   SDValue Src = Op.getOperand(0);
5844 
5845   // The expected mask is shifted left when the AND is found around SHL
5846   // patterns.
5847   //   ((x >> 1) & 0x55555555)
5848   //   ((x << 1) & 0xAAAAAAAA)
5849   bool SHLExpMask = IsSHL;
5850 
5851   if (!Mask) {
5852     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
5853     // the mask is all ones: consume that now.
5854     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
5855       Mask = Src.getConstantOperandVal(1);
5856       Src = Src.getOperand(0);
5857       // The expected mask is now in fact shifted left for SRL, so reverse the
5858       // decision.
5859       //   ((x & 0xAAAAAAAA) >> 1)
5860       //   ((x & 0x55555555) << 1)
5861       SHLExpMask = !SHLExpMask;
5862     } else {
5863       // Use a default shifted mask of all-ones if there's no AND, truncated
5864       // down to the expected width. This simplifies the logic later on.
5865       Mask = maskTrailingOnes<uint64_t>(Width);
5866       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
5867     }
5868   }
5869 
5870   unsigned MaskIdx = Log2_32(ShAmt);
5871   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5872 
5873   if (SHLExpMask)
5874     ExpMask <<= ShAmt;
5875 
5876   if (Mask != ExpMask)
5877     return None;
5878 
5879   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
5880 }
5881 
5882 // Matches any of the following bit-manipulation patterns:
5883 //   (and (shl x, 1), (0x55555555 << 1))
5884 //   (and (srl x, 1), 0x55555555)
5885 //   (shl (and x, 0x55555555), 1)
5886 //   (srl (and x, (0x55555555 << 1)), 1)
5887 // where the shift amount and mask may vary thus:
5888 //   [1]  = 0x55555555 / 0xAAAAAAAA
5889 //   [2]  = 0x33333333 / 0xCCCCCCCC
5890 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
5891 //   [8]  = 0x00FF00FF / 0xFF00FF00
5892 //   [16] = 0x0000FFFF / 0xFFFFFFFF
5893 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
5894 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
5895   // These are the unshifted masks which we use to match bit-manipulation
5896   // patterns. They may be shifted left in certain circumstances.
5897   static const uint64_t BitmanipMasks[] = {
5898       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
5899       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
5900 
5901   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5902 }
5903 
5904 // Match the following pattern as a GREVI(W) operation
5905 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
5906 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
5907                                const RISCVSubtarget &Subtarget) {
5908   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5909   EVT VT = Op.getValueType();
5910 
5911   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5912     auto LHS = matchGREVIPat(Op.getOperand(0));
5913     auto RHS = matchGREVIPat(Op.getOperand(1));
5914     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
5915       SDLoc DL(Op);
5916       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
5917                          DAG.getConstant(LHS->ShAmt, DL, VT));
5918     }
5919   }
5920   return SDValue();
5921 }
5922 
5923 // Matches any the following pattern as a GORCI(W) operation
5924 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
5925 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
5926 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
5927 // Note that with the variant of 3.,
5928 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
5929 // the inner pattern will first be matched as GREVI and then the outer
5930 // pattern will be matched to GORC via the first rule above.
5931 // 4.  (or (rotl/rotr x, bitwidth/2), x)
5932 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
5933                                const RISCVSubtarget &Subtarget) {
5934   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5935   EVT VT = Op.getValueType();
5936 
5937   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5938     SDLoc DL(Op);
5939     SDValue Op0 = Op.getOperand(0);
5940     SDValue Op1 = Op.getOperand(1);
5941 
5942     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
5943       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
5944           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
5945           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
5946         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
5947       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
5948       if ((Reverse.getOpcode() == ISD::ROTL ||
5949            Reverse.getOpcode() == ISD::ROTR) &&
5950           Reverse.getOperand(0) == X &&
5951           isa<ConstantSDNode>(Reverse.getOperand(1))) {
5952         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
5953         if (RotAmt == (VT.getSizeInBits() / 2))
5954           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
5955                              DAG.getConstant(RotAmt, DL, VT));
5956       }
5957       return SDValue();
5958     };
5959 
5960     // Check for either commutable permutation of (or (GREVI x, shamt), x)
5961     if (SDValue V = MatchOROfReverse(Op0, Op1))
5962       return V;
5963     if (SDValue V = MatchOROfReverse(Op1, Op0))
5964       return V;
5965 
5966     // OR is commutable so canonicalize its OR operand to the left
5967     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
5968       std::swap(Op0, Op1);
5969     if (Op0.getOpcode() != ISD::OR)
5970       return SDValue();
5971     SDValue OrOp0 = Op0.getOperand(0);
5972     SDValue OrOp1 = Op0.getOperand(1);
5973     auto LHS = matchGREVIPat(OrOp0);
5974     // OR is commutable so swap the operands and try again: x might have been
5975     // on the left
5976     if (!LHS) {
5977       std::swap(OrOp0, OrOp1);
5978       LHS = matchGREVIPat(OrOp0);
5979     }
5980     auto RHS = matchGREVIPat(Op1);
5981     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
5982       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
5983                          DAG.getConstant(LHS->ShAmt, DL, VT));
5984     }
5985   }
5986   return SDValue();
5987 }
5988 
5989 // Matches any of the following bit-manipulation patterns:
5990 //   (and (shl x, 1), (0x22222222 << 1))
5991 //   (and (srl x, 1), 0x22222222)
5992 //   (shl (and x, 0x22222222), 1)
5993 //   (srl (and x, (0x22222222 << 1)), 1)
5994 // where the shift amount and mask may vary thus:
5995 //   [1]  = 0x22222222 / 0x44444444
5996 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
5997 //   [4]  = 0x00F000F0 / 0x0F000F00
5998 //   [8]  = 0x0000FF00 / 0x00FF0000
5999 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6000 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6001   // These are the unshifted masks which we use to match bit-manipulation
6002   // patterns. They may be shifted left in certain circumstances.
6003   static const uint64_t BitmanipMasks[] = {
6004       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6005       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6006 
6007   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6008 }
6009 
6010 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6011 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6012                                const RISCVSubtarget &Subtarget) {
6013   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6014   EVT VT = Op.getValueType();
6015 
6016   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6017     return SDValue();
6018 
6019   SDValue Op0 = Op.getOperand(0);
6020   SDValue Op1 = Op.getOperand(1);
6021 
6022   // Or is commutable so canonicalize the second OR to the LHS.
6023   if (Op0.getOpcode() != ISD::OR)
6024     std::swap(Op0, Op1);
6025   if (Op0.getOpcode() != ISD::OR)
6026     return SDValue();
6027 
6028   // We found an inner OR, so our operands are the operands of the inner OR
6029   // and the other operand of the outer OR.
6030   SDValue A = Op0.getOperand(0);
6031   SDValue B = Op0.getOperand(1);
6032   SDValue C = Op1;
6033 
6034   auto Match1 = matchSHFLPat(A);
6035   auto Match2 = matchSHFLPat(B);
6036 
6037   // If neither matched, we failed.
6038   if (!Match1 && !Match2)
6039     return SDValue();
6040 
6041   // We had at least one match. if one failed, try the remaining C operand.
6042   if (!Match1) {
6043     std::swap(A, C);
6044     Match1 = matchSHFLPat(A);
6045     if (!Match1)
6046       return SDValue();
6047   } else if (!Match2) {
6048     std::swap(B, C);
6049     Match2 = matchSHFLPat(B);
6050     if (!Match2)
6051       return SDValue();
6052   }
6053   assert(Match1 && Match2);
6054 
6055   // Make sure our matches pair up.
6056   if (!Match1->formsPairWith(*Match2))
6057     return SDValue();
6058 
6059   // All the remains is to make sure C is an AND with the same input, that masks
6060   // out the bits that are being shuffled.
6061   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6062       C.getOperand(0) != Match1->Op)
6063     return SDValue();
6064 
6065   uint64_t Mask = C.getConstantOperandVal(1);
6066 
6067   static const uint64_t BitmanipMasks[] = {
6068       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6069       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6070   };
6071 
6072   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6073   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6074   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6075 
6076   if (Mask != ExpMask)
6077     return SDValue();
6078 
6079   SDLoc DL(Op);
6080   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6081                      DAG.getConstant(Match1->ShAmt, DL, VT));
6082 }
6083 
6084 // Optimize (add (shl x, c0), (shl y, c1)) ->
6085 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6086 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6087                                   const RISCVSubtarget &Subtarget) {
6088   // Perform this optimization only in the zba extension.
6089   if (!Subtarget.hasStdExtZba())
6090     return SDValue();
6091 
6092   // Skip for vector types and larger types.
6093   EVT VT = N->getValueType(0);
6094   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6095     return SDValue();
6096 
6097   // The two operand nodes must be SHL and have no other use.
6098   SDValue N0 = N->getOperand(0);
6099   SDValue N1 = N->getOperand(1);
6100   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6101       !N0->hasOneUse() || !N1->hasOneUse())
6102     return SDValue();
6103 
6104   // Check c0 and c1.
6105   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6106   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6107   if (!N0C || !N1C)
6108     return SDValue();
6109   int64_t C0 = N0C->getSExtValue();
6110   int64_t C1 = N1C->getSExtValue();
6111   if (C0 <= 0 || C1 <= 0)
6112     return SDValue();
6113 
6114   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6115   int64_t Bits = std::min(C0, C1);
6116   int64_t Diff = std::abs(C0 - C1);
6117   if (Diff != 1 && Diff != 2 && Diff != 3)
6118     return SDValue();
6119 
6120   // Build nodes.
6121   SDLoc DL(N);
6122   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6123   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6124   SDValue NA0 =
6125       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6126   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6127   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6128 }
6129 
6130 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6131 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6132 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6133 // not undo itself, but they are redundant.
6134 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6135   SDValue Src = N->getOperand(0);
6136 
6137   if (Src.getOpcode() != N->getOpcode())
6138     return SDValue();
6139 
6140   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6141       !isa<ConstantSDNode>(Src.getOperand(1)))
6142     return SDValue();
6143 
6144   unsigned ShAmt1 = N->getConstantOperandVal(1);
6145   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6146   Src = Src.getOperand(0);
6147 
6148   unsigned CombinedShAmt;
6149   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6150     CombinedShAmt = ShAmt1 | ShAmt2;
6151   else
6152     CombinedShAmt = ShAmt1 ^ ShAmt2;
6153 
6154   if (CombinedShAmt == 0)
6155     return Src;
6156 
6157   SDLoc DL(N);
6158   return DAG.getNode(
6159       N->getOpcode(), DL, N->getValueType(0), Src,
6160       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6161 }
6162 
6163 // Combine a constant select operand into its use:
6164 //
6165 // (and (select cond, -1, c), x)
6166 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6167 // (or  (select cond, 0, c), x)
6168 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6169 // (xor (select cond, 0, c), x)
6170 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6171 // (add (select cond, 0, c), x)
6172 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6173 // (sub x, (select cond, 0, c))
6174 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6175 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6176                                    SelectionDAG &DAG, bool AllOnes) {
6177   EVT VT = N->getValueType(0);
6178 
6179   // Skip vectors.
6180   if (VT.isVector())
6181     return SDValue();
6182 
6183   if ((Slct.getOpcode() != ISD::SELECT &&
6184        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6185       !Slct.hasOneUse())
6186     return SDValue();
6187 
6188   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6189     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6190   };
6191 
6192   bool SwapSelectOps;
6193   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6194   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6195   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6196   SDValue NonConstantVal;
6197   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6198     SwapSelectOps = false;
6199     NonConstantVal = FalseVal;
6200   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6201     SwapSelectOps = true;
6202     NonConstantVal = TrueVal;
6203   } else
6204     return SDValue();
6205 
6206   // Slct is now know to be the desired identity constant when CC is true.
6207   TrueVal = OtherOp;
6208   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6209   // Unless SwapSelectOps says the condition should be false.
6210   if (SwapSelectOps)
6211     std::swap(TrueVal, FalseVal);
6212 
6213   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6214     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6215                        {Slct.getOperand(0), Slct.getOperand(1),
6216                         Slct.getOperand(2), TrueVal, FalseVal});
6217 
6218   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6219                      {Slct.getOperand(0), TrueVal, FalseVal});
6220 }
6221 
6222 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6223 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6224                                               bool AllOnes) {
6225   SDValue N0 = N->getOperand(0);
6226   SDValue N1 = N->getOperand(1);
6227   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6228     return Result;
6229   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6230     return Result;
6231   return SDValue();
6232 }
6233 
6234 // Transform (add (mul x, c0), c1) ->
6235 //           (add (mul (add x, c1/c0), c0), c1%c0).
6236 // if c1/c0 and c1%c0 are simm12, while c1 is not.
6237 // Or transform (add (mul x, c0), c1) ->
6238 //              (mul (add x, c1/c0), c0).
6239 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6240 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6241                                      const RISCVSubtarget &Subtarget) {
6242   // Skip for vector types and larger types.
6243   EVT VT = N->getValueType(0);
6244   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6245     return SDValue();
6246   // The first operand node must be a MUL and has no other use.
6247   SDValue N0 = N->getOperand(0);
6248   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6249     return SDValue();
6250   // Check if c0 and c1 match above conditions.
6251   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6252   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6253   if (!N0C || !N1C)
6254     return SDValue();
6255   int64_t C0 = N0C->getSExtValue();
6256   int64_t C1 = N1C->getSExtValue();
6257   if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) ||
6258       !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0))
6259     return SDValue();
6260   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6261   SDLoc DL(N);
6262   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6263                              DAG.getConstant(C1 / C0, DL, VT));
6264   SDValue New1 =
6265       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6266   if ((C1 % C0) == 0)
6267     return New1;
6268   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT));
6269 }
6270 
6271 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6272                                  const RISCVSubtarget &Subtarget) {
6273   // Transform (add (mul x, c0), c1) ->
6274   //           (add (mul (add x, c1/c0), c0), c1%c0).
6275   // if c1/c0 and c1%c0 are simm12, while c1 is not.
6276   // Or transform (add (mul x, c0), c1) ->
6277   //              (mul (add x, c1/c0), c0).
6278   // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6279   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6280     return V;
6281   // Fold (add (shl x, c0), (shl y, c1)) ->
6282   //      (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6283   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6284     return V;
6285   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6286   //      (select lhs, rhs, cc, x, (add x, y))
6287   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6288 }
6289 
6290 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6291   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6292   //      (select lhs, rhs, cc, x, (sub x, y))
6293   SDValue N0 = N->getOperand(0);
6294   SDValue N1 = N->getOperand(1);
6295   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6296 }
6297 
6298 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6299   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6300   //      (select lhs, rhs, cc, x, (and x, y))
6301   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6302 }
6303 
6304 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6305                                 const RISCVSubtarget &Subtarget) {
6306   if (Subtarget.hasStdExtZbp()) {
6307     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6308       return GREV;
6309     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6310       return GORC;
6311     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6312       return SHFL;
6313   }
6314 
6315   // fold (or (select cond, 0, y), x) ->
6316   //      (select cond, x, (or x, y))
6317   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6318 }
6319 
6320 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6321   // fold (xor (select cond, 0, y), x) ->
6322   //      (select cond, x, (xor x, y))
6323   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6324 }
6325 
6326 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6327 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6328 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6329 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6330 // ADDW/SUBW/MULW.
6331 static SDValue performANY_EXTENDCombine(SDNode *N,
6332                                         TargetLowering::DAGCombinerInfo &DCI,
6333                                         const RISCVSubtarget &Subtarget) {
6334   if (!Subtarget.is64Bit())
6335     return SDValue();
6336 
6337   SelectionDAG &DAG = DCI.DAG;
6338 
6339   SDValue Src = N->getOperand(0);
6340   EVT VT = N->getValueType(0);
6341   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6342     return SDValue();
6343 
6344   // The opcode must be one that can implicitly sign_extend.
6345   // FIXME: Additional opcodes.
6346   switch (Src.getOpcode()) {
6347   default:
6348     return SDValue();
6349   case ISD::MUL:
6350     if (!Subtarget.hasStdExtM())
6351       return SDValue();
6352     LLVM_FALLTHROUGH;
6353   case ISD::ADD:
6354   case ISD::SUB:
6355     break;
6356   }
6357 
6358   // Only handle cases where the result is used by a CopyToReg. That likely
6359   // means the value is a liveout of the basic block. This helps prevent
6360   // infinite combine loops like PR51206.
6361   if (none_of(N->uses(),
6362               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6363     return SDValue();
6364 
6365   SmallVector<SDNode *, 4> SetCCs;
6366   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6367                             UE = Src.getNode()->use_end();
6368        UI != UE; ++UI) {
6369     SDNode *User = *UI;
6370     if (User == N)
6371       continue;
6372     if (UI.getUse().getResNo() != Src.getResNo())
6373       continue;
6374     // All i32 setccs are legalized by sign extending operands.
6375     if (User->getOpcode() == ISD::SETCC) {
6376       SetCCs.push_back(User);
6377       continue;
6378     }
6379     // We don't know if we can extend this user.
6380     break;
6381   }
6382 
6383   // If we don't have any SetCCs, this isn't worthwhile.
6384   if (SetCCs.empty())
6385     return SDValue();
6386 
6387   SDLoc DL(N);
6388   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6389   DCI.CombineTo(N, SExt);
6390 
6391   // Promote all the setccs.
6392   for (SDNode *SetCC : SetCCs) {
6393     SmallVector<SDValue, 4> Ops;
6394 
6395     for (unsigned j = 0; j != 2; ++j) {
6396       SDValue SOp = SetCC->getOperand(j);
6397       if (SOp == Src)
6398         Ops.push_back(SExt);
6399       else
6400         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6401     }
6402 
6403     Ops.push_back(SetCC->getOperand(2));
6404     DCI.CombineTo(SetCC,
6405                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6406   }
6407   return SDValue(N, 0);
6408 }
6409 
6410 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6411                                                DAGCombinerInfo &DCI) const {
6412   SelectionDAG &DAG = DCI.DAG;
6413 
6414   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6415   // bits are demanded. N will be added to the Worklist if it was not deleted.
6416   // Caller should return SDValue(N, 0) if this returns true.
6417   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6418     SDValue Op = N->getOperand(OpNo);
6419     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6420     if (!SimplifyDemandedBits(Op, Mask, DCI))
6421       return false;
6422 
6423     if (N->getOpcode() != ISD::DELETED_NODE)
6424       DCI.AddToWorklist(N);
6425     return true;
6426   };
6427 
6428   switch (N->getOpcode()) {
6429   default:
6430     break;
6431   case RISCVISD::SplitF64: {
6432     SDValue Op0 = N->getOperand(0);
6433     // If the input to SplitF64 is just BuildPairF64 then the operation is
6434     // redundant. Instead, use BuildPairF64's operands directly.
6435     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6436       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6437 
6438     SDLoc DL(N);
6439 
6440     // It's cheaper to materialise two 32-bit integers than to load a double
6441     // from the constant pool and transfer it to integer registers through the
6442     // stack.
6443     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6444       APInt V = C->getValueAPF().bitcastToAPInt();
6445       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6446       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6447       return DCI.CombineTo(N, Lo, Hi);
6448     }
6449 
6450     // This is a target-specific version of a DAGCombine performed in
6451     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6452     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6453     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6454     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6455         !Op0.getNode()->hasOneUse())
6456       break;
6457     SDValue NewSplitF64 =
6458         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6459                     Op0.getOperand(0));
6460     SDValue Lo = NewSplitF64.getValue(0);
6461     SDValue Hi = NewSplitF64.getValue(1);
6462     APInt SignBit = APInt::getSignMask(32);
6463     if (Op0.getOpcode() == ISD::FNEG) {
6464       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6465                                   DAG.getConstant(SignBit, DL, MVT::i32));
6466       return DCI.CombineTo(N, Lo, NewHi);
6467     }
6468     assert(Op0.getOpcode() == ISD::FABS);
6469     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6470                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6471     return DCI.CombineTo(N, Lo, NewHi);
6472   }
6473   case RISCVISD::SLLW:
6474   case RISCVISD::SRAW:
6475   case RISCVISD::SRLW:
6476   case RISCVISD::ROLW:
6477   case RISCVISD::RORW: {
6478     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6479     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6480         SimplifyDemandedLowBitsHelper(1, 5))
6481       return SDValue(N, 0);
6482     break;
6483   }
6484   case RISCVISD::CLZW:
6485   case RISCVISD::CTZW: {
6486     // Only the lower 32 bits of the first operand are read
6487     if (SimplifyDemandedLowBitsHelper(0, 32))
6488       return SDValue(N, 0);
6489     break;
6490   }
6491   case RISCVISD::FSL:
6492   case RISCVISD::FSR: {
6493     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6494     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6495     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6496     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6497       return SDValue(N, 0);
6498     break;
6499   }
6500   case RISCVISD::FSLW:
6501   case RISCVISD::FSRW: {
6502     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6503     // read.
6504     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6505         SimplifyDemandedLowBitsHelper(1, 32) ||
6506         SimplifyDemandedLowBitsHelper(2, 6))
6507       return SDValue(N, 0);
6508     break;
6509   }
6510   case RISCVISD::GREV:
6511   case RISCVISD::GORC: {
6512     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6513     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6514     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6515     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6516       return SDValue(N, 0);
6517 
6518     return combineGREVI_GORCI(N, DCI.DAG);
6519   }
6520   case RISCVISD::GREVW:
6521   case RISCVISD::GORCW: {
6522     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6523     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6524         SimplifyDemandedLowBitsHelper(1, 5))
6525       return SDValue(N, 0);
6526 
6527     return combineGREVI_GORCI(N, DCI.DAG);
6528   }
6529   case RISCVISD::SHFL:
6530   case RISCVISD::UNSHFL: {
6531     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6532     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6533     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6534     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6535       return SDValue(N, 0);
6536 
6537     break;
6538   }
6539   case RISCVISD::SHFLW:
6540   case RISCVISD::UNSHFLW: {
6541     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6542     SDValue LHS = N->getOperand(0);
6543     SDValue RHS = N->getOperand(1);
6544     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6545     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6546     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6547         SimplifyDemandedLowBitsHelper(1, 4))
6548       return SDValue(N, 0);
6549 
6550     break;
6551   }
6552   case RISCVISD::BCOMPRESSW:
6553   case RISCVISD::BDECOMPRESSW: {
6554     // Only the lower 32 bits of LHS and RHS are read.
6555     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6556         SimplifyDemandedLowBitsHelper(1, 32))
6557       return SDValue(N, 0);
6558 
6559     break;
6560   }
6561   case RISCVISD::FMV_X_ANYEXTH:
6562   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6563     SDLoc DL(N);
6564     SDValue Op0 = N->getOperand(0);
6565     MVT VT = N->getSimpleValueType(0);
6566     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6567     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6568     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6569     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6570          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6571         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6572          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6573       assert(Op0.getOperand(0).getValueType() == VT &&
6574              "Unexpected value type!");
6575       return Op0.getOperand(0);
6576     }
6577 
6578     // This is a target-specific version of a DAGCombine performed in
6579     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6580     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6581     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6582     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6583         !Op0.getNode()->hasOneUse())
6584       break;
6585     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6586     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6587     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6588     if (Op0.getOpcode() == ISD::FNEG)
6589       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6590                          DAG.getConstant(SignBit, DL, VT));
6591 
6592     assert(Op0.getOpcode() == ISD::FABS);
6593     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6594                        DAG.getConstant(~SignBit, DL, VT));
6595   }
6596   case ISD::ADD:
6597     return performADDCombine(N, DAG, Subtarget);
6598   case ISD::SUB:
6599     return performSUBCombine(N, DAG);
6600   case ISD::AND:
6601     return performANDCombine(N, DAG);
6602   case ISD::OR:
6603     return performORCombine(N, DAG, Subtarget);
6604   case ISD::XOR:
6605     return performXORCombine(N, DAG);
6606   case ISD::ANY_EXTEND:
6607     return performANY_EXTENDCombine(N, DCI, Subtarget);
6608   case ISD::ZERO_EXTEND:
6609     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6610     // type legalization. This is safe because fp_to_uint produces poison if
6611     // it overflows.
6612     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6613         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6614         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6615       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6616                          N->getOperand(0).getOperand(0));
6617     return SDValue();
6618   case RISCVISD::SELECT_CC: {
6619     // Transform
6620     SDValue LHS = N->getOperand(0);
6621     SDValue RHS = N->getOperand(1);
6622     SDValue TrueV = N->getOperand(3);
6623     SDValue FalseV = N->getOperand(4);
6624 
6625     // If the True and False values are the same, we don't need a select_cc.
6626     if (TrueV == FalseV)
6627       return TrueV;
6628 
6629     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6630     if (!ISD::isIntEqualitySetCC(CCVal))
6631       break;
6632 
6633     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6634     //      (select_cc X, Y, lt, trueV, falseV)
6635     // Sometimes the setcc is introduced after select_cc has been formed.
6636     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6637         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6638       // If we're looking for eq 0 instead of ne 0, we need to invert the
6639       // condition.
6640       bool Invert = CCVal == ISD::SETEQ;
6641       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6642       if (Invert)
6643         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6644 
6645       SDLoc DL(N);
6646       RHS = LHS.getOperand(1);
6647       LHS = LHS.getOperand(0);
6648       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6649 
6650       SDValue TargetCC = DAG.getCondCode(CCVal);
6651       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6652                          {LHS, RHS, TargetCC, TrueV, FalseV});
6653     }
6654 
6655     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6656     //      (select_cc X, Y, eq/ne, trueV, falseV)
6657     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6658       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6659                          {LHS.getOperand(0), LHS.getOperand(1),
6660                           N->getOperand(2), TrueV, FalseV});
6661     // (select_cc X, 1, setne, trueV, falseV) ->
6662     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6663     // This can occur when legalizing some floating point comparisons.
6664     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6665     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6666       SDLoc DL(N);
6667       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6668       SDValue TargetCC = DAG.getCondCode(CCVal);
6669       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6670       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6671                          {LHS, RHS, TargetCC, TrueV, FalseV});
6672     }
6673 
6674     break;
6675   }
6676   case RISCVISD::BR_CC: {
6677     SDValue LHS = N->getOperand(1);
6678     SDValue RHS = N->getOperand(2);
6679     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6680     if (!ISD::isIntEqualitySetCC(CCVal))
6681       break;
6682 
6683     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6684     //      (br_cc X, Y, lt, dest)
6685     // Sometimes the setcc is introduced after br_cc has been formed.
6686     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6687         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6688       // If we're looking for eq 0 instead of ne 0, we need to invert the
6689       // condition.
6690       bool Invert = CCVal == ISD::SETEQ;
6691       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6692       if (Invert)
6693         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6694 
6695       SDLoc DL(N);
6696       RHS = LHS.getOperand(1);
6697       LHS = LHS.getOperand(0);
6698       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6699 
6700       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6701                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6702                          N->getOperand(4));
6703     }
6704 
6705     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6706     //      (br_cc X, Y, eq/ne, trueV, falseV)
6707     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6708       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6709                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6710                          N->getOperand(3), N->getOperand(4));
6711 
6712     // (br_cc X, 1, setne, br_cc) ->
6713     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6714     // This can occur when legalizing some floating point comparisons.
6715     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6716     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6717       SDLoc DL(N);
6718       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6719       SDValue TargetCC = DAG.getCondCode(CCVal);
6720       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6721       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6722                          N->getOperand(0), LHS, RHS, TargetCC,
6723                          N->getOperand(4));
6724     }
6725     break;
6726   }
6727   case ISD::FCOPYSIGN: {
6728     EVT VT = N->getValueType(0);
6729     if (!VT.isVector())
6730       break;
6731     // There is a form of VFSGNJ which injects the negated sign of its second
6732     // operand. Try and bubble any FNEG up after the extend/round to produce
6733     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6734     // TRUNC=1.
6735     SDValue In2 = N->getOperand(1);
6736     // Avoid cases where the extend/round has multiple uses, as duplicating
6737     // those is typically more expensive than removing a fneg.
6738     if (!In2.hasOneUse())
6739       break;
6740     if (In2.getOpcode() != ISD::FP_EXTEND &&
6741         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6742       break;
6743     In2 = In2.getOperand(0);
6744     if (In2.getOpcode() != ISD::FNEG)
6745       break;
6746     SDLoc DL(N);
6747     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6748     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6749                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6750   }
6751   case ISD::MGATHER:
6752   case ISD::MSCATTER:
6753   case ISD::VP_GATHER:
6754   case ISD::VP_SCATTER: {
6755     if (!DCI.isBeforeLegalize())
6756       break;
6757     SDValue Index, ScaleOp;
6758     bool IsIndexScaled = false;
6759     bool IsIndexSigned = false;
6760     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
6761       Index = VPGSN->getIndex();
6762       ScaleOp = VPGSN->getScale();
6763       IsIndexScaled = VPGSN->isIndexScaled();
6764       IsIndexSigned = VPGSN->isIndexSigned();
6765     } else {
6766       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
6767       Index = MGSN->getIndex();
6768       ScaleOp = MGSN->getScale();
6769       IsIndexScaled = MGSN->isIndexScaled();
6770       IsIndexSigned = MGSN->isIndexSigned();
6771     }
6772     EVT IndexVT = Index.getValueType();
6773     MVT XLenVT = Subtarget.getXLenVT();
6774     // RISCV indexed loads only support the "unsigned unscaled" addressing
6775     // mode, so anything else must be manually legalized.
6776     bool NeedsIdxLegalization =
6777         IsIndexScaled ||
6778         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
6779     if (!NeedsIdxLegalization)
6780       break;
6781 
6782     SDLoc DL(N);
6783 
6784     // Any index legalization should first promote to XLenVT, so we don't lose
6785     // bits when scaling. This may create an illegal index type so we let
6786     // LLVM's legalization take care of the splitting.
6787     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
6788     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6789       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6790       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6791                           DL, IndexVT, Index);
6792     }
6793 
6794     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
6795     if (IsIndexScaled && Scale != 1) {
6796       // Manually scale the indices by the element size.
6797       // TODO: Sanitize the scale operand here?
6798       // TODO: For VP nodes, should we use VP_SHL here?
6799       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6800       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6801       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6802     }
6803 
6804     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6805     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
6806       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
6807                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
6808                               VPGN->getScale(), VPGN->getMask(),
6809                               VPGN->getVectorLength()},
6810                              VPGN->getMemOperand(), NewIndexTy);
6811     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
6812       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
6813                               {VPSN->getChain(), VPSN->getValue(),
6814                                VPSN->getBasePtr(), Index, VPSN->getScale(),
6815                                VPSN->getMask(), VPSN->getVectorLength()},
6816                               VPSN->getMemOperand(), NewIndexTy);
6817     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
6818       return DAG.getMaskedGather(
6819           N->getVTList(), MGN->getMemoryVT(), DL,
6820           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
6821            MGN->getBasePtr(), Index, MGN->getScale()},
6822           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6823     const auto *MSN = cast<MaskedScatterSDNode>(N);
6824     return DAG.getMaskedScatter(
6825         N->getVTList(), MSN->getMemoryVT(), DL,
6826         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
6827          Index, MSN->getScale()},
6828         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6829   }
6830   case RISCVISD::SRA_VL:
6831   case RISCVISD::SRL_VL:
6832   case RISCVISD::SHL_VL: {
6833     SDValue ShAmt = N->getOperand(1);
6834     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6835       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6836       SDLoc DL(N);
6837       SDValue VL = N->getOperand(3);
6838       EVT VT = N->getValueType(0);
6839       ShAmt =
6840           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
6841       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
6842                          N->getOperand(2), N->getOperand(3));
6843     }
6844     break;
6845   }
6846   case ISD::SRA:
6847   case ISD::SRL:
6848   case ISD::SHL: {
6849     SDValue ShAmt = N->getOperand(1);
6850     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6851       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6852       SDLoc DL(N);
6853       EVT VT = N->getValueType(0);
6854       ShAmt =
6855           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
6856       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
6857     }
6858     break;
6859   }
6860   case RISCVISD::MUL_VL: {
6861     // Try to form VWMUL or VWMULU.
6862     // FIXME: Look for splat of extended scalar as well.
6863     // FIXME: Support VWMULSU.
6864     SDValue Op0 = N->getOperand(0);
6865     SDValue Op1 = N->getOperand(1);
6866     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6867     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6868     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
6869       return SDValue();
6870 
6871     // Make sure the extends have a single use.
6872     if (!Op0.hasOneUse() || !Op1.hasOneUse())
6873       return SDValue();
6874 
6875     SDValue Mask = N->getOperand(2);
6876     SDValue VL = N->getOperand(3);
6877     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
6878         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
6879       return SDValue();
6880 
6881     Op0 = Op0.getOperand(0);
6882     Op1 = Op1.getOperand(0);
6883 
6884     MVT VT = N->getSimpleValueType(0);
6885     MVT NarrowVT =
6886         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
6887                          VT.getVectorElementCount());
6888 
6889     SDLoc DL(N);
6890 
6891     // Re-introduce narrower extends if needed.
6892     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6893     if (Op0.getValueType() != NarrowVT)
6894       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6895     if (Op1.getValueType() != NarrowVT)
6896       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6897 
6898     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6899     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6900   }
6901   }
6902 
6903   return SDValue();
6904 }
6905 
6906 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
6907     const SDNode *N, CombineLevel Level) const {
6908   // The following folds are only desirable if `(OP _, c1 << c2)` can be
6909   // materialised in fewer instructions than `(OP _, c1)`:
6910   //
6911   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6912   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6913   SDValue N0 = N->getOperand(0);
6914   EVT Ty = N0.getValueType();
6915   if (Ty.isScalarInteger() &&
6916       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
6917     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6918     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
6919     if (C1 && C2) {
6920       const APInt &C1Int = C1->getAPIntValue();
6921       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
6922 
6923       // We can materialise `c1 << c2` into an add immediate, so it's "free",
6924       // and the combine should happen, to potentially allow further combines
6925       // later.
6926       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
6927           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
6928         return true;
6929 
6930       // We can materialise `c1` in an add immediate, so it's "free", and the
6931       // combine should be prevented.
6932       if (C1Int.getMinSignedBits() <= 64 &&
6933           isLegalAddImmediate(C1Int.getSExtValue()))
6934         return false;
6935 
6936       // Neither constant will fit into an immediate, so find materialisation
6937       // costs.
6938       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
6939                                               Subtarget.getFeatureBits(),
6940                                               /*CompressionCost*/true);
6941       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
6942           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
6943           /*CompressionCost*/true);
6944 
6945       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
6946       // combine should be prevented.
6947       if (C1Cost < ShiftedC1Cost)
6948         return false;
6949     }
6950   }
6951   return true;
6952 }
6953 
6954 bool RISCVTargetLowering::targetShrinkDemandedConstant(
6955     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
6956     TargetLoweringOpt &TLO) const {
6957   // Delay this optimization as late as possible.
6958   if (!TLO.LegalOps)
6959     return false;
6960 
6961   EVT VT = Op.getValueType();
6962   if (VT.isVector())
6963     return false;
6964 
6965   // Only handle AND for now.
6966   if (Op.getOpcode() != ISD::AND)
6967     return false;
6968 
6969   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6970   if (!C)
6971     return false;
6972 
6973   const APInt &Mask = C->getAPIntValue();
6974 
6975   // Clear all non-demanded bits initially.
6976   APInt ShrunkMask = Mask & DemandedBits;
6977 
6978   // Try to make a smaller immediate by setting undemanded bits.
6979 
6980   APInt ExpandedMask = Mask | ~DemandedBits;
6981 
6982   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
6983     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
6984   };
6985   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
6986     if (NewMask == Mask)
6987       return true;
6988     SDLoc DL(Op);
6989     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
6990     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
6991     return TLO.CombineTo(Op, NewOp);
6992   };
6993 
6994   // If the shrunk mask fits in sign extended 12 bits, let the target
6995   // independent code apply it.
6996   if (ShrunkMask.isSignedIntN(12))
6997     return false;
6998 
6999   // Preserve (and X, 0xffff) when zext.h is supported.
7000   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7001     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7002     if (IsLegalMask(NewMask))
7003       return UseMask(NewMask);
7004   }
7005 
7006   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7007   if (VT == MVT::i64) {
7008     APInt NewMask = APInt(64, 0xffffffff);
7009     if (IsLegalMask(NewMask))
7010       return UseMask(NewMask);
7011   }
7012 
7013   // For the remaining optimizations, we need to be able to make a negative
7014   // number through a combination of mask and undemanded bits.
7015   if (!ExpandedMask.isNegative())
7016     return false;
7017 
7018   // What is the fewest number of bits we need to represent the negative number.
7019   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7020 
7021   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7022   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7023   APInt NewMask = ShrunkMask;
7024   if (MinSignedBits <= 12)
7025     NewMask.setBitsFrom(11);
7026   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7027     NewMask.setBitsFrom(31);
7028   else
7029     return false;
7030 
7031   // Sanity check that our new mask is a subset of the demanded mask.
7032   assert(IsLegalMask(NewMask));
7033   return UseMask(NewMask);
7034 }
7035 
7036 static void computeGREV(APInt &Src, unsigned ShAmt) {
7037   ShAmt &= Src.getBitWidth() - 1;
7038   uint64_t x = Src.getZExtValue();
7039   if (ShAmt & 1)
7040     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7041   if (ShAmt & 2)
7042     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7043   if (ShAmt & 4)
7044     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7045   if (ShAmt & 8)
7046     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7047   if (ShAmt & 16)
7048     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7049   if (ShAmt & 32)
7050     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7051   Src = x;
7052 }
7053 
7054 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7055                                                         KnownBits &Known,
7056                                                         const APInt &DemandedElts,
7057                                                         const SelectionDAG &DAG,
7058                                                         unsigned Depth) const {
7059   unsigned BitWidth = Known.getBitWidth();
7060   unsigned Opc = Op.getOpcode();
7061   assert((Opc >= ISD::BUILTIN_OP_END ||
7062           Opc == ISD::INTRINSIC_WO_CHAIN ||
7063           Opc == ISD::INTRINSIC_W_CHAIN ||
7064           Opc == ISD::INTRINSIC_VOID) &&
7065          "Should use MaskedValueIsZero if you don't know whether Op"
7066          " is a target node!");
7067 
7068   Known.resetAll();
7069   switch (Opc) {
7070   default: break;
7071   case RISCVISD::SELECT_CC: {
7072     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7073     // If we don't know any bits, early out.
7074     if (Known.isUnknown())
7075       break;
7076     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7077 
7078     // Only known if known in both the LHS and RHS.
7079     Known = KnownBits::commonBits(Known, Known2);
7080     break;
7081   }
7082   case RISCVISD::REMUW: {
7083     KnownBits Known2;
7084     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7085     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7086     // We only care about the lower 32 bits.
7087     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7088     // Restore the original width by sign extending.
7089     Known = Known.sext(BitWidth);
7090     break;
7091   }
7092   case RISCVISD::DIVUW: {
7093     KnownBits Known2;
7094     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7095     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7096     // We only care about the lower 32 bits.
7097     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7098     // Restore the original width by sign extending.
7099     Known = Known.sext(BitWidth);
7100     break;
7101   }
7102   case RISCVISD::CTZW: {
7103     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7104     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7105     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7106     Known.Zero.setBitsFrom(LowBits);
7107     break;
7108   }
7109   case RISCVISD::CLZW: {
7110     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7111     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7112     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7113     Known.Zero.setBitsFrom(LowBits);
7114     break;
7115   }
7116   case RISCVISD::GREV:
7117   case RISCVISD::GREVW: {
7118     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7119       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7120       if (Opc == RISCVISD::GREVW)
7121         Known = Known.trunc(32);
7122       unsigned ShAmt = C->getZExtValue();
7123       computeGREV(Known.Zero, ShAmt);
7124       computeGREV(Known.One, ShAmt);
7125       if (Opc == RISCVISD::GREVW)
7126         Known = Known.sext(BitWidth);
7127     }
7128     break;
7129   }
7130   case RISCVISD::READ_VLENB:
7131     // We assume VLENB is at least 16 bytes.
7132     Known.Zero.setLowBits(4);
7133     // We assume VLENB is no more than 65536 / 8 bytes.
7134     Known.Zero.setBitsFrom(14);
7135     break;
7136   case ISD::INTRINSIC_W_CHAIN: {
7137     unsigned IntNo = Op.getConstantOperandVal(1);
7138     switch (IntNo) {
7139     default:
7140       // We can't do anything for most intrinsics.
7141       break;
7142     case Intrinsic::riscv_vsetvli:
7143     case Intrinsic::riscv_vsetvlimax:
7144       // Assume that VL output is positive and would fit in an int32_t.
7145       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7146       if (BitWidth >= 32)
7147         Known.Zero.setBitsFrom(31);
7148       break;
7149     }
7150     break;
7151   }
7152   }
7153 }
7154 
7155 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7156     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7157     unsigned Depth) const {
7158   switch (Op.getOpcode()) {
7159   default:
7160     break;
7161   case RISCVISD::SELECT_CC: {
7162     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7163     if (Tmp == 1) return 1;  // Early out.
7164     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7165     return std::min(Tmp, Tmp2);
7166   }
7167   case RISCVISD::SLLW:
7168   case RISCVISD::SRAW:
7169   case RISCVISD::SRLW:
7170   case RISCVISD::DIVW:
7171   case RISCVISD::DIVUW:
7172   case RISCVISD::REMUW:
7173   case RISCVISD::ROLW:
7174   case RISCVISD::RORW:
7175   case RISCVISD::GREVW:
7176   case RISCVISD::GORCW:
7177   case RISCVISD::FSLW:
7178   case RISCVISD::FSRW:
7179   case RISCVISD::SHFLW:
7180   case RISCVISD::UNSHFLW:
7181   case RISCVISD::BCOMPRESSW:
7182   case RISCVISD::BDECOMPRESSW:
7183   case RISCVISD::FCVT_W_RTZ_RV64:
7184   case RISCVISD::FCVT_WU_RTZ_RV64:
7185     // TODO: As the result is sign-extended, this is conservatively correct. A
7186     // more precise answer could be calculated for SRAW depending on known
7187     // bits in the shift amount.
7188     return 33;
7189   case RISCVISD::SHFL:
7190   case RISCVISD::UNSHFL: {
7191     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7192     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7193     // will stay within the upper 32 bits. If there were more than 32 sign bits
7194     // before there will be at least 33 sign bits after.
7195     if (Op.getValueType() == MVT::i64 &&
7196         isa<ConstantSDNode>(Op.getOperand(1)) &&
7197         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7198       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7199       if (Tmp > 32)
7200         return 33;
7201     }
7202     break;
7203   }
7204   case RISCVISD::VMV_X_S:
7205     // The number of sign bits of the scalar result is computed by obtaining the
7206     // element type of the input vector operand, subtracting its width from the
7207     // XLEN, and then adding one (sign bit within the element type). If the
7208     // element type is wider than XLen, the least-significant XLEN bits are
7209     // taken.
7210     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7211       return 1;
7212     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7213   }
7214 
7215   return 1;
7216 }
7217 
7218 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7219                                                   MachineBasicBlock *BB) {
7220   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7221 
7222   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7223   // Should the count have wrapped while it was being read, we need to try
7224   // again.
7225   // ...
7226   // read:
7227   // rdcycleh x3 # load high word of cycle
7228   // rdcycle  x2 # load low word of cycle
7229   // rdcycleh x4 # load high word of cycle
7230   // bne x3, x4, read # check if high word reads match, otherwise try again
7231   // ...
7232 
7233   MachineFunction &MF = *BB->getParent();
7234   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7235   MachineFunction::iterator It = ++BB->getIterator();
7236 
7237   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7238   MF.insert(It, LoopMBB);
7239 
7240   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7241   MF.insert(It, DoneMBB);
7242 
7243   // Transfer the remainder of BB and its successor edges to DoneMBB.
7244   DoneMBB->splice(DoneMBB->begin(), BB,
7245                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7246   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7247 
7248   BB->addSuccessor(LoopMBB);
7249 
7250   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7251   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7252   Register LoReg = MI.getOperand(0).getReg();
7253   Register HiReg = MI.getOperand(1).getReg();
7254   DebugLoc DL = MI.getDebugLoc();
7255 
7256   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7257   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7258       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7259       .addReg(RISCV::X0);
7260   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7261       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7262       .addReg(RISCV::X0);
7263   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7264       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7265       .addReg(RISCV::X0);
7266 
7267   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7268       .addReg(HiReg)
7269       .addReg(ReadAgainReg)
7270       .addMBB(LoopMBB);
7271 
7272   LoopMBB->addSuccessor(LoopMBB);
7273   LoopMBB->addSuccessor(DoneMBB);
7274 
7275   MI.eraseFromParent();
7276 
7277   return DoneMBB;
7278 }
7279 
7280 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7281                                              MachineBasicBlock *BB) {
7282   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7283 
7284   MachineFunction &MF = *BB->getParent();
7285   DebugLoc DL = MI.getDebugLoc();
7286   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7287   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7288   Register LoReg = MI.getOperand(0).getReg();
7289   Register HiReg = MI.getOperand(1).getReg();
7290   Register SrcReg = MI.getOperand(2).getReg();
7291   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7292   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7293 
7294   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7295                           RI);
7296   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7297   MachineMemOperand *MMOLo =
7298       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7299   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7300       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7301   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7302       .addFrameIndex(FI)
7303       .addImm(0)
7304       .addMemOperand(MMOLo);
7305   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7306       .addFrameIndex(FI)
7307       .addImm(4)
7308       .addMemOperand(MMOHi);
7309   MI.eraseFromParent(); // The pseudo instruction is gone now.
7310   return BB;
7311 }
7312 
7313 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7314                                                  MachineBasicBlock *BB) {
7315   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7316          "Unexpected instruction");
7317 
7318   MachineFunction &MF = *BB->getParent();
7319   DebugLoc DL = MI.getDebugLoc();
7320   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7321   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7322   Register DstReg = MI.getOperand(0).getReg();
7323   Register LoReg = MI.getOperand(1).getReg();
7324   Register HiReg = MI.getOperand(2).getReg();
7325   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7326   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7327 
7328   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7329   MachineMemOperand *MMOLo =
7330       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7331   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7332       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7333   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7334       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7335       .addFrameIndex(FI)
7336       .addImm(0)
7337       .addMemOperand(MMOLo);
7338   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7339       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7340       .addFrameIndex(FI)
7341       .addImm(4)
7342       .addMemOperand(MMOHi);
7343   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7344   MI.eraseFromParent(); // The pseudo instruction is gone now.
7345   return BB;
7346 }
7347 
7348 static bool isSelectPseudo(MachineInstr &MI) {
7349   switch (MI.getOpcode()) {
7350   default:
7351     return false;
7352   case RISCV::Select_GPR_Using_CC_GPR:
7353   case RISCV::Select_FPR16_Using_CC_GPR:
7354   case RISCV::Select_FPR32_Using_CC_GPR:
7355   case RISCV::Select_FPR64_Using_CC_GPR:
7356     return true;
7357   }
7358 }
7359 
7360 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7361                                            MachineBasicBlock *BB,
7362                                            const RISCVSubtarget &Subtarget) {
7363   // To "insert" Select_* instructions, we actually have to insert the triangle
7364   // control-flow pattern.  The incoming instructions know the destination vreg
7365   // to set, the condition code register to branch on, the true/false values to
7366   // select between, and the condcode to use to select the appropriate branch.
7367   //
7368   // We produce the following control flow:
7369   //     HeadMBB
7370   //     |  \
7371   //     |  IfFalseMBB
7372   //     | /
7373   //    TailMBB
7374   //
7375   // When we find a sequence of selects we attempt to optimize their emission
7376   // by sharing the control flow. Currently we only handle cases where we have
7377   // multiple selects with the exact same condition (same LHS, RHS and CC).
7378   // The selects may be interleaved with other instructions if the other
7379   // instructions meet some requirements we deem safe:
7380   // - They are debug instructions. Otherwise,
7381   // - They do not have side-effects, do not access memory and their inputs do
7382   //   not depend on the results of the select pseudo-instructions.
7383   // The TrueV/FalseV operands of the selects cannot depend on the result of
7384   // previous selects in the sequence.
7385   // These conditions could be further relaxed. See the X86 target for a
7386   // related approach and more information.
7387   Register LHS = MI.getOperand(1).getReg();
7388   Register RHS = MI.getOperand(2).getReg();
7389   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7390 
7391   SmallVector<MachineInstr *, 4> SelectDebugValues;
7392   SmallSet<Register, 4> SelectDests;
7393   SelectDests.insert(MI.getOperand(0).getReg());
7394 
7395   MachineInstr *LastSelectPseudo = &MI;
7396 
7397   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7398        SequenceMBBI != E; ++SequenceMBBI) {
7399     if (SequenceMBBI->isDebugInstr())
7400       continue;
7401     else if (isSelectPseudo(*SequenceMBBI)) {
7402       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7403           SequenceMBBI->getOperand(2).getReg() != RHS ||
7404           SequenceMBBI->getOperand(3).getImm() != CC ||
7405           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7406           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7407         break;
7408       LastSelectPseudo = &*SequenceMBBI;
7409       SequenceMBBI->collectDebugValues(SelectDebugValues);
7410       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7411     } else {
7412       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7413           SequenceMBBI->mayLoadOrStore())
7414         break;
7415       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7416             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7417           }))
7418         break;
7419     }
7420   }
7421 
7422   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7423   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7424   DebugLoc DL = MI.getDebugLoc();
7425   MachineFunction::iterator I = ++BB->getIterator();
7426 
7427   MachineBasicBlock *HeadMBB = BB;
7428   MachineFunction *F = BB->getParent();
7429   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7430   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7431 
7432   F->insert(I, IfFalseMBB);
7433   F->insert(I, TailMBB);
7434 
7435   // Transfer debug instructions associated with the selects to TailMBB.
7436   for (MachineInstr *DebugInstr : SelectDebugValues) {
7437     TailMBB->push_back(DebugInstr->removeFromParent());
7438   }
7439 
7440   // Move all instructions after the sequence to TailMBB.
7441   TailMBB->splice(TailMBB->end(), HeadMBB,
7442                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7443   // Update machine-CFG edges by transferring all successors of the current
7444   // block to the new block which will contain the Phi nodes for the selects.
7445   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7446   // Set the successors for HeadMBB.
7447   HeadMBB->addSuccessor(IfFalseMBB);
7448   HeadMBB->addSuccessor(TailMBB);
7449 
7450   // Insert appropriate branch.
7451   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7452     .addReg(LHS)
7453     .addReg(RHS)
7454     .addMBB(TailMBB);
7455 
7456   // IfFalseMBB just falls through to TailMBB.
7457   IfFalseMBB->addSuccessor(TailMBB);
7458 
7459   // Create PHIs for all of the select pseudo-instructions.
7460   auto SelectMBBI = MI.getIterator();
7461   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7462   auto InsertionPoint = TailMBB->begin();
7463   while (SelectMBBI != SelectEnd) {
7464     auto Next = std::next(SelectMBBI);
7465     if (isSelectPseudo(*SelectMBBI)) {
7466       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7467       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7468               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7469           .addReg(SelectMBBI->getOperand(4).getReg())
7470           .addMBB(HeadMBB)
7471           .addReg(SelectMBBI->getOperand(5).getReg())
7472           .addMBB(IfFalseMBB);
7473       SelectMBBI->eraseFromParent();
7474     }
7475     SelectMBBI = Next;
7476   }
7477 
7478   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7479   return TailMBB;
7480 }
7481 
7482 MachineBasicBlock *
7483 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7484                                                  MachineBasicBlock *BB) const {
7485   switch (MI.getOpcode()) {
7486   default:
7487     llvm_unreachable("Unexpected instr type to insert");
7488   case RISCV::ReadCycleWide:
7489     assert(!Subtarget.is64Bit() &&
7490            "ReadCycleWrite is only to be used on riscv32");
7491     return emitReadCycleWidePseudo(MI, BB);
7492   case RISCV::Select_GPR_Using_CC_GPR:
7493   case RISCV::Select_FPR16_Using_CC_GPR:
7494   case RISCV::Select_FPR32_Using_CC_GPR:
7495   case RISCV::Select_FPR64_Using_CC_GPR:
7496     return emitSelectPseudo(MI, BB, Subtarget);
7497   case RISCV::BuildPairF64Pseudo:
7498     return emitBuildPairF64Pseudo(MI, BB);
7499   case RISCV::SplitF64Pseudo:
7500     return emitSplitF64Pseudo(MI, BB);
7501   }
7502 }
7503 
7504 // Calling Convention Implementation.
7505 // The expectations for frontend ABI lowering vary from target to target.
7506 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7507 // details, but this is a longer term goal. For now, we simply try to keep the
7508 // role of the frontend as simple and well-defined as possible. The rules can
7509 // be summarised as:
7510 // * Never split up large scalar arguments. We handle them here.
7511 // * If a hardfloat calling convention is being used, and the struct may be
7512 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7513 // available, then pass as two separate arguments. If either the GPRs or FPRs
7514 // are exhausted, then pass according to the rule below.
7515 // * If a struct could never be passed in registers or directly in a stack
7516 // slot (as it is larger than 2*XLEN and the floating point rules don't
7517 // apply), then pass it using a pointer with the byval attribute.
7518 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7519 // word-sized array or a 2*XLEN scalar (depending on alignment).
7520 // * The frontend can determine whether a struct is returned by reference or
7521 // not based on its size and fields. If it will be returned by reference, the
7522 // frontend must modify the prototype so a pointer with the sret annotation is
7523 // passed as the first argument. This is not necessary for large scalar
7524 // returns.
7525 // * Struct return values and varargs should be coerced to structs containing
7526 // register-size fields in the same situations they would be for fixed
7527 // arguments.
7528 
7529 static const MCPhysReg ArgGPRs[] = {
7530   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7531   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7532 };
7533 static const MCPhysReg ArgFPR16s[] = {
7534   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7535   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7536 };
7537 static const MCPhysReg ArgFPR32s[] = {
7538   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7539   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7540 };
7541 static const MCPhysReg ArgFPR64s[] = {
7542   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7543   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7544 };
7545 // This is an interim calling convention and it may be changed in the future.
7546 static const MCPhysReg ArgVRs[] = {
7547     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7548     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7549     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7550 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7551                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7552                                      RISCV::V20M2, RISCV::V22M2};
7553 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7554                                      RISCV::V20M4};
7555 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7556 
7557 // Pass a 2*XLEN argument that has been split into two XLEN values through
7558 // registers or the stack as necessary.
7559 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7560                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7561                                 MVT ValVT2, MVT LocVT2,
7562                                 ISD::ArgFlagsTy ArgFlags2) {
7563   unsigned XLenInBytes = XLen / 8;
7564   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7565     // At least one half can be passed via register.
7566     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7567                                      VA1.getLocVT(), CCValAssign::Full));
7568   } else {
7569     // Both halves must be passed on the stack, with proper alignment.
7570     Align StackAlign =
7571         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7572     State.addLoc(
7573         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7574                             State.AllocateStack(XLenInBytes, StackAlign),
7575                             VA1.getLocVT(), CCValAssign::Full));
7576     State.addLoc(CCValAssign::getMem(
7577         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7578         LocVT2, CCValAssign::Full));
7579     return false;
7580   }
7581 
7582   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7583     // The second half can also be passed via register.
7584     State.addLoc(
7585         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7586   } else {
7587     // The second half is passed via the stack, without additional alignment.
7588     State.addLoc(CCValAssign::getMem(
7589         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7590         LocVT2, CCValAssign::Full));
7591   }
7592 
7593   return false;
7594 }
7595 
7596 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7597                                Optional<unsigned> FirstMaskArgument,
7598                                CCState &State, const RISCVTargetLowering &TLI) {
7599   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7600   if (RC == &RISCV::VRRegClass) {
7601     // Assign the first mask argument to V0.
7602     // This is an interim calling convention and it may be changed in the
7603     // future.
7604     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7605       return State.AllocateReg(RISCV::V0);
7606     return State.AllocateReg(ArgVRs);
7607   }
7608   if (RC == &RISCV::VRM2RegClass)
7609     return State.AllocateReg(ArgVRM2s);
7610   if (RC == &RISCV::VRM4RegClass)
7611     return State.AllocateReg(ArgVRM4s);
7612   if (RC == &RISCV::VRM8RegClass)
7613     return State.AllocateReg(ArgVRM8s);
7614   llvm_unreachable("Unhandled register class for ValueType");
7615 }
7616 
7617 // Implements the RISC-V calling convention. Returns true upon failure.
7618 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7619                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7620                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7621                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7622                      Optional<unsigned> FirstMaskArgument) {
7623   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7624   assert(XLen == 32 || XLen == 64);
7625   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7626 
7627   // Any return value split in to more than two values can't be returned
7628   // directly. Vectors are returned via the available vector registers.
7629   if (!LocVT.isVector() && IsRet && ValNo > 1)
7630     return true;
7631 
7632   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7633   // variadic argument, or if no F16/F32 argument registers are available.
7634   bool UseGPRForF16_F32 = true;
7635   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7636   // variadic argument, or if no F64 argument registers are available.
7637   bool UseGPRForF64 = true;
7638 
7639   switch (ABI) {
7640   default:
7641     llvm_unreachable("Unexpected ABI");
7642   case RISCVABI::ABI_ILP32:
7643   case RISCVABI::ABI_LP64:
7644     break;
7645   case RISCVABI::ABI_ILP32F:
7646   case RISCVABI::ABI_LP64F:
7647     UseGPRForF16_F32 = !IsFixed;
7648     break;
7649   case RISCVABI::ABI_ILP32D:
7650   case RISCVABI::ABI_LP64D:
7651     UseGPRForF16_F32 = !IsFixed;
7652     UseGPRForF64 = !IsFixed;
7653     break;
7654   }
7655 
7656   // FPR16, FPR32, and FPR64 alias each other.
7657   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7658     UseGPRForF16_F32 = true;
7659     UseGPRForF64 = true;
7660   }
7661 
7662   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7663   // similar local variables rather than directly checking against the target
7664   // ABI.
7665 
7666   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7667     LocVT = XLenVT;
7668     LocInfo = CCValAssign::BCvt;
7669   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7670     LocVT = MVT::i64;
7671     LocInfo = CCValAssign::BCvt;
7672   }
7673 
7674   // If this is a variadic argument, the RISC-V calling convention requires
7675   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7676   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7677   // be used regardless of whether the original argument was split during
7678   // legalisation or not. The argument will not be passed by registers if the
7679   // original type is larger than 2*XLEN, so the register alignment rule does
7680   // not apply.
7681   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7682   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7683       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7684     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7685     // Skip 'odd' register if necessary.
7686     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7687       State.AllocateReg(ArgGPRs);
7688   }
7689 
7690   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7691   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7692       State.getPendingArgFlags();
7693 
7694   assert(PendingLocs.size() == PendingArgFlags.size() &&
7695          "PendingLocs and PendingArgFlags out of sync");
7696 
7697   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7698   // registers are exhausted.
7699   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7700     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7701            "Can't lower f64 if it is split");
7702     // Depending on available argument GPRS, f64 may be passed in a pair of
7703     // GPRs, split between a GPR and the stack, or passed completely on the
7704     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7705     // cases.
7706     Register Reg = State.AllocateReg(ArgGPRs);
7707     LocVT = MVT::i32;
7708     if (!Reg) {
7709       unsigned StackOffset = State.AllocateStack(8, Align(8));
7710       State.addLoc(
7711           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7712       return false;
7713     }
7714     if (!State.AllocateReg(ArgGPRs))
7715       State.AllocateStack(4, Align(4));
7716     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7717     return false;
7718   }
7719 
7720   // Fixed-length vectors are located in the corresponding scalable-vector
7721   // container types.
7722   if (ValVT.isFixedLengthVector())
7723     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7724 
7725   // Split arguments might be passed indirectly, so keep track of the pending
7726   // values. Split vectors are passed via a mix of registers and indirectly, so
7727   // treat them as we would any other argument.
7728   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7729     LocVT = XLenVT;
7730     LocInfo = CCValAssign::Indirect;
7731     PendingLocs.push_back(
7732         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7733     PendingArgFlags.push_back(ArgFlags);
7734     if (!ArgFlags.isSplitEnd()) {
7735       return false;
7736     }
7737   }
7738 
7739   // If the split argument only had two elements, it should be passed directly
7740   // in registers or on the stack.
7741   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7742       PendingLocs.size() <= 2) {
7743     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7744     // Apply the normal calling convention rules to the first half of the
7745     // split argument.
7746     CCValAssign VA = PendingLocs[0];
7747     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7748     PendingLocs.clear();
7749     PendingArgFlags.clear();
7750     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7751                                ArgFlags);
7752   }
7753 
7754   // Allocate to a register if possible, or else a stack slot.
7755   Register Reg;
7756   unsigned StoreSizeBytes = XLen / 8;
7757   Align StackAlign = Align(XLen / 8);
7758 
7759   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7760     Reg = State.AllocateReg(ArgFPR16s);
7761   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7762     Reg = State.AllocateReg(ArgFPR32s);
7763   else if (ValVT == MVT::f64 && !UseGPRForF64)
7764     Reg = State.AllocateReg(ArgFPR64s);
7765   else if (ValVT.isVector()) {
7766     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7767     if (!Reg) {
7768       // For return values, the vector must be passed fully via registers or
7769       // via the stack.
7770       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7771       // but we're using all of them.
7772       if (IsRet)
7773         return true;
7774       // Try using a GPR to pass the address
7775       if ((Reg = State.AllocateReg(ArgGPRs))) {
7776         LocVT = XLenVT;
7777         LocInfo = CCValAssign::Indirect;
7778       } else if (ValVT.isScalableVector()) {
7779         report_fatal_error("Unable to pass scalable vector types on the stack");
7780       } else {
7781         // Pass fixed-length vectors on the stack.
7782         LocVT = ValVT;
7783         StoreSizeBytes = ValVT.getStoreSize();
7784         // Align vectors to their element sizes, being careful for vXi1
7785         // vectors.
7786         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7787       }
7788     }
7789   } else {
7790     Reg = State.AllocateReg(ArgGPRs);
7791   }
7792 
7793   unsigned StackOffset =
7794       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7795 
7796   // If we reach this point and PendingLocs is non-empty, we must be at the
7797   // end of a split argument that must be passed indirectly.
7798   if (!PendingLocs.empty()) {
7799     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7800     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7801 
7802     for (auto &It : PendingLocs) {
7803       if (Reg)
7804         It.convertToReg(Reg);
7805       else
7806         It.convertToMem(StackOffset);
7807       State.addLoc(It);
7808     }
7809     PendingLocs.clear();
7810     PendingArgFlags.clear();
7811     return false;
7812   }
7813 
7814   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7815           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7816          "Expected an XLenVT or vector types at this stage");
7817 
7818   if (Reg) {
7819     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7820     return false;
7821   }
7822 
7823   // When a floating-point value is passed on the stack, no bit-conversion is
7824   // needed.
7825   if (ValVT.isFloatingPoint()) {
7826     LocVT = ValVT;
7827     LocInfo = CCValAssign::Full;
7828   }
7829   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7830   return false;
7831 }
7832 
7833 template <typename ArgTy>
7834 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
7835   for (const auto &ArgIdx : enumerate(Args)) {
7836     MVT ArgVT = ArgIdx.value().VT;
7837     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
7838       return ArgIdx.index();
7839   }
7840   return None;
7841 }
7842 
7843 void RISCVTargetLowering::analyzeInputArgs(
7844     MachineFunction &MF, CCState &CCInfo,
7845     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
7846     RISCVCCAssignFn Fn) const {
7847   unsigned NumArgs = Ins.size();
7848   FunctionType *FType = MF.getFunction().getFunctionType();
7849 
7850   Optional<unsigned> FirstMaskArgument;
7851   if (Subtarget.hasStdExtV())
7852     FirstMaskArgument = preAssignMask(Ins);
7853 
7854   for (unsigned i = 0; i != NumArgs; ++i) {
7855     MVT ArgVT = Ins[i].VT;
7856     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
7857 
7858     Type *ArgTy = nullptr;
7859     if (IsRet)
7860       ArgTy = FType->getReturnType();
7861     else if (Ins[i].isOrigArg())
7862       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
7863 
7864     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7865     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7866            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
7867            FirstMaskArgument)) {
7868       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
7869                         << EVT(ArgVT).getEVTString() << '\n');
7870       llvm_unreachable(nullptr);
7871     }
7872   }
7873 }
7874 
7875 void RISCVTargetLowering::analyzeOutputArgs(
7876     MachineFunction &MF, CCState &CCInfo,
7877     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
7878     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
7879   unsigned NumArgs = Outs.size();
7880 
7881   Optional<unsigned> FirstMaskArgument;
7882   if (Subtarget.hasStdExtV())
7883     FirstMaskArgument = preAssignMask(Outs);
7884 
7885   for (unsigned i = 0; i != NumArgs; i++) {
7886     MVT ArgVT = Outs[i].VT;
7887     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7888     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
7889 
7890     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7891     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7892            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
7893            FirstMaskArgument)) {
7894       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
7895                         << EVT(ArgVT).getEVTString() << "\n");
7896       llvm_unreachable(nullptr);
7897     }
7898   }
7899 }
7900 
7901 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
7902 // values.
7903 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
7904                                    const CCValAssign &VA, const SDLoc &DL,
7905                                    const RISCVSubtarget &Subtarget) {
7906   switch (VA.getLocInfo()) {
7907   default:
7908     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7909   case CCValAssign::Full:
7910     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
7911       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
7912     break;
7913   case CCValAssign::BCvt:
7914     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7915       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
7916     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7917       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
7918     else
7919       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
7920     break;
7921   }
7922   return Val;
7923 }
7924 
7925 // The caller is responsible for loading the full value if the argument is
7926 // passed with CCValAssign::Indirect.
7927 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
7928                                 const CCValAssign &VA, const SDLoc &DL,
7929                                 const RISCVTargetLowering &TLI) {
7930   MachineFunction &MF = DAG.getMachineFunction();
7931   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7932   EVT LocVT = VA.getLocVT();
7933   SDValue Val;
7934   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
7935   Register VReg = RegInfo.createVirtualRegister(RC);
7936   RegInfo.addLiveIn(VA.getLocReg(), VReg);
7937   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
7938 
7939   if (VA.getLocInfo() == CCValAssign::Indirect)
7940     return Val;
7941 
7942   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
7943 }
7944 
7945 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
7946                                    const CCValAssign &VA, const SDLoc &DL,
7947                                    const RISCVSubtarget &Subtarget) {
7948   EVT LocVT = VA.getLocVT();
7949 
7950   switch (VA.getLocInfo()) {
7951   default:
7952     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7953   case CCValAssign::Full:
7954     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
7955       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
7956     break;
7957   case CCValAssign::BCvt:
7958     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7959       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
7960     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7961       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
7962     else
7963       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
7964     break;
7965   }
7966   return Val;
7967 }
7968 
7969 // The caller is responsible for loading the full value if the argument is
7970 // passed with CCValAssign::Indirect.
7971 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
7972                                 const CCValAssign &VA, const SDLoc &DL) {
7973   MachineFunction &MF = DAG.getMachineFunction();
7974   MachineFrameInfo &MFI = MF.getFrameInfo();
7975   EVT LocVT = VA.getLocVT();
7976   EVT ValVT = VA.getValVT();
7977   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
7978   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
7979                                  /*Immutable=*/true);
7980   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7981   SDValue Val;
7982 
7983   ISD::LoadExtType ExtType;
7984   switch (VA.getLocInfo()) {
7985   default:
7986     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7987   case CCValAssign::Full:
7988   case CCValAssign::Indirect:
7989   case CCValAssign::BCvt:
7990     ExtType = ISD::NON_EXTLOAD;
7991     break;
7992   }
7993   Val = DAG.getExtLoad(
7994       ExtType, DL, LocVT, Chain, FIN,
7995       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
7996   return Val;
7997 }
7998 
7999 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8000                                        const CCValAssign &VA, const SDLoc &DL) {
8001   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8002          "Unexpected VA");
8003   MachineFunction &MF = DAG.getMachineFunction();
8004   MachineFrameInfo &MFI = MF.getFrameInfo();
8005   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8006 
8007   if (VA.isMemLoc()) {
8008     // f64 is passed on the stack.
8009     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8010     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8011     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8012                        MachinePointerInfo::getFixedStack(MF, FI));
8013   }
8014 
8015   assert(VA.isRegLoc() && "Expected register VA assignment");
8016 
8017   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8018   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8019   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8020   SDValue Hi;
8021   if (VA.getLocReg() == RISCV::X17) {
8022     // Second half of f64 is passed on the stack.
8023     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8024     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8025     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8026                      MachinePointerInfo::getFixedStack(MF, FI));
8027   } else {
8028     // Second half of f64 is passed in another GPR.
8029     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8030     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8031     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8032   }
8033   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8034 }
8035 
8036 // FastCC has less than 1% performance improvement for some particular
8037 // benchmark. But theoretically, it may has benenfit for some cases.
8038 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8039                             unsigned ValNo, MVT ValVT, MVT LocVT,
8040                             CCValAssign::LocInfo LocInfo,
8041                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8042                             bool IsFixed, bool IsRet, Type *OrigTy,
8043                             const RISCVTargetLowering &TLI,
8044                             Optional<unsigned> FirstMaskArgument) {
8045 
8046   // X5 and X6 might be used for save-restore libcall.
8047   static const MCPhysReg GPRList[] = {
8048       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8049       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8050       RISCV::X29, RISCV::X30, RISCV::X31};
8051 
8052   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8053     if (unsigned Reg = State.AllocateReg(GPRList)) {
8054       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8055       return false;
8056     }
8057   }
8058 
8059   if (LocVT == MVT::f16) {
8060     static const MCPhysReg FPR16List[] = {
8061         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8062         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8063         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8064         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8065     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8066       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8067       return false;
8068     }
8069   }
8070 
8071   if (LocVT == MVT::f32) {
8072     static const MCPhysReg FPR32List[] = {
8073         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8074         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8075         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8076         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8077     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8078       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8079       return false;
8080     }
8081   }
8082 
8083   if (LocVT == MVT::f64) {
8084     static const MCPhysReg FPR64List[] = {
8085         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8086         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8087         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8088         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8089     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8090       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8091       return false;
8092     }
8093   }
8094 
8095   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8096     unsigned Offset4 = State.AllocateStack(4, Align(4));
8097     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8098     return false;
8099   }
8100 
8101   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8102     unsigned Offset5 = State.AllocateStack(8, Align(8));
8103     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8104     return false;
8105   }
8106 
8107   if (LocVT.isVector()) {
8108     if (unsigned Reg =
8109             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8110       // Fixed-length vectors are located in the corresponding scalable-vector
8111       // container types.
8112       if (ValVT.isFixedLengthVector())
8113         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8114       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8115     } else {
8116       // Try and pass the address via a "fast" GPR.
8117       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8118         LocInfo = CCValAssign::Indirect;
8119         LocVT = TLI.getSubtarget().getXLenVT();
8120         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8121       } else if (ValVT.isFixedLengthVector()) {
8122         auto StackAlign =
8123             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8124         unsigned StackOffset =
8125             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8126         State.addLoc(
8127             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8128       } else {
8129         // Can't pass scalable vectors on the stack.
8130         return true;
8131       }
8132     }
8133 
8134     return false;
8135   }
8136 
8137   return true; // CC didn't match.
8138 }
8139 
8140 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8141                          CCValAssign::LocInfo LocInfo,
8142                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8143 
8144   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8145     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8146     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8147     static const MCPhysReg GPRList[] = {
8148         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8149         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8150     if (unsigned Reg = State.AllocateReg(GPRList)) {
8151       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8152       return false;
8153     }
8154   }
8155 
8156   if (LocVT == MVT::f32) {
8157     // Pass in STG registers: F1, ..., F6
8158     //                        fs0 ... fs5
8159     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8160                                           RISCV::F18_F, RISCV::F19_F,
8161                                           RISCV::F20_F, RISCV::F21_F};
8162     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8163       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8164       return false;
8165     }
8166   }
8167 
8168   if (LocVT == MVT::f64) {
8169     // Pass in STG registers: D1, ..., D6
8170     //                        fs6 ... fs11
8171     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8172                                           RISCV::F24_D, RISCV::F25_D,
8173                                           RISCV::F26_D, RISCV::F27_D};
8174     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8175       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8176       return false;
8177     }
8178   }
8179 
8180   report_fatal_error("No registers left in GHC calling convention");
8181   return true;
8182 }
8183 
8184 // Transform physical registers into virtual registers.
8185 SDValue RISCVTargetLowering::LowerFormalArguments(
8186     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8187     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8188     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8189 
8190   MachineFunction &MF = DAG.getMachineFunction();
8191 
8192   switch (CallConv) {
8193   default:
8194     report_fatal_error("Unsupported calling convention");
8195   case CallingConv::C:
8196   case CallingConv::Fast:
8197     break;
8198   case CallingConv::GHC:
8199     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8200         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8201       report_fatal_error(
8202         "GHC calling convention requires the F and D instruction set extensions");
8203   }
8204 
8205   const Function &Func = MF.getFunction();
8206   if (Func.hasFnAttribute("interrupt")) {
8207     if (!Func.arg_empty())
8208       report_fatal_error(
8209         "Functions with the interrupt attribute cannot have arguments!");
8210 
8211     StringRef Kind =
8212       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8213 
8214     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8215       report_fatal_error(
8216         "Function interrupt attribute argument not supported!");
8217   }
8218 
8219   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8220   MVT XLenVT = Subtarget.getXLenVT();
8221   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8222   // Used with vargs to acumulate store chains.
8223   std::vector<SDValue> OutChains;
8224 
8225   // Assign locations to all of the incoming arguments.
8226   SmallVector<CCValAssign, 16> ArgLocs;
8227   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8228 
8229   if (CallConv == CallingConv::GHC)
8230     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8231   else
8232     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8233                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8234                                                    : CC_RISCV);
8235 
8236   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8237     CCValAssign &VA = ArgLocs[i];
8238     SDValue ArgValue;
8239     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8240     // case.
8241     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8242       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8243     else if (VA.isRegLoc())
8244       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8245     else
8246       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8247 
8248     if (VA.getLocInfo() == CCValAssign::Indirect) {
8249       // If the original argument was split and passed by reference (e.g. i128
8250       // on RV32), we need to load all parts of it here (using the same
8251       // address). Vectors may be partly split to registers and partly to the
8252       // stack, in which case the base address is partly offset and subsequent
8253       // stores are relative to that.
8254       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8255                                    MachinePointerInfo()));
8256       unsigned ArgIndex = Ins[i].OrigArgIndex;
8257       unsigned ArgPartOffset = Ins[i].PartOffset;
8258       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8259       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8260         CCValAssign &PartVA = ArgLocs[i + 1];
8261         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8262         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8263         if (PartVA.getValVT().isScalableVector())
8264           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8265         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8266         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8267                                      MachinePointerInfo()));
8268         ++i;
8269       }
8270       continue;
8271     }
8272     InVals.push_back(ArgValue);
8273   }
8274 
8275   if (IsVarArg) {
8276     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8277     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8278     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8279     MachineFrameInfo &MFI = MF.getFrameInfo();
8280     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8281     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8282 
8283     // Offset of the first variable argument from stack pointer, and size of
8284     // the vararg save area. For now, the varargs save area is either zero or
8285     // large enough to hold a0-a7.
8286     int VaArgOffset, VarArgsSaveSize;
8287 
8288     // If all registers are allocated, then all varargs must be passed on the
8289     // stack and we don't need to save any argregs.
8290     if (ArgRegs.size() == Idx) {
8291       VaArgOffset = CCInfo.getNextStackOffset();
8292       VarArgsSaveSize = 0;
8293     } else {
8294       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8295       VaArgOffset = -VarArgsSaveSize;
8296     }
8297 
8298     // Record the frame index of the first variable argument
8299     // which is a value necessary to VASTART.
8300     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8301     RVFI->setVarArgsFrameIndex(FI);
8302 
8303     // If saving an odd number of registers then create an extra stack slot to
8304     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8305     // offsets to even-numbered registered remain 2*XLEN-aligned.
8306     if (Idx % 2) {
8307       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8308       VarArgsSaveSize += XLenInBytes;
8309     }
8310 
8311     // Copy the integer registers that may have been used for passing varargs
8312     // to the vararg save area.
8313     for (unsigned I = Idx; I < ArgRegs.size();
8314          ++I, VaArgOffset += XLenInBytes) {
8315       const Register Reg = RegInfo.createVirtualRegister(RC);
8316       RegInfo.addLiveIn(ArgRegs[I], Reg);
8317       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8318       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8319       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8320       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8321                                    MachinePointerInfo::getFixedStack(MF, FI));
8322       cast<StoreSDNode>(Store.getNode())
8323           ->getMemOperand()
8324           ->setValue((Value *)nullptr);
8325       OutChains.push_back(Store);
8326     }
8327     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8328   }
8329 
8330   // All stores are grouped in one node to allow the matching between
8331   // the size of Ins and InVals. This only happens for vararg functions.
8332   if (!OutChains.empty()) {
8333     OutChains.push_back(Chain);
8334     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8335   }
8336 
8337   return Chain;
8338 }
8339 
8340 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8341 /// for tail call optimization.
8342 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8343 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8344     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8345     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8346 
8347   auto &Callee = CLI.Callee;
8348   auto CalleeCC = CLI.CallConv;
8349   auto &Outs = CLI.Outs;
8350   auto &Caller = MF.getFunction();
8351   auto CallerCC = Caller.getCallingConv();
8352 
8353   // Exception-handling functions need a special set of instructions to
8354   // indicate a return to the hardware. Tail-calling another function would
8355   // probably break this.
8356   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8357   // should be expanded as new function attributes are introduced.
8358   if (Caller.hasFnAttribute("interrupt"))
8359     return false;
8360 
8361   // Do not tail call opt if the stack is used to pass parameters.
8362   if (CCInfo.getNextStackOffset() != 0)
8363     return false;
8364 
8365   // Do not tail call opt if any parameters need to be passed indirectly.
8366   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8367   // passed indirectly. So the address of the value will be passed in a
8368   // register, or if not available, then the address is put on the stack. In
8369   // order to pass indirectly, space on the stack often needs to be allocated
8370   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8371   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8372   // are passed CCValAssign::Indirect.
8373   for (auto &VA : ArgLocs)
8374     if (VA.getLocInfo() == CCValAssign::Indirect)
8375       return false;
8376 
8377   // Do not tail call opt if either caller or callee uses struct return
8378   // semantics.
8379   auto IsCallerStructRet = Caller.hasStructRetAttr();
8380   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8381   if (IsCallerStructRet || IsCalleeStructRet)
8382     return false;
8383 
8384   // Externally-defined functions with weak linkage should not be
8385   // tail-called. The behaviour of branch instructions in this situation (as
8386   // used for tail calls) is implementation-defined, so we cannot rely on the
8387   // linker replacing the tail call with a return.
8388   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8389     const GlobalValue *GV = G->getGlobal();
8390     if (GV->hasExternalWeakLinkage())
8391       return false;
8392   }
8393 
8394   // The callee has to preserve all registers the caller needs to preserve.
8395   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8396   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8397   if (CalleeCC != CallerCC) {
8398     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8399     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8400       return false;
8401   }
8402 
8403   // Byval parameters hand the function a pointer directly into the stack area
8404   // we want to reuse during a tail call. Working around this *is* possible
8405   // but less efficient and uglier in LowerCall.
8406   for (auto &Arg : Outs)
8407     if (Arg.Flags.isByVal())
8408       return false;
8409 
8410   return true;
8411 }
8412 
8413 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8414   return DAG.getDataLayout().getPrefTypeAlign(
8415       VT.getTypeForEVT(*DAG.getContext()));
8416 }
8417 
8418 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8419 // and output parameter nodes.
8420 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8421                                        SmallVectorImpl<SDValue> &InVals) const {
8422   SelectionDAG &DAG = CLI.DAG;
8423   SDLoc &DL = CLI.DL;
8424   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8425   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8426   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8427   SDValue Chain = CLI.Chain;
8428   SDValue Callee = CLI.Callee;
8429   bool &IsTailCall = CLI.IsTailCall;
8430   CallingConv::ID CallConv = CLI.CallConv;
8431   bool IsVarArg = CLI.IsVarArg;
8432   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8433   MVT XLenVT = Subtarget.getXLenVT();
8434 
8435   MachineFunction &MF = DAG.getMachineFunction();
8436 
8437   // Analyze the operands of the call, assigning locations to each operand.
8438   SmallVector<CCValAssign, 16> ArgLocs;
8439   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8440 
8441   if (CallConv == CallingConv::GHC)
8442     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8443   else
8444     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8445                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8446                                                     : CC_RISCV);
8447 
8448   // Check if it's really possible to do a tail call.
8449   if (IsTailCall)
8450     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8451 
8452   if (IsTailCall)
8453     ++NumTailCalls;
8454   else if (CLI.CB && CLI.CB->isMustTailCall())
8455     report_fatal_error("failed to perform tail call elimination on a call "
8456                        "site marked musttail");
8457 
8458   // Get a count of how many bytes are to be pushed on the stack.
8459   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8460 
8461   // Create local copies for byval args
8462   SmallVector<SDValue, 8> ByValArgs;
8463   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8464     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8465     if (!Flags.isByVal())
8466       continue;
8467 
8468     SDValue Arg = OutVals[i];
8469     unsigned Size = Flags.getByValSize();
8470     Align Alignment = Flags.getNonZeroByValAlign();
8471 
8472     int FI =
8473         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8474     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8475     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8476 
8477     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8478                           /*IsVolatile=*/false,
8479                           /*AlwaysInline=*/false, IsTailCall,
8480                           MachinePointerInfo(), MachinePointerInfo());
8481     ByValArgs.push_back(FIPtr);
8482   }
8483 
8484   if (!IsTailCall)
8485     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8486 
8487   // Copy argument values to their designated locations.
8488   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8489   SmallVector<SDValue, 8> MemOpChains;
8490   SDValue StackPtr;
8491   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8492     CCValAssign &VA = ArgLocs[i];
8493     SDValue ArgValue = OutVals[i];
8494     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8495 
8496     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8497     bool IsF64OnRV32DSoftABI =
8498         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8499     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8500       SDValue SplitF64 = DAG.getNode(
8501           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8502       SDValue Lo = SplitF64.getValue(0);
8503       SDValue Hi = SplitF64.getValue(1);
8504 
8505       Register RegLo = VA.getLocReg();
8506       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8507 
8508       if (RegLo == RISCV::X17) {
8509         // Second half of f64 is passed on the stack.
8510         // Work out the address of the stack slot.
8511         if (!StackPtr.getNode())
8512           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8513         // Emit the store.
8514         MemOpChains.push_back(
8515             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8516       } else {
8517         // Second half of f64 is passed in another GPR.
8518         assert(RegLo < RISCV::X31 && "Invalid register pair");
8519         Register RegHigh = RegLo + 1;
8520         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8521       }
8522       continue;
8523     }
8524 
8525     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8526     // as any other MemLoc.
8527 
8528     // Promote the value if needed.
8529     // For now, only handle fully promoted and indirect arguments.
8530     if (VA.getLocInfo() == CCValAssign::Indirect) {
8531       // Store the argument in a stack slot and pass its address.
8532       Align StackAlign =
8533           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8534                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8535       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8536       // If the original argument was split (e.g. i128), we need
8537       // to store the required parts of it here (and pass just one address).
8538       // Vectors may be partly split to registers and partly to the stack, in
8539       // which case the base address is partly offset and subsequent stores are
8540       // relative to that.
8541       unsigned ArgIndex = Outs[i].OrigArgIndex;
8542       unsigned ArgPartOffset = Outs[i].PartOffset;
8543       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8544       // Calculate the total size to store. We don't have access to what we're
8545       // actually storing other than performing the loop and collecting the
8546       // info.
8547       SmallVector<std::pair<SDValue, SDValue>> Parts;
8548       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8549         SDValue PartValue = OutVals[i + 1];
8550         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8551         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8552         EVT PartVT = PartValue.getValueType();
8553         if (PartVT.isScalableVector())
8554           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8555         StoredSize += PartVT.getStoreSize();
8556         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8557         Parts.push_back(std::make_pair(PartValue, Offset));
8558         ++i;
8559       }
8560       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8561       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8562       MemOpChains.push_back(
8563           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8564                        MachinePointerInfo::getFixedStack(MF, FI)));
8565       for (const auto &Part : Parts) {
8566         SDValue PartValue = Part.first;
8567         SDValue PartOffset = Part.second;
8568         SDValue Address =
8569             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8570         MemOpChains.push_back(
8571             DAG.getStore(Chain, DL, PartValue, Address,
8572                          MachinePointerInfo::getFixedStack(MF, FI)));
8573       }
8574       ArgValue = SpillSlot;
8575     } else {
8576       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8577     }
8578 
8579     // Use local copy if it is a byval arg.
8580     if (Flags.isByVal())
8581       ArgValue = ByValArgs[j++];
8582 
8583     if (VA.isRegLoc()) {
8584       // Queue up the argument copies and emit them at the end.
8585       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8586     } else {
8587       assert(VA.isMemLoc() && "Argument not register or memory");
8588       assert(!IsTailCall && "Tail call not allowed if stack is used "
8589                             "for passing parameters");
8590 
8591       // Work out the address of the stack slot.
8592       if (!StackPtr.getNode())
8593         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8594       SDValue Address =
8595           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8596                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8597 
8598       // Emit the store.
8599       MemOpChains.push_back(
8600           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8601     }
8602   }
8603 
8604   // Join the stores, which are independent of one another.
8605   if (!MemOpChains.empty())
8606     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8607 
8608   SDValue Glue;
8609 
8610   // Build a sequence of copy-to-reg nodes, chained and glued together.
8611   for (auto &Reg : RegsToPass) {
8612     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8613     Glue = Chain.getValue(1);
8614   }
8615 
8616   // Validate that none of the argument registers have been marked as
8617   // reserved, if so report an error. Do the same for the return address if this
8618   // is not a tailcall.
8619   validateCCReservedRegs(RegsToPass, MF);
8620   if (!IsTailCall &&
8621       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8622     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8623         MF.getFunction(),
8624         "Return address register required, but has been reserved."});
8625 
8626   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8627   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8628   // split it and then direct call can be matched by PseudoCALL.
8629   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8630     const GlobalValue *GV = S->getGlobal();
8631 
8632     unsigned OpFlags = RISCVII::MO_CALL;
8633     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8634       OpFlags = RISCVII::MO_PLT;
8635 
8636     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8637   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8638     unsigned OpFlags = RISCVII::MO_CALL;
8639 
8640     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8641                                                  nullptr))
8642       OpFlags = RISCVII::MO_PLT;
8643 
8644     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8645   }
8646 
8647   // The first call operand is the chain and the second is the target address.
8648   SmallVector<SDValue, 8> Ops;
8649   Ops.push_back(Chain);
8650   Ops.push_back(Callee);
8651 
8652   // Add argument registers to the end of the list so that they are
8653   // known live into the call.
8654   for (auto &Reg : RegsToPass)
8655     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8656 
8657   if (!IsTailCall) {
8658     // Add a register mask operand representing the call-preserved registers.
8659     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8660     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8661     assert(Mask && "Missing call preserved mask for calling convention");
8662     Ops.push_back(DAG.getRegisterMask(Mask));
8663   }
8664 
8665   // Glue the call to the argument copies, if any.
8666   if (Glue.getNode())
8667     Ops.push_back(Glue);
8668 
8669   // Emit the call.
8670   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8671 
8672   if (IsTailCall) {
8673     MF.getFrameInfo().setHasTailCall();
8674     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8675   }
8676 
8677   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8678   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8679   Glue = Chain.getValue(1);
8680 
8681   // Mark the end of the call, which is glued to the call itself.
8682   Chain = DAG.getCALLSEQ_END(Chain,
8683                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8684                              DAG.getConstant(0, DL, PtrVT, true),
8685                              Glue, DL);
8686   Glue = Chain.getValue(1);
8687 
8688   // Assign locations to each value returned by this call.
8689   SmallVector<CCValAssign, 16> RVLocs;
8690   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8691   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8692 
8693   // Copy all of the result registers out of their specified physreg.
8694   for (auto &VA : RVLocs) {
8695     // Copy the value out
8696     SDValue RetValue =
8697         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8698     // Glue the RetValue to the end of the call sequence
8699     Chain = RetValue.getValue(1);
8700     Glue = RetValue.getValue(2);
8701 
8702     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8703       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8704       SDValue RetValue2 =
8705           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8706       Chain = RetValue2.getValue(1);
8707       Glue = RetValue2.getValue(2);
8708       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8709                              RetValue2);
8710     }
8711 
8712     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8713 
8714     InVals.push_back(RetValue);
8715   }
8716 
8717   return Chain;
8718 }
8719 
8720 bool RISCVTargetLowering::CanLowerReturn(
8721     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8722     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8723   SmallVector<CCValAssign, 16> RVLocs;
8724   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8725 
8726   Optional<unsigned> FirstMaskArgument;
8727   if (Subtarget.hasStdExtV())
8728     FirstMaskArgument = preAssignMask(Outs);
8729 
8730   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8731     MVT VT = Outs[i].VT;
8732     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8733     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8734     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8735                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8736                  *this, FirstMaskArgument))
8737       return false;
8738   }
8739   return true;
8740 }
8741 
8742 SDValue
8743 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8744                                  bool IsVarArg,
8745                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8746                                  const SmallVectorImpl<SDValue> &OutVals,
8747                                  const SDLoc &DL, SelectionDAG &DAG) const {
8748   const MachineFunction &MF = DAG.getMachineFunction();
8749   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8750 
8751   // Stores the assignment of the return value to a location.
8752   SmallVector<CCValAssign, 16> RVLocs;
8753 
8754   // Info about the registers and stack slot.
8755   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8756                  *DAG.getContext());
8757 
8758   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8759                     nullptr, CC_RISCV);
8760 
8761   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8762     report_fatal_error("GHC functions return void only");
8763 
8764   SDValue Glue;
8765   SmallVector<SDValue, 4> RetOps(1, Chain);
8766 
8767   // Copy the result values into the output registers.
8768   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8769     SDValue Val = OutVals[i];
8770     CCValAssign &VA = RVLocs[i];
8771     assert(VA.isRegLoc() && "Can only return in registers!");
8772 
8773     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8774       // Handle returning f64 on RV32D with a soft float ABI.
8775       assert(VA.isRegLoc() && "Expected return via registers");
8776       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8777                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8778       SDValue Lo = SplitF64.getValue(0);
8779       SDValue Hi = SplitF64.getValue(1);
8780       Register RegLo = VA.getLocReg();
8781       assert(RegLo < RISCV::X31 && "Invalid register pair");
8782       Register RegHi = RegLo + 1;
8783 
8784       if (STI.isRegisterReservedByUser(RegLo) ||
8785           STI.isRegisterReservedByUser(RegHi))
8786         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8787             MF.getFunction(),
8788             "Return value register required, but has been reserved."});
8789 
8790       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8791       Glue = Chain.getValue(1);
8792       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8793       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8794       Glue = Chain.getValue(1);
8795       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8796     } else {
8797       // Handle a 'normal' return.
8798       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8799       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8800 
8801       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8802         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8803             MF.getFunction(),
8804             "Return value register required, but has been reserved."});
8805 
8806       // Guarantee that all emitted copies are stuck together.
8807       Glue = Chain.getValue(1);
8808       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8809     }
8810   }
8811 
8812   RetOps[0] = Chain; // Update chain.
8813 
8814   // Add the glue node if we have it.
8815   if (Glue.getNode()) {
8816     RetOps.push_back(Glue);
8817   }
8818 
8819   unsigned RetOpc = RISCVISD::RET_FLAG;
8820   // Interrupt service routines use different return instructions.
8821   const Function &Func = DAG.getMachineFunction().getFunction();
8822   if (Func.hasFnAttribute("interrupt")) {
8823     if (!Func.getReturnType()->isVoidTy())
8824       report_fatal_error(
8825           "Functions with the interrupt attribute must have void return type!");
8826 
8827     MachineFunction &MF = DAG.getMachineFunction();
8828     StringRef Kind =
8829       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8830 
8831     if (Kind == "user")
8832       RetOpc = RISCVISD::URET_FLAG;
8833     else if (Kind == "supervisor")
8834       RetOpc = RISCVISD::SRET_FLAG;
8835     else
8836       RetOpc = RISCVISD::MRET_FLAG;
8837   }
8838 
8839   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
8840 }
8841 
8842 void RISCVTargetLowering::validateCCReservedRegs(
8843     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
8844     MachineFunction &MF) const {
8845   const Function &F = MF.getFunction();
8846   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8847 
8848   if (llvm::any_of(Regs, [&STI](auto Reg) {
8849         return STI.isRegisterReservedByUser(Reg.first);
8850       }))
8851     F.getContext().diagnose(DiagnosticInfoUnsupported{
8852         F, "Argument register required, but has been reserved."});
8853 }
8854 
8855 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
8856   return CI->isTailCall();
8857 }
8858 
8859 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
8860 #define NODE_NAME_CASE(NODE)                                                   \
8861   case RISCVISD::NODE:                                                         \
8862     return "RISCVISD::" #NODE;
8863   // clang-format off
8864   switch ((RISCVISD::NodeType)Opcode) {
8865   case RISCVISD::FIRST_NUMBER:
8866     break;
8867   NODE_NAME_CASE(RET_FLAG)
8868   NODE_NAME_CASE(URET_FLAG)
8869   NODE_NAME_CASE(SRET_FLAG)
8870   NODE_NAME_CASE(MRET_FLAG)
8871   NODE_NAME_CASE(CALL)
8872   NODE_NAME_CASE(SELECT_CC)
8873   NODE_NAME_CASE(BR_CC)
8874   NODE_NAME_CASE(BuildPairF64)
8875   NODE_NAME_CASE(SplitF64)
8876   NODE_NAME_CASE(TAIL)
8877   NODE_NAME_CASE(MULHSU)
8878   NODE_NAME_CASE(SLLW)
8879   NODE_NAME_CASE(SRAW)
8880   NODE_NAME_CASE(SRLW)
8881   NODE_NAME_CASE(DIVW)
8882   NODE_NAME_CASE(DIVUW)
8883   NODE_NAME_CASE(REMUW)
8884   NODE_NAME_CASE(ROLW)
8885   NODE_NAME_CASE(RORW)
8886   NODE_NAME_CASE(CLZW)
8887   NODE_NAME_CASE(CTZW)
8888   NODE_NAME_CASE(FSLW)
8889   NODE_NAME_CASE(FSRW)
8890   NODE_NAME_CASE(FSL)
8891   NODE_NAME_CASE(FSR)
8892   NODE_NAME_CASE(FMV_H_X)
8893   NODE_NAME_CASE(FMV_X_ANYEXTH)
8894   NODE_NAME_CASE(FMV_W_X_RV64)
8895   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
8896   NODE_NAME_CASE(FCVT_X_RTZ)
8897   NODE_NAME_CASE(FCVT_XU_RTZ)
8898   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
8899   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
8900   NODE_NAME_CASE(READ_CYCLE_WIDE)
8901   NODE_NAME_CASE(GREV)
8902   NODE_NAME_CASE(GREVW)
8903   NODE_NAME_CASE(GORC)
8904   NODE_NAME_CASE(GORCW)
8905   NODE_NAME_CASE(SHFL)
8906   NODE_NAME_CASE(SHFLW)
8907   NODE_NAME_CASE(UNSHFL)
8908   NODE_NAME_CASE(UNSHFLW)
8909   NODE_NAME_CASE(BCOMPRESS)
8910   NODE_NAME_CASE(BCOMPRESSW)
8911   NODE_NAME_CASE(BDECOMPRESS)
8912   NODE_NAME_CASE(BDECOMPRESSW)
8913   NODE_NAME_CASE(VMV_V_X_VL)
8914   NODE_NAME_CASE(VFMV_V_F_VL)
8915   NODE_NAME_CASE(VMV_X_S)
8916   NODE_NAME_CASE(VMV_S_X_VL)
8917   NODE_NAME_CASE(VFMV_S_F_VL)
8918   NODE_NAME_CASE(SPLAT_VECTOR_I64)
8919   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
8920   NODE_NAME_CASE(READ_VLENB)
8921   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
8922   NODE_NAME_CASE(VSLIDEUP_VL)
8923   NODE_NAME_CASE(VSLIDE1UP_VL)
8924   NODE_NAME_CASE(VSLIDEDOWN_VL)
8925   NODE_NAME_CASE(VSLIDE1DOWN_VL)
8926   NODE_NAME_CASE(VID_VL)
8927   NODE_NAME_CASE(VFNCVT_ROD_VL)
8928   NODE_NAME_CASE(VECREDUCE_ADD_VL)
8929   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
8930   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
8931   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
8932   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
8933   NODE_NAME_CASE(VECREDUCE_AND_VL)
8934   NODE_NAME_CASE(VECREDUCE_OR_VL)
8935   NODE_NAME_CASE(VECREDUCE_XOR_VL)
8936   NODE_NAME_CASE(VECREDUCE_FADD_VL)
8937   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
8938   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
8939   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
8940   NODE_NAME_CASE(ADD_VL)
8941   NODE_NAME_CASE(AND_VL)
8942   NODE_NAME_CASE(MUL_VL)
8943   NODE_NAME_CASE(OR_VL)
8944   NODE_NAME_CASE(SDIV_VL)
8945   NODE_NAME_CASE(SHL_VL)
8946   NODE_NAME_CASE(SREM_VL)
8947   NODE_NAME_CASE(SRA_VL)
8948   NODE_NAME_CASE(SRL_VL)
8949   NODE_NAME_CASE(SUB_VL)
8950   NODE_NAME_CASE(UDIV_VL)
8951   NODE_NAME_CASE(UREM_VL)
8952   NODE_NAME_CASE(XOR_VL)
8953   NODE_NAME_CASE(SADDSAT_VL)
8954   NODE_NAME_CASE(UADDSAT_VL)
8955   NODE_NAME_CASE(SSUBSAT_VL)
8956   NODE_NAME_CASE(USUBSAT_VL)
8957   NODE_NAME_CASE(FADD_VL)
8958   NODE_NAME_CASE(FSUB_VL)
8959   NODE_NAME_CASE(FMUL_VL)
8960   NODE_NAME_CASE(FDIV_VL)
8961   NODE_NAME_CASE(FNEG_VL)
8962   NODE_NAME_CASE(FABS_VL)
8963   NODE_NAME_CASE(FSQRT_VL)
8964   NODE_NAME_CASE(FMA_VL)
8965   NODE_NAME_CASE(FCOPYSIGN_VL)
8966   NODE_NAME_CASE(SMIN_VL)
8967   NODE_NAME_CASE(SMAX_VL)
8968   NODE_NAME_CASE(UMIN_VL)
8969   NODE_NAME_CASE(UMAX_VL)
8970   NODE_NAME_CASE(FMINNUM_VL)
8971   NODE_NAME_CASE(FMAXNUM_VL)
8972   NODE_NAME_CASE(MULHS_VL)
8973   NODE_NAME_CASE(MULHU_VL)
8974   NODE_NAME_CASE(FP_TO_SINT_VL)
8975   NODE_NAME_CASE(FP_TO_UINT_VL)
8976   NODE_NAME_CASE(SINT_TO_FP_VL)
8977   NODE_NAME_CASE(UINT_TO_FP_VL)
8978   NODE_NAME_CASE(FP_EXTEND_VL)
8979   NODE_NAME_CASE(FP_ROUND_VL)
8980   NODE_NAME_CASE(VWMUL_VL)
8981   NODE_NAME_CASE(VWMULU_VL)
8982   NODE_NAME_CASE(SETCC_VL)
8983   NODE_NAME_CASE(VSELECT_VL)
8984   NODE_NAME_CASE(VMAND_VL)
8985   NODE_NAME_CASE(VMOR_VL)
8986   NODE_NAME_CASE(VMXOR_VL)
8987   NODE_NAME_CASE(VMCLR_VL)
8988   NODE_NAME_CASE(VMSET_VL)
8989   NODE_NAME_CASE(VRGATHER_VX_VL)
8990   NODE_NAME_CASE(VRGATHER_VV_VL)
8991   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
8992   NODE_NAME_CASE(VSEXT_VL)
8993   NODE_NAME_CASE(VZEXT_VL)
8994   NODE_NAME_CASE(VPOPC_VL)
8995   NODE_NAME_CASE(VLE_VL)
8996   NODE_NAME_CASE(VSE_VL)
8997   NODE_NAME_CASE(READ_CSR)
8998   NODE_NAME_CASE(WRITE_CSR)
8999   NODE_NAME_CASE(SWAP_CSR)
9000   }
9001   // clang-format on
9002   return nullptr;
9003 #undef NODE_NAME_CASE
9004 }
9005 
9006 /// getConstraintType - Given a constraint letter, return the type of
9007 /// constraint it is for this target.
9008 RISCVTargetLowering::ConstraintType
9009 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9010   if (Constraint.size() == 1) {
9011     switch (Constraint[0]) {
9012     default:
9013       break;
9014     case 'f':
9015       return C_RegisterClass;
9016     case 'I':
9017     case 'J':
9018     case 'K':
9019       return C_Immediate;
9020     case 'A':
9021       return C_Memory;
9022     case 'S': // A symbolic address
9023       return C_Other;
9024     }
9025   } else {
9026     if (Constraint == "vr" || Constraint == "vm")
9027       return C_RegisterClass;
9028   }
9029   return TargetLowering::getConstraintType(Constraint);
9030 }
9031 
9032 std::pair<unsigned, const TargetRegisterClass *>
9033 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9034                                                   StringRef Constraint,
9035                                                   MVT VT) const {
9036   // First, see if this is a constraint that directly corresponds to a
9037   // RISCV register class.
9038   if (Constraint.size() == 1) {
9039     switch (Constraint[0]) {
9040     case 'r':
9041       return std::make_pair(0U, &RISCV::GPRRegClass);
9042     case 'f':
9043       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9044         return std::make_pair(0U, &RISCV::FPR16RegClass);
9045       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9046         return std::make_pair(0U, &RISCV::FPR32RegClass);
9047       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9048         return std::make_pair(0U, &RISCV::FPR64RegClass);
9049       break;
9050     default:
9051       break;
9052     }
9053   } else {
9054     if (Constraint == "vr") {
9055       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9056                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9057         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9058           return std::make_pair(0U, RC);
9059       }
9060     } else if (Constraint == "vm") {
9061       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9062         return std::make_pair(0U, &RISCV::VMRegClass);
9063     }
9064   }
9065 
9066   // Clang will correctly decode the usage of register name aliases into their
9067   // official names. However, other frontends like `rustc` do not. This allows
9068   // users of these frontends to use the ABI names for registers in LLVM-style
9069   // register constraints.
9070   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9071                                .Case("{zero}", RISCV::X0)
9072                                .Case("{ra}", RISCV::X1)
9073                                .Case("{sp}", RISCV::X2)
9074                                .Case("{gp}", RISCV::X3)
9075                                .Case("{tp}", RISCV::X4)
9076                                .Case("{t0}", RISCV::X5)
9077                                .Case("{t1}", RISCV::X6)
9078                                .Case("{t2}", RISCV::X7)
9079                                .Cases("{s0}", "{fp}", RISCV::X8)
9080                                .Case("{s1}", RISCV::X9)
9081                                .Case("{a0}", RISCV::X10)
9082                                .Case("{a1}", RISCV::X11)
9083                                .Case("{a2}", RISCV::X12)
9084                                .Case("{a3}", RISCV::X13)
9085                                .Case("{a4}", RISCV::X14)
9086                                .Case("{a5}", RISCV::X15)
9087                                .Case("{a6}", RISCV::X16)
9088                                .Case("{a7}", RISCV::X17)
9089                                .Case("{s2}", RISCV::X18)
9090                                .Case("{s3}", RISCV::X19)
9091                                .Case("{s4}", RISCV::X20)
9092                                .Case("{s5}", RISCV::X21)
9093                                .Case("{s6}", RISCV::X22)
9094                                .Case("{s7}", RISCV::X23)
9095                                .Case("{s8}", RISCV::X24)
9096                                .Case("{s9}", RISCV::X25)
9097                                .Case("{s10}", RISCV::X26)
9098                                .Case("{s11}", RISCV::X27)
9099                                .Case("{t3}", RISCV::X28)
9100                                .Case("{t4}", RISCV::X29)
9101                                .Case("{t5}", RISCV::X30)
9102                                .Case("{t6}", RISCV::X31)
9103                                .Default(RISCV::NoRegister);
9104   if (XRegFromAlias != RISCV::NoRegister)
9105     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9106 
9107   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9108   // TableGen record rather than the AsmName to choose registers for InlineAsm
9109   // constraints, plus we want to match those names to the widest floating point
9110   // register type available, manually select floating point registers here.
9111   //
9112   // The second case is the ABI name of the register, so that frontends can also
9113   // use the ABI names in register constraint lists.
9114   if (Subtarget.hasStdExtF()) {
9115     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9116                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9117                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9118                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9119                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9120                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9121                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9122                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9123                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9124                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9125                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9126                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9127                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9128                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9129                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9130                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9131                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9132                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9133                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9134                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9135                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9136                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9137                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9138                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9139                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9140                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9141                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9142                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9143                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9144                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9145                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9146                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9147                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9148                         .Default(RISCV::NoRegister);
9149     if (FReg != RISCV::NoRegister) {
9150       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9151       if (Subtarget.hasStdExtD()) {
9152         unsigned RegNo = FReg - RISCV::F0_F;
9153         unsigned DReg = RISCV::F0_D + RegNo;
9154         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9155       }
9156       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9157     }
9158   }
9159 
9160   if (Subtarget.hasStdExtV()) {
9161     Register VReg = StringSwitch<Register>(Constraint.lower())
9162                         .Case("{v0}", RISCV::V0)
9163                         .Case("{v1}", RISCV::V1)
9164                         .Case("{v2}", RISCV::V2)
9165                         .Case("{v3}", RISCV::V3)
9166                         .Case("{v4}", RISCV::V4)
9167                         .Case("{v5}", RISCV::V5)
9168                         .Case("{v6}", RISCV::V6)
9169                         .Case("{v7}", RISCV::V7)
9170                         .Case("{v8}", RISCV::V8)
9171                         .Case("{v9}", RISCV::V9)
9172                         .Case("{v10}", RISCV::V10)
9173                         .Case("{v11}", RISCV::V11)
9174                         .Case("{v12}", RISCV::V12)
9175                         .Case("{v13}", RISCV::V13)
9176                         .Case("{v14}", RISCV::V14)
9177                         .Case("{v15}", RISCV::V15)
9178                         .Case("{v16}", RISCV::V16)
9179                         .Case("{v17}", RISCV::V17)
9180                         .Case("{v18}", RISCV::V18)
9181                         .Case("{v19}", RISCV::V19)
9182                         .Case("{v20}", RISCV::V20)
9183                         .Case("{v21}", RISCV::V21)
9184                         .Case("{v22}", RISCV::V22)
9185                         .Case("{v23}", RISCV::V23)
9186                         .Case("{v24}", RISCV::V24)
9187                         .Case("{v25}", RISCV::V25)
9188                         .Case("{v26}", RISCV::V26)
9189                         .Case("{v27}", RISCV::V27)
9190                         .Case("{v28}", RISCV::V28)
9191                         .Case("{v29}", RISCV::V29)
9192                         .Case("{v30}", RISCV::V30)
9193                         .Case("{v31}", RISCV::V31)
9194                         .Default(RISCV::NoRegister);
9195     if (VReg != RISCV::NoRegister) {
9196       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9197         return std::make_pair(VReg, &RISCV::VMRegClass);
9198       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9199         return std::make_pair(VReg, &RISCV::VRRegClass);
9200       for (const auto *RC :
9201            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9202         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9203           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9204           return std::make_pair(VReg, RC);
9205         }
9206       }
9207     }
9208   }
9209 
9210   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9211 }
9212 
9213 unsigned
9214 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9215   // Currently only support length 1 constraints.
9216   if (ConstraintCode.size() == 1) {
9217     switch (ConstraintCode[0]) {
9218     case 'A':
9219       return InlineAsm::Constraint_A;
9220     default:
9221       break;
9222     }
9223   }
9224 
9225   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9226 }
9227 
9228 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9229     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9230     SelectionDAG &DAG) const {
9231   // Currently only support length 1 constraints.
9232   if (Constraint.length() == 1) {
9233     switch (Constraint[0]) {
9234     case 'I':
9235       // Validate & create a 12-bit signed immediate operand.
9236       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9237         uint64_t CVal = C->getSExtValue();
9238         if (isInt<12>(CVal))
9239           Ops.push_back(
9240               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9241       }
9242       return;
9243     case 'J':
9244       // Validate & create an integer zero operand.
9245       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9246         if (C->getZExtValue() == 0)
9247           Ops.push_back(
9248               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9249       return;
9250     case 'K':
9251       // Validate & create a 5-bit unsigned immediate operand.
9252       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9253         uint64_t CVal = C->getZExtValue();
9254         if (isUInt<5>(CVal))
9255           Ops.push_back(
9256               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9257       }
9258       return;
9259     case 'S':
9260       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9261         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9262                                                  GA->getValueType(0)));
9263       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9264         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9265                                                 BA->getValueType(0)));
9266       }
9267       return;
9268     default:
9269       break;
9270     }
9271   }
9272   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9273 }
9274 
9275 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9276                                                    Instruction *Inst,
9277                                                    AtomicOrdering Ord) const {
9278   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9279     return Builder.CreateFence(Ord);
9280   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9281     return Builder.CreateFence(AtomicOrdering::Release);
9282   return nullptr;
9283 }
9284 
9285 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9286                                                     Instruction *Inst,
9287                                                     AtomicOrdering Ord) const {
9288   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9289     return Builder.CreateFence(AtomicOrdering::Acquire);
9290   return nullptr;
9291 }
9292 
9293 TargetLowering::AtomicExpansionKind
9294 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9295   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9296   // point operations can't be used in an lr/sc sequence without breaking the
9297   // forward-progress guarantee.
9298   if (AI->isFloatingPointOperation())
9299     return AtomicExpansionKind::CmpXChg;
9300 
9301   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9302   if (Size == 8 || Size == 16)
9303     return AtomicExpansionKind::MaskedIntrinsic;
9304   return AtomicExpansionKind::None;
9305 }
9306 
9307 static Intrinsic::ID
9308 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9309   if (XLen == 32) {
9310     switch (BinOp) {
9311     default:
9312       llvm_unreachable("Unexpected AtomicRMW BinOp");
9313     case AtomicRMWInst::Xchg:
9314       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9315     case AtomicRMWInst::Add:
9316       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9317     case AtomicRMWInst::Sub:
9318       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9319     case AtomicRMWInst::Nand:
9320       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9321     case AtomicRMWInst::Max:
9322       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9323     case AtomicRMWInst::Min:
9324       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9325     case AtomicRMWInst::UMax:
9326       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9327     case AtomicRMWInst::UMin:
9328       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9329     }
9330   }
9331 
9332   if (XLen == 64) {
9333     switch (BinOp) {
9334     default:
9335       llvm_unreachable("Unexpected AtomicRMW BinOp");
9336     case AtomicRMWInst::Xchg:
9337       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9338     case AtomicRMWInst::Add:
9339       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9340     case AtomicRMWInst::Sub:
9341       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9342     case AtomicRMWInst::Nand:
9343       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9344     case AtomicRMWInst::Max:
9345       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9346     case AtomicRMWInst::Min:
9347       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9348     case AtomicRMWInst::UMax:
9349       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9350     case AtomicRMWInst::UMin:
9351       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9352     }
9353   }
9354 
9355   llvm_unreachable("Unexpected XLen\n");
9356 }
9357 
9358 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9359     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9360     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9361   unsigned XLen = Subtarget.getXLen();
9362   Value *Ordering =
9363       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9364   Type *Tys[] = {AlignedAddr->getType()};
9365   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9366       AI->getModule(),
9367       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9368 
9369   if (XLen == 64) {
9370     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9371     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9372     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9373   }
9374 
9375   Value *Result;
9376 
9377   // Must pass the shift amount needed to sign extend the loaded value prior
9378   // to performing a signed comparison for min/max. ShiftAmt is the number of
9379   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9380   // is the number of bits to left+right shift the value in order to
9381   // sign-extend.
9382   if (AI->getOperation() == AtomicRMWInst::Min ||
9383       AI->getOperation() == AtomicRMWInst::Max) {
9384     const DataLayout &DL = AI->getModule()->getDataLayout();
9385     unsigned ValWidth =
9386         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9387     Value *SextShamt =
9388         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9389     Result = Builder.CreateCall(LrwOpScwLoop,
9390                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9391   } else {
9392     Result =
9393         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9394   }
9395 
9396   if (XLen == 64)
9397     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9398   return Result;
9399 }
9400 
9401 TargetLowering::AtomicExpansionKind
9402 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9403     AtomicCmpXchgInst *CI) const {
9404   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9405   if (Size == 8 || Size == 16)
9406     return AtomicExpansionKind::MaskedIntrinsic;
9407   return AtomicExpansionKind::None;
9408 }
9409 
9410 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9411     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9412     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9413   unsigned XLen = Subtarget.getXLen();
9414   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9415   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9416   if (XLen == 64) {
9417     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9418     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9419     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9420     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9421   }
9422   Type *Tys[] = {AlignedAddr->getType()};
9423   Function *MaskedCmpXchg =
9424       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9425   Value *Result = Builder.CreateCall(
9426       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9427   if (XLen == 64)
9428     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9429   return Result;
9430 }
9431 
9432 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9433   return false;
9434 }
9435 
9436 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9437                                                      EVT VT) const {
9438   VT = VT.getScalarType();
9439 
9440   if (!VT.isSimple())
9441     return false;
9442 
9443   switch (VT.getSimpleVT().SimpleTy) {
9444   case MVT::f16:
9445     return Subtarget.hasStdExtZfh();
9446   case MVT::f32:
9447     return Subtarget.hasStdExtF();
9448   case MVT::f64:
9449     return Subtarget.hasStdExtD();
9450   default:
9451     break;
9452   }
9453 
9454   return false;
9455 }
9456 
9457 Register RISCVTargetLowering::getExceptionPointerRegister(
9458     const Constant *PersonalityFn) const {
9459   return RISCV::X10;
9460 }
9461 
9462 Register RISCVTargetLowering::getExceptionSelectorRegister(
9463     const Constant *PersonalityFn) const {
9464   return RISCV::X11;
9465 }
9466 
9467 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9468   // Return false to suppress the unnecessary extensions if the LibCall
9469   // arguments or return value is f32 type for LP64 ABI.
9470   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9471   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9472     return false;
9473 
9474   return true;
9475 }
9476 
9477 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9478   if (Subtarget.is64Bit() && Type == MVT::i32)
9479     return true;
9480 
9481   return IsSigned;
9482 }
9483 
9484 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9485                                                  SDValue C) const {
9486   // Check integral scalar types.
9487   if (VT.isScalarInteger()) {
9488     // Omit the optimization if the sub target has the M extension and the data
9489     // size exceeds XLen.
9490     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9491       return false;
9492     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9493       // Break the MUL to a SLLI and an ADD/SUB.
9494       const APInt &Imm = ConstNode->getAPIntValue();
9495       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9496           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9497         return true;
9498       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9499       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9500           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9501            (Imm - 8).isPowerOf2()))
9502         return true;
9503       // Omit the following optimization if the sub target has the M extension
9504       // and the data size >= XLen.
9505       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9506         return false;
9507       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9508       // a pair of LUI/ADDI.
9509       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9510         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9511         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9512             (1 - ImmS).isPowerOf2())
9513         return true;
9514       }
9515     }
9516   }
9517 
9518   return false;
9519 }
9520 
9521 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9522     const SDValue &AddNode, const SDValue &ConstNode) const {
9523   // Let the DAGCombiner decide for vectors.
9524   EVT VT = AddNode.getValueType();
9525   if (VT.isVector())
9526     return true;
9527 
9528   // Let the DAGCombiner decide for larger types.
9529   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9530     return true;
9531 
9532   // It is worse if c1 is simm12 while c1*c2 is not.
9533   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9534   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9535   const APInt &C1 = C1Node->getAPIntValue();
9536   const APInt &C2 = C2Node->getAPIntValue();
9537   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9538     return false;
9539 
9540   // Default to true and let the DAGCombiner decide.
9541   return true;
9542 }
9543 
9544 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9545     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9546     bool *Fast) const {
9547   if (!VT.isVector())
9548     return false;
9549 
9550   EVT ElemVT = VT.getVectorElementType();
9551   if (Alignment >= ElemVT.getStoreSize()) {
9552     if (Fast)
9553       *Fast = true;
9554     return true;
9555   }
9556 
9557   return false;
9558 }
9559 
9560 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9561     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9562     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9563   bool IsABIRegCopy = CC.hasValue();
9564   EVT ValueVT = Val.getValueType();
9565   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9566     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9567     // and cast to f32.
9568     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9569     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9570     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9571                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9572     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9573     Parts[0] = Val;
9574     return true;
9575   }
9576 
9577   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9578     LLVMContext &Context = *DAG.getContext();
9579     EVT ValueEltVT = ValueVT.getVectorElementType();
9580     EVT PartEltVT = PartVT.getVectorElementType();
9581     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9582     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9583     if (PartVTBitSize % ValueVTBitSize == 0) {
9584       // If the element types are different, bitcast to the same element type of
9585       // PartVT first.
9586       if (ValueEltVT != PartEltVT) {
9587         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9588         assert(Count != 0 && "The number of element should not be zero.");
9589         EVT SameEltTypeVT =
9590             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9591         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9592       }
9593       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9594                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9595       Parts[0] = Val;
9596       return true;
9597     }
9598   }
9599   return false;
9600 }
9601 
9602 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9603     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9604     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9605   bool IsABIRegCopy = CC.hasValue();
9606   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9607     SDValue Val = Parts[0];
9608 
9609     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9610     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9611     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9612     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9613     return Val;
9614   }
9615 
9616   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9617     LLVMContext &Context = *DAG.getContext();
9618     SDValue Val = Parts[0];
9619     EVT ValueEltVT = ValueVT.getVectorElementType();
9620     EVT PartEltVT = PartVT.getVectorElementType();
9621     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9622     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9623     if (PartVTBitSize % ValueVTBitSize == 0) {
9624       EVT SameEltTypeVT = ValueVT;
9625       // If the element types are different, convert it to the same element type
9626       // of PartVT.
9627       if (ValueEltVT != PartEltVT) {
9628         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9629         assert(Count != 0 && "The number of element should not be zero.");
9630         SameEltTypeVT =
9631             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9632       }
9633       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9634                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9635       if (ValueEltVT != PartEltVT)
9636         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9637       return Val;
9638     }
9639   }
9640   return SDValue();
9641 }
9642 
9643 #define GET_REGISTER_MATCHER
9644 #include "RISCVGenAsmMatcher.inc"
9645 
9646 Register
9647 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9648                                        const MachineFunction &MF) const {
9649   Register Reg = MatchRegisterAltName(RegName);
9650   if (Reg == RISCV::NoRegister)
9651     Reg = MatchRegisterName(RegName);
9652   if (Reg == RISCV::NoRegister)
9653     report_fatal_error(
9654         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9655   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9656   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9657     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9658                              StringRef(RegName) + "\"."));
9659   return Reg;
9660 }
9661 
9662 namespace llvm {
9663 namespace RISCVVIntrinsicsTable {
9664 
9665 #define GET_RISCVVIntrinsicsTable_IMPL
9666 #include "RISCVGenSearchableTables.inc"
9667 
9668 } // namespace RISCVVIntrinsicsTable
9669 
9670 } // namespace llvm
9671