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