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