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