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