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