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