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