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