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