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