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