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