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/Analysis/MemoryLocation.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/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasVInstructions()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs) {
132       if (VT.getVectorElementType() == MVT::i64 &&
133           !Subtarget.hasVInstructionsI64())
134         continue;
135       addRegClassForRVV(VT);
136     }
137 
138     if (Subtarget.hasVInstructionsF16())
139       for (MVT VT : F16VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasVInstructionsF32())
143       for (MVT VT : F32VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.hasVInstructionsF64())
147       for (MVT VT : F64VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.useRVVForFixedLengthVectors()) {
151       auto addRegClassForFixedVectors = [this](MVT VT) {
152         MVT ContainerVT = getContainerForFixedLengthVector(VT);
153         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
154         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
155         addRegisterClass(VT, TRI.getRegClass(RCID));
156       };
157       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160 
161       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164     }
165   }
166 
167   // Compute derived properties from the register classes.
168   computeRegisterProperties(STI.getRegisterInfo());
169 
170   setStackPointerRegisterToSaveRestore(RISCV::X2);
171 
172   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
173     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
174 
175   // TODO: add all necessary setOperationAction calls.
176   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
177 
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::BR_CC, XLenVT, Expand);
180   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
181   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
182 
183   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
184   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction(ISD::VAARG, MVT::Other, Expand);
188   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
189   setOperationAction(ISD::VAEND, MVT::Other, Expand);
190 
191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
192   if (!Subtarget.hasStdExtZbb()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195   }
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::ADD, MVT::i32, Custom);
199     setOperationAction(ISD::SUB, MVT::i32, Custom);
200     setOperationAction(ISD::SHL, MVT::i32, Custom);
201     setOperationAction(ISD::SRA, MVT::i32, Custom);
202     setOperationAction(ISD::SRL, MVT::i32, Custom);
203 
204     setOperationAction(ISD::UADDO, MVT::i32, Custom);
205     setOperationAction(ISD::USUBO, MVT::i32, Custom);
206     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
207     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
208   } else {
209     setLibcallName(RTLIB::SHL_I128, nullptr);
210     setLibcallName(RTLIB::SRL_I128, nullptr);
211     setLibcallName(RTLIB::SRA_I128, nullptr);
212     setLibcallName(RTLIB::MUL_I128, nullptr);
213     setLibcallName(RTLIB::MULO_I64, nullptr);
214   }
215 
216   if (!Subtarget.hasStdExtM()) {
217     setOperationAction(ISD::MUL, XLenVT, Expand);
218     setOperationAction(ISD::MULHS, XLenVT, Expand);
219     setOperationAction(ISD::MULHU, XLenVT, Expand);
220     setOperationAction(ISD::SDIV, XLenVT, Expand);
221     setOperationAction(ISD::UDIV, XLenVT, Expand);
222     setOperationAction(ISD::SREM, XLenVT, Expand);
223     setOperationAction(ISD::UREM, XLenVT, Expand);
224   } else {
225     if (Subtarget.is64Bit()) {
226       setOperationAction(ISD::MUL, MVT::i32, Custom);
227       setOperationAction(ISD::MUL, MVT::i128, Custom);
228 
229       setOperationAction(ISD::SDIV, MVT::i8, Custom);
230       setOperationAction(ISD::UDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UREM, MVT::i8, Custom);
232       setOperationAction(ISD::SDIV, MVT::i16, Custom);
233       setOperationAction(ISD::UDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UREM, MVT::i16, Custom);
235       setOperationAction(ISD::SDIV, MVT::i32, Custom);
236       setOperationAction(ISD::UDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UREM, MVT::i32, Custom);
238     } else {
239       setOperationAction(ISD::MUL, MVT::i64, Custom);
240     }
241   }
242 
243   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
244   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
246   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
247 
248   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
249   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
251 
252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
253     if (Subtarget.is64Bit()) {
254       setOperationAction(ISD::ROTL, MVT::i32, Custom);
255       setOperationAction(ISD::ROTR, MVT::i32, Custom);
256     }
257   } else {
258     setOperationAction(ISD::ROTL, XLenVT, Expand);
259     setOperationAction(ISD::ROTR, XLenVT, Expand);
260   }
261 
262   if (Subtarget.hasStdExtZbp()) {
263     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
264     // more combining.
265     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
266     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
267     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
268     // BSWAP i8 doesn't exist.
269     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
270     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
271 
272     if (Subtarget.is64Bit()) {
273       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
274       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
275     }
276   } else {
277     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
278     // pattern match it directly in isel.
279     setOperationAction(ISD::BSWAP, XLenVT,
280                        Subtarget.hasStdExtZbb() ? Legal : Expand);
281   }
282 
283   if (Subtarget.hasStdExtZbb()) {
284     setOperationAction(ISD::SMIN, XLenVT, Legal);
285     setOperationAction(ISD::SMAX, XLenVT, Legal);
286     setOperationAction(ISD::UMIN, XLenVT, Legal);
287     setOperationAction(ISD::UMAX, XLenVT, Legal);
288 
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
291       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
292       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
294     }
295   } else {
296     setOperationAction(ISD::CTTZ, XLenVT, Expand);
297     setOperationAction(ISD::CTLZ, XLenVT, Expand);
298     setOperationAction(ISD::CTPOP, XLenVT, Expand);
299   }
300 
301   if (Subtarget.hasStdExtZbt()) {
302     setOperationAction(ISD::FSHL, XLenVT, Custom);
303     setOperationAction(ISD::FSHR, XLenVT, Custom);
304     setOperationAction(ISD::SELECT, XLenVT, Legal);
305 
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FSHL, MVT::i32, Custom);
308       setOperationAction(ISD::FSHR, MVT::i32, Custom);
309     }
310   } else {
311     setOperationAction(ISD::SELECT, XLenVT, Custom);
312   }
313 
314   static const ISD::CondCode FPCCToExpand[] = {
315       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
316       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
317       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
318 
319   static const ISD::NodeType FPOpToExpand[] = {
320       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
321       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
322 
323   if (Subtarget.hasStdExtZfh())
324     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
325 
326   if (Subtarget.hasStdExtZfh()) {
327     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
328     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
329     setOperationAction(ISD::LRINT, MVT::f16, Legal);
330     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LROUND, MVT::f16, Legal);
332     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
333     for (auto CC : FPCCToExpand)
334       setCondCodeAction(CC, MVT::f16, Expand);
335     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
336     setOperationAction(ISD::SELECT, MVT::f16, Custom);
337     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
338 
339     setOperationAction(ISD::FREM,       MVT::f16, Promote);
340     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
341     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
342     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
343     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
344     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
345     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
346     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
347     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
348     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
349     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
350     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
351     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
352     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
353     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
354     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
355     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
356     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
357 
358     // We need to custom promote this.
359     if (Subtarget.is64Bit())
360       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
361   }
362 
363   if (Subtarget.hasStdExtF()) {
364     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
365     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
366     setOperationAction(ISD::LRINT, MVT::f32, Legal);
367     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
368     setOperationAction(ISD::LROUND, MVT::f32, Legal);
369     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
370     for (auto CC : FPCCToExpand)
371       setCondCodeAction(CC, MVT::f32, Expand);
372     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
373     setOperationAction(ISD::SELECT, MVT::f32, Custom);
374     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
375     for (auto Op : FPOpToExpand)
376       setOperationAction(Op, MVT::f32, Expand);
377     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
378     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
379   }
380 
381   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
382     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
383 
384   if (Subtarget.hasStdExtD()) {
385     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
386     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
387     setOperationAction(ISD::LRINT, MVT::f64, Legal);
388     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
389     setOperationAction(ISD::LROUND, MVT::f64, Legal);
390     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
391     for (auto CC : FPCCToExpand)
392       setCondCodeAction(CC, MVT::f64, Expand);
393     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
394     setOperationAction(ISD::SELECT, MVT::f64, Custom);
395     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
396     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
397     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
398     for (auto Op : FPOpToExpand)
399       setOperationAction(Op, MVT::f64, Expand);
400     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
401     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
402   }
403 
404   if (Subtarget.is64Bit()) {
405     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
406     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
407     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
408     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
409   }
410 
411   if (Subtarget.hasStdExtF()) {
412     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
413     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
414 
415     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
416     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
417   }
418 
419   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
420   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
421   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
422   setOperationAction(ISD::JumpTable, XLenVT, Custom);
423 
424   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
425 
426   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
427   // Unfortunately this can't be determined just from the ISA naming string.
428   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
429                      Subtarget.is64Bit() ? Legal : Custom);
430 
431   setOperationAction(ISD::TRAP, MVT::Other, Legal);
432   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
433   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
434   if (Subtarget.is64Bit())
435     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
436 
437   if (Subtarget.hasStdExtA()) {
438     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
439     setMinCmpXchgSizeInBits(32);
440   } else {
441     setMaxAtomicSizeInBitsSupported(0);
442   }
443 
444   setBooleanContents(ZeroOrOneBooleanContent);
445 
446   if (Subtarget.hasVInstructions()) {
447     setBooleanVectorContents(ZeroOrOneBooleanContent);
448 
449     setOperationAction(ISD::VSCALE, XLenVT, Custom);
450 
451     // RVV intrinsics may have illegal operands.
452     // We also need to custom legalize vmv.x.s.
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
454     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
455     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
456     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
457     if (Subtarget.is64Bit()) {
458       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
459     } else {
460       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
461       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
462     }
463 
464     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
465     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
466 
467     static const unsigned IntegerVPOps[] = {
468         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
469         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
470         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
471         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
472         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
473         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
474         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
475         ISD::VP_SELECT};
476 
477     static const unsigned FloatingPointVPOps[] = {
478         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
479         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
480         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
481 
482     if (!Subtarget.is64Bit()) {
483       // We must custom-lower certain vXi64 operations on RV32 due to the vector
484       // element type being illegal.
485       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
486       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
487 
488       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
489       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
490       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
491       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
492       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
493       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
494       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
495       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
496 
497       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
498       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
499       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
500       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
501       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
502       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
503       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
504       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
505     }
506 
507     for (MVT VT : BoolVecVTs) {
508       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
509 
510       // Mask VTs are custom-expanded into a series of standard nodes
511       setOperationAction(ISD::TRUNCATE, VT, Custom);
512       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
513       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
514       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
515 
516       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
517       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
518 
519       setOperationAction(ISD::SELECT, VT, Custom);
520       setOperationAction(ISD::SELECT_CC, VT, Expand);
521       setOperationAction(ISD::VSELECT, VT, Expand);
522 
523       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
524       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
525       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
526 
527       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
528       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
529       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
530 
531       // RVV has native int->float & float->int conversions where the
532       // element type sizes are within one power-of-two of each other. Any
533       // wider distances between type sizes have to be lowered as sequences
534       // which progressively narrow the gap in stages.
535       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
536       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
537       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
538       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
539 
540       // Expand all extending loads to types larger than this, and truncating
541       // stores from types larger than this.
542       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
543         setTruncStoreAction(OtherVT, VT, Expand);
544         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
545         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
546         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
547       }
548     }
549 
550     for (MVT VT : IntVecVTs) {
551       if (VT.getVectorElementType() == MVT::i64 &&
552           !Subtarget.hasVInstructionsI64())
553         continue;
554 
555       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
556       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
557 
558       // Vectors implement MULHS/MULHU.
559       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
560       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
561 
562       setOperationAction(ISD::SMIN, VT, Legal);
563       setOperationAction(ISD::SMAX, VT, Legal);
564       setOperationAction(ISD::UMIN, VT, Legal);
565       setOperationAction(ISD::UMAX, VT, Legal);
566 
567       setOperationAction(ISD::ROTL, VT, Expand);
568       setOperationAction(ISD::ROTR, VT, Expand);
569 
570       setOperationAction(ISD::CTTZ, VT, Expand);
571       setOperationAction(ISD::CTLZ, VT, Expand);
572       setOperationAction(ISD::CTPOP, VT, Expand);
573 
574       setOperationAction(ISD::BSWAP, VT, Expand);
575 
576       // Custom-lower extensions and truncations from/to mask types.
577       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
578       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
579       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
580 
581       // RVV has native int->float & float->int conversions where the
582       // element type sizes are within one power-of-two of each other. Any
583       // wider distances between type sizes have to be lowered as sequences
584       // which progressively narrow the gap in stages.
585       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
586       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
587       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
588       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
589 
590       setOperationAction(ISD::SADDSAT, VT, Legal);
591       setOperationAction(ISD::UADDSAT, VT, Legal);
592       setOperationAction(ISD::SSUBSAT, VT, Legal);
593       setOperationAction(ISD::USUBSAT, VT, Legal);
594 
595       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
596       // nodes which truncate by one power of two at a time.
597       setOperationAction(ISD::TRUNCATE, VT, Custom);
598 
599       // Custom-lower insert/extract operations to simplify patterns.
600       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
601       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
602 
603       // Custom-lower reduction operations to set up the corresponding custom
604       // nodes' operands.
605       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
606       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
607       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
608       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
609       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
610       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
611       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
612       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
613 
614       for (unsigned VPOpc : IntegerVPOps)
615         setOperationAction(VPOpc, VT, Custom);
616 
617       setOperationAction(ISD::LOAD, VT, Custom);
618       setOperationAction(ISD::STORE, VT, Custom);
619 
620       setOperationAction(ISD::MLOAD, VT, Custom);
621       setOperationAction(ISD::MSTORE, VT, Custom);
622       setOperationAction(ISD::MGATHER, VT, Custom);
623       setOperationAction(ISD::MSCATTER, VT, Custom);
624 
625       setOperationAction(ISD::VP_LOAD, VT, Custom);
626       setOperationAction(ISD::VP_STORE, VT, Custom);
627       setOperationAction(ISD::VP_GATHER, VT, Custom);
628       setOperationAction(ISD::VP_SCATTER, VT, Custom);
629 
630       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
631       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
632       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
633 
634       setOperationAction(ISD::SELECT, VT, Custom);
635       setOperationAction(ISD::SELECT_CC, VT, Expand);
636 
637       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
638       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
639 
640       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
641         setTruncStoreAction(VT, OtherVT, Expand);
642         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
643         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
644         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
645       }
646 
647       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
648       // type that can represent the value exactly.
649       if (VT.getVectorElementType() != MVT::i64) {
650         MVT FloatEltVT =
651             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
652         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
653         if (isTypeLegal(FloatVT)) {
654           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
655           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
656         }
657       }
658     }
659 
660     // Expand various CCs to best match the RVV ISA, which natively supports UNE
661     // but no other unordered comparisons, and supports all ordered comparisons
662     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
663     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
664     // and we pattern-match those back to the "original", swapping operands once
665     // more. This way we catch both operations and both "vf" and "fv" forms with
666     // fewer patterns.
667     static const ISD::CondCode VFPCCToExpand[] = {
668         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
669         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
670         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
671     };
672 
673     // Sets common operation actions on RVV floating-point vector types.
674     const auto SetCommonVFPActions = [&](MVT VT) {
675       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
676       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
677       // sizes are within one power-of-two of each other. Therefore conversions
678       // between vXf16 and vXf64 must be lowered as sequences which convert via
679       // vXf32.
680       setOperationAction(ISD::FP_ROUND, VT, Custom);
681       setOperationAction(ISD::FP_EXTEND, VT, Custom);
682       // Custom-lower insert/extract operations to simplify patterns.
683       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
684       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
685       // Expand various condition codes (explained above).
686       for (auto CC : VFPCCToExpand)
687         setCondCodeAction(CC, VT, Expand);
688 
689       setOperationAction(ISD::FMINNUM, VT, Legal);
690       setOperationAction(ISD::FMAXNUM, VT, Legal);
691 
692       setOperationAction(ISD::FTRUNC, VT, Custom);
693       setOperationAction(ISD::FCEIL, VT, Custom);
694       setOperationAction(ISD::FFLOOR, VT, Custom);
695 
696       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
697       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
698       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
699       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
700 
701       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
702 
703       setOperationAction(ISD::LOAD, VT, Custom);
704       setOperationAction(ISD::STORE, VT, Custom);
705 
706       setOperationAction(ISD::MLOAD, VT, Custom);
707       setOperationAction(ISD::MSTORE, VT, Custom);
708       setOperationAction(ISD::MGATHER, VT, Custom);
709       setOperationAction(ISD::MSCATTER, VT, Custom);
710 
711       setOperationAction(ISD::VP_LOAD, VT, Custom);
712       setOperationAction(ISD::VP_STORE, VT, Custom);
713       setOperationAction(ISD::VP_GATHER, VT, Custom);
714       setOperationAction(ISD::VP_SCATTER, VT, Custom);
715 
716       setOperationAction(ISD::SELECT, VT, Custom);
717       setOperationAction(ISD::SELECT_CC, VT, Expand);
718 
719       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
720       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
721       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
722 
723       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
724 
725       for (unsigned VPOpc : FloatingPointVPOps)
726         setOperationAction(VPOpc, VT, Custom);
727     };
728 
729     // Sets common extload/truncstore actions on RVV floating-point vector
730     // types.
731     const auto SetCommonVFPExtLoadTruncStoreActions =
732         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
733           for (auto SmallVT : SmallerVTs) {
734             setTruncStoreAction(VT, SmallVT, Expand);
735             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
736           }
737         };
738 
739     if (Subtarget.hasVInstructionsF16())
740       for (MVT VT : F16VecVTs)
741         SetCommonVFPActions(VT);
742 
743     for (MVT VT : F32VecVTs) {
744       if (Subtarget.hasVInstructionsF32())
745         SetCommonVFPActions(VT);
746       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
747     }
748 
749     for (MVT VT : F64VecVTs) {
750       if (Subtarget.hasVInstructionsF64())
751         SetCommonVFPActions(VT);
752       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
753       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
754     }
755 
756     if (Subtarget.useRVVForFixedLengthVectors()) {
757       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
758         if (!useRVVForFixedLengthVectorVT(VT))
759           continue;
760 
761         // By default everything must be expanded.
762         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
763           setOperationAction(Op, VT, Expand);
764         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
765           setTruncStoreAction(VT, OtherVT, Expand);
766           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
767           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
768           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
769         }
770 
771         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
772         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
773         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
774 
775         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
776         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
777 
778         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
779         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
780 
781         setOperationAction(ISD::LOAD, VT, Custom);
782         setOperationAction(ISD::STORE, VT, Custom);
783 
784         setOperationAction(ISD::SETCC, VT, Custom);
785 
786         setOperationAction(ISD::SELECT, VT, Custom);
787 
788         setOperationAction(ISD::TRUNCATE, VT, Custom);
789 
790         setOperationAction(ISD::BITCAST, VT, Custom);
791 
792         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
793         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
794         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
795 
796         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
797         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
798         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
799 
800         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
801         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
802         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
803         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
804 
805         // Operations below are different for between masks and other vectors.
806         if (VT.getVectorElementType() == MVT::i1) {
807           setOperationAction(ISD::AND, VT, Custom);
808           setOperationAction(ISD::OR, VT, Custom);
809           setOperationAction(ISD::XOR, VT, Custom);
810           continue;
811         }
812 
813         // Use SPLAT_VECTOR to prevent type legalization from destroying the
814         // splats when type legalizing i64 scalar on RV32.
815         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
816         // improvements first.
817         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
818           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
819           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
820         }
821 
822         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
823         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
824 
825         setOperationAction(ISD::MLOAD, VT, Custom);
826         setOperationAction(ISD::MSTORE, VT, Custom);
827         setOperationAction(ISD::MGATHER, VT, Custom);
828         setOperationAction(ISD::MSCATTER, VT, Custom);
829 
830         setOperationAction(ISD::VP_LOAD, VT, Custom);
831         setOperationAction(ISD::VP_STORE, VT, Custom);
832         setOperationAction(ISD::VP_GATHER, VT, Custom);
833         setOperationAction(ISD::VP_SCATTER, VT, Custom);
834 
835         setOperationAction(ISD::ADD, VT, Custom);
836         setOperationAction(ISD::MUL, VT, Custom);
837         setOperationAction(ISD::SUB, VT, Custom);
838         setOperationAction(ISD::AND, VT, Custom);
839         setOperationAction(ISD::OR, VT, Custom);
840         setOperationAction(ISD::XOR, VT, Custom);
841         setOperationAction(ISD::SDIV, VT, Custom);
842         setOperationAction(ISD::SREM, VT, Custom);
843         setOperationAction(ISD::UDIV, VT, Custom);
844         setOperationAction(ISD::UREM, VT, Custom);
845         setOperationAction(ISD::SHL, VT, Custom);
846         setOperationAction(ISD::SRA, VT, Custom);
847         setOperationAction(ISD::SRL, VT, Custom);
848 
849         setOperationAction(ISD::SMIN, VT, Custom);
850         setOperationAction(ISD::SMAX, VT, Custom);
851         setOperationAction(ISD::UMIN, VT, Custom);
852         setOperationAction(ISD::UMAX, VT, Custom);
853         setOperationAction(ISD::ABS,  VT, Custom);
854 
855         setOperationAction(ISD::MULHS, VT, Custom);
856         setOperationAction(ISD::MULHU, VT, Custom);
857 
858         setOperationAction(ISD::SADDSAT, VT, Custom);
859         setOperationAction(ISD::UADDSAT, VT, Custom);
860         setOperationAction(ISD::SSUBSAT, VT, Custom);
861         setOperationAction(ISD::USUBSAT, VT, Custom);
862 
863         setOperationAction(ISD::VSELECT, VT, Custom);
864         setOperationAction(ISD::SELECT_CC, VT, Expand);
865 
866         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
867         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
868         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
869 
870         // Custom-lower reduction operations to set up the corresponding custom
871         // nodes' operands.
872         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
873         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
874         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
875         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
876         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
877 
878         for (unsigned VPOpc : IntegerVPOps)
879           setOperationAction(VPOpc, VT, Custom);
880 
881         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
882         // type that can represent the value exactly.
883         if (VT.getVectorElementType() != MVT::i64) {
884           MVT FloatEltVT =
885               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
886           EVT FloatVT =
887               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
888           if (isTypeLegal(FloatVT)) {
889             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
890             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
891           }
892         }
893       }
894 
895       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
896         if (!useRVVForFixedLengthVectorVT(VT))
897           continue;
898 
899         // By default everything must be expanded.
900         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
901           setOperationAction(Op, VT, Expand);
902         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
903           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
904           setTruncStoreAction(VT, OtherVT, Expand);
905         }
906 
907         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
908         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
909         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
910 
911         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
912         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
913         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
914         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
915         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
916 
917         setOperationAction(ISD::LOAD, VT, Custom);
918         setOperationAction(ISD::STORE, VT, Custom);
919         setOperationAction(ISD::MLOAD, VT, Custom);
920         setOperationAction(ISD::MSTORE, VT, Custom);
921         setOperationAction(ISD::MGATHER, VT, Custom);
922         setOperationAction(ISD::MSCATTER, VT, Custom);
923 
924         setOperationAction(ISD::VP_LOAD, VT, Custom);
925         setOperationAction(ISD::VP_STORE, VT, Custom);
926         setOperationAction(ISD::VP_GATHER, VT, Custom);
927         setOperationAction(ISD::VP_SCATTER, VT, Custom);
928 
929         setOperationAction(ISD::FADD, VT, Custom);
930         setOperationAction(ISD::FSUB, VT, Custom);
931         setOperationAction(ISD::FMUL, VT, Custom);
932         setOperationAction(ISD::FDIV, VT, Custom);
933         setOperationAction(ISD::FNEG, VT, Custom);
934         setOperationAction(ISD::FABS, VT, Custom);
935         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
936         setOperationAction(ISD::FSQRT, VT, Custom);
937         setOperationAction(ISD::FMA, VT, Custom);
938         setOperationAction(ISD::FMINNUM, VT, Custom);
939         setOperationAction(ISD::FMAXNUM, VT, Custom);
940 
941         setOperationAction(ISD::FP_ROUND, VT, Custom);
942         setOperationAction(ISD::FP_EXTEND, VT, Custom);
943 
944         setOperationAction(ISD::FTRUNC, VT, Custom);
945         setOperationAction(ISD::FCEIL, VT, Custom);
946         setOperationAction(ISD::FFLOOR, VT, Custom);
947 
948         for (auto CC : VFPCCToExpand)
949           setCondCodeAction(CC, VT, Expand);
950 
951         setOperationAction(ISD::VSELECT, VT, Custom);
952         setOperationAction(ISD::SELECT, VT, Custom);
953         setOperationAction(ISD::SELECT_CC, VT, Expand);
954 
955         setOperationAction(ISD::BITCAST, VT, Custom);
956 
957         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
958         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
959         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
960         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
961 
962         for (unsigned VPOpc : FloatingPointVPOps)
963           setOperationAction(VPOpc, VT, Custom);
964       }
965 
966       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
967       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
968       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
969       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
970       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
971       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
972       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
973       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
974     }
975   }
976 
977   // Function alignments.
978   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
979   setMinFunctionAlignment(FunctionAlignment);
980   setPrefFunctionAlignment(FunctionAlignment);
981 
982   setMinimumJumpTableEntries(5);
983 
984   // Jumps are expensive, compared to logic
985   setJumpIsExpensive();
986 
987   setTargetDAGCombine(ISD::ADD);
988   setTargetDAGCombine(ISD::SUB);
989   setTargetDAGCombine(ISD::AND);
990   setTargetDAGCombine(ISD::OR);
991   setTargetDAGCombine(ISD::XOR);
992   setTargetDAGCombine(ISD::ANY_EXTEND);
993   setTargetDAGCombine(ISD::ZERO_EXTEND);
994   if (Subtarget.hasVInstructions()) {
995     setTargetDAGCombine(ISD::FCOPYSIGN);
996     setTargetDAGCombine(ISD::MGATHER);
997     setTargetDAGCombine(ISD::MSCATTER);
998     setTargetDAGCombine(ISD::VP_GATHER);
999     setTargetDAGCombine(ISD::VP_SCATTER);
1000     setTargetDAGCombine(ISD::SRA);
1001     setTargetDAGCombine(ISD::SRL);
1002     setTargetDAGCombine(ISD::SHL);
1003     setTargetDAGCombine(ISD::STORE);
1004   }
1005 }
1006 
1007 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1008                                             LLVMContext &Context,
1009                                             EVT VT) const {
1010   if (!VT.isVector())
1011     return getPointerTy(DL);
1012   if (Subtarget.hasVInstructions() &&
1013       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1014     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1015   return VT.changeVectorElementTypeToInteger();
1016 }
1017 
1018 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1019   return Subtarget.getXLenVT();
1020 }
1021 
1022 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1023                                              const CallInst &I,
1024                                              MachineFunction &MF,
1025                                              unsigned Intrinsic) const {
1026   auto &DL = I.getModule()->getDataLayout();
1027   switch (Intrinsic) {
1028   default:
1029     return false;
1030   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1031   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1032   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1033   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1034   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1035   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1036   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1037   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1038   case Intrinsic::riscv_masked_cmpxchg_i32: {
1039     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1040     Info.opc = ISD::INTRINSIC_W_CHAIN;
1041     Info.memVT = MVT::getVT(PtrTy->getElementType());
1042     Info.ptrVal = I.getArgOperand(0);
1043     Info.offset = 0;
1044     Info.align = Align(4);
1045     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1046                  MachineMemOperand::MOVolatile;
1047     return true;
1048   }
1049   case Intrinsic::riscv_masked_strided_load:
1050     Info.opc = ISD::INTRINSIC_W_CHAIN;
1051     Info.ptrVal = I.getArgOperand(1);
1052     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1053     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1054     Info.size = MemoryLocation::UnknownSize;
1055     Info.flags |= MachineMemOperand::MOLoad;
1056     return true;
1057   case Intrinsic::riscv_masked_strided_store:
1058     Info.opc = ISD::INTRINSIC_VOID;
1059     Info.ptrVal = I.getArgOperand(1);
1060     Info.memVT =
1061         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1062     Info.align = Align(
1063         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1064         8);
1065     Info.size = MemoryLocation::UnknownSize;
1066     Info.flags |= MachineMemOperand::MOStore;
1067     return true;
1068   }
1069 }
1070 
1071 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1072                                                 const AddrMode &AM, Type *Ty,
1073                                                 unsigned AS,
1074                                                 Instruction *I) const {
1075   // No global is ever allowed as a base.
1076   if (AM.BaseGV)
1077     return false;
1078 
1079   // Require a 12-bit signed offset.
1080   if (!isInt<12>(AM.BaseOffs))
1081     return false;
1082 
1083   switch (AM.Scale) {
1084   case 0: // "r+i" or just "i", depending on HasBaseReg.
1085     break;
1086   case 1:
1087     if (!AM.HasBaseReg) // allow "r+i".
1088       break;
1089     return false; // disallow "r+r" or "r+r+i".
1090   default:
1091     return false;
1092   }
1093 
1094   return true;
1095 }
1096 
1097 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1098   return isInt<12>(Imm);
1099 }
1100 
1101 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1102   return isInt<12>(Imm);
1103 }
1104 
1105 // On RV32, 64-bit integers are split into their high and low parts and held
1106 // in two different registers, so the trunc is free since the low register can
1107 // just be used.
1108 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1109   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1110     return false;
1111   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1112   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1113   return (SrcBits == 64 && DestBits == 32);
1114 }
1115 
1116 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1117   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1118       !SrcVT.isInteger() || !DstVT.isInteger())
1119     return false;
1120   unsigned SrcBits = SrcVT.getSizeInBits();
1121   unsigned DestBits = DstVT.getSizeInBits();
1122   return (SrcBits == 64 && DestBits == 32);
1123 }
1124 
1125 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1126   // Zexts are free if they can be combined with a load.
1127   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1128     EVT MemVT = LD->getMemoryVT();
1129     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1130          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1131         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1132          LD->getExtensionType() == ISD::ZEXTLOAD))
1133       return true;
1134   }
1135 
1136   return TargetLowering::isZExtFree(Val, VT2);
1137 }
1138 
1139 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1140   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1141 }
1142 
1143 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1144   return Subtarget.hasStdExtZbb();
1145 }
1146 
1147 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1148   return Subtarget.hasStdExtZbb();
1149 }
1150 
1151 bool RISCVTargetLowering::hasAndNot(SDValue Y) const {
1152   EVT VT = Y.getValueType();
1153 
1154   // FIXME: Support vectors once we have tests.
1155   if (VT.isVector())
1156     return false;
1157 
1158   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1159 }
1160 
1161 /// Check if sinking \p I's operands to I's basic block is profitable, because
1162 /// the operands can be folded into a target instruction, e.g.
1163 /// splats of scalars can fold into vector instructions.
1164 bool RISCVTargetLowering::shouldSinkOperands(
1165     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1166   using namespace llvm::PatternMatch;
1167 
1168   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1169     return false;
1170 
1171   auto IsSinker = [&](Instruction *I, int Operand) {
1172     switch (I->getOpcode()) {
1173     case Instruction::Add:
1174     case Instruction::Sub:
1175     case Instruction::Mul:
1176     case Instruction::And:
1177     case Instruction::Or:
1178     case Instruction::Xor:
1179     case Instruction::FAdd:
1180     case Instruction::FSub:
1181     case Instruction::FMul:
1182     case Instruction::FDiv:
1183     case Instruction::ICmp:
1184     case Instruction::FCmp:
1185       return true;
1186     case Instruction::Shl:
1187     case Instruction::LShr:
1188     case Instruction::AShr:
1189     case Instruction::UDiv:
1190     case Instruction::SDiv:
1191     case Instruction::URem:
1192     case Instruction::SRem:
1193       return Operand == 1;
1194     case Instruction::Call:
1195       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1196         switch (II->getIntrinsicID()) {
1197         case Intrinsic::fma:
1198           return Operand == 0 || Operand == 1;
1199         default:
1200           return false;
1201         }
1202       }
1203       return false;
1204     default:
1205       return false;
1206     }
1207   };
1208 
1209   for (auto OpIdx : enumerate(I->operands())) {
1210     if (!IsSinker(I, OpIdx.index()))
1211       continue;
1212 
1213     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1214     // Make sure we are not already sinking this operand
1215     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1216       continue;
1217 
1218     // We are looking for a splat that can be sunk.
1219     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1220                              m_Undef(), m_ZeroMask())))
1221       continue;
1222 
1223     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1224     // and vector registers
1225     for (Use &U : Op->uses()) {
1226       Instruction *Insn = cast<Instruction>(U.getUser());
1227       if (!IsSinker(Insn, U.getOperandNo()))
1228         return false;
1229     }
1230 
1231     Ops.push_back(&Op->getOperandUse(0));
1232     Ops.push_back(&OpIdx.value());
1233   }
1234   return true;
1235 }
1236 
1237 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1238                                        bool ForCodeSize) const {
1239   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1240     return false;
1241   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1242     return false;
1243   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1244     return false;
1245   if (Imm.isNegZero())
1246     return false;
1247   return Imm.isZero();
1248 }
1249 
1250 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1251   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1252          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1253          (VT == MVT::f64 && Subtarget.hasStdExtD());
1254 }
1255 
1256 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1257                                                       CallingConv::ID CC,
1258                                                       EVT VT) const {
1259   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1260   // We might still end up using a GPR but that will be decided based on ABI.
1261   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1262     return MVT::f32;
1263 
1264   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1265 }
1266 
1267 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1268                                                            CallingConv::ID CC,
1269                                                            EVT VT) const {
1270   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1271   // We might still end up using a GPR but that will be decided based on ABI.
1272   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1273     return 1;
1274 
1275   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1276 }
1277 
1278 // Changes the condition code and swaps operands if necessary, so the SetCC
1279 // operation matches one of the comparisons supported directly by branches
1280 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1281 // with 1/-1.
1282 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1283                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1284   // Convert X > -1 to X >= 0.
1285   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1286     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1287     CC = ISD::SETGE;
1288     return;
1289   }
1290   // Convert X < 1 to 0 >= X.
1291   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1292     RHS = LHS;
1293     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1294     CC = ISD::SETGE;
1295     return;
1296   }
1297 
1298   switch (CC) {
1299   default:
1300     break;
1301   case ISD::SETGT:
1302   case ISD::SETLE:
1303   case ISD::SETUGT:
1304   case ISD::SETULE:
1305     CC = ISD::getSetCCSwappedOperands(CC);
1306     std::swap(LHS, RHS);
1307     break;
1308   }
1309 }
1310 
1311 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1312   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1313   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1314   if (VT.getVectorElementType() == MVT::i1)
1315     KnownSize *= 8;
1316 
1317   switch (KnownSize) {
1318   default:
1319     llvm_unreachable("Invalid LMUL.");
1320   case 8:
1321     return RISCVII::VLMUL::LMUL_F8;
1322   case 16:
1323     return RISCVII::VLMUL::LMUL_F4;
1324   case 32:
1325     return RISCVII::VLMUL::LMUL_F2;
1326   case 64:
1327     return RISCVII::VLMUL::LMUL_1;
1328   case 128:
1329     return RISCVII::VLMUL::LMUL_2;
1330   case 256:
1331     return RISCVII::VLMUL::LMUL_4;
1332   case 512:
1333     return RISCVII::VLMUL::LMUL_8;
1334   }
1335 }
1336 
1337 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1338   switch (LMul) {
1339   default:
1340     llvm_unreachable("Invalid LMUL.");
1341   case RISCVII::VLMUL::LMUL_F8:
1342   case RISCVII::VLMUL::LMUL_F4:
1343   case RISCVII::VLMUL::LMUL_F2:
1344   case RISCVII::VLMUL::LMUL_1:
1345     return RISCV::VRRegClassID;
1346   case RISCVII::VLMUL::LMUL_2:
1347     return RISCV::VRM2RegClassID;
1348   case RISCVII::VLMUL::LMUL_4:
1349     return RISCV::VRM4RegClassID;
1350   case RISCVII::VLMUL::LMUL_8:
1351     return RISCV::VRM8RegClassID;
1352   }
1353 }
1354 
1355 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1356   RISCVII::VLMUL LMUL = getLMUL(VT);
1357   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1358       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1359       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1360       LMUL == RISCVII::VLMUL::LMUL_1) {
1361     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1362                   "Unexpected subreg numbering");
1363     return RISCV::sub_vrm1_0 + Index;
1364   }
1365   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1366     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1367                   "Unexpected subreg numbering");
1368     return RISCV::sub_vrm2_0 + Index;
1369   }
1370   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1371     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1372                   "Unexpected subreg numbering");
1373     return RISCV::sub_vrm4_0 + Index;
1374   }
1375   llvm_unreachable("Invalid vector type.");
1376 }
1377 
1378 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1379   if (VT.getVectorElementType() == MVT::i1)
1380     return RISCV::VRRegClassID;
1381   return getRegClassIDForLMUL(getLMUL(VT));
1382 }
1383 
1384 // Attempt to decompose a subvector insert/extract between VecVT and
1385 // SubVecVT via subregister indices. Returns the subregister index that
1386 // can perform the subvector insert/extract with the given element index, as
1387 // well as the index corresponding to any leftover subvectors that must be
1388 // further inserted/extracted within the register class for SubVecVT.
1389 std::pair<unsigned, unsigned>
1390 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1391     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1392     const RISCVRegisterInfo *TRI) {
1393   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1394                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1395                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1396                 "Register classes not ordered");
1397   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1398   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1399   // Try to compose a subregister index that takes us from the incoming
1400   // LMUL>1 register class down to the outgoing one. At each step we half
1401   // the LMUL:
1402   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1403   // Note that this is not guaranteed to find a subregister index, such as
1404   // when we are extracting from one VR type to another.
1405   unsigned SubRegIdx = RISCV::NoSubRegister;
1406   for (const unsigned RCID :
1407        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1408     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1409       VecVT = VecVT.getHalfNumVectorElementsVT();
1410       bool IsHi =
1411           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1412       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1413                                             getSubregIndexByMVT(VecVT, IsHi));
1414       if (IsHi)
1415         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1416     }
1417   return {SubRegIdx, InsertExtractIdx};
1418 }
1419 
1420 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1421 // stores for those types.
1422 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1423   return !Subtarget.useRVVForFixedLengthVectors() ||
1424          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1425 }
1426 
1427 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1428   if (ScalarTy->isPointerTy())
1429     return true;
1430 
1431   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1432       ScalarTy->isIntegerTy(32))
1433     return true;
1434 
1435   if (ScalarTy->isIntegerTy(64))
1436     return Subtarget.hasVInstructionsI64();
1437 
1438   if (ScalarTy->isHalfTy())
1439     return Subtarget.hasVInstructionsF16();
1440   if (ScalarTy->isFloatTy())
1441     return Subtarget.hasVInstructionsF32();
1442   if (ScalarTy->isDoubleTy())
1443     return Subtarget.hasVInstructionsF64();
1444 
1445   return false;
1446 }
1447 
1448 static bool useRVVForFixedLengthVectorVT(MVT VT,
1449                                          const RISCVSubtarget &Subtarget) {
1450   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1451   if (!Subtarget.useRVVForFixedLengthVectors())
1452     return false;
1453 
1454   // We only support a set of vector types with a consistent maximum fixed size
1455   // across all supported vector element types to avoid legalization issues.
1456   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1457   // fixed-length vector type we support is 1024 bytes.
1458   if (VT.getFixedSizeInBits() > 1024 * 8)
1459     return false;
1460 
1461   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1462 
1463   MVT EltVT = VT.getVectorElementType();
1464 
1465   // Don't use RVV for vectors we cannot scalarize if required.
1466   switch (EltVT.SimpleTy) {
1467   // i1 is supported but has different rules.
1468   default:
1469     return false;
1470   case MVT::i1:
1471     // Masks can only use a single register.
1472     if (VT.getVectorNumElements() > MinVLen)
1473       return false;
1474     MinVLen /= 8;
1475     break;
1476   case MVT::i8:
1477   case MVT::i16:
1478   case MVT::i32:
1479     break;
1480   case MVT::i64:
1481     if (!Subtarget.hasVInstructionsI64())
1482       return false;
1483     break;
1484   case MVT::f16:
1485     if (!Subtarget.hasVInstructionsF16())
1486       return false;
1487     break;
1488   case MVT::f32:
1489     if (!Subtarget.hasVInstructionsF32())
1490       return false;
1491     break;
1492   case MVT::f64:
1493     if (!Subtarget.hasVInstructionsF64())
1494       return false;
1495     break;
1496   }
1497 
1498   // Reject elements larger than ELEN.
1499   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1500     return false;
1501 
1502   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1503   // Don't use RVV for types that don't fit.
1504   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1505     return false;
1506 
1507   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1508   // the base fixed length RVV support in place.
1509   if (!VT.isPow2VectorType())
1510     return false;
1511 
1512   return true;
1513 }
1514 
1515 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1516   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1517 }
1518 
1519 // Return the largest legal scalable vector type that matches VT's element type.
1520 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1521                                             const RISCVSubtarget &Subtarget) {
1522   // This may be called before legal types are setup.
1523   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1524           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1525          "Expected legal fixed length vector!");
1526 
1527   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1528   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1529 
1530   MVT EltVT = VT.getVectorElementType();
1531   switch (EltVT.SimpleTy) {
1532   default:
1533     llvm_unreachable("unexpected element type for RVV container");
1534   case MVT::i1:
1535   case MVT::i8:
1536   case MVT::i16:
1537   case MVT::i32:
1538   case MVT::i64:
1539   case MVT::f16:
1540   case MVT::f32:
1541   case MVT::f64: {
1542     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1543     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1544     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1545     unsigned NumElts =
1546         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1547     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1548     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1549     return MVT::getScalableVectorVT(EltVT, NumElts);
1550   }
1551   }
1552 }
1553 
1554 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1555                                             const RISCVSubtarget &Subtarget) {
1556   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1557                                           Subtarget);
1558 }
1559 
1560 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1561   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1562 }
1563 
1564 // Grow V to consume an entire RVV register.
1565 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1566                                        const RISCVSubtarget &Subtarget) {
1567   assert(VT.isScalableVector() &&
1568          "Expected to convert into a scalable vector!");
1569   assert(V.getValueType().isFixedLengthVector() &&
1570          "Expected a fixed length vector operand!");
1571   SDLoc DL(V);
1572   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1573   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1574 }
1575 
1576 // Shrink V so it's just big enough to maintain a VT's worth of data.
1577 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1578                                          const RISCVSubtarget &Subtarget) {
1579   assert(VT.isFixedLengthVector() &&
1580          "Expected to convert into a fixed length vector!");
1581   assert(V.getValueType().isScalableVector() &&
1582          "Expected a scalable vector operand!");
1583   SDLoc DL(V);
1584   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1585   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1586 }
1587 
1588 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1589 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1590 // the vector type that it is contained in.
1591 static std::pair<SDValue, SDValue>
1592 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1593                 const RISCVSubtarget &Subtarget) {
1594   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1595   MVT XLenVT = Subtarget.getXLenVT();
1596   SDValue VL = VecVT.isFixedLengthVector()
1597                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1598                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1599   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1600   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1601   return {Mask, VL};
1602 }
1603 
1604 // As above but assuming the given type is a scalable vector type.
1605 static std::pair<SDValue, SDValue>
1606 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1607                         const RISCVSubtarget &Subtarget) {
1608   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1609   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1610 }
1611 
1612 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1613 // of either is (currently) supported. This can get us into an infinite loop
1614 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1615 // as a ..., etc.
1616 // Until either (or both) of these can reliably lower any node, reporting that
1617 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1618 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1619 // which is not desirable.
1620 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1621     EVT VT, unsigned DefinedValues) const {
1622   return false;
1623 }
1624 
1625 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1626   // Only splats are currently supported.
1627   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1628     return true;
1629 
1630   return false;
1631 }
1632 
1633 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1634   // RISCV FP-to-int conversions saturate to the destination register size, but
1635   // don't produce 0 for nan. We can use a conversion instruction and fix the
1636   // nan case with a compare and a select.
1637   SDValue Src = Op.getOperand(0);
1638 
1639   EVT DstVT = Op.getValueType();
1640   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1641 
1642   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1643   unsigned Opc;
1644   if (SatVT == DstVT)
1645     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1646   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1647     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1648   else
1649     return SDValue();
1650   // FIXME: Support other SatVTs by clamping before or after the conversion.
1651 
1652   SDLoc DL(Op);
1653   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1654 
1655   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1656   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1657 }
1658 
1659 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1660 // and back. Taking care to avoid converting values that are nan or already
1661 // correct.
1662 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1663 // have FRM dependencies modeled yet.
1664 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1665   MVT VT = Op.getSimpleValueType();
1666   assert(VT.isVector() && "Unexpected type");
1667 
1668   SDLoc DL(Op);
1669 
1670   // Freeze the source since we are increasing the number of uses.
1671   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1672 
1673   // Truncate to integer and convert back to FP.
1674   MVT IntVT = VT.changeVectorElementTypeToInteger();
1675   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1676   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1677 
1678   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1679 
1680   if (Op.getOpcode() == ISD::FCEIL) {
1681     // If the truncated value is the greater than or equal to the original
1682     // value, we've computed the ceil. Otherwise, we went the wrong way and
1683     // need to increase by 1.
1684     // FIXME: This should use a masked operation. Handle here or in isel?
1685     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1686                                  DAG.getConstantFP(1.0, DL, VT));
1687     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1688     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1689   } else if (Op.getOpcode() == ISD::FFLOOR) {
1690     // If the truncated value is the less than or equal to the original value,
1691     // we've computed the floor. Otherwise, we went the wrong way and need to
1692     // decrease by 1.
1693     // FIXME: This should use a masked operation. Handle here or in isel?
1694     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1695                                  DAG.getConstantFP(1.0, DL, VT));
1696     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1697     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1698   }
1699 
1700   // Restore the original sign so that -0.0 is preserved.
1701   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1702 
1703   // Determine the largest integer that can be represented exactly. This and
1704   // values larger than it don't have any fractional bits so don't need to
1705   // be converted.
1706   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1707   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1708   APFloat MaxVal = APFloat(FltSem);
1709   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1710                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1711   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1712 
1713   // If abs(Src) was larger than MaxVal or nan, keep it.
1714   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1715   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1716   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1717 }
1718 
1719 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1720                                  const RISCVSubtarget &Subtarget) {
1721   MVT VT = Op.getSimpleValueType();
1722   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1723 
1724   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1725 
1726   SDLoc DL(Op);
1727   SDValue Mask, VL;
1728   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1729 
1730   unsigned Opc =
1731       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1732   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1733   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1734 }
1735 
1736 struct VIDSequence {
1737   int64_t StepNumerator;
1738   unsigned StepDenominator;
1739   int64_t Addend;
1740 };
1741 
1742 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1743 // to the (non-zero) step S and start value X. This can be then lowered as the
1744 // RVV sequence (VID * S) + X, for example.
1745 // The step S is represented as an integer numerator divided by a positive
1746 // denominator. Note that the implementation currently only identifies
1747 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1748 // cannot detect 2/3, for example.
1749 // Note that this method will also match potentially unappealing index
1750 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1751 // determine whether this is worth generating code for.
1752 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1753   unsigned NumElts = Op.getNumOperands();
1754   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1755   if (!Op.getValueType().isInteger())
1756     return None;
1757 
1758   Optional<unsigned> SeqStepDenom;
1759   Optional<int64_t> SeqStepNum, SeqAddend;
1760   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1761   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1762   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1763     // Assume undef elements match the sequence; we just have to be careful
1764     // when interpolating across them.
1765     if (Op.getOperand(Idx).isUndef())
1766       continue;
1767     // The BUILD_VECTOR must be all constants.
1768     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1769       return None;
1770 
1771     uint64_t Val = Op.getConstantOperandVal(Idx) &
1772                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1773 
1774     if (PrevElt) {
1775       // Calculate the step since the last non-undef element, and ensure
1776       // it's consistent across the entire sequence.
1777       unsigned IdxDiff = Idx - PrevElt->second;
1778       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1779 
1780       // A zero-value value difference means that we're somewhere in the middle
1781       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1782       // step change before evaluating the sequence.
1783       if (ValDiff != 0) {
1784         int64_t Remainder = ValDiff % IdxDiff;
1785         // Normalize the step if it's greater than 1.
1786         if (Remainder != ValDiff) {
1787           // The difference must cleanly divide the element span.
1788           if (Remainder != 0)
1789             return None;
1790           ValDiff /= IdxDiff;
1791           IdxDiff = 1;
1792         }
1793 
1794         if (!SeqStepNum)
1795           SeqStepNum = ValDiff;
1796         else if (ValDiff != SeqStepNum)
1797           return None;
1798 
1799         if (!SeqStepDenom)
1800           SeqStepDenom = IdxDiff;
1801         else if (IdxDiff != *SeqStepDenom)
1802           return None;
1803       }
1804     }
1805 
1806     // Record and/or check any addend.
1807     if (SeqStepNum && SeqStepDenom) {
1808       uint64_t ExpectedVal =
1809           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1810       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1811       if (!SeqAddend)
1812         SeqAddend = Addend;
1813       else if (SeqAddend != Addend)
1814         return None;
1815     }
1816 
1817     // Record this non-undef element for later.
1818     if (!PrevElt || PrevElt->first != Val)
1819       PrevElt = std::make_pair(Val, Idx);
1820   }
1821   // We need to have logged both a step and an addend for this to count as
1822   // a legal index sequence.
1823   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1824     return None;
1825 
1826   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1827 }
1828 
1829 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1830                                  const RISCVSubtarget &Subtarget) {
1831   MVT VT = Op.getSimpleValueType();
1832   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1833 
1834   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1835 
1836   SDLoc DL(Op);
1837   SDValue Mask, VL;
1838   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1839 
1840   MVT XLenVT = Subtarget.getXLenVT();
1841   unsigned NumElts = Op.getNumOperands();
1842 
1843   if (VT.getVectorElementType() == MVT::i1) {
1844     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1845       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1846       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1847     }
1848 
1849     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1850       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1851       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1852     }
1853 
1854     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1855     // scalar integer chunks whose bit-width depends on the number of mask
1856     // bits and XLEN.
1857     // First, determine the most appropriate scalar integer type to use. This
1858     // is at most XLenVT, but may be shrunk to a smaller vector element type
1859     // according to the size of the final vector - use i8 chunks rather than
1860     // XLenVT if we're producing a v8i1. This results in more consistent
1861     // codegen across RV32 and RV64.
1862     unsigned NumViaIntegerBits =
1863         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1864     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1865       // If we have to use more than one INSERT_VECTOR_ELT then this
1866       // optimization is likely to increase code size; avoid peforming it in
1867       // such a case. We can use a load from a constant pool in this case.
1868       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1869         return SDValue();
1870       // Now we can create our integer vector type. Note that it may be larger
1871       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1872       MVT IntegerViaVecVT =
1873           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1874                            divideCeil(NumElts, NumViaIntegerBits));
1875 
1876       uint64_t Bits = 0;
1877       unsigned BitPos = 0, IntegerEltIdx = 0;
1878       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1879 
1880       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1881         // Once we accumulate enough bits to fill our scalar type, insert into
1882         // our vector and clear our accumulated data.
1883         if (I != 0 && I % NumViaIntegerBits == 0) {
1884           if (NumViaIntegerBits <= 32)
1885             Bits = SignExtend64(Bits, 32);
1886           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1887           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1888                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1889           Bits = 0;
1890           BitPos = 0;
1891           IntegerEltIdx++;
1892         }
1893         SDValue V = Op.getOperand(I);
1894         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1895         Bits |= ((uint64_t)BitValue << BitPos);
1896       }
1897 
1898       // Insert the (remaining) scalar value into position in our integer
1899       // vector type.
1900       if (NumViaIntegerBits <= 32)
1901         Bits = SignExtend64(Bits, 32);
1902       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1903       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1904                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1905 
1906       if (NumElts < NumViaIntegerBits) {
1907         // If we're producing a smaller vector than our minimum legal integer
1908         // type, bitcast to the equivalent (known-legal) mask type, and extract
1909         // our final mask.
1910         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1911         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1912         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1913                           DAG.getConstant(0, DL, XLenVT));
1914       } else {
1915         // Else we must have produced an integer type with the same size as the
1916         // mask type; bitcast for the final result.
1917         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1918         Vec = DAG.getBitcast(VT, Vec);
1919       }
1920 
1921       return Vec;
1922     }
1923 
1924     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1925     // vector type, we have a legal equivalently-sized i8 type, so we can use
1926     // that.
1927     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1928     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1929 
1930     SDValue WideVec;
1931     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1932       // For a splat, perform a scalar truncate before creating the wider
1933       // vector.
1934       assert(Splat.getValueType() == XLenVT &&
1935              "Unexpected type for i1 splat value");
1936       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1937                           DAG.getConstant(1, DL, XLenVT));
1938       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1939     } else {
1940       SmallVector<SDValue, 8> Ops(Op->op_values());
1941       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1942       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1943       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1944     }
1945 
1946     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1947   }
1948 
1949   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1950     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1951                                         : RISCVISD::VMV_V_X_VL;
1952     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1953     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1954   }
1955 
1956   // Try and match index sequences, which we can lower to the vid instruction
1957   // with optional modifications. An all-undef vector is matched by
1958   // getSplatValue, above.
1959   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1960     int64_t StepNumerator = SimpleVID->StepNumerator;
1961     unsigned StepDenominator = SimpleVID->StepDenominator;
1962     int64_t Addend = SimpleVID->Addend;
1963     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1964     // threshold since it's the immediate value many RVV instructions accept.
1965     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1966         isInt<5>(Addend)) {
1967       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1968       // Convert right out of the scalable type so we can use standard ISD
1969       // nodes for the rest of the computation. If we used scalable types with
1970       // these, we'd lose the fixed-length vector info and generate worse
1971       // vsetvli code.
1972       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1973       assert(StepNumerator != 0 && "Invalid step");
1974       bool Negate = false;
1975       if (StepNumerator != 1) {
1976         int64_t SplatStepVal = StepNumerator;
1977         unsigned Opcode = ISD::MUL;
1978         if (isPowerOf2_64(std::abs(StepNumerator))) {
1979           Negate = StepNumerator < 0;
1980           Opcode = ISD::SHL;
1981           SplatStepVal = Log2_64(std::abs(StepNumerator));
1982         }
1983         SDValue SplatStep = DAG.getSplatVector(
1984             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1985         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1986       }
1987       if (StepDenominator != 1) {
1988         SDValue SplatStep = DAG.getSplatVector(
1989             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1990         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1991       }
1992       if (Addend != 0 || Negate) {
1993         SDValue SplatAddend =
1994             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1995         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1996       }
1997       return VID;
1998     }
1999   }
2000 
2001   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2002   // when re-interpreted as a vector with a larger element type. For example,
2003   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2004   // could be instead splat as
2005   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2006   // TODO: This optimization could also work on non-constant splats, but it
2007   // would require bit-manipulation instructions to construct the splat value.
2008   SmallVector<SDValue> Sequence;
2009   unsigned EltBitSize = VT.getScalarSizeInBits();
2010   const auto *BV = cast<BuildVectorSDNode>(Op);
2011   if (VT.isInteger() && EltBitSize < 64 &&
2012       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2013       BV->getRepeatedSequence(Sequence) &&
2014       (Sequence.size() * EltBitSize) <= 64) {
2015     unsigned SeqLen = Sequence.size();
2016     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2017     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2018     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2019             ViaIntVT == MVT::i64) &&
2020            "Unexpected sequence type");
2021 
2022     unsigned EltIdx = 0;
2023     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2024     uint64_t SplatValue = 0;
2025     // Construct the amalgamated value which can be splatted as this larger
2026     // vector type.
2027     for (const auto &SeqV : Sequence) {
2028       if (!SeqV.isUndef())
2029         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2030                        << (EltIdx * EltBitSize));
2031       EltIdx++;
2032     }
2033 
2034     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2035     // achieve better constant materializion.
2036     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2037       SplatValue = SignExtend64(SplatValue, 32);
2038 
2039     // Since we can't introduce illegal i64 types at this stage, we can only
2040     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2041     // way we can use RVV instructions to splat.
2042     assert((ViaIntVT.bitsLE(XLenVT) ||
2043             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2044            "Unexpected bitcast sequence");
2045     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2046       SDValue ViaVL =
2047           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2048       MVT ViaContainerVT =
2049           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2050       SDValue Splat =
2051           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2052                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2053       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2054       return DAG.getBitcast(VT, Splat);
2055     }
2056   }
2057 
2058   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2059   // which constitute a large proportion of the elements. In such cases we can
2060   // splat a vector with the dominant element and make up the shortfall with
2061   // INSERT_VECTOR_ELTs.
2062   // Note that this includes vectors of 2 elements by association. The
2063   // upper-most element is the "dominant" one, allowing us to use a splat to
2064   // "insert" the upper element, and an insert of the lower element at position
2065   // 0, which improves codegen.
2066   SDValue DominantValue;
2067   unsigned MostCommonCount = 0;
2068   DenseMap<SDValue, unsigned> ValueCounts;
2069   unsigned NumUndefElts =
2070       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2071 
2072   // Track the number of scalar loads we know we'd be inserting, estimated as
2073   // any non-zero floating-point constant. Other kinds of element are either
2074   // already in registers or are materialized on demand. The threshold at which
2075   // a vector load is more desirable than several scalar materializion and
2076   // vector-insertion instructions is not known.
2077   unsigned NumScalarLoads = 0;
2078 
2079   for (SDValue V : Op->op_values()) {
2080     if (V.isUndef())
2081       continue;
2082 
2083     ValueCounts.insert(std::make_pair(V, 0));
2084     unsigned &Count = ValueCounts[V];
2085 
2086     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2087       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2088 
2089     // Is this value dominant? In case of a tie, prefer the highest element as
2090     // it's cheaper to insert near the beginning of a vector than it is at the
2091     // end.
2092     if (++Count >= MostCommonCount) {
2093       DominantValue = V;
2094       MostCommonCount = Count;
2095     }
2096   }
2097 
2098   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2099   unsigned NumDefElts = NumElts - NumUndefElts;
2100   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2101 
2102   // Don't perform this optimization when optimizing for size, since
2103   // materializing elements and inserting them tends to cause code bloat.
2104   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2105       ((MostCommonCount > DominantValueCountThreshold) ||
2106        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2107     // Start by splatting the most common element.
2108     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2109 
2110     DenseSet<SDValue> Processed{DominantValue};
2111     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2112     for (const auto &OpIdx : enumerate(Op->ops())) {
2113       const SDValue &V = OpIdx.value();
2114       if (V.isUndef() || !Processed.insert(V).second)
2115         continue;
2116       if (ValueCounts[V] == 1) {
2117         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2118                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2119       } else {
2120         // Blend in all instances of this value using a VSELECT, using a
2121         // mask where each bit signals whether that element is the one
2122         // we're after.
2123         SmallVector<SDValue> Ops;
2124         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2125           return DAG.getConstant(V == V1, DL, XLenVT);
2126         });
2127         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2128                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2129                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2130       }
2131     }
2132 
2133     return Vec;
2134   }
2135 
2136   return SDValue();
2137 }
2138 
2139 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2140                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2141   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2142     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2143     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2144     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2145     // node in order to try and match RVV vector/scalar instructions.
2146     if ((LoC >> 31) == HiC)
2147       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2148   }
2149 
2150   // Fall back to a stack store and stride x0 vector load.
2151   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2152 }
2153 
2154 // Called by type legalization to handle splat of i64 on RV32.
2155 // FIXME: We can optimize this when the type has sign or zero bits in one
2156 // of the halves.
2157 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2158                                    SDValue VL, SelectionDAG &DAG) {
2159   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2160   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2161                            DAG.getConstant(0, DL, MVT::i32));
2162   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2163                            DAG.getConstant(1, DL, MVT::i32));
2164   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2165 }
2166 
2167 // This function lowers a splat of a scalar operand Splat with the vector
2168 // length VL. It ensures the final sequence is type legal, which is useful when
2169 // lowering a splat after type legalization.
2170 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2171                                 SelectionDAG &DAG,
2172                                 const RISCVSubtarget &Subtarget) {
2173   if (VT.isFloatingPoint())
2174     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2175 
2176   MVT XLenVT = Subtarget.getXLenVT();
2177 
2178   // Simplest case is that the operand needs to be promoted to XLenVT.
2179   if (Scalar.getValueType().bitsLE(XLenVT)) {
2180     // If the operand is a constant, sign extend to increase our chances
2181     // of being able to use a .vi instruction. ANY_EXTEND would become a
2182     // a zero extend and the simm5 check in isel would fail.
2183     // FIXME: Should we ignore the upper bits in isel instead?
2184     unsigned ExtOpc =
2185         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2186     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2187     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2188   }
2189 
2190   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2191          "Unexpected scalar for splat lowering!");
2192 
2193   // Otherwise use the more complicated splatting algorithm.
2194   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2195 }
2196 
2197 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2198                                    const RISCVSubtarget &Subtarget) {
2199   SDValue V1 = Op.getOperand(0);
2200   SDValue V2 = Op.getOperand(1);
2201   SDLoc DL(Op);
2202   MVT XLenVT = Subtarget.getXLenVT();
2203   MVT VT = Op.getSimpleValueType();
2204   unsigned NumElts = VT.getVectorNumElements();
2205   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2206 
2207   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2208 
2209   SDValue TrueMask, VL;
2210   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2211 
2212   if (SVN->isSplat()) {
2213     const int Lane = SVN->getSplatIndex();
2214     if (Lane >= 0) {
2215       MVT SVT = VT.getVectorElementType();
2216 
2217       // Turn splatted vector load into a strided load with an X0 stride.
2218       SDValue V = V1;
2219       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2220       // with undef.
2221       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2222       int Offset = Lane;
2223       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2224         int OpElements =
2225             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2226         V = V.getOperand(Offset / OpElements);
2227         Offset %= OpElements;
2228       }
2229 
2230       // We need to ensure the load isn't atomic or volatile.
2231       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2232         auto *Ld = cast<LoadSDNode>(V);
2233         Offset *= SVT.getStoreSize();
2234         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2235                                                    TypeSize::Fixed(Offset), DL);
2236 
2237         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2238         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2239           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2240           SDValue IntID =
2241               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2242           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2243                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2244           SDValue NewLoad = DAG.getMemIntrinsicNode(
2245               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2246               DAG.getMachineFunction().getMachineMemOperand(
2247                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2248           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2249           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2250         }
2251 
2252         // Otherwise use a scalar load and splat. This will give the best
2253         // opportunity to fold a splat into the operation. ISel can turn it into
2254         // the x0 strided load if we aren't able to fold away the select.
2255         if (SVT.isFloatingPoint())
2256           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2257                           Ld->getPointerInfo().getWithOffset(Offset),
2258                           Ld->getOriginalAlign(),
2259                           Ld->getMemOperand()->getFlags());
2260         else
2261           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2262                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2263                              Ld->getOriginalAlign(),
2264                              Ld->getMemOperand()->getFlags());
2265         DAG.makeEquivalentMemoryOrdering(Ld, V);
2266 
2267         unsigned Opc =
2268             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2269         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2270         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2271       }
2272 
2273       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2274       assert(Lane < (int)NumElts && "Unexpected lane!");
2275       SDValue Gather =
2276           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2277                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2278       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2279     }
2280   }
2281 
2282   // Detect shuffles which can be re-expressed as vector selects; these are
2283   // shuffles in which each element in the destination is taken from an element
2284   // at the corresponding index in either source vectors.
2285   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2286     int MaskIndex = MaskIdx.value();
2287     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2288   });
2289 
2290   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2291 
2292   SmallVector<SDValue> MaskVals;
2293   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2294   // merged with a second vrgather.
2295   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2296 
2297   // By default we preserve the original operand order, and use a mask to
2298   // select LHS as true and RHS as false. However, since RVV vector selects may
2299   // feature splats but only on the LHS, we may choose to invert our mask and
2300   // instead select between RHS and LHS.
2301   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2302   bool InvertMask = IsSelect == SwapOps;
2303 
2304   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2305   // half.
2306   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2307 
2308   // Now construct the mask that will be used by the vselect or blended
2309   // vrgather operation. For vrgathers, construct the appropriate indices into
2310   // each vector.
2311   for (int MaskIndex : SVN->getMask()) {
2312     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2313     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2314     if (!IsSelect) {
2315       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2316       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2317                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2318                                      : DAG.getUNDEF(XLenVT));
2319       GatherIndicesRHS.push_back(
2320           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2321                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2322       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2323         ++LHSIndexCounts[MaskIndex];
2324       if (!IsLHSOrUndefIndex)
2325         ++RHSIndexCounts[MaskIndex - NumElts];
2326     }
2327   }
2328 
2329   if (SwapOps) {
2330     std::swap(V1, V2);
2331     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2332   }
2333 
2334   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2335   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2336   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2337 
2338   if (IsSelect)
2339     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2340 
2341   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2342     // On such a large vector we're unable to use i8 as the index type.
2343     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2344     // may involve vector splitting if we're already at LMUL=8, or our
2345     // user-supplied maximum fixed-length LMUL.
2346     return SDValue();
2347   }
2348 
2349   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2350   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2351   MVT IndexVT = VT.changeTypeToInteger();
2352   // Since we can't introduce illegal index types at this stage, use i16 and
2353   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2354   // than XLenVT.
2355   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2356     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2357     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2358   }
2359 
2360   MVT IndexContainerVT =
2361       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2362 
2363   SDValue Gather;
2364   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2365   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2366   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2367     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2368   } else {
2369     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2370     // If only one index is used, we can use a "splat" vrgather.
2371     // TODO: We can splat the most-common index and fix-up any stragglers, if
2372     // that's beneficial.
2373     if (LHSIndexCounts.size() == 1) {
2374       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2375       Gather =
2376           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2377                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2378     } else {
2379       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2380       LHSIndices =
2381           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2382 
2383       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2384                            TrueMask, VL);
2385     }
2386   }
2387 
2388   // If a second vector operand is used by this shuffle, blend it in with an
2389   // additional vrgather.
2390   if (!V2.isUndef()) {
2391     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2392     // If only one index is used, we can use a "splat" vrgather.
2393     // TODO: We can splat the most-common index and fix-up any stragglers, if
2394     // that's beneficial.
2395     if (RHSIndexCounts.size() == 1) {
2396       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2397       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2398                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2399     } else {
2400       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2401       RHSIndices =
2402           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2403       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2404                        VL);
2405     }
2406 
2407     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2408     SelectMask =
2409         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2410 
2411     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2412                          Gather, VL);
2413   }
2414 
2415   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2416 }
2417 
2418 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2419                                      SDLoc DL, SelectionDAG &DAG,
2420                                      const RISCVSubtarget &Subtarget) {
2421   if (VT.isScalableVector())
2422     return DAG.getFPExtendOrRound(Op, DL, VT);
2423   assert(VT.isFixedLengthVector() &&
2424          "Unexpected value type for RVV FP extend/round lowering");
2425   SDValue Mask, VL;
2426   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2427   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2428                         ? RISCVISD::FP_EXTEND_VL
2429                         : RISCVISD::FP_ROUND_VL;
2430   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2431 }
2432 
2433 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2434 // the exponent.
2435 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2436   MVT VT = Op.getSimpleValueType();
2437   unsigned EltSize = VT.getScalarSizeInBits();
2438   SDValue Src = Op.getOperand(0);
2439   SDLoc DL(Op);
2440 
2441   // We need a FP type that can represent the value.
2442   // TODO: Use f16 for i8 when possible?
2443   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2444   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2445 
2446   // Legal types should have been checked in the RISCVTargetLowering
2447   // constructor.
2448   // TODO: Splitting may make sense in some cases.
2449   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2450          "Expected legal float type!");
2451 
2452   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2453   // The trailing zero count is equal to log2 of this single bit value.
2454   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2455     SDValue Neg =
2456         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2457     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2458   }
2459 
2460   // We have a legal FP type, convert to it.
2461   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2462   // Bitcast to integer and shift the exponent to the LSB.
2463   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2464   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2465   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2466   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2467                               DAG.getConstant(ShiftAmt, DL, IntVT));
2468   // Truncate back to original type to allow vnsrl.
2469   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2470   // The exponent contains log2 of the value in biased form.
2471   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2472 
2473   // For trailing zeros, we just need to subtract the bias.
2474   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2475     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2476                        DAG.getConstant(ExponentBias, DL, VT));
2477 
2478   // For leading zeros, we need to remove the bias and convert from log2 to
2479   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2480   unsigned Adjust = ExponentBias + (EltSize - 1);
2481   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2482 }
2483 
2484 // While RVV has alignment restrictions, we should always be able to load as a
2485 // legal equivalently-sized byte-typed vector instead. This method is
2486 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2487 // the load is already correctly-aligned, it returns SDValue().
2488 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2489                                                     SelectionDAG &DAG) const {
2490   auto *Load = cast<LoadSDNode>(Op);
2491   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2492 
2493   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2494                                      Load->getMemoryVT(),
2495                                      *Load->getMemOperand()))
2496     return SDValue();
2497 
2498   SDLoc DL(Op);
2499   MVT VT = Op.getSimpleValueType();
2500   unsigned EltSizeBits = VT.getScalarSizeInBits();
2501   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2502          "Unexpected unaligned RVV load type");
2503   MVT NewVT =
2504       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2505   assert(NewVT.isValid() &&
2506          "Expecting equally-sized RVV vector types to be legal");
2507   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2508                           Load->getPointerInfo(), Load->getOriginalAlign(),
2509                           Load->getMemOperand()->getFlags());
2510   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2511 }
2512 
2513 // While RVV has alignment restrictions, we should always be able to store as a
2514 // legal equivalently-sized byte-typed vector instead. This method is
2515 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2516 // returns SDValue() if the store is already correctly aligned.
2517 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2518                                                      SelectionDAG &DAG) const {
2519   auto *Store = cast<StoreSDNode>(Op);
2520   assert(Store && Store->getValue().getValueType().isVector() &&
2521          "Expected vector store");
2522 
2523   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2524                                      Store->getMemoryVT(),
2525                                      *Store->getMemOperand()))
2526     return SDValue();
2527 
2528   SDLoc DL(Op);
2529   SDValue StoredVal = Store->getValue();
2530   MVT VT = StoredVal.getSimpleValueType();
2531   unsigned EltSizeBits = VT.getScalarSizeInBits();
2532   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2533          "Unexpected unaligned RVV store type");
2534   MVT NewVT =
2535       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2536   assert(NewVT.isValid() &&
2537          "Expecting equally-sized RVV vector types to be legal");
2538   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2539   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2540                       Store->getPointerInfo(), Store->getOriginalAlign(),
2541                       Store->getMemOperand()->getFlags());
2542 }
2543 
2544 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2545                                             SelectionDAG &DAG) const {
2546   switch (Op.getOpcode()) {
2547   default:
2548     report_fatal_error("unimplemented operand");
2549   case ISD::GlobalAddress:
2550     return lowerGlobalAddress(Op, DAG);
2551   case ISD::BlockAddress:
2552     return lowerBlockAddress(Op, DAG);
2553   case ISD::ConstantPool:
2554     return lowerConstantPool(Op, DAG);
2555   case ISD::JumpTable:
2556     return lowerJumpTable(Op, DAG);
2557   case ISD::GlobalTLSAddress:
2558     return lowerGlobalTLSAddress(Op, DAG);
2559   case ISD::SELECT:
2560     return lowerSELECT(Op, DAG);
2561   case ISD::BRCOND:
2562     return lowerBRCOND(Op, DAG);
2563   case ISD::VASTART:
2564     return lowerVASTART(Op, DAG);
2565   case ISD::FRAMEADDR:
2566     return lowerFRAMEADDR(Op, DAG);
2567   case ISD::RETURNADDR:
2568     return lowerRETURNADDR(Op, DAG);
2569   case ISD::SHL_PARTS:
2570     return lowerShiftLeftParts(Op, DAG);
2571   case ISD::SRA_PARTS:
2572     return lowerShiftRightParts(Op, DAG, true);
2573   case ISD::SRL_PARTS:
2574     return lowerShiftRightParts(Op, DAG, false);
2575   case ISD::BITCAST: {
2576     SDLoc DL(Op);
2577     EVT VT = Op.getValueType();
2578     SDValue Op0 = Op.getOperand(0);
2579     EVT Op0VT = Op0.getValueType();
2580     MVT XLenVT = Subtarget.getXLenVT();
2581     if (VT.isFixedLengthVector()) {
2582       // We can handle fixed length vector bitcasts with a simple replacement
2583       // in isel.
2584       if (Op0VT.isFixedLengthVector())
2585         return Op;
2586       // When bitcasting from scalar to fixed-length vector, insert the scalar
2587       // into a one-element vector of the result type, and perform a vector
2588       // bitcast.
2589       if (!Op0VT.isVector()) {
2590         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2591         if (!isTypeLegal(BVT))
2592           return SDValue();
2593         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2594                                               DAG.getUNDEF(BVT), Op0,
2595                                               DAG.getConstant(0, DL, XLenVT)));
2596       }
2597       return SDValue();
2598     }
2599     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2600     // thus: bitcast the vector to a one-element vector type whose element type
2601     // is the same as the result type, and extract the first element.
2602     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2603       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2604       if (!isTypeLegal(BVT))
2605         return SDValue();
2606       SDValue BVec = DAG.getBitcast(BVT, Op0);
2607       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2608                          DAG.getConstant(0, DL, XLenVT));
2609     }
2610     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2611       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2612       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2613       return FPConv;
2614     }
2615     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2616         Subtarget.hasStdExtF()) {
2617       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2618       SDValue FPConv =
2619           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2620       return FPConv;
2621     }
2622     return SDValue();
2623   }
2624   case ISD::INTRINSIC_WO_CHAIN:
2625     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2626   case ISD::INTRINSIC_W_CHAIN:
2627     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2628   case ISD::INTRINSIC_VOID:
2629     return LowerINTRINSIC_VOID(Op, DAG);
2630   case ISD::BSWAP:
2631   case ISD::BITREVERSE: {
2632     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2633     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2634     MVT VT = Op.getSimpleValueType();
2635     SDLoc DL(Op);
2636     // Start with the maximum immediate value which is the bitwidth - 1.
2637     unsigned Imm = VT.getSizeInBits() - 1;
2638     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2639     if (Op.getOpcode() == ISD::BSWAP)
2640       Imm &= ~0x7U;
2641     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2642                        DAG.getConstant(Imm, DL, VT));
2643   }
2644   case ISD::FSHL:
2645   case ISD::FSHR: {
2646     MVT VT = Op.getSimpleValueType();
2647     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2648     SDLoc DL(Op);
2649     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2650       return Op;
2651     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2652     // use log(XLen) bits. Mask the shift amount accordingly.
2653     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2654     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2655                                 DAG.getConstant(ShAmtWidth, DL, VT));
2656     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2657     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2658   }
2659   case ISD::TRUNCATE: {
2660     SDLoc DL(Op);
2661     MVT VT = Op.getSimpleValueType();
2662     // Only custom-lower vector truncates
2663     if (!VT.isVector())
2664       return Op;
2665 
2666     // Truncates to mask types are handled differently
2667     if (VT.getVectorElementType() == MVT::i1)
2668       return lowerVectorMaskTrunc(Op, DAG);
2669 
2670     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2671     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2672     // truncate by one power of two at a time.
2673     MVT DstEltVT = VT.getVectorElementType();
2674 
2675     SDValue Src = Op.getOperand(0);
2676     MVT SrcVT = Src.getSimpleValueType();
2677     MVT SrcEltVT = SrcVT.getVectorElementType();
2678 
2679     assert(DstEltVT.bitsLT(SrcEltVT) &&
2680            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2681            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2682            "Unexpected vector truncate lowering");
2683 
2684     MVT ContainerVT = SrcVT;
2685     if (SrcVT.isFixedLengthVector()) {
2686       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2687       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2688     }
2689 
2690     SDValue Result = Src;
2691     SDValue Mask, VL;
2692     std::tie(Mask, VL) =
2693         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2694     LLVMContext &Context = *DAG.getContext();
2695     const ElementCount Count = ContainerVT.getVectorElementCount();
2696     do {
2697       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2698       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2699       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2700                            Mask, VL);
2701     } while (SrcEltVT != DstEltVT);
2702 
2703     if (SrcVT.isFixedLengthVector())
2704       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2705 
2706     return Result;
2707   }
2708   case ISD::ANY_EXTEND:
2709   case ISD::ZERO_EXTEND:
2710     if (Op.getOperand(0).getValueType().isVector() &&
2711         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2712       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2713     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2714   case ISD::SIGN_EXTEND:
2715     if (Op.getOperand(0).getValueType().isVector() &&
2716         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2717       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2718     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2719   case ISD::SPLAT_VECTOR_PARTS:
2720     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2721   case ISD::INSERT_VECTOR_ELT:
2722     return lowerINSERT_VECTOR_ELT(Op, DAG);
2723   case ISD::EXTRACT_VECTOR_ELT:
2724     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2725   case ISD::VSCALE: {
2726     MVT VT = Op.getSimpleValueType();
2727     SDLoc DL(Op);
2728     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2729     // We define our scalable vector types for lmul=1 to use a 64 bit known
2730     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2731     // vscale as VLENB / 8.
2732     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2733     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2734       // We assume VLENB is a multiple of 8. We manually choose the best shift
2735       // here because SimplifyDemandedBits isn't always able to simplify it.
2736       uint64_t Val = Op.getConstantOperandVal(0);
2737       if (isPowerOf2_64(Val)) {
2738         uint64_t Log2 = Log2_64(Val);
2739         if (Log2 < 3)
2740           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2741                              DAG.getConstant(3 - Log2, DL, VT));
2742         if (Log2 > 3)
2743           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2744                              DAG.getConstant(Log2 - 3, DL, VT));
2745         return VLENB;
2746       }
2747       // If the multiplier is a multiple of 8, scale it down to avoid needing
2748       // to shift the VLENB value.
2749       if ((Val % 8) == 0)
2750         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2751                            DAG.getConstant(Val / 8, DL, VT));
2752     }
2753 
2754     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2755                                  DAG.getConstant(3, DL, VT));
2756     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2757   }
2758   case ISD::FPOWI: {
2759     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2760     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2761     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2762         Op.getOperand(1).getValueType() == MVT::i32) {
2763       SDLoc DL(Op);
2764       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2765       SDValue Powi =
2766           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2767       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2768                          DAG.getIntPtrConstant(0, DL));
2769     }
2770     return SDValue();
2771   }
2772   case ISD::FP_EXTEND: {
2773     // RVV can only do fp_extend to types double the size as the source. We
2774     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2775     // via f32.
2776     SDLoc DL(Op);
2777     MVT VT = Op.getSimpleValueType();
2778     SDValue Src = Op.getOperand(0);
2779     MVT SrcVT = Src.getSimpleValueType();
2780 
2781     // Prepare any fixed-length vector operands.
2782     MVT ContainerVT = VT;
2783     if (SrcVT.isFixedLengthVector()) {
2784       ContainerVT = getContainerForFixedLengthVector(VT);
2785       MVT SrcContainerVT =
2786           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2787       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2788     }
2789 
2790     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2791         SrcVT.getVectorElementType() != MVT::f16) {
2792       // For scalable vectors, we only need to close the gap between
2793       // vXf16->vXf64.
2794       if (!VT.isFixedLengthVector())
2795         return Op;
2796       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2797       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2798       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2799     }
2800 
2801     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2802     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2803     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2804         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2805 
2806     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2807                                            DL, DAG, Subtarget);
2808     if (VT.isFixedLengthVector())
2809       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2810     return Extend;
2811   }
2812   case ISD::FP_ROUND: {
2813     // RVV can only do fp_round to types half the size as the source. We
2814     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2815     // conversion instruction.
2816     SDLoc DL(Op);
2817     MVT VT = Op.getSimpleValueType();
2818     SDValue Src = Op.getOperand(0);
2819     MVT SrcVT = Src.getSimpleValueType();
2820 
2821     // Prepare any fixed-length vector operands.
2822     MVT ContainerVT = VT;
2823     if (VT.isFixedLengthVector()) {
2824       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2825       ContainerVT =
2826           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2827       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2828     }
2829 
2830     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2831         SrcVT.getVectorElementType() != MVT::f64) {
2832       // For scalable vectors, we only need to close the gap between
2833       // vXf64<->vXf16.
2834       if (!VT.isFixedLengthVector())
2835         return Op;
2836       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2837       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2838       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2839     }
2840 
2841     SDValue Mask, VL;
2842     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2843 
2844     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2845     SDValue IntermediateRound =
2846         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2847     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2848                                           DL, DAG, Subtarget);
2849 
2850     if (VT.isFixedLengthVector())
2851       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2852     return Round;
2853   }
2854   case ISD::FP_TO_SINT:
2855   case ISD::FP_TO_UINT:
2856   case ISD::SINT_TO_FP:
2857   case ISD::UINT_TO_FP: {
2858     // RVV can only do fp<->int conversions to types half/double the size as
2859     // the source. We custom-lower any conversions that do two hops into
2860     // sequences.
2861     MVT VT = Op.getSimpleValueType();
2862     if (!VT.isVector())
2863       return Op;
2864     SDLoc DL(Op);
2865     SDValue Src = Op.getOperand(0);
2866     MVT EltVT = VT.getVectorElementType();
2867     MVT SrcVT = Src.getSimpleValueType();
2868     MVT SrcEltVT = SrcVT.getVectorElementType();
2869     unsigned EltSize = EltVT.getSizeInBits();
2870     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2871     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2872            "Unexpected vector element types");
2873 
2874     bool IsInt2FP = SrcEltVT.isInteger();
2875     // Widening conversions
2876     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2877       if (IsInt2FP) {
2878         // Do a regular integer sign/zero extension then convert to float.
2879         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2880                                       VT.getVectorElementCount());
2881         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2882                                  ? ISD::ZERO_EXTEND
2883                                  : ISD::SIGN_EXTEND;
2884         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2885         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2886       }
2887       // FP2Int
2888       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2889       // Do one doubling fp_extend then complete the operation by converting
2890       // to int.
2891       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2892       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2893       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2894     }
2895 
2896     // Narrowing conversions
2897     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2898       if (IsInt2FP) {
2899         // One narrowing int_to_fp, then an fp_round.
2900         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2901         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2902         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2903         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2904       }
2905       // FP2Int
2906       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2907       // representable by the integer, the result is poison.
2908       MVT IVecVT =
2909           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2910                            VT.getVectorElementCount());
2911       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2912       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2913     }
2914 
2915     // Scalable vectors can exit here. Patterns will handle equally-sized
2916     // conversions halving/doubling ones.
2917     if (!VT.isFixedLengthVector())
2918       return Op;
2919 
2920     // For fixed-length vectors we lower to a custom "VL" node.
2921     unsigned RVVOpc = 0;
2922     switch (Op.getOpcode()) {
2923     default:
2924       llvm_unreachable("Impossible opcode");
2925     case ISD::FP_TO_SINT:
2926       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2927       break;
2928     case ISD::FP_TO_UINT:
2929       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2930       break;
2931     case ISD::SINT_TO_FP:
2932       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2933       break;
2934     case ISD::UINT_TO_FP:
2935       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2936       break;
2937     }
2938 
2939     MVT ContainerVT, SrcContainerVT;
2940     // Derive the reference container type from the larger vector type.
2941     if (SrcEltSize > EltSize) {
2942       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2943       ContainerVT =
2944           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2945     } else {
2946       ContainerVT = getContainerForFixedLengthVector(VT);
2947       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2948     }
2949 
2950     SDValue Mask, VL;
2951     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2952 
2953     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2954     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2955     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2956   }
2957   case ISD::FP_TO_SINT_SAT:
2958   case ISD::FP_TO_UINT_SAT:
2959     return lowerFP_TO_INT_SAT(Op, DAG);
2960   case ISD::FTRUNC:
2961   case ISD::FCEIL:
2962   case ISD::FFLOOR:
2963     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
2964   case ISD::VECREDUCE_ADD:
2965   case ISD::VECREDUCE_UMAX:
2966   case ISD::VECREDUCE_SMAX:
2967   case ISD::VECREDUCE_UMIN:
2968   case ISD::VECREDUCE_SMIN:
2969     return lowerVECREDUCE(Op, DAG);
2970   case ISD::VECREDUCE_AND:
2971   case ISD::VECREDUCE_OR:
2972   case ISD::VECREDUCE_XOR:
2973     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2974       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2975     return lowerVECREDUCE(Op, DAG);
2976   case ISD::VECREDUCE_FADD:
2977   case ISD::VECREDUCE_SEQ_FADD:
2978   case ISD::VECREDUCE_FMIN:
2979   case ISD::VECREDUCE_FMAX:
2980     return lowerFPVECREDUCE(Op, DAG);
2981   case ISD::VP_REDUCE_ADD:
2982   case ISD::VP_REDUCE_UMAX:
2983   case ISD::VP_REDUCE_SMAX:
2984   case ISD::VP_REDUCE_UMIN:
2985   case ISD::VP_REDUCE_SMIN:
2986   case ISD::VP_REDUCE_FADD:
2987   case ISD::VP_REDUCE_SEQ_FADD:
2988   case ISD::VP_REDUCE_FMIN:
2989   case ISD::VP_REDUCE_FMAX:
2990     return lowerVPREDUCE(Op, DAG);
2991   case ISD::VP_REDUCE_AND:
2992   case ISD::VP_REDUCE_OR:
2993   case ISD::VP_REDUCE_XOR:
2994     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2995       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2996     return lowerVPREDUCE(Op, DAG);
2997   case ISD::INSERT_SUBVECTOR:
2998     return lowerINSERT_SUBVECTOR(Op, DAG);
2999   case ISD::EXTRACT_SUBVECTOR:
3000     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3001   case ISD::STEP_VECTOR:
3002     return lowerSTEP_VECTOR(Op, DAG);
3003   case ISD::VECTOR_REVERSE:
3004     return lowerVECTOR_REVERSE(Op, DAG);
3005   case ISD::BUILD_VECTOR:
3006     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3007   case ISD::SPLAT_VECTOR:
3008     if (Op.getValueType().getVectorElementType() == MVT::i1)
3009       return lowerVectorMaskSplat(Op, DAG);
3010     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3011   case ISD::VECTOR_SHUFFLE:
3012     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3013   case ISD::CONCAT_VECTORS: {
3014     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3015     // better than going through the stack, as the default expansion does.
3016     SDLoc DL(Op);
3017     MVT VT = Op.getSimpleValueType();
3018     unsigned NumOpElts =
3019         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3020     SDValue Vec = DAG.getUNDEF(VT);
3021     for (const auto &OpIdx : enumerate(Op->ops()))
3022       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3023                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3024     return Vec;
3025   }
3026   case ISD::LOAD:
3027     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3028       return V;
3029     if (Op.getValueType().isFixedLengthVector())
3030       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3031     return Op;
3032   case ISD::STORE:
3033     if (auto V = expandUnalignedRVVStore(Op, DAG))
3034       return V;
3035     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3036       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3037     return Op;
3038   case ISD::MLOAD:
3039   case ISD::VP_LOAD:
3040     return lowerMaskedLoad(Op, DAG);
3041   case ISD::MSTORE:
3042   case ISD::VP_STORE:
3043     return lowerMaskedStore(Op, DAG);
3044   case ISD::SETCC:
3045     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3046   case ISD::ADD:
3047     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3048   case ISD::SUB:
3049     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3050   case ISD::MUL:
3051     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3052   case ISD::MULHS:
3053     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3054   case ISD::MULHU:
3055     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3056   case ISD::AND:
3057     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3058                                               RISCVISD::AND_VL);
3059   case ISD::OR:
3060     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3061                                               RISCVISD::OR_VL);
3062   case ISD::XOR:
3063     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3064                                               RISCVISD::XOR_VL);
3065   case ISD::SDIV:
3066     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3067   case ISD::SREM:
3068     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3069   case ISD::UDIV:
3070     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3071   case ISD::UREM:
3072     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3073   case ISD::SHL:
3074   case ISD::SRA:
3075   case ISD::SRL:
3076     if (Op.getSimpleValueType().isFixedLengthVector())
3077       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3078     // This can be called for an i32 shift amount that needs to be promoted.
3079     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3080            "Unexpected custom legalisation");
3081     return SDValue();
3082   case ISD::SADDSAT:
3083     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3084   case ISD::UADDSAT:
3085     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3086   case ISD::SSUBSAT:
3087     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3088   case ISD::USUBSAT:
3089     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3090   case ISD::FADD:
3091     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3092   case ISD::FSUB:
3093     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3094   case ISD::FMUL:
3095     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3096   case ISD::FDIV:
3097     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3098   case ISD::FNEG:
3099     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3100   case ISD::FABS:
3101     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3102   case ISD::FSQRT:
3103     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3104   case ISD::FMA:
3105     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3106   case ISD::SMIN:
3107     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3108   case ISD::SMAX:
3109     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3110   case ISD::UMIN:
3111     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3112   case ISD::UMAX:
3113     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3114   case ISD::FMINNUM:
3115     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3116   case ISD::FMAXNUM:
3117     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3118   case ISD::ABS:
3119     return lowerABS(Op, DAG);
3120   case ISD::CTLZ_ZERO_UNDEF:
3121   case ISD::CTTZ_ZERO_UNDEF:
3122     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3123   case ISD::VSELECT:
3124     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3125   case ISD::FCOPYSIGN:
3126     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3127   case ISD::MGATHER:
3128   case ISD::VP_GATHER:
3129     return lowerMaskedGather(Op, DAG);
3130   case ISD::MSCATTER:
3131   case ISD::VP_SCATTER:
3132     return lowerMaskedScatter(Op, DAG);
3133   case ISD::FLT_ROUNDS_:
3134     return lowerGET_ROUNDING(Op, DAG);
3135   case ISD::SET_ROUNDING:
3136     return lowerSET_ROUNDING(Op, DAG);
3137   case ISD::VP_SELECT:
3138     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3139   case ISD::VP_ADD:
3140     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3141   case ISD::VP_SUB:
3142     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3143   case ISD::VP_MUL:
3144     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3145   case ISD::VP_SDIV:
3146     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3147   case ISD::VP_UDIV:
3148     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3149   case ISD::VP_SREM:
3150     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3151   case ISD::VP_UREM:
3152     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3153   case ISD::VP_AND:
3154     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
3155   case ISD::VP_OR:
3156     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
3157   case ISD::VP_XOR:
3158     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
3159   case ISD::VP_ASHR:
3160     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3161   case ISD::VP_LSHR:
3162     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3163   case ISD::VP_SHL:
3164     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3165   case ISD::VP_FADD:
3166     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3167   case ISD::VP_FSUB:
3168     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3169   case ISD::VP_FMUL:
3170     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3171   case ISD::VP_FDIV:
3172     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3173   }
3174 }
3175 
3176 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3177                              SelectionDAG &DAG, unsigned Flags) {
3178   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3179 }
3180 
3181 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3182                              SelectionDAG &DAG, unsigned Flags) {
3183   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3184                                    Flags);
3185 }
3186 
3187 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3188                              SelectionDAG &DAG, unsigned Flags) {
3189   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3190                                    N->getOffset(), Flags);
3191 }
3192 
3193 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3194                              SelectionDAG &DAG, unsigned Flags) {
3195   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3196 }
3197 
3198 template <class NodeTy>
3199 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3200                                      bool IsLocal) const {
3201   SDLoc DL(N);
3202   EVT Ty = getPointerTy(DAG.getDataLayout());
3203 
3204   if (isPositionIndependent()) {
3205     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3206     if (IsLocal)
3207       // Use PC-relative addressing to access the symbol. This generates the
3208       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3209       // %pcrel_lo(auipc)).
3210       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3211 
3212     // Use PC-relative addressing to access the GOT for this symbol, then load
3213     // the address from the GOT. This generates the pattern (PseudoLA sym),
3214     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3215     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3216   }
3217 
3218   switch (getTargetMachine().getCodeModel()) {
3219   default:
3220     report_fatal_error("Unsupported code model for lowering");
3221   case CodeModel::Small: {
3222     // Generate a sequence for accessing addresses within the first 2 GiB of
3223     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3224     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3225     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3226     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3227     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3228   }
3229   case CodeModel::Medium: {
3230     // Generate a sequence for accessing addresses within any 2GiB range within
3231     // the address space. This generates the pattern (PseudoLLA sym), which
3232     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3233     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3234     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3235   }
3236   }
3237 }
3238 
3239 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3240                                                 SelectionDAG &DAG) const {
3241   SDLoc DL(Op);
3242   EVT Ty = Op.getValueType();
3243   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3244   int64_t Offset = N->getOffset();
3245   MVT XLenVT = Subtarget.getXLenVT();
3246 
3247   const GlobalValue *GV = N->getGlobal();
3248   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3249   SDValue Addr = getAddr(N, DAG, IsLocal);
3250 
3251   // In order to maximise the opportunity for common subexpression elimination,
3252   // emit a separate ADD node for the global address offset instead of folding
3253   // it in the global address node. Later peephole optimisations may choose to
3254   // fold it back in when profitable.
3255   if (Offset != 0)
3256     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3257                        DAG.getConstant(Offset, DL, XLenVT));
3258   return Addr;
3259 }
3260 
3261 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3262                                                SelectionDAG &DAG) const {
3263   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3264 
3265   return getAddr(N, DAG);
3266 }
3267 
3268 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3269                                                SelectionDAG &DAG) const {
3270   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3271 
3272   return getAddr(N, DAG);
3273 }
3274 
3275 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3276                                             SelectionDAG &DAG) const {
3277   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3278 
3279   return getAddr(N, DAG);
3280 }
3281 
3282 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3283                                               SelectionDAG &DAG,
3284                                               bool UseGOT) const {
3285   SDLoc DL(N);
3286   EVT Ty = getPointerTy(DAG.getDataLayout());
3287   const GlobalValue *GV = N->getGlobal();
3288   MVT XLenVT = Subtarget.getXLenVT();
3289 
3290   if (UseGOT) {
3291     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3292     // load the address from the GOT and add the thread pointer. This generates
3293     // the pattern (PseudoLA_TLS_IE sym), which expands to
3294     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3295     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3296     SDValue Load =
3297         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3298 
3299     // Add the thread pointer.
3300     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3301     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3302   }
3303 
3304   // Generate a sequence for accessing the address relative to the thread
3305   // pointer, with the appropriate adjustment for the thread pointer offset.
3306   // This generates the pattern
3307   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3308   SDValue AddrHi =
3309       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3310   SDValue AddrAdd =
3311       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3312   SDValue AddrLo =
3313       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3314 
3315   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3316   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3317   SDValue MNAdd = SDValue(
3318       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3319       0);
3320   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3321 }
3322 
3323 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3324                                                SelectionDAG &DAG) const {
3325   SDLoc DL(N);
3326   EVT Ty = getPointerTy(DAG.getDataLayout());
3327   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3328   const GlobalValue *GV = N->getGlobal();
3329 
3330   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3331   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3332   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3333   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3334   SDValue Load =
3335       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3336 
3337   // Prepare argument list to generate call.
3338   ArgListTy Args;
3339   ArgListEntry Entry;
3340   Entry.Node = Load;
3341   Entry.Ty = CallTy;
3342   Args.push_back(Entry);
3343 
3344   // Setup call to __tls_get_addr.
3345   TargetLowering::CallLoweringInfo CLI(DAG);
3346   CLI.setDebugLoc(DL)
3347       .setChain(DAG.getEntryNode())
3348       .setLibCallee(CallingConv::C, CallTy,
3349                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3350                     std::move(Args));
3351 
3352   return LowerCallTo(CLI).first;
3353 }
3354 
3355 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3356                                                    SelectionDAG &DAG) const {
3357   SDLoc DL(Op);
3358   EVT Ty = Op.getValueType();
3359   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3360   int64_t Offset = N->getOffset();
3361   MVT XLenVT = Subtarget.getXLenVT();
3362 
3363   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3364 
3365   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3366       CallingConv::GHC)
3367     report_fatal_error("In GHC calling convention TLS is not supported");
3368 
3369   SDValue Addr;
3370   switch (Model) {
3371   case TLSModel::LocalExec:
3372     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3373     break;
3374   case TLSModel::InitialExec:
3375     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3376     break;
3377   case TLSModel::LocalDynamic:
3378   case TLSModel::GeneralDynamic:
3379     Addr = getDynamicTLSAddr(N, DAG);
3380     break;
3381   }
3382 
3383   // In order to maximise the opportunity for common subexpression elimination,
3384   // emit a separate ADD node for the global address offset instead of folding
3385   // it in the global address node. Later peephole optimisations may choose to
3386   // fold it back in when profitable.
3387   if (Offset != 0)
3388     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3389                        DAG.getConstant(Offset, DL, XLenVT));
3390   return Addr;
3391 }
3392 
3393 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3394   SDValue CondV = Op.getOperand(0);
3395   SDValue TrueV = Op.getOperand(1);
3396   SDValue FalseV = Op.getOperand(2);
3397   SDLoc DL(Op);
3398   MVT VT = Op.getSimpleValueType();
3399   MVT XLenVT = Subtarget.getXLenVT();
3400 
3401   // Lower vector SELECTs to VSELECTs by splatting the condition.
3402   if (VT.isVector()) {
3403     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3404     SDValue CondSplat = VT.isScalableVector()
3405                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3406                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3407     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3408   }
3409 
3410   // If the result type is XLenVT and CondV is the output of a SETCC node
3411   // which also operated on XLenVT inputs, then merge the SETCC node into the
3412   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3413   // compare+branch instructions. i.e.:
3414   // (select (setcc lhs, rhs, cc), truev, falsev)
3415   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3416   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3417       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3418     SDValue LHS = CondV.getOperand(0);
3419     SDValue RHS = CondV.getOperand(1);
3420     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3421     ISD::CondCode CCVal = CC->get();
3422 
3423     // Special case for a select of 2 constants that have a diffence of 1.
3424     // Normally this is done by DAGCombine, but if the select is introduced by
3425     // type legalization or op legalization, we miss it. Restricting to SETLT
3426     // case for now because that is what signed saturating add/sub need.
3427     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3428     // but we would probably want to swap the true/false values if the condition
3429     // is SETGE/SETLE to avoid an XORI.
3430     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3431         CCVal == ISD::SETLT) {
3432       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3433       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3434       if (TrueVal - 1 == FalseVal)
3435         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3436       if (TrueVal + 1 == FalseVal)
3437         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3438     }
3439 
3440     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3441 
3442     SDValue TargetCC = DAG.getCondCode(CCVal);
3443     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3444     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3445   }
3446 
3447   // Otherwise:
3448   // (select condv, truev, falsev)
3449   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3450   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3451   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3452 
3453   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3454 
3455   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3456 }
3457 
3458 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3459   SDValue CondV = Op.getOperand(1);
3460   SDLoc DL(Op);
3461   MVT XLenVT = Subtarget.getXLenVT();
3462 
3463   if (CondV.getOpcode() == ISD::SETCC &&
3464       CondV.getOperand(0).getValueType() == XLenVT) {
3465     SDValue LHS = CondV.getOperand(0);
3466     SDValue RHS = CondV.getOperand(1);
3467     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3468 
3469     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3470 
3471     SDValue TargetCC = DAG.getCondCode(CCVal);
3472     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3473                        LHS, RHS, TargetCC, Op.getOperand(2));
3474   }
3475 
3476   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3477                      CondV, DAG.getConstant(0, DL, XLenVT),
3478                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3479 }
3480 
3481 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3482   MachineFunction &MF = DAG.getMachineFunction();
3483   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3484 
3485   SDLoc DL(Op);
3486   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3487                                  getPointerTy(MF.getDataLayout()));
3488 
3489   // vastart just stores the address of the VarArgsFrameIndex slot into the
3490   // memory location argument.
3491   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3492   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3493                       MachinePointerInfo(SV));
3494 }
3495 
3496 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3497                                             SelectionDAG &DAG) const {
3498   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3499   MachineFunction &MF = DAG.getMachineFunction();
3500   MachineFrameInfo &MFI = MF.getFrameInfo();
3501   MFI.setFrameAddressIsTaken(true);
3502   Register FrameReg = RI.getFrameRegister(MF);
3503   int XLenInBytes = Subtarget.getXLen() / 8;
3504 
3505   EVT VT = Op.getValueType();
3506   SDLoc DL(Op);
3507   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3508   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3509   while (Depth--) {
3510     int Offset = -(XLenInBytes * 2);
3511     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3512                               DAG.getIntPtrConstant(Offset, DL));
3513     FrameAddr =
3514         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3515   }
3516   return FrameAddr;
3517 }
3518 
3519 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3520                                              SelectionDAG &DAG) const {
3521   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3522   MachineFunction &MF = DAG.getMachineFunction();
3523   MachineFrameInfo &MFI = MF.getFrameInfo();
3524   MFI.setReturnAddressIsTaken(true);
3525   MVT XLenVT = Subtarget.getXLenVT();
3526   int XLenInBytes = Subtarget.getXLen() / 8;
3527 
3528   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3529     return SDValue();
3530 
3531   EVT VT = Op.getValueType();
3532   SDLoc DL(Op);
3533   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3534   if (Depth) {
3535     int Off = -XLenInBytes;
3536     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3537     SDValue Offset = DAG.getConstant(Off, DL, VT);
3538     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3539                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3540                        MachinePointerInfo());
3541   }
3542 
3543   // Return the value of the return address register, marking it an implicit
3544   // live-in.
3545   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3546   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3547 }
3548 
3549 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3550                                                  SelectionDAG &DAG) const {
3551   SDLoc DL(Op);
3552   SDValue Lo = Op.getOperand(0);
3553   SDValue Hi = Op.getOperand(1);
3554   SDValue Shamt = Op.getOperand(2);
3555   EVT VT = Lo.getValueType();
3556 
3557   // if Shamt-XLEN < 0: // Shamt < XLEN
3558   //   Lo = Lo << Shamt
3559   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3560   // else:
3561   //   Lo = 0
3562   //   Hi = Lo << (Shamt-XLEN)
3563 
3564   SDValue Zero = DAG.getConstant(0, DL, VT);
3565   SDValue One = DAG.getConstant(1, DL, VT);
3566   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3567   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3568   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3569   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3570 
3571   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3572   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3573   SDValue ShiftRightLo =
3574       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3575   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3576   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3577   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3578 
3579   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3580 
3581   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3582   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3583 
3584   SDValue Parts[2] = {Lo, Hi};
3585   return DAG.getMergeValues(Parts, DL);
3586 }
3587 
3588 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3589                                                   bool IsSRA) const {
3590   SDLoc DL(Op);
3591   SDValue Lo = Op.getOperand(0);
3592   SDValue Hi = Op.getOperand(1);
3593   SDValue Shamt = Op.getOperand(2);
3594   EVT VT = Lo.getValueType();
3595 
3596   // SRA expansion:
3597   //   if Shamt-XLEN < 0: // Shamt < XLEN
3598   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3599   //     Hi = Hi >>s Shamt
3600   //   else:
3601   //     Lo = Hi >>s (Shamt-XLEN);
3602   //     Hi = Hi >>s (XLEN-1)
3603   //
3604   // SRL expansion:
3605   //   if Shamt-XLEN < 0: // Shamt < XLEN
3606   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3607   //     Hi = Hi >>u Shamt
3608   //   else:
3609   //     Lo = Hi >>u (Shamt-XLEN);
3610   //     Hi = 0;
3611 
3612   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3613 
3614   SDValue Zero = DAG.getConstant(0, DL, VT);
3615   SDValue One = DAG.getConstant(1, DL, VT);
3616   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3617   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3618   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3619   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3620 
3621   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3622   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3623   SDValue ShiftLeftHi =
3624       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3625   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3626   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3627   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3628   SDValue HiFalse =
3629       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3630 
3631   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3632 
3633   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3634   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3635 
3636   SDValue Parts[2] = {Lo, Hi};
3637   return DAG.getMergeValues(Parts, DL);
3638 }
3639 
3640 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3641 // legal equivalently-sized i8 type, so we can use that as a go-between.
3642 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3643                                                   SelectionDAG &DAG) const {
3644   SDLoc DL(Op);
3645   MVT VT = Op.getSimpleValueType();
3646   SDValue SplatVal = Op.getOperand(0);
3647   // All-zeros or all-ones splats are handled specially.
3648   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3649     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3650     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3651   }
3652   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3653     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3654     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3655   }
3656   MVT XLenVT = Subtarget.getXLenVT();
3657   assert(SplatVal.getValueType() == XLenVT &&
3658          "Unexpected type for i1 splat value");
3659   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3660   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3661                          DAG.getConstant(1, DL, XLenVT));
3662   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3663   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3664   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3665 }
3666 
3667 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3668 // illegal (currently only vXi64 RV32).
3669 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3670 // them to SPLAT_VECTOR_I64
3671 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3672                                                      SelectionDAG &DAG) const {
3673   SDLoc DL(Op);
3674   MVT VecVT = Op.getSimpleValueType();
3675   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3676          "Unexpected SPLAT_VECTOR_PARTS lowering");
3677 
3678   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3679   SDValue Lo = Op.getOperand(0);
3680   SDValue Hi = Op.getOperand(1);
3681 
3682   if (VecVT.isFixedLengthVector()) {
3683     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3684     SDLoc DL(Op);
3685     SDValue Mask, VL;
3686     std::tie(Mask, VL) =
3687         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3688 
3689     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3690     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3691   }
3692 
3693   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3694     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3695     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3696     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3697     // node in order to try and match RVV vector/scalar instructions.
3698     if ((LoC >> 31) == HiC)
3699       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3700   }
3701 
3702   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3703   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3704       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3705       Hi.getConstantOperandVal(1) == 31)
3706     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3707 
3708   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3709   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3710                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3711 }
3712 
3713 // Custom-lower extensions from mask vectors by using a vselect either with 1
3714 // for zero/any-extension or -1 for sign-extension:
3715 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3716 // Note that any-extension is lowered identically to zero-extension.
3717 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3718                                                 int64_t ExtTrueVal) const {
3719   SDLoc DL(Op);
3720   MVT VecVT = Op.getSimpleValueType();
3721   SDValue Src = Op.getOperand(0);
3722   // Only custom-lower extensions from mask types
3723   assert(Src.getValueType().isVector() &&
3724          Src.getValueType().getVectorElementType() == MVT::i1);
3725 
3726   MVT XLenVT = Subtarget.getXLenVT();
3727   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3728   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3729 
3730   if (VecVT.isScalableVector()) {
3731     // Be careful not to introduce illegal scalar types at this stage, and be
3732     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3733     // illegal and must be expanded. Since we know that the constants are
3734     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3735     bool IsRV32E64 =
3736         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3737 
3738     if (!IsRV32E64) {
3739       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3740       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3741     } else {
3742       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3743       SplatTrueVal =
3744           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3745     }
3746 
3747     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3748   }
3749 
3750   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3751   MVT I1ContainerVT =
3752       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3753 
3754   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3755 
3756   SDValue Mask, VL;
3757   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3758 
3759   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3760   SplatTrueVal =
3761       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3762   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3763                                SplatTrueVal, SplatZero, VL);
3764 
3765   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3766 }
3767 
3768 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3769     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3770   MVT ExtVT = Op.getSimpleValueType();
3771   // Only custom-lower extensions from fixed-length vector types.
3772   if (!ExtVT.isFixedLengthVector())
3773     return Op;
3774   MVT VT = Op.getOperand(0).getSimpleValueType();
3775   // Grab the canonical container type for the extended type. Infer the smaller
3776   // type from that to ensure the same number of vector elements, as we know
3777   // the LMUL will be sufficient to hold the smaller type.
3778   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3779   // Get the extended container type manually to ensure the same number of
3780   // vector elements between source and dest.
3781   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3782                                      ContainerExtVT.getVectorElementCount());
3783 
3784   SDValue Op1 =
3785       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3786 
3787   SDLoc DL(Op);
3788   SDValue Mask, VL;
3789   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3790 
3791   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3792 
3793   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3794 }
3795 
3796 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3797 // setcc operation:
3798 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3799 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3800                                                   SelectionDAG &DAG) const {
3801   SDLoc DL(Op);
3802   EVT MaskVT = Op.getValueType();
3803   // Only expect to custom-lower truncations to mask types
3804   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3805          "Unexpected type for vector mask lowering");
3806   SDValue Src = Op.getOperand(0);
3807   MVT VecVT = Src.getSimpleValueType();
3808 
3809   // If this is a fixed vector, we need to convert it to a scalable vector.
3810   MVT ContainerVT = VecVT;
3811   if (VecVT.isFixedLengthVector()) {
3812     ContainerVT = getContainerForFixedLengthVector(VecVT);
3813     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3814   }
3815 
3816   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3817   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3818 
3819   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3820   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3821 
3822   if (VecVT.isScalableVector()) {
3823     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3824     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3825   }
3826 
3827   SDValue Mask, VL;
3828   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3829 
3830   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3831   SDValue Trunc =
3832       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3833   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3834                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3835   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3836 }
3837 
3838 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3839 // first position of a vector, and that vector is slid up to the insert index.
3840 // By limiting the active vector length to index+1 and merging with the
3841 // original vector (with an undisturbed tail policy for elements >= VL), we
3842 // achieve the desired result of leaving all elements untouched except the one
3843 // at VL-1, which is replaced with the desired value.
3844 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3845                                                     SelectionDAG &DAG) const {
3846   SDLoc DL(Op);
3847   MVT VecVT = Op.getSimpleValueType();
3848   SDValue Vec = Op.getOperand(0);
3849   SDValue Val = Op.getOperand(1);
3850   SDValue Idx = Op.getOperand(2);
3851 
3852   if (VecVT.getVectorElementType() == MVT::i1) {
3853     // FIXME: For now we just promote to an i8 vector and insert into that,
3854     // but this is probably not optimal.
3855     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3856     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3857     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3858     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3859   }
3860 
3861   MVT ContainerVT = VecVT;
3862   // If the operand is a fixed-length vector, convert to a scalable one.
3863   if (VecVT.isFixedLengthVector()) {
3864     ContainerVT = getContainerForFixedLengthVector(VecVT);
3865     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3866   }
3867 
3868   MVT XLenVT = Subtarget.getXLenVT();
3869 
3870   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3871   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3872   // Even i64-element vectors on RV32 can be lowered without scalar
3873   // legalization if the most-significant 32 bits of the value are not affected
3874   // by the sign-extension of the lower 32 bits.
3875   // TODO: We could also catch sign extensions of a 32-bit value.
3876   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3877     const auto *CVal = cast<ConstantSDNode>(Val);
3878     if (isInt<32>(CVal->getSExtValue())) {
3879       IsLegalInsert = true;
3880       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3881     }
3882   }
3883 
3884   SDValue Mask, VL;
3885   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3886 
3887   SDValue ValInVec;
3888 
3889   if (IsLegalInsert) {
3890     unsigned Opc =
3891         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3892     if (isNullConstant(Idx)) {
3893       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3894       if (!VecVT.isFixedLengthVector())
3895         return Vec;
3896       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3897     }
3898     ValInVec =
3899         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3900   } else {
3901     // On RV32, i64-element vectors must be specially handled to place the
3902     // value at element 0, by using two vslide1up instructions in sequence on
3903     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3904     // this.
3905     SDValue One = DAG.getConstant(1, DL, XLenVT);
3906     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3907     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3908     MVT I32ContainerVT =
3909         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3910     SDValue I32Mask =
3911         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3912     // Limit the active VL to two.
3913     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3914     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3915     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3916     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3917                            InsertI64VL);
3918     // First slide in the hi value, then the lo in underneath it.
3919     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3920                            ValHi, I32Mask, InsertI64VL);
3921     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3922                            ValLo, I32Mask, InsertI64VL);
3923     // Bitcast back to the right container type.
3924     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3925   }
3926 
3927   // Now that the value is in a vector, slide it into position.
3928   SDValue InsertVL =
3929       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3930   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3931                                 ValInVec, Idx, Mask, InsertVL);
3932   if (!VecVT.isFixedLengthVector())
3933     return Slideup;
3934   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3935 }
3936 
3937 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3938 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3939 // types this is done using VMV_X_S to allow us to glean information about the
3940 // sign bits of the result.
3941 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3942                                                      SelectionDAG &DAG) const {
3943   SDLoc DL(Op);
3944   SDValue Idx = Op.getOperand(1);
3945   SDValue Vec = Op.getOperand(0);
3946   EVT EltVT = Op.getValueType();
3947   MVT VecVT = Vec.getSimpleValueType();
3948   MVT XLenVT = Subtarget.getXLenVT();
3949 
3950   if (VecVT.getVectorElementType() == MVT::i1) {
3951     // FIXME: For now we just promote to an i8 vector and extract from that,
3952     // but this is probably not optimal.
3953     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3954     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3955     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3956   }
3957 
3958   // If this is a fixed vector, we need to convert it to a scalable vector.
3959   MVT ContainerVT = VecVT;
3960   if (VecVT.isFixedLengthVector()) {
3961     ContainerVT = getContainerForFixedLengthVector(VecVT);
3962     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3963   }
3964 
3965   // If the index is 0, the vector is already in the right position.
3966   if (!isNullConstant(Idx)) {
3967     // Use a VL of 1 to avoid processing more elements than we need.
3968     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3969     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3970     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3971     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3972                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3973   }
3974 
3975   if (!EltVT.isInteger()) {
3976     // Floating-point extracts are handled in TableGen.
3977     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3978                        DAG.getConstant(0, DL, XLenVT));
3979   }
3980 
3981   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3982   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3983 }
3984 
3985 // Some RVV intrinsics may claim that they want an integer operand to be
3986 // promoted or expanded.
3987 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3988                                           const RISCVSubtarget &Subtarget) {
3989   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3990           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3991          "Unexpected opcode");
3992 
3993   if (!Subtarget.hasVInstructions())
3994     return SDValue();
3995 
3996   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3997   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3998   SDLoc DL(Op);
3999 
4000   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4001       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4002   if (!II || !II->SplatOperand)
4003     return SDValue();
4004 
4005   unsigned SplatOp = II->SplatOperand + HasChain;
4006   assert(SplatOp < Op.getNumOperands());
4007 
4008   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4009   SDValue &ScalarOp = Operands[SplatOp];
4010   MVT OpVT = ScalarOp.getSimpleValueType();
4011   MVT XLenVT = Subtarget.getXLenVT();
4012 
4013   // If this isn't a scalar, or its type is XLenVT we're done.
4014   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4015     return SDValue();
4016 
4017   // Simplest case is that the operand needs to be promoted to XLenVT.
4018   if (OpVT.bitsLT(XLenVT)) {
4019     // If the operand is a constant, sign extend to increase our chances
4020     // of being able to use a .vi instruction. ANY_EXTEND would become a
4021     // a zero extend and the simm5 check in isel would fail.
4022     // FIXME: Should we ignore the upper bits in isel instead?
4023     unsigned ExtOpc =
4024         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4025     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4026     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4027   }
4028 
4029   // Use the previous operand to get the vXi64 VT. The result might be a mask
4030   // VT for compares. Using the previous operand assumes that the previous
4031   // operand will never have a smaller element size than a scalar operand and
4032   // that a widening operation never uses SEW=64.
4033   // NOTE: If this fails the below assert, we can probably just find the
4034   // element count from any operand or result and use it to construct the VT.
4035   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4036   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4037 
4038   // The more complex case is when the scalar is larger than XLenVT.
4039   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4040          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4041 
4042   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4043   // on the instruction to sign-extend since SEW>XLEN.
4044   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4045     if (isInt<32>(CVal->getSExtValue())) {
4046       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4047       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4048     }
4049   }
4050 
4051   // We need to convert the scalar to a splat vector.
4052   // FIXME: Can we implicitly truncate the scalar if it is known to
4053   // be sign extended?
4054   // VL should be the last operand.
4055   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4056   assert(VL.getValueType() == XLenVT);
4057   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4058   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4059 }
4060 
4061 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4062                                                      SelectionDAG &DAG) const {
4063   unsigned IntNo = Op.getConstantOperandVal(0);
4064   SDLoc DL(Op);
4065   MVT XLenVT = Subtarget.getXLenVT();
4066 
4067   switch (IntNo) {
4068   default:
4069     break; // Don't custom lower most intrinsics.
4070   case Intrinsic::thread_pointer: {
4071     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4072     return DAG.getRegister(RISCV::X4, PtrVT);
4073   }
4074   case Intrinsic::riscv_orc_b:
4075     // Lower to the GORCI encoding for orc.b.
4076     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4077                        DAG.getConstant(7, DL, XLenVT));
4078   case Intrinsic::riscv_grev:
4079   case Intrinsic::riscv_gorc: {
4080     unsigned Opc =
4081         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4082     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4083   }
4084   case Intrinsic::riscv_shfl:
4085   case Intrinsic::riscv_unshfl: {
4086     unsigned Opc =
4087         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4088     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4089   }
4090   case Intrinsic::riscv_bcompress:
4091   case Intrinsic::riscv_bdecompress: {
4092     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4093                                                        : RISCVISD::BDECOMPRESS;
4094     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4095   }
4096   case Intrinsic::riscv_vmv_x_s:
4097     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4098     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4099                        Op.getOperand(1));
4100   case Intrinsic::riscv_vmv_v_x:
4101     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4102                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4103   case Intrinsic::riscv_vfmv_v_f:
4104     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4105                        Op.getOperand(1), Op.getOperand(2));
4106   case Intrinsic::riscv_vmv_s_x: {
4107     SDValue Scalar = Op.getOperand(2);
4108 
4109     if (Scalar.getValueType().bitsLE(XLenVT)) {
4110       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4111       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4112                          Op.getOperand(1), Scalar, Op.getOperand(3));
4113     }
4114 
4115     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4116 
4117     // This is an i64 value that lives in two scalar registers. We have to
4118     // insert this in a convoluted way. First we build vXi64 splat containing
4119     // the/ two values that we assemble using some bit math. Next we'll use
4120     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4121     // to merge element 0 from our splat into the source vector.
4122     // FIXME: This is probably not the best way to do this, but it is
4123     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4124     // point.
4125     //   sw lo, (a0)
4126     //   sw hi, 4(a0)
4127     //   vlse vX, (a0)
4128     //
4129     //   vid.v      vVid
4130     //   vmseq.vx   mMask, vVid, 0
4131     //   vmerge.vvm vDest, vSrc, vVal, mMask
4132     MVT VT = Op.getSimpleValueType();
4133     SDValue Vec = Op.getOperand(1);
4134     SDValue VL = Op.getOperand(3);
4135 
4136     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4137     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4138                                       DAG.getConstant(0, DL, MVT::i32), VL);
4139 
4140     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4141     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4142     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4143     SDValue SelectCond =
4144         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4145                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4146     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4147                        Vec, VL);
4148   }
4149   case Intrinsic::riscv_vslide1up:
4150   case Intrinsic::riscv_vslide1down:
4151   case Intrinsic::riscv_vslide1up_mask:
4152   case Intrinsic::riscv_vslide1down_mask: {
4153     // We need to special case these when the scalar is larger than XLen.
4154     unsigned NumOps = Op.getNumOperands();
4155     bool IsMasked = NumOps == 7;
4156     unsigned OpOffset = IsMasked ? 1 : 0;
4157     SDValue Scalar = Op.getOperand(2 + OpOffset);
4158     if (Scalar.getValueType().bitsLE(XLenVT))
4159       break;
4160 
4161     // Splatting a sign extended constant is fine.
4162     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4163       if (isInt<32>(CVal->getSExtValue()))
4164         break;
4165 
4166     MVT VT = Op.getSimpleValueType();
4167     assert(VT.getVectorElementType() == MVT::i64 &&
4168            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4169 
4170     // Convert the vector source to the equivalent nxvXi32 vector.
4171     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4172     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4173 
4174     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4175                                    DAG.getConstant(0, DL, XLenVT));
4176     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4177                                    DAG.getConstant(1, DL, XLenVT));
4178 
4179     // Double the VL since we halved SEW.
4180     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4181     SDValue I32VL =
4182         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4183 
4184     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4185     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4186 
4187     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4188     // instructions.
4189     if (IntNo == Intrinsic::riscv_vslide1up ||
4190         IntNo == Intrinsic::riscv_vslide1up_mask) {
4191       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4192                         I32Mask, I32VL);
4193       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4194                         I32Mask, I32VL);
4195     } else {
4196       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4197                         I32Mask, I32VL);
4198       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4199                         I32Mask, I32VL);
4200     }
4201 
4202     // Convert back to nxvXi64.
4203     Vec = DAG.getBitcast(VT, Vec);
4204 
4205     if (!IsMasked)
4206       return Vec;
4207 
4208     // Apply mask after the operation.
4209     SDValue Mask = Op.getOperand(NumOps - 3);
4210     SDValue MaskedOff = Op.getOperand(1);
4211     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4212   }
4213   }
4214 
4215   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4216 }
4217 
4218 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4219                                                     SelectionDAG &DAG) const {
4220   unsigned IntNo = Op.getConstantOperandVal(1);
4221   switch (IntNo) {
4222   default:
4223     break;
4224   case Intrinsic::riscv_masked_strided_load: {
4225     SDLoc DL(Op);
4226     MVT XLenVT = Subtarget.getXLenVT();
4227 
4228     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4229     // the selection of the masked intrinsics doesn't do this for us.
4230     SDValue Mask = Op.getOperand(5);
4231     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4232 
4233     MVT VT = Op->getSimpleValueType(0);
4234     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4235 
4236     SDValue PassThru = Op.getOperand(2);
4237     if (!IsUnmasked) {
4238       MVT MaskVT =
4239           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4240       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4241       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4242     }
4243 
4244     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4245 
4246     SDValue IntID = DAG.getTargetConstant(
4247         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4248         XLenVT);
4249 
4250     auto *Load = cast<MemIntrinsicSDNode>(Op);
4251     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4252     if (!IsUnmasked)
4253       Ops.push_back(PassThru);
4254     Ops.push_back(Op.getOperand(3)); // Ptr
4255     Ops.push_back(Op.getOperand(4)); // Stride
4256     if (!IsUnmasked)
4257       Ops.push_back(Mask);
4258     Ops.push_back(VL);
4259     if (!IsUnmasked) {
4260       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4261       Ops.push_back(Policy);
4262     }
4263 
4264     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4265     SDValue Result =
4266         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4267                                 Load->getMemoryVT(), Load->getMemOperand());
4268     SDValue Chain = Result.getValue(1);
4269     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4270     return DAG.getMergeValues({Result, Chain}, DL);
4271   }
4272   }
4273 
4274   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4275 }
4276 
4277 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4278                                                  SelectionDAG &DAG) const {
4279   unsigned IntNo = Op.getConstantOperandVal(1);
4280   switch (IntNo) {
4281   default:
4282     break;
4283   case Intrinsic::riscv_masked_strided_store: {
4284     SDLoc DL(Op);
4285     MVT XLenVT = Subtarget.getXLenVT();
4286 
4287     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4288     // the selection of the masked intrinsics doesn't do this for us.
4289     SDValue Mask = Op.getOperand(5);
4290     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4291 
4292     SDValue Val = Op.getOperand(2);
4293     MVT VT = Val.getSimpleValueType();
4294     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4295 
4296     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4297     if (!IsUnmasked) {
4298       MVT MaskVT =
4299           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4300       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4301     }
4302 
4303     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4304 
4305     SDValue IntID = DAG.getTargetConstant(
4306         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4307         XLenVT);
4308 
4309     auto *Store = cast<MemIntrinsicSDNode>(Op);
4310     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4311     Ops.push_back(Val);
4312     Ops.push_back(Op.getOperand(3)); // Ptr
4313     Ops.push_back(Op.getOperand(4)); // Stride
4314     if (!IsUnmasked)
4315       Ops.push_back(Mask);
4316     Ops.push_back(VL);
4317 
4318     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4319                                    Ops, Store->getMemoryVT(),
4320                                    Store->getMemOperand());
4321   }
4322   }
4323 
4324   return SDValue();
4325 }
4326 
4327 static MVT getLMUL1VT(MVT VT) {
4328   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4329          "Unexpected vector MVT");
4330   return MVT::getScalableVectorVT(
4331       VT.getVectorElementType(),
4332       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4333 }
4334 
4335 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4336   switch (ISDOpcode) {
4337   default:
4338     llvm_unreachable("Unhandled reduction");
4339   case ISD::VECREDUCE_ADD:
4340     return RISCVISD::VECREDUCE_ADD_VL;
4341   case ISD::VECREDUCE_UMAX:
4342     return RISCVISD::VECREDUCE_UMAX_VL;
4343   case ISD::VECREDUCE_SMAX:
4344     return RISCVISD::VECREDUCE_SMAX_VL;
4345   case ISD::VECREDUCE_UMIN:
4346     return RISCVISD::VECREDUCE_UMIN_VL;
4347   case ISD::VECREDUCE_SMIN:
4348     return RISCVISD::VECREDUCE_SMIN_VL;
4349   case ISD::VECREDUCE_AND:
4350     return RISCVISD::VECREDUCE_AND_VL;
4351   case ISD::VECREDUCE_OR:
4352     return RISCVISD::VECREDUCE_OR_VL;
4353   case ISD::VECREDUCE_XOR:
4354     return RISCVISD::VECREDUCE_XOR_VL;
4355   }
4356 }
4357 
4358 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4359                                                          SelectionDAG &DAG,
4360                                                          bool IsVP) const {
4361   SDLoc DL(Op);
4362   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4363   MVT VecVT = Vec.getSimpleValueType();
4364   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4365           Op.getOpcode() == ISD::VECREDUCE_OR ||
4366           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4367           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4368           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4369           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4370          "Unexpected reduction lowering");
4371 
4372   MVT XLenVT = Subtarget.getXLenVT();
4373   assert(Op.getValueType() == XLenVT &&
4374          "Expected reduction output to be legalized to XLenVT");
4375 
4376   MVT ContainerVT = VecVT;
4377   if (VecVT.isFixedLengthVector()) {
4378     ContainerVT = getContainerForFixedLengthVector(VecVT);
4379     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4380   }
4381 
4382   SDValue Mask, VL;
4383   if (IsVP) {
4384     Mask = Op.getOperand(2);
4385     VL = Op.getOperand(3);
4386   } else {
4387     std::tie(Mask, VL) =
4388         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4389   }
4390 
4391   unsigned BaseOpc;
4392   ISD::CondCode CC;
4393   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4394 
4395   switch (Op.getOpcode()) {
4396   default:
4397     llvm_unreachable("Unhandled reduction");
4398   case ISD::VECREDUCE_AND:
4399   case ISD::VP_REDUCE_AND: {
4400     // vcpop ~x == 0
4401     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4402     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4403     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4404     CC = ISD::SETEQ;
4405     BaseOpc = ISD::AND;
4406     break;
4407   }
4408   case ISD::VECREDUCE_OR:
4409   case ISD::VP_REDUCE_OR:
4410     // vcpop x != 0
4411     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4412     CC = ISD::SETNE;
4413     BaseOpc = ISD::OR;
4414     break;
4415   case ISD::VECREDUCE_XOR:
4416   case ISD::VP_REDUCE_XOR: {
4417     // ((vcpop x) & 1) != 0
4418     SDValue One = DAG.getConstant(1, DL, XLenVT);
4419     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4420     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4421     CC = ISD::SETNE;
4422     BaseOpc = ISD::XOR;
4423     break;
4424   }
4425   }
4426 
4427   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4428 
4429   if (!IsVP)
4430     return SetCC;
4431 
4432   // Now include the start value in the operation.
4433   // Note that we must return the start value when no elements are operated
4434   // upon. The vcpop instructions we've emitted in each case above will return
4435   // 0 for an inactive vector, and so we've already received the neutral value:
4436   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4437   // can simply include the start value.
4438   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4439 }
4440 
4441 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4442                                             SelectionDAG &DAG) const {
4443   SDLoc DL(Op);
4444   SDValue Vec = Op.getOperand(0);
4445   EVT VecEVT = Vec.getValueType();
4446 
4447   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4448 
4449   // Due to ordering in legalize types we may have a vector type that needs to
4450   // be split. Do that manually so we can get down to a legal type.
4451   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4452          TargetLowering::TypeSplitVector) {
4453     SDValue Lo, Hi;
4454     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4455     VecEVT = Lo.getValueType();
4456     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4457   }
4458 
4459   // TODO: The type may need to be widened rather than split. Or widened before
4460   // it can be split.
4461   if (!isTypeLegal(VecEVT))
4462     return SDValue();
4463 
4464   MVT VecVT = VecEVT.getSimpleVT();
4465   MVT VecEltVT = VecVT.getVectorElementType();
4466   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4467 
4468   MVT ContainerVT = VecVT;
4469   if (VecVT.isFixedLengthVector()) {
4470     ContainerVT = getContainerForFixedLengthVector(VecVT);
4471     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4472   }
4473 
4474   MVT M1VT = getLMUL1VT(ContainerVT);
4475 
4476   SDValue Mask, VL;
4477   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4478 
4479   // FIXME: This is a VLMAX splat which might be too large and can prevent
4480   // vsetvli removal.
4481   SDValue NeutralElem =
4482       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4483   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4484   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4485                                   IdentitySplat, Mask, VL);
4486   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4487                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4488   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4489 }
4490 
4491 // Given a reduction op, this function returns the matching reduction opcode,
4492 // the vector SDValue and the scalar SDValue required to lower this to a
4493 // RISCVISD node.
4494 static std::tuple<unsigned, SDValue, SDValue>
4495 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4496   SDLoc DL(Op);
4497   auto Flags = Op->getFlags();
4498   unsigned Opcode = Op.getOpcode();
4499   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4500   switch (Opcode) {
4501   default:
4502     llvm_unreachable("Unhandled reduction");
4503   case ISD::VECREDUCE_FADD:
4504     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4505                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4506   case ISD::VECREDUCE_SEQ_FADD:
4507     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4508                            Op.getOperand(0));
4509   case ISD::VECREDUCE_FMIN:
4510     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4511                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4512   case ISD::VECREDUCE_FMAX:
4513     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4514                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4515   }
4516 }
4517 
4518 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4519                                               SelectionDAG &DAG) const {
4520   SDLoc DL(Op);
4521   MVT VecEltVT = Op.getSimpleValueType();
4522 
4523   unsigned RVVOpcode;
4524   SDValue VectorVal, ScalarVal;
4525   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4526       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4527   MVT VecVT = VectorVal.getSimpleValueType();
4528 
4529   MVT ContainerVT = VecVT;
4530   if (VecVT.isFixedLengthVector()) {
4531     ContainerVT = getContainerForFixedLengthVector(VecVT);
4532     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4533   }
4534 
4535   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4536 
4537   SDValue Mask, VL;
4538   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4539 
4540   // FIXME: This is a VLMAX splat which might be too large and can prevent
4541   // vsetvli removal.
4542   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4543   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4544                                   VectorVal, ScalarSplat, Mask, VL);
4545   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4546                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4547 }
4548 
4549 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4550   switch (ISDOpcode) {
4551   default:
4552     llvm_unreachable("Unhandled reduction");
4553   case ISD::VP_REDUCE_ADD:
4554     return RISCVISD::VECREDUCE_ADD_VL;
4555   case ISD::VP_REDUCE_UMAX:
4556     return RISCVISD::VECREDUCE_UMAX_VL;
4557   case ISD::VP_REDUCE_SMAX:
4558     return RISCVISD::VECREDUCE_SMAX_VL;
4559   case ISD::VP_REDUCE_UMIN:
4560     return RISCVISD::VECREDUCE_UMIN_VL;
4561   case ISD::VP_REDUCE_SMIN:
4562     return RISCVISD::VECREDUCE_SMIN_VL;
4563   case ISD::VP_REDUCE_AND:
4564     return RISCVISD::VECREDUCE_AND_VL;
4565   case ISD::VP_REDUCE_OR:
4566     return RISCVISD::VECREDUCE_OR_VL;
4567   case ISD::VP_REDUCE_XOR:
4568     return RISCVISD::VECREDUCE_XOR_VL;
4569   case ISD::VP_REDUCE_FADD:
4570     return RISCVISD::VECREDUCE_FADD_VL;
4571   case ISD::VP_REDUCE_SEQ_FADD:
4572     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4573   case ISD::VP_REDUCE_FMAX:
4574     return RISCVISD::VECREDUCE_FMAX_VL;
4575   case ISD::VP_REDUCE_FMIN:
4576     return RISCVISD::VECREDUCE_FMIN_VL;
4577   }
4578 }
4579 
4580 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4581                                            SelectionDAG &DAG) const {
4582   SDLoc DL(Op);
4583   SDValue Vec = Op.getOperand(1);
4584   EVT VecEVT = Vec.getValueType();
4585 
4586   // TODO: The type may need to be widened rather than split. Or widened before
4587   // it can be split.
4588   if (!isTypeLegal(VecEVT))
4589     return SDValue();
4590 
4591   MVT VecVT = VecEVT.getSimpleVT();
4592   MVT VecEltVT = VecVT.getVectorElementType();
4593   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4594 
4595   MVT ContainerVT = VecVT;
4596   if (VecVT.isFixedLengthVector()) {
4597     ContainerVT = getContainerForFixedLengthVector(VecVT);
4598     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4599   }
4600 
4601   SDValue VL = Op.getOperand(3);
4602   SDValue Mask = Op.getOperand(2);
4603 
4604   MVT M1VT = getLMUL1VT(ContainerVT);
4605   MVT XLenVT = Subtarget.getXLenVT();
4606   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4607 
4608   // FIXME: This is a VLMAX splat which might be too large and can prevent
4609   // vsetvli removal.
4610   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4611   SDValue Reduction =
4612       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4613   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4614                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4615   if (!VecVT.isInteger())
4616     return Elt0;
4617   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4618 }
4619 
4620 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4621                                                    SelectionDAG &DAG) const {
4622   SDValue Vec = Op.getOperand(0);
4623   SDValue SubVec = Op.getOperand(1);
4624   MVT VecVT = Vec.getSimpleValueType();
4625   MVT SubVecVT = SubVec.getSimpleValueType();
4626 
4627   SDLoc DL(Op);
4628   MVT XLenVT = Subtarget.getXLenVT();
4629   unsigned OrigIdx = Op.getConstantOperandVal(2);
4630   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4631 
4632   // We don't have the ability to slide mask vectors up indexed by their i1
4633   // elements; the smallest we can do is i8. Often we are able to bitcast to
4634   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4635   // into a scalable one, we might not necessarily have enough scalable
4636   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4637   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4638       (OrigIdx != 0 || !Vec.isUndef())) {
4639     if (VecVT.getVectorMinNumElements() >= 8 &&
4640         SubVecVT.getVectorMinNumElements() >= 8) {
4641       assert(OrigIdx % 8 == 0 && "Invalid index");
4642       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4643              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4644              "Unexpected mask vector lowering");
4645       OrigIdx /= 8;
4646       SubVecVT =
4647           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4648                            SubVecVT.isScalableVector());
4649       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4650                                VecVT.isScalableVector());
4651       Vec = DAG.getBitcast(VecVT, Vec);
4652       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4653     } else {
4654       // We can't slide this mask vector up indexed by its i1 elements.
4655       // This poses a problem when we wish to insert a scalable vector which
4656       // can't be re-expressed as a larger type. Just choose the slow path and
4657       // extend to a larger type, then truncate back down.
4658       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4659       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4660       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4661       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4662       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4663                         Op.getOperand(2));
4664       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4665       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4666     }
4667   }
4668 
4669   // If the subvector vector is a fixed-length type, we cannot use subregister
4670   // manipulation to simplify the codegen; we don't know which register of a
4671   // LMUL group contains the specific subvector as we only know the minimum
4672   // register size. Therefore we must slide the vector group up the full
4673   // amount.
4674   if (SubVecVT.isFixedLengthVector()) {
4675     if (OrigIdx == 0 && Vec.isUndef())
4676       return Op;
4677     MVT ContainerVT = VecVT;
4678     if (VecVT.isFixedLengthVector()) {
4679       ContainerVT = getContainerForFixedLengthVector(VecVT);
4680       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4681     }
4682     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4683                          DAG.getUNDEF(ContainerVT), SubVec,
4684                          DAG.getConstant(0, DL, XLenVT));
4685     SDValue Mask =
4686         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4687     // Set the vector length to only the number of elements we care about. Note
4688     // that for slideup this includes the offset.
4689     SDValue VL =
4690         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4691     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4692     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4693                                   SubVec, SlideupAmt, Mask, VL);
4694     if (VecVT.isFixedLengthVector())
4695       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4696     return DAG.getBitcast(Op.getValueType(), Slideup);
4697   }
4698 
4699   unsigned SubRegIdx, RemIdx;
4700   std::tie(SubRegIdx, RemIdx) =
4701       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4702           VecVT, SubVecVT, OrigIdx, TRI);
4703 
4704   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4705   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4706                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4707                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4708 
4709   // 1. If the Idx has been completely eliminated and this subvector's size is
4710   // a vector register or a multiple thereof, or the surrounding elements are
4711   // undef, then this is a subvector insert which naturally aligns to a vector
4712   // register. These can easily be handled using subregister manipulation.
4713   // 2. If the subvector is smaller than a vector register, then the insertion
4714   // must preserve the undisturbed elements of the register. We do this by
4715   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4716   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4717   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4718   // LMUL=1 type back into the larger vector (resolving to another subregister
4719   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4720   // to avoid allocating a large register group to hold our subvector.
4721   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4722     return Op;
4723 
4724   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4725   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4726   // (in our case undisturbed). This means we can set up a subvector insertion
4727   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4728   // size of the subvector.
4729   MVT InterSubVT = VecVT;
4730   SDValue AlignedExtract = Vec;
4731   unsigned AlignedIdx = OrigIdx - RemIdx;
4732   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4733     InterSubVT = getLMUL1VT(VecVT);
4734     // Extract a subvector equal to the nearest full vector register type. This
4735     // should resolve to a EXTRACT_SUBREG instruction.
4736     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4737                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4738   }
4739 
4740   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4741   // For scalable vectors this must be further multiplied by vscale.
4742   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4743 
4744   SDValue Mask, VL;
4745   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4746 
4747   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4748   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4749   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4750   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4751 
4752   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4753                        DAG.getUNDEF(InterSubVT), SubVec,
4754                        DAG.getConstant(0, DL, XLenVT));
4755 
4756   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4757                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4758 
4759   // If required, insert this subvector back into the correct vector register.
4760   // This should resolve to an INSERT_SUBREG instruction.
4761   if (VecVT.bitsGT(InterSubVT))
4762     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4763                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4764 
4765   // We might have bitcast from a mask type: cast back to the original type if
4766   // required.
4767   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4768 }
4769 
4770 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4771                                                     SelectionDAG &DAG) const {
4772   SDValue Vec = Op.getOperand(0);
4773   MVT SubVecVT = Op.getSimpleValueType();
4774   MVT VecVT = Vec.getSimpleValueType();
4775 
4776   SDLoc DL(Op);
4777   MVT XLenVT = Subtarget.getXLenVT();
4778   unsigned OrigIdx = Op.getConstantOperandVal(1);
4779   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4780 
4781   // We don't have the ability to slide mask vectors down indexed by their i1
4782   // elements; the smallest we can do is i8. Often we are able to bitcast to
4783   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4784   // from a scalable one, we might not necessarily have enough scalable
4785   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4786   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4787     if (VecVT.getVectorMinNumElements() >= 8 &&
4788         SubVecVT.getVectorMinNumElements() >= 8) {
4789       assert(OrigIdx % 8 == 0 && "Invalid index");
4790       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4791              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4792              "Unexpected mask vector lowering");
4793       OrigIdx /= 8;
4794       SubVecVT =
4795           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4796                            SubVecVT.isScalableVector());
4797       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4798                                VecVT.isScalableVector());
4799       Vec = DAG.getBitcast(VecVT, Vec);
4800     } else {
4801       // We can't slide this mask vector down, indexed by its i1 elements.
4802       // This poses a problem when we wish to extract a scalable vector which
4803       // can't be re-expressed as a larger type. Just choose the slow path and
4804       // extend to a larger type, then truncate back down.
4805       // TODO: We could probably improve this when extracting certain fixed
4806       // from fixed, where we can extract as i8 and shift the correct element
4807       // right to reach the desired subvector?
4808       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4809       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4810       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4811       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4812                         Op.getOperand(1));
4813       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4814       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4815     }
4816   }
4817 
4818   // If the subvector vector is a fixed-length type, we cannot use subregister
4819   // manipulation to simplify the codegen; we don't know which register of a
4820   // LMUL group contains the specific subvector as we only know the minimum
4821   // register size. Therefore we must slide the vector group down the full
4822   // amount.
4823   if (SubVecVT.isFixedLengthVector()) {
4824     // With an index of 0 this is a cast-like subvector, which can be performed
4825     // with subregister operations.
4826     if (OrigIdx == 0)
4827       return Op;
4828     MVT ContainerVT = VecVT;
4829     if (VecVT.isFixedLengthVector()) {
4830       ContainerVT = getContainerForFixedLengthVector(VecVT);
4831       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4832     }
4833     SDValue Mask =
4834         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4835     // Set the vector length to only the number of elements we care about. This
4836     // avoids sliding down elements we're going to discard straight away.
4837     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4838     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4839     SDValue Slidedown =
4840         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4841                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4842     // Now we can use a cast-like subvector extract to get the result.
4843     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4844                             DAG.getConstant(0, DL, XLenVT));
4845     return DAG.getBitcast(Op.getValueType(), Slidedown);
4846   }
4847 
4848   unsigned SubRegIdx, RemIdx;
4849   std::tie(SubRegIdx, RemIdx) =
4850       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4851           VecVT, SubVecVT, OrigIdx, TRI);
4852 
4853   // If the Idx has been completely eliminated then this is a subvector extract
4854   // which naturally aligns to a vector register. These can easily be handled
4855   // using subregister manipulation.
4856   if (RemIdx == 0)
4857     return Op;
4858 
4859   // Else we must shift our vector register directly to extract the subvector.
4860   // Do this using VSLIDEDOWN.
4861 
4862   // If the vector type is an LMUL-group type, extract a subvector equal to the
4863   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4864   // instruction.
4865   MVT InterSubVT = VecVT;
4866   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4867     InterSubVT = getLMUL1VT(VecVT);
4868     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4869                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4870   }
4871 
4872   // Slide this vector register down by the desired number of elements in order
4873   // to place the desired subvector starting at element 0.
4874   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4875   // For scalable vectors this must be further multiplied by vscale.
4876   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4877 
4878   SDValue Mask, VL;
4879   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4880   SDValue Slidedown =
4881       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4882                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4883 
4884   // Now the vector is in the right position, extract our final subvector. This
4885   // should resolve to a COPY.
4886   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4887                           DAG.getConstant(0, DL, XLenVT));
4888 
4889   // We might have bitcast from a mask type: cast back to the original type if
4890   // required.
4891   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4892 }
4893 
4894 // Lower step_vector to the vid instruction. Any non-identity step value must
4895 // be accounted for my manual expansion.
4896 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4897                                               SelectionDAG &DAG) const {
4898   SDLoc DL(Op);
4899   MVT VT = Op.getSimpleValueType();
4900   MVT XLenVT = Subtarget.getXLenVT();
4901   SDValue Mask, VL;
4902   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4903   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4904   uint64_t StepValImm = Op.getConstantOperandVal(0);
4905   if (StepValImm != 1) {
4906     if (isPowerOf2_64(StepValImm)) {
4907       SDValue StepVal =
4908           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4909                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4910       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4911     } else {
4912       SDValue StepVal = lowerScalarSplat(
4913           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4914           DL, DAG, Subtarget);
4915       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4916     }
4917   }
4918   return StepVec;
4919 }
4920 
4921 // Implement vector_reverse using vrgather.vv with indices determined by
4922 // subtracting the id of each element from (VLMAX-1). This will convert
4923 // the indices like so:
4924 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4925 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4926 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4927                                                  SelectionDAG &DAG) const {
4928   SDLoc DL(Op);
4929   MVT VecVT = Op.getSimpleValueType();
4930   unsigned EltSize = VecVT.getScalarSizeInBits();
4931   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4932 
4933   unsigned MaxVLMAX = 0;
4934   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4935   if (VectorBitsMax != 0)
4936     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4937 
4938   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4939   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4940 
4941   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4942   // to use vrgatherei16.vv.
4943   // TODO: It's also possible to use vrgatherei16.vv for other types to
4944   // decrease register width for the index calculation.
4945   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4946     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4947     // Reverse each half, then reassemble them in reverse order.
4948     // NOTE: It's also possible that after splitting that VLMAX no longer
4949     // requires vrgatherei16.vv.
4950     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4951       SDValue Lo, Hi;
4952       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4953       EVT LoVT, HiVT;
4954       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4955       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4956       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4957       // Reassemble the low and high pieces reversed.
4958       // FIXME: This is a CONCAT_VECTORS.
4959       SDValue Res =
4960           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4961                       DAG.getIntPtrConstant(0, DL));
4962       return DAG.getNode(
4963           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4964           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4965     }
4966 
4967     // Just promote the int type to i16 which will double the LMUL.
4968     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4969     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4970   }
4971 
4972   MVT XLenVT = Subtarget.getXLenVT();
4973   SDValue Mask, VL;
4974   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4975 
4976   // Calculate VLMAX-1 for the desired SEW.
4977   unsigned MinElts = VecVT.getVectorMinNumElements();
4978   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4979                               DAG.getConstant(MinElts, DL, XLenVT));
4980   SDValue VLMinus1 =
4981       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4982 
4983   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4984   bool IsRV32E64 =
4985       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4986   SDValue SplatVL;
4987   if (!IsRV32E64)
4988     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4989   else
4990     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4991 
4992   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4993   SDValue Indices =
4994       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4995 
4996   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4997 }
4998 
4999 SDValue
5000 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5001                                                      SelectionDAG &DAG) const {
5002   SDLoc DL(Op);
5003   auto *Load = cast<LoadSDNode>(Op);
5004 
5005   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5006                                         Load->getMemoryVT(),
5007                                         *Load->getMemOperand()) &&
5008          "Expecting a correctly-aligned load");
5009 
5010   MVT VT = Op.getSimpleValueType();
5011   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5012 
5013   SDValue VL =
5014       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5015 
5016   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5017   SDValue NewLoad = DAG.getMemIntrinsicNode(
5018       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5019       Load->getMemoryVT(), Load->getMemOperand());
5020 
5021   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5022   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5023 }
5024 
5025 SDValue
5026 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5027                                                       SelectionDAG &DAG) const {
5028   SDLoc DL(Op);
5029   auto *Store = cast<StoreSDNode>(Op);
5030 
5031   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5032                                         Store->getMemoryVT(),
5033                                         *Store->getMemOperand()) &&
5034          "Expecting a correctly-aligned store");
5035 
5036   SDValue StoreVal = Store->getValue();
5037   MVT VT = StoreVal.getSimpleValueType();
5038 
5039   // If the size less than a byte, we need to pad with zeros to make a byte.
5040   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5041     VT = MVT::v8i1;
5042     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5043                            DAG.getConstant(0, DL, VT), StoreVal,
5044                            DAG.getIntPtrConstant(0, DL));
5045   }
5046 
5047   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5048 
5049   SDValue VL =
5050       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5051 
5052   SDValue NewValue =
5053       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5054   return DAG.getMemIntrinsicNode(
5055       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5056       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5057       Store->getMemoryVT(), Store->getMemOperand());
5058 }
5059 
5060 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5061                                              SelectionDAG &DAG) const {
5062   SDLoc DL(Op);
5063   MVT VT = Op.getSimpleValueType();
5064 
5065   const auto *MemSD = cast<MemSDNode>(Op);
5066   EVT MemVT = MemSD->getMemoryVT();
5067   MachineMemOperand *MMO = MemSD->getMemOperand();
5068   SDValue Chain = MemSD->getChain();
5069   SDValue BasePtr = MemSD->getBasePtr();
5070 
5071   SDValue Mask, PassThru, VL;
5072   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5073     Mask = VPLoad->getMask();
5074     PassThru = DAG.getUNDEF(VT);
5075     VL = VPLoad->getVectorLength();
5076   } else {
5077     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5078     Mask = MLoad->getMask();
5079     PassThru = MLoad->getPassThru();
5080   }
5081 
5082   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5083 
5084   MVT XLenVT = Subtarget.getXLenVT();
5085 
5086   MVT ContainerVT = VT;
5087   if (VT.isFixedLengthVector()) {
5088     ContainerVT = getContainerForFixedLengthVector(VT);
5089     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5090     if (!IsUnmasked) {
5091       MVT MaskVT =
5092           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5093       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5094     }
5095   }
5096 
5097   if (!VL)
5098     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5099 
5100   unsigned IntID =
5101       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5102   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5103   if (!IsUnmasked)
5104     Ops.push_back(PassThru);
5105   Ops.push_back(BasePtr);
5106   if (!IsUnmasked)
5107     Ops.push_back(Mask);
5108   Ops.push_back(VL);
5109   if (!IsUnmasked)
5110     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5111 
5112   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5113 
5114   SDValue Result =
5115       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5116   Chain = Result.getValue(1);
5117 
5118   if (VT.isFixedLengthVector())
5119     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5120 
5121   return DAG.getMergeValues({Result, Chain}, DL);
5122 }
5123 
5124 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5125                                               SelectionDAG &DAG) const {
5126   SDLoc DL(Op);
5127 
5128   const auto *MemSD = cast<MemSDNode>(Op);
5129   EVT MemVT = MemSD->getMemoryVT();
5130   MachineMemOperand *MMO = MemSD->getMemOperand();
5131   SDValue Chain = MemSD->getChain();
5132   SDValue BasePtr = MemSD->getBasePtr();
5133   SDValue Val, Mask, VL;
5134 
5135   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5136     Val = VPStore->getValue();
5137     Mask = VPStore->getMask();
5138     VL = VPStore->getVectorLength();
5139   } else {
5140     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5141     Val = MStore->getValue();
5142     Mask = MStore->getMask();
5143   }
5144 
5145   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5146 
5147   MVT VT = Val.getSimpleValueType();
5148   MVT XLenVT = Subtarget.getXLenVT();
5149 
5150   MVT ContainerVT = VT;
5151   if (VT.isFixedLengthVector()) {
5152     ContainerVT = getContainerForFixedLengthVector(VT);
5153 
5154     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5155     if (!IsUnmasked) {
5156       MVT MaskVT =
5157           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5158       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5159     }
5160   }
5161 
5162   if (!VL)
5163     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5164 
5165   unsigned IntID =
5166       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5167   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5168   Ops.push_back(Val);
5169   Ops.push_back(BasePtr);
5170   if (!IsUnmasked)
5171     Ops.push_back(Mask);
5172   Ops.push_back(VL);
5173 
5174   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5175                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5176 }
5177 
5178 SDValue
5179 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5180                                                       SelectionDAG &DAG) const {
5181   MVT InVT = Op.getOperand(0).getSimpleValueType();
5182   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5183 
5184   MVT VT = Op.getSimpleValueType();
5185 
5186   SDValue Op1 =
5187       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5188   SDValue Op2 =
5189       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5190 
5191   SDLoc DL(Op);
5192   SDValue VL =
5193       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5194 
5195   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5196   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5197 
5198   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5199                             Op.getOperand(2), Mask, VL);
5200 
5201   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5202 }
5203 
5204 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5205     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5206   MVT VT = Op.getSimpleValueType();
5207 
5208   if (VT.getVectorElementType() == MVT::i1)
5209     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5210 
5211   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5212 }
5213 
5214 SDValue
5215 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5216                                                       SelectionDAG &DAG) const {
5217   unsigned Opc;
5218   switch (Op.getOpcode()) {
5219   default: llvm_unreachable("Unexpected opcode!");
5220   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5221   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5222   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5223   }
5224 
5225   return lowerToScalableOp(Op, DAG, Opc);
5226 }
5227 
5228 // Lower vector ABS to smax(X, sub(0, X)).
5229 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5230   SDLoc DL(Op);
5231   MVT VT = Op.getSimpleValueType();
5232   SDValue X = Op.getOperand(0);
5233 
5234   assert(VT.isFixedLengthVector() && "Unexpected type");
5235 
5236   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5237   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5238 
5239   SDValue Mask, VL;
5240   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5241 
5242   SDValue SplatZero =
5243       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5244                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5245   SDValue NegX =
5246       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5247   SDValue Max =
5248       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5249 
5250   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5251 }
5252 
5253 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5254     SDValue Op, SelectionDAG &DAG) const {
5255   SDLoc DL(Op);
5256   MVT VT = Op.getSimpleValueType();
5257   SDValue Mag = Op.getOperand(0);
5258   SDValue Sign = Op.getOperand(1);
5259   assert(Mag.getValueType() == Sign.getValueType() &&
5260          "Can only handle COPYSIGN with matching types.");
5261 
5262   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5263   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5264   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5265 
5266   SDValue Mask, VL;
5267   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5268 
5269   SDValue CopySign =
5270       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5271 
5272   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5273 }
5274 
5275 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5276     SDValue Op, SelectionDAG &DAG) const {
5277   MVT VT = Op.getSimpleValueType();
5278   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5279 
5280   MVT I1ContainerVT =
5281       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5282 
5283   SDValue CC =
5284       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5285   SDValue Op1 =
5286       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5287   SDValue Op2 =
5288       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5289 
5290   SDLoc DL(Op);
5291   SDValue Mask, VL;
5292   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5293 
5294   SDValue Select =
5295       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5296 
5297   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5298 }
5299 
5300 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5301                                                unsigned NewOpc,
5302                                                bool HasMask) const {
5303   MVT VT = Op.getSimpleValueType();
5304   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5305 
5306   // Create list of operands by converting existing ones to scalable types.
5307   SmallVector<SDValue, 6> Ops;
5308   for (const SDValue &V : Op->op_values()) {
5309     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5310 
5311     // Pass through non-vector operands.
5312     if (!V.getValueType().isVector()) {
5313       Ops.push_back(V);
5314       continue;
5315     }
5316 
5317     // "cast" fixed length vector to a scalable vector.
5318     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5319            "Only fixed length vectors are supported!");
5320     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5321   }
5322 
5323   SDLoc DL(Op);
5324   SDValue Mask, VL;
5325   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5326   if (HasMask)
5327     Ops.push_back(Mask);
5328   Ops.push_back(VL);
5329 
5330   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5331   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5332 }
5333 
5334 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5335 // * Operands of each node are assumed to be in the same order.
5336 // * The EVL operand is promoted from i32 to i64 on RV64.
5337 // * Fixed-length vectors are converted to their scalable-vector container
5338 //   types.
5339 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5340                                        unsigned RISCVISDOpc) const {
5341   SDLoc DL(Op);
5342   MVT VT = Op.getSimpleValueType();
5343   SmallVector<SDValue, 4> Ops;
5344 
5345   for (const auto &OpIdx : enumerate(Op->ops())) {
5346     SDValue V = OpIdx.value();
5347     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5348     // Pass through operands which aren't fixed-length vectors.
5349     if (!V.getValueType().isFixedLengthVector()) {
5350       Ops.push_back(V);
5351       continue;
5352     }
5353     // "cast" fixed length vector to a scalable vector.
5354     MVT OpVT = V.getSimpleValueType();
5355     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5356     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5357            "Only fixed length vectors are supported!");
5358     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5359   }
5360 
5361   if (!VT.isFixedLengthVector())
5362     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5363 
5364   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5365 
5366   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5367 
5368   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5369 }
5370 
5371 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5372 // matched to a RVV indexed load. The RVV indexed load instructions only
5373 // support the "unsigned unscaled" addressing mode; indices are implicitly
5374 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5375 // signed or scaled indexing is extended to the XLEN value type and scaled
5376 // accordingly.
5377 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5378                                                SelectionDAG &DAG) const {
5379   SDLoc DL(Op);
5380   MVT VT = Op.getSimpleValueType();
5381 
5382   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5383   EVT MemVT = MemSD->getMemoryVT();
5384   MachineMemOperand *MMO = MemSD->getMemOperand();
5385   SDValue Chain = MemSD->getChain();
5386   SDValue BasePtr = MemSD->getBasePtr();
5387 
5388   ISD::LoadExtType LoadExtType;
5389   SDValue Index, Mask, PassThru, VL;
5390 
5391   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5392     Index = VPGN->getIndex();
5393     Mask = VPGN->getMask();
5394     PassThru = DAG.getUNDEF(VT);
5395     VL = VPGN->getVectorLength();
5396     // VP doesn't support extending loads.
5397     LoadExtType = ISD::NON_EXTLOAD;
5398   } else {
5399     // Else it must be a MGATHER.
5400     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5401     Index = MGN->getIndex();
5402     Mask = MGN->getMask();
5403     PassThru = MGN->getPassThru();
5404     LoadExtType = MGN->getExtensionType();
5405   }
5406 
5407   MVT IndexVT = Index.getSimpleValueType();
5408   MVT XLenVT = Subtarget.getXLenVT();
5409 
5410   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5411          "Unexpected VTs!");
5412   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5413   // Targets have to explicitly opt-in for extending vector loads.
5414   assert(LoadExtType == ISD::NON_EXTLOAD &&
5415          "Unexpected extending MGATHER/VP_GATHER");
5416   (void)LoadExtType;
5417 
5418   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5419   // the selection of the masked intrinsics doesn't do this for us.
5420   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5421 
5422   MVT ContainerVT = VT;
5423   if (VT.isFixedLengthVector()) {
5424     // We need to use the larger of the result and index type to determine the
5425     // scalable type to use so we don't increase LMUL for any operand/result.
5426     if (VT.bitsGE(IndexVT)) {
5427       ContainerVT = getContainerForFixedLengthVector(VT);
5428       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5429                                  ContainerVT.getVectorElementCount());
5430     } else {
5431       IndexVT = getContainerForFixedLengthVector(IndexVT);
5432       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5433                                      IndexVT.getVectorElementCount());
5434     }
5435 
5436     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5437 
5438     if (!IsUnmasked) {
5439       MVT MaskVT =
5440           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5441       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5442       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5443     }
5444   }
5445 
5446   if (!VL)
5447     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5448 
5449   unsigned IntID =
5450       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5451   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5452   if (!IsUnmasked)
5453     Ops.push_back(PassThru);
5454   Ops.push_back(BasePtr);
5455   Ops.push_back(Index);
5456   if (!IsUnmasked)
5457     Ops.push_back(Mask);
5458   Ops.push_back(VL);
5459   if (!IsUnmasked)
5460     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5461 
5462   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5463   SDValue Result =
5464       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5465   Chain = Result.getValue(1);
5466 
5467   if (VT.isFixedLengthVector())
5468     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5469 
5470   return DAG.getMergeValues({Result, Chain}, DL);
5471 }
5472 
5473 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5474 // matched to a RVV indexed store. The RVV indexed store instructions only
5475 // support the "unsigned unscaled" addressing mode; indices are implicitly
5476 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5477 // signed or scaled indexing is extended to the XLEN value type and scaled
5478 // accordingly.
5479 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5480                                                 SelectionDAG &DAG) const {
5481   SDLoc DL(Op);
5482   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5483   EVT MemVT = MemSD->getMemoryVT();
5484   MachineMemOperand *MMO = MemSD->getMemOperand();
5485   SDValue Chain = MemSD->getChain();
5486   SDValue BasePtr = MemSD->getBasePtr();
5487 
5488   bool IsTruncatingStore = false;
5489   SDValue Index, Mask, Val, VL;
5490 
5491   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5492     Index = VPSN->getIndex();
5493     Mask = VPSN->getMask();
5494     Val = VPSN->getValue();
5495     VL = VPSN->getVectorLength();
5496     // VP doesn't support truncating stores.
5497     IsTruncatingStore = false;
5498   } else {
5499     // Else it must be a MSCATTER.
5500     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5501     Index = MSN->getIndex();
5502     Mask = MSN->getMask();
5503     Val = MSN->getValue();
5504     IsTruncatingStore = MSN->isTruncatingStore();
5505   }
5506 
5507   MVT VT = Val.getSimpleValueType();
5508   MVT IndexVT = Index.getSimpleValueType();
5509   MVT XLenVT = Subtarget.getXLenVT();
5510 
5511   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5512          "Unexpected VTs!");
5513   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5514   // Targets have to explicitly opt-in for extending vector loads and
5515   // truncating vector stores.
5516   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5517   (void)IsTruncatingStore;
5518 
5519   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5520   // the selection of the masked intrinsics doesn't do this for us.
5521   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5522 
5523   MVT ContainerVT = VT;
5524   if (VT.isFixedLengthVector()) {
5525     // We need to use the larger of the value and index type to determine the
5526     // scalable type to use so we don't increase LMUL for any operand/result.
5527     if (VT.bitsGE(IndexVT)) {
5528       ContainerVT = getContainerForFixedLengthVector(VT);
5529       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5530                                  ContainerVT.getVectorElementCount());
5531     } else {
5532       IndexVT = getContainerForFixedLengthVector(IndexVT);
5533       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5534                                      IndexVT.getVectorElementCount());
5535     }
5536 
5537     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5538     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5539 
5540     if (!IsUnmasked) {
5541       MVT MaskVT =
5542           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5543       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5544     }
5545   }
5546 
5547   if (!VL)
5548     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5549 
5550   unsigned IntID =
5551       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5552   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5553   Ops.push_back(Val);
5554   Ops.push_back(BasePtr);
5555   Ops.push_back(Index);
5556   if (!IsUnmasked)
5557     Ops.push_back(Mask);
5558   Ops.push_back(VL);
5559 
5560   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5561                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5562 }
5563 
5564 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5565                                                SelectionDAG &DAG) const {
5566   const MVT XLenVT = Subtarget.getXLenVT();
5567   SDLoc DL(Op);
5568   SDValue Chain = Op->getOperand(0);
5569   SDValue SysRegNo = DAG.getTargetConstant(
5570       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5571   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5572   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5573 
5574   // Encoding used for rounding mode in RISCV differs from that used in
5575   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5576   // table, which consists of a sequence of 4-bit fields, each representing
5577   // corresponding FLT_ROUNDS mode.
5578   static const int Table =
5579       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5580       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5581       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5582       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5583       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5584 
5585   SDValue Shift =
5586       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5587   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5588                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5589   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5590                                DAG.getConstant(7, DL, XLenVT));
5591 
5592   return DAG.getMergeValues({Masked, Chain}, DL);
5593 }
5594 
5595 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5596                                                SelectionDAG &DAG) const {
5597   const MVT XLenVT = Subtarget.getXLenVT();
5598   SDLoc DL(Op);
5599   SDValue Chain = Op->getOperand(0);
5600   SDValue RMValue = Op->getOperand(1);
5601   SDValue SysRegNo = DAG.getTargetConstant(
5602       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5603 
5604   // Encoding used for rounding mode in RISCV differs from that used in
5605   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5606   // a table, which consists of a sequence of 4-bit fields, each representing
5607   // corresponding RISCV mode.
5608   static const unsigned Table =
5609       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5610       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5611       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5612       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5613       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5614 
5615   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5616                               DAG.getConstant(2, DL, XLenVT));
5617   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5618                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5619   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5620                         DAG.getConstant(0x7, DL, XLenVT));
5621   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5622                      RMValue);
5623 }
5624 
5625 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5626 // form of the given Opcode.
5627 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5628   switch (Opcode) {
5629   default:
5630     llvm_unreachable("Unexpected opcode");
5631   case ISD::SHL:
5632     return RISCVISD::SLLW;
5633   case ISD::SRA:
5634     return RISCVISD::SRAW;
5635   case ISD::SRL:
5636     return RISCVISD::SRLW;
5637   case ISD::SDIV:
5638     return RISCVISD::DIVW;
5639   case ISD::UDIV:
5640     return RISCVISD::DIVUW;
5641   case ISD::UREM:
5642     return RISCVISD::REMUW;
5643   case ISD::ROTL:
5644     return RISCVISD::ROLW;
5645   case ISD::ROTR:
5646     return RISCVISD::RORW;
5647   case RISCVISD::GREV:
5648     return RISCVISD::GREVW;
5649   case RISCVISD::GORC:
5650     return RISCVISD::GORCW;
5651   }
5652 }
5653 
5654 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5655 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5656 // otherwise be promoted to i64, making it difficult to select the
5657 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5658 // type i8/i16/i32 is lost.
5659 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5660                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5661   SDLoc DL(N);
5662   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5663   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5664   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5665   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5666   // ReplaceNodeResults requires we maintain the same type for the return value.
5667   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5668 }
5669 
5670 // Converts the given 32-bit operation to a i64 operation with signed extension
5671 // semantic to reduce the signed extension instructions.
5672 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5673   SDLoc DL(N);
5674   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5675   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5676   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5677   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5678                                DAG.getValueType(MVT::i32));
5679   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5680 }
5681 
5682 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5683                                              SmallVectorImpl<SDValue> &Results,
5684                                              SelectionDAG &DAG) const {
5685   SDLoc DL(N);
5686   switch (N->getOpcode()) {
5687   default:
5688     llvm_unreachable("Don't know how to custom type legalize this operation!");
5689   case ISD::STRICT_FP_TO_SINT:
5690   case ISD::STRICT_FP_TO_UINT:
5691   case ISD::FP_TO_SINT:
5692   case ISD::FP_TO_UINT: {
5693     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5694            "Unexpected custom legalisation");
5695     bool IsStrict = N->isStrictFPOpcode();
5696     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5697                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5698     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5699     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5700         TargetLowering::TypeSoftenFloat) {
5701       // FIXME: Support strict FP.
5702       if (IsStrict)
5703         return;
5704       if (!isTypeLegal(Op0.getValueType()))
5705         return;
5706       unsigned Opc =
5707           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5708       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5709       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5710       return;
5711     }
5712     // If the FP type needs to be softened, emit a library call using the 'si'
5713     // version. If we left it to default legalization we'd end up with 'di'. If
5714     // the FP type doesn't need to be softened just let generic type
5715     // legalization promote the result type.
5716     RTLIB::Libcall LC;
5717     if (IsSigned)
5718       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5719     else
5720       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5721     MakeLibCallOptions CallOptions;
5722     EVT OpVT = Op0.getValueType();
5723     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5724     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5725     SDValue Result;
5726     std::tie(Result, Chain) =
5727         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5728     Results.push_back(Result);
5729     if (IsStrict)
5730       Results.push_back(Chain);
5731     break;
5732   }
5733   case ISD::READCYCLECOUNTER: {
5734     assert(!Subtarget.is64Bit() &&
5735            "READCYCLECOUNTER only has custom type legalization on riscv32");
5736 
5737     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5738     SDValue RCW =
5739         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5740 
5741     Results.push_back(
5742         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5743     Results.push_back(RCW.getValue(2));
5744     break;
5745   }
5746   case ISD::MUL: {
5747     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5748     unsigned XLen = Subtarget.getXLen();
5749     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5750     if (Size > XLen) {
5751       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5752       SDValue LHS = N->getOperand(0);
5753       SDValue RHS = N->getOperand(1);
5754       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5755 
5756       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5757       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5758       // We need exactly one side to be unsigned.
5759       if (LHSIsU == RHSIsU)
5760         return;
5761 
5762       auto MakeMULPair = [&](SDValue S, SDValue U) {
5763         MVT XLenVT = Subtarget.getXLenVT();
5764         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5765         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5766         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5767         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5768         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5769       };
5770 
5771       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5772       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5773 
5774       // The other operand should be signed, but still prefer MULH when
5775       // possible.
5776       if (RHSIsU && LHSIsS && !RHSIsS)
5777         Results.push_back(MakeMULPair(LHS, RHS));
5778       else if (LHSIsU && RHSIsS && !LHSIsS)
5779         Results.push_back(MakeMULPair(RHS, LHS));
5780 
5781       return;
5782     }
5783     LLVM_FALLTHROUGH;
5784   }
5785   case ISD::ADD:
5786   case ISD::SUB:
5787     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5788            "Unexpected custom legalisation");
5789     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5790     break;
5791   case ISD::SHL:
5792   case ISD::SRA:
5793   case ISD::SRL:
5794     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5795            "Unexpected custom legalisation");
5796     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5797       Results.push_back(customLegalizeToWOp(N, DAG));
5798       break;
5799     }
5800 
5801     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5802     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5803     // shift amount.
5804     if (N->getOpcode() == ISD::SHL) {
5805       SDLoc DL(N);
5806       SDValue NewOp0 =
5807           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5808       SDValue NewOp1 =
5809           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5810       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5811       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5812                                    DAG.getValueType(MVT::i32));
5813       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5814     }
5815 
5816     break;
5817   case ISD::ROTL:
5818   case ISD::ROTR:
5819     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5820            "Unexpected custom legalisation");
5821     Results.push_back(customLegalizeToWOp(N, DAG));
5822     break;
5823   case ISD::CTTZ:
5824   case ISD::CTTZ_ZERO_UNDEF:
5825   case ISD::CTLZ:
5826   case ISD::CTLZ_ZERO_UNDEF: {
5827     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5828            "Unexpected custom legalisation");
5829 
5830     SDValue NewOp0 =
5831         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5832     bool IsCTZ =
5833         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5834     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5835     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5836     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5837     return;
5838   }
5839   case ISD::SDIV:
5840   case ISD::UDIV:
5841   case ISD::UREM: {
5842     MVT VT = N->getSimpleValueType(0);
5843     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5844            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5845            "Unexpected custom legalisation");
5846     // Don't promote division/remainder by constant since we should expand those
5847     // to multiply by magic constant.
5848     // FIXME: What if the expansion is disabled for minsize.
5849     if (N->getOperand(1).getOpcode() == ISD::Constant)
5850       return;
5851 
5852     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5853     // the upper 32 bits. For other types we need to sign or zero extend
5854     // based on the opcode.
5855     unsigned ExtOpc = ISD::ANY_EXTEND;
5856     if (VT != MVT::i32)
5857       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5858                                            : ISD::ZERO_EXTEND;
5859 
5860     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5861     break;
5862   }
5863   case ISD::UADDO:
5864   case ISD::USUBO: {
5865     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5866            "Unexpected custom legalisation");
5867     bool IsAdd = N->getOpcode() == ISD::UADDO;
5868     // Create an ADDW or SUBW.
5869     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5870     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5871     SDValue Res =
5872         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5873     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5874                       DAG.getValueType(MVT::i32));
5875 
5876     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5877     // Since the inputs are sign extended from i32, this is equivalent to
5878     // comparing the lower 32 bits.
5879     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5880     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5881                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5882 
5883     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5884     Results.push_back(Overflow);
5885     return;
5886   }
5887   case ISD::UADDSAT:
5888   case ISD::USUBSAT: {
5889     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5890            "Unexpected custom legalisation");
5891     if (Subtarget.hasStdExtZbb()) {
5892       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5893       // sign extend allows overflow of the lower 32 bits to be detected on
5894       // the promoted size.
5895       SDValue LHS =
5896           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5897       SDValue RHS =
5898           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5899       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5900       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5901       return;
5902     }
5903 
5904     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5905     // promotion for UADDO/USUBO.
5906     Results.push_back(expandAddSubSat(N, DAG));
5907     return;
5908   }
5909   case ISD::BITCAST: {
5910     EVT VT = N->getValueType(0);
5911     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5912     SDValue Op0 = N->getOperand(0);
5913     EVT Op0VT = Op0.getValueType();
5914     MVT XLenVT = Subtarget.getXLenVT();
5915     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5916       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5917       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5918     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5919                Subtarget.hasStdExtF()) {
5920       SDValue FPConv =
5921           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5922       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5923     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5924                isTypeLegal(Op0VT)) {
5925       // Custom-legalize bitcasts from fixed-length vector types to illegal
5926       // scalar types in order to improve codegen. Bitcast the vector to a
5927       // one-element vector type whose element type is the same as the result
5928       // type, and extract the first element.
5929       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
5930       if (isTypeLegal(BVT)) {
5931         SDValue BVec = DAG.getBitcast(BVT, Op0);
5932         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5933                                       DAG.getConstant(0, DL, XLenVT)));
5934       }
5935     }
5936     break;
5937   }
5938   case RISCVISD::GREV:
5939   case RISCVISD::GORC: {
5940     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5941            "Unexpected custom legalisation");
5942     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5943     // This is similar to customLegalizeToWOp, except that we pass the second
5944     // operand (a TargetConstant) straight through: it is already of type
5945     // XLenVT.
5946     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5947     SDValue NewOp0 =
5948         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5949     SDValue NewOp1 =
5950         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5951     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5952     // ReplaceNodeResults requires we maintain the same type for the return
5953     // value.
5954     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5955     break;
5956   }
5957   case RISCVISD::SHFL: {
5958     // There is no SHFLIW instruction, but we can just promote the operation.
5959     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5960            "Unexpected custom legalisation");
5961     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5962     SDValue NewOp0 =
5963         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5964     SDValue NewOp1 =
5965         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5966     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5967     // ReplaceNodeResults requires we maintain the same type for the return
5968     // value.
5969     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5970     break;
5971   }
5972   case ISD::BSWAP:
5973   case ISD::BITREVERSE: {
5974     MVT VT = N->getSimpleValueType(0);
5975     MVT XLenVT = Subtarget.getXLenVT();
5976     assert((VT == MVT::i8 || VT == MVT::i16 ||
5977             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5978            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5979     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5980     unsigned Imm = VT.getSizeInBits() - 1;
5981     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5982     if (N->getOpcode() == ISD::BSWAP)
5983       Imm &= ~0x7U;
5984     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5985     SDValue GREVI =
5986         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5987     // ReplaceNodeResults requires we maintain the same type for the return
5988     // value.
5989     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5990     break;
5991   }
5992   case ISD::FSHL:
5993   case ISD::FSHR: {
5994     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5995            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5996     SDValue NewOp0 =
5997         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5998     SDValue NewOp1 =
5999         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6000     SDValue NewOp2 =
6001         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6002     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6003     // Mask the shift amount to 5 bits.
6004     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6005                          DAG.getConstant(0x1f, DL, MVT::i64));
6006     unsigned Opc =
6007         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6008     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6009     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6010     break;
6011   }
6012   case ISD::EXTRACT_VECTOR_ELT: {
6013     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6014     // type is illegal (currently only vXi64 RV32).
6015     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6016     // transferred to the destination register. We issue two of these from the
6017     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6018     // first element.
6019     SDValue Vec = N->getOperand(0);
6020     SDValue Idx = N->getOperand(1);
6021 
6022     // The vector type hasn't been legalized yet so we can't issue target
6023     // specific nodes if it needs legalization.
6024     // FIXME: We would manually legalize if it's important.
6025     if (!isTypeLegal(Vec.getValueType()))
6026       return;
6027 
6028     MVT VecVT = Vec.getSimpleValueType();
6029 
6030     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6031            VecVT.getVectorElementType() == MVT::i64 &&
6032            "Unexpected EXTRACT_VECTOR_ELT legalization");
6033 
6034     // If this is a fixed vector, we need to convert it to a scalable vector.
6035     MVT ContainerVT = VecVT;
6036     if (VecVT.isFixedLengthVector()) {
6037       ContainerVT = getContainerForFixedLengthVector(VecVT);
6038       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6039     }
6040 
6041     MVT XLenVT = Subtarget.getXLenVT();
6042 
6043     // Use a VL of 1 to avoid processing more elements than we need.
6044     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6045     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6046     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6047 
6048     // Unless the index is known to be 0, we must slide the vector down to get
6049     // the desired element into index 0.
6050     if (!isNullConstant(Idx)) {
6051       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6052                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6053     }
6054 
6055     // Extract the lower XLEN bits of the correct vector element.
6056     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6057 
6058     // To extract the upper XLEN bits of the vector element, shift the first
6059     // element right by 32 bits and re-extract the lower XLEN bits.
6060     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6061                                      DAG.getConstant(32, DL, XLenVT), VL);
6062     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6063                                  ThirtyTwoV, Mask, VL);
6064 
6065     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6066 
6067     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6068     break;
6069   }
6070   case ISD::INTRINSIC_WO_CHAIN: {
6071     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6072     switch (IntNo) {
6073     default:
6074       llvm_unreachable(
6075           "Don't know how to custom type legalize this intrinsic!");
6076     case Intrinsic::riscv_orc_b: {
6077       // Lower to the GORCI encoding for orc.b with the operand extended.
6078       SDValue NewOp =
6079           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6080       // If Zbp is enabled, use GORCIW which will sign extend the result.
6081       unsigned Opc =
6082           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6083       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6084                                 DAG.getConstant(7, DL, MVT::i64));
6085       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6086       return;
6087     }
6088     case Intrinsic::riscv_grev:
6089     case Intrinsic::riscv_gorc: {
6090       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6091              "Unexpected custom legalisation");
6092       SDValue NewOp1 =
6093           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6094       SDValue NewOp2 =
6095           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6096       unsigned Opc =
6097           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6098       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6099       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6100       break;
6101     }
6102     case Intrinsic::riscv_shfl:
6103     case Intrinsic::riscv_unshfl: {
6104       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6105              "Unexpected custom legalisation");
6106       SDValue NewOp1 =
6107           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6108       SDValue NewOp2 =
6109           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6110       unsigned Opc =
6111           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6112       if (isa<ConstantSDNode>(N->getOperand(2))) {
6113         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6114                              DAG.getConstant(0xf, DL, MVT::i64));
6115         Opc =
6116             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6117       }
6118       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6119       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6120       break;
6121     }
6122     case Intrinsic::riscv_bcompress:
6123     case Intrinsic::riscv_bdecompress: {
6124       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6125              "Unexpected custom legalisation");
6126       SDValue NewOp1 =
6127           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6128       SDValue NewOp2 =
6129           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6130       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6131                          ? RISCVISD::BCOMPRESSW
6132                          : RISCVISD::BDECOMPRESSW;
6133       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6134       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6135       break;
6136     }
6137     case Intrinsic::riscv_vmv_x_s: {
6138       EVT VT = N->getValueType(0);
6139       MVT XLenVT = Subtarget.getXLenVT();
6140       if (VT.bitsLT(XLenVT)) {
6141         // Simple case just extract using vmv.x.s and truncate.
6142         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6143                                       Subtarget.getXLenVT(), N->getOperand(1));
6144         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6145         return;
6146       }
6147 
6148       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6149              "Unexpected custom legalization");
6150 
6151       // We need to do the move in two steps.
6152       SDValue Vec = N->getOperand(1);
6153       MVT VecVT = Vec.getSimpleValueType();
6154 
6155       // First extract the lower XLEN bits of the element.
6156       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6157 
6158       // To extract the upper XLEN bits of the vector element, shift the first
6159       // element right by 32 bits and re-extract the lower XLEN bits.
6160       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6161       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6162       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6163       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6164                                        DAG.getConstant(32, DL, XLenVT), VL);
6165       SDValue LShr32 =
6166           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6167       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6168 
6169       Results.push_back(
6170           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6171       break;
6172     }
6173     }
6174     break;
6175   }
6176   case ISD::VECREDUCE_ADD:
6177   case ISD::VECREDUCE_AND:
6178   case ISD::VECREDUCE_OR:
6179   case ISD::VECREDUCE_XOR:
6180   case ISD::VECREDUCE_SMAX:
6181   case ISD::VECREDUCE_UMAX:
6182   case ISD::VECREDUCE_SMIN:
6183   case ISD::VECREDUCE_UMIN:
6184     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6185       Results.push_back(V);
6186     break;
6187   case ISD::VP_REDUCE_ADD:
6188   case ISD::VP_REDUCE_AND:
6189   case ISD::VP_REDUCE_OR:
6190   case ISD::VP_REDUCE_XOR:
6191   case ISD::VP_REDUCE_SMAX:
6192   case ISD::VP_REDUCE_UMAX:
6193   case ISD::VP_REDUCE_SMIN:
6194   case ISD::VP_REDUCE_UMIN:
6195     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6196       Results.push_back(V);
6197     break;
6198   case ISD::FLT_ROUNDS_: {
6199     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6200     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6201     Results.push_back(Res.getValue(0));
6202     Results.push_back(Res.getValue(1));
6203     break;
6204   }
6205   }
6206 }
6207 
6208 // A structure to hold one of the bit-manipulation patterns below. Together, a
6209 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6210 //   (or (and (shl x, 1), 0xAAAAAAAA),
6211 //       (and (srl x, 1), 0x55555555))
6212 struct RISCVBitmanipPat {
6213   SDValue Op;
6214   unsigned ShAmt;
6215   bool IsSHL;
6216 
6217   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6218     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6219   }
6220 };
6221 
6222 // Matches patterns of the form
6223 //   (and (shl x, C2), (C1 << C2))
6224 //   (and (srl x, C2), C1)
6225 //   (shl (and x, C1), C2)
6226 //   (srl (and x, (C1 << C2)), C2)
6227 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6228 // The expected masks for each shift amount are specified in BitmanipMasks where
6229 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6230 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6231 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6232 // XLen is 64.
6233 static Optional<RISCVBitmanipPat>
6234 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6235   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6236          "Unexpected number of masks");
6237   Optional<uint64_t> Mask;
6238   // Optionally consume a mask around the shift operation.
6239   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6240     Mask = Op.getConstantOperandVal(1);
6241     Op = Op.getOperand(0);
6242   }
6243   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6244     return None;
6245   bool IsSHL = Op.getOpcode() == ISD::SHL;
6246 
6247   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6248     return None;
6249   uint64_t ShAmt = Op.getConstantOperandVal(1);
6250 
6251   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6252   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6253     return None;
6254   // If we don't have enough masks for 64 bit, then we must be trying to
6255   // match SHFL so we're only allowed to shift 1/4 of the width.
6256   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6257     return None;
6258 
6259   SDValue Src = Op.getOperand(0);
6260 
6261   // The expected mask is shifted left when the AND is found around SHL
6262   // patterns.
6263   //   ((x >> 1) & 0x55555555)
6264   //   ((x << 1) & 0xAAAAAAAA)
6265   bool SHLExpMask = IsSHL;
6266 
6267   if (!Mask) {
6268     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6269     // the mask is all ones: consume that now.
6270     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6271       Mask = Src.getConstantOperandVal(1);
6272       Src = Src.getOperand(0);
6273       // The expected mask is now in fact shifted left for SRL, so reverse the
6274       // decision.
6275       //   ((x & 0xAAAAAAAA) >> 1)
6276       //   ((x & 0x55555555) << 1)
6277       SHLExpMask = !SHLExpMask;
6278     } else {
6279       // Use a default shifted mask of all-ones if there's no AND, truncated
6280       // down to the expected width. This simplifies the logic later on.
6281       Mask = maskTrailingOnes<uint64_t>(Width);
6282       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6283     }
6284   }
6285 
6286   unsigned MaskIdx = Log2_32(ShAmt);
6287   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6288 
6289   if (SHLExpMask)
6290     ExpMask <<= ShAmt;
6291 
6292   if (Mask != ExpMask)
6293     return None;
6294 
6295   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6296 }
6297 
6298 // Matches any of the following bit-manipulation patterns:
6299 //   (and (shl x, 1), (0x55555555 << 1))
6300 //   (and (srl x, 1), 0x55555555)
6301 //   (shl (and x, 0x55555555), 1)
6302 //   (srl (and x, (0x55555555 << 1)), 1)
6303 // where the shift amount and mask may vary thus:
6304 //   [1]  = 0x55555555 / 0xAAAAAAAA
6305 //   [2]  = 0x33333333 / 0xCCCCCCCC
6306 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6307 //   [8]  = 0x00FF00FF / 0xFF00FF00
6308 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6309 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6310 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6311   // These are the unshifted masks which we use to match bit-manipulation
6312   // patterns. They may be shifted left in certain circumstances.
6313   static const uint64_t BitmanipMasks[] = {
6314       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6315       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6316 
6317   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6318 }
6319 
6320 // Match the following pattern as a GREVI(W) operation
6321 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6322 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6323                                const RISCVSubtarget &Subtarget) {
6324   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6325   EVT VT = Op.getValueType();
6326 
6327   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6328     auto LHS = matchGREVIPat(Op.getOperand(0));
6329     auto RHS = matchGREVIPat(Op.getOperand(1));
6330     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6331       SDLoc DL(Op);
6332       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6333                          DAG.getConstant(LHS->ShAmt, DL, VT));
6334     }
6335   }
6336   return SDValue();
6337 }
6338 
6339 // Matches any the following pattern as a GORCI(W) operation
6340 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6341 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6342 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6343 // Note that with the variant of 3.,
6344 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6345 // the inner pattern will first be matched as GREVI and then the outer
6346 // pattern will be matched to GORC via the first rule above.
6347 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6348 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6349                                const RISCVSubtarget &Subtarget) {
6350   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6351   EVT VT = Op.getValueType();
6352 
6353   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6354     SDLoc DL(Op);
6355     SDValue Op0 = Op.getOperand(0);
6356     SDValue Op1 = Op.getOperand(1);
6357 
6358     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6359       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6360           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6361           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6362         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6363       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6364       if ((Reverse.getOpcode() == ISD::ROTL ||
6365            Reverse.getOpcode() == ISD::ROTR) &&
6366           Reverse.getOperand(0) == X &&
6367           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6368         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6369         if (RotAmt == (VT.getSizeInBits() / 2))
6370           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6371                              DAG.getConstant(RotAmt, DL, VT));
6372       }
6373       return SDValue();
6374     };
6375 
6376     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6377     if (SDValue V = MatchOROfReverse(Op0, Op1))
6378       return V;
6379     if (SDValue V = MatchOROfReverse(Op1, Op0))
6380       return V;
6381 
6382     // OR is commutable so canonicalize its OR operand to the left
6383     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6384       std::swap(Op0, Op1);
6385     if (Op0.getOpcode() != ISD::OR)
6386       return SDValue();
6387     SDValue OrOp0 = Op0.getOperand(0);
6388     SDValue OrOp1 = Op0.getOperand(1);
6389     auto LHS = matchGREVIPat(OrOp0);
6390     // OR is commutable so swap the operands and try again: x might have been
6391     // on the left
6392     if (!LHS) {
6393       std::swap(OrOp0, OrOp1);
6394       LHS = matchGREVIPat(OrOp0);
6395     }
6396     auto RHS = matchGREVIPat(Op1);
6397     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6398       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6399                          DAG.getConstant(LHS->ShAmt, DL, VT));
6400     }
6401   }
6402   return SDValue();
6403 }
6404 
6405 // Matches any of the following bit-manipulation patterns:
6406 //   (and (shl x, 1), (0x22222222 << 1))
6407 //   (and (srl x, 1), 0x22222222)
6408 //   (shl (and x, 0x22222222), 1)
6409 //   (srl (and x, (0x22222222 << 1)), 1)
6410 // where the shift amount and mask may vary thus:
6411 //   [1]  = 0x22222222 / 0x44444444
6412 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6413 //   [4]  = 0x00F000F0 / 0x0F000F00
6414 //   [8]  = 0x0000FF00 / 0x00FF0000
6415 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6416 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6417   // These are the unshifted masks which we use to match bit-manipulation
6418   // patterns. They may be shifted left in certain circumstances.
6419   static const uint64_t BitmanipMasks[] = {
6420       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6421       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6422 
6423   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6424 }
6425 
6426 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6427 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6428                                const RISCVSubtarget &Subtarget) {
6429   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6430   EVT VT = Op.getValueType();
6431 
6432   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6433     return SDValue();
6434 
6435   SDValue Op0 = Op.getOperand(0);
6436   SDValue Op1 = Op.getOperand(1);
6437 
6438   // Or is commutable so canonicalize the second OR to the LHS.
6439   if (Op0.getOpcode() != ISD::OR)
6440     std::swap(Op0, Op1);
6441   if (Op0.getOpcode() != ISD::OR)
6442     return SDValue();
6443 
6444   // We found an inner OR, so our operands are the operands of the inner OR
6445   // and the other operand of the outer OR.
6446   SDValue A = Op0.getOperand(0);
6447   SDValue B = Op0.getOperand(1);
6448   SDValue C = Op1;
6449 
6450   auto Match1 = matchSHFLPat(A);
6451   auto Match2 = matchSHFLPat(B);
6452 
6453   // If neither matched, we failed.
6454   if (!Match1 && !Match2)
6455     return SDValue();
6456 
6457   // We had at least one match. if one failed, try the remaining C operand.
6458   if (!Match1) {
6459     std::swap(A, C);
6460     Match1 = matchSHFLPat(A);
6461     if (!Match1)
6462       return SDValue();
6463   } else if (!Match2) {
6464     std::swap(B, C);
6465     Match2 = matchSHFLPat(B);
6466     if (!Match2)
6467       return SDValue();
6468   }
6469   assert(Match1 && Match2);
6470 
6471   // Make sure our matches pair up.
6472   if (!Match1->formsPairWith(*Match2))
6473     return SDValue();
6474 
6475   // All the remains is to make sure C is an AND with the same input, that masks
6476   // out the bits that are being shuffled.
6477   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6478       C.getOperand(0) != Match1->Op)
6479     return SDValue();
6480 
6481   uint64_t Mask = C.getConstantOperandVal(1);
6482 
6483   static const uint64_t BitmanipMasks[] = {
6484       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6485       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6486   };
6487 
6488   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6489   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6490   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6491 
6492   if (Mask != ExpMask)
6493     return SDValue();
6494 
6495   SDLoc DL(Op);
6496   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6497                      DAG.getConstant(Match1->ShAmt, DL, VT));
6498 }
6499 
6500 // Optimize (add (shl x, c0), (shl y, c1)) ->
6501 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6502 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6503                                   const RISCVSubtarget &Subtarget) {
6504   // Perform this optimization only in the zba extension.
6505   if (!Subtarget.hasStdExtZba())
6506     return SDValue();
6507 
6508   // Skip for vector types and larger types.
6509   EVT VT = N->getValueType(0);
6510   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6511     return SDValue();
6512 
6513   // The two operand nodes must be SHL and have no other use.
6514   SDValue N0 = N->getOperand(0);
6515   SDValue N1 = N->getOperand(1);
6516   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6517       !N0->hasOneUse() || !N1->hasOneUse())
6518     return SDValue();
6519 
6520   // Check c0 and c1.
6521   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6522   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6523   if (!N0C || !N1C)
6524     return SDValue();
6525   int64_t C0 = N0C->getSExtValue();
6526   int64_t C1 = N1C->getSExtValue();
6527   if (C0 <= 0 || C1 <= 0)
6528     return SDValue();
6529 
6530   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6531   int64_t Bits = std::min(C0, C1);
6532   int64_t Diff = std::abs(C0 - C1);
6533   if (Diff != 1 && Diff != 2 && Diff != 3)
6534     return SDValue();
6535 
6536   // Build nodes.
6537   SDLoc DL(N);
6538   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6539   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6540   SDValue NA0 =
6541       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6542   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6543   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6544 }
6545 
6546 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6547 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6548 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6549 // not undo itself, but they are redundant.
6550 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6551   SDValue Src = N->getOperand(0);
6552 
6553   if (Src.getOpcode() != N->getOpcode())
6554     return SDValue();
6555 
6556   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6557       !isa<ConstantSDNode>(Src.getOperand(1)))
6558     return SDValue();
6559 
6560   unsigned ShAmt1 = N->getConstantOperandVal(1);
6561   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6562   Src = Src.getOperand(0);
6563 
6564   unsigned CombinedShAmt;
6565   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6566     CombinedShAmt = ShAmt1 | ShAmt2;
6567   else
6568     CombinedShAmt = ShAmt1 ^ ShAmt2;
6569 
6570   if (CombinedShAmt == 0)
6571     return Src;
6572 
6573   SDLoc DL(N);
6574   return DAG.getNode(
6575       N->getOpcode(), DL, N->getValueType(0), Src,
6576       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6577 }
6578 
6579 // Combine a constant select operand into its use:
6580 //
6581 // (and (select cond, -1, c), x)
6582 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6583 // (or  (select cond, 0, c), x)
6584 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6585 // (xor (select cond, 0, c), x)
6586 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6587 // (add (select cond, 0, c), x)
6588 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6589 // (sub x, (select cond, 0, c))
6590 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6591 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6592                                    SelectionDAG &DAG, bool AllOnes) {
6593   EVT VT = N->getValueType(0);
6594 
6595   // Skip vectors.
6596   if (VT.isVector())
6597     return SDValue();
6598 
6599   if ((Slct.getOpcode() != ISD::SELECT &&
6600        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6601       !Slct.hasOneUse())
6602     return SDValue();
6603 
6604   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6605     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6606   };
6607 
6608   bool SwapSelectOps;
6609   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6610   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6611   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6612   SDValue NonConstantVal;
6613   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6614     SwapSelectOps = false;
6615     NonConstantVal = FalseVal;
6616   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6617     SwapSelectOps = true;
6618     NonConstantVal = TrueVal;
6619   } else
6620     return SDValue();
6621 
6622   // Slct is now know to be the desired identity constant when CC is true.
6623   TrueVal = OtherOp;
6624   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6625   // Unless SwapSelectOps says the condition should be false.
6626   if (SwapSelectOps)
6627     std::swap(TrueVal, FalseVal);
6628 
6629   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6630     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6631                        {Slct.getOperand(0), Slct.getOperand(1),
6632                         Slct.getOperand(2), TrueVal, FalseVal});
6633 
6634   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6635                      {Slct.getOperand(0), TrueVal, FalseVal});
6636 }
6637 
6638 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6639 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6640                                               bool AllOnes) {
6641   SDValue N0 = N->getOperand(0);
6642   SDValue N1 = N->getOperand(1);
6643   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6644     return Result;
6645   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6646     return Result;
6647   return SDValue();
6648 }
6649 
6650 // Transform (add (mul x, c0), c1) ->
6651 //           (add (mul (add x, c1/c0), c0), c1%c0).
6652 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6653 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6654 // to an infinite loop in DAGCombine if transformed.
6655 // Or transform (add (mul x, c0), c1) ->
6656 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6657 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6658 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6659 // lead to an infinite loop in DAGCombine if transformed.
6660 // Or transform (add (mul x, c0), c1) ->
6661 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6662 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6663 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6664 // lead to an infinite loop in DAGCombine if transformed.
6665 // Or transform (add (mul x, c0), c1) ->
6666 //              (mul (add x, c1/c0), c0).
6667 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6668 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6669                                      const RISCVSubtarget &Subtarget) {
6670   // Skip for vector types and larger types.
6671   EVT VT = N->getValueType(0);
6672   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6673     return SDValue();
6674   // The first operand node must be a MUL and has no other use.
6675   SDValue N0 = N->getOperand(0);
6676   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6677     return SDValue();
6678   // Check if c0 and c1 match above conditions.
6679   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6680   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6681   if (!N0C || !N1C)
6682     return SDValue();
6683   int64_t C0 = N0C->getSExtValue();
6684   int64_t C1 = N1C->getSExtValue();
6685   int64_t CA, CB;
6686   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6687     return SDValue();
6688   // Search for proper CA (non-zero) and CB that both are simm12.
6689   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6690       !isInt<12>(C0 * (C1 / C0))) {
6691     CA = C1 / C0;
6692     CB = C1 % C0;
6693   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6694              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6695     CA = C1 / C0 + 1;
6696     CB = C1 % C0 - C0;
6697   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6698              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6699     CA = C1 / C0 - 1;
6700     CB = C1 % C0 + C0;
6701   } else
6702     return SDValue();
6703   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6704   SDLoc DL(N);
6705   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6706                              DAG.getConstant(CA, DL, VT));
6707   SDValue New1 =
6708       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6709   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6710 }
6711 
6712 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6713                                  const RISCVSubtarget &Subtarget) {
6714   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6715     return V;
6716   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6717     return V;
6718   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6719   //      (select lhs, rhs, cc, x, (add x, y))
6720   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6721 }
6722 
6723 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6724   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6725   //      (select lhs, rhs, cc, x, (sub x, y))
6726   SDValue N0 = N->getOperand(0);
6727   SDValue N1 = N->getOperand(1);
6728   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6729 }
6730 
6731 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6732   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6733   //      (select lhs, rhs, cc, x, (and x, y))
6734   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6735 }
6736 
6737 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6738                                 const RISCVSubtarget &Subtarget) {
6739   if (Subtarget.hasStdExtZbp()) {
6740     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6741       return GREV;
6742     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6743       return GORC;
6744     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6745       return SHFL;
6746   }
6747 
6748   // fold (or (select cond, 0, y), x) ->
6749   //      (select cond, x, (or x, y))
6750   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6751 }
6752 
6753 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6754   // fold (xor (select cond, 0, y), x) ->
6755   //      (select cond, x, (xor x, y))
6756   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6757 }
6758 
6759 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6760 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6761 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6762 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6763 // ADDW/SUBW/MULW.
6764 static SDValue performANY_EXTENDCombine(SDNode *N,
6765                                         TargetLowering::DAGCombinerInfo &DCI,
6766                                         const RISCVSubtarget &Subtarget) {
6767   if (!Subtarget.is64Bit())
6768     return SDValue();
6769 
6770   SelectionDAG &DAG = DCI.DAG;
6771 
6772   SDValue Src = N->getOperand(0);
6773   EVT VT = N->getValueType(0);
6774   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6775     return SDValue();
6776 
6777   // The opcode must be one that can implicitly sign_extend.
6778   // FIXME: Additional opcodes.
6779   switch (Src.getOpcode()) {
6780   default:
6781     return SDValue();
6782   case ISD::MUL:
6783     if (!Subtarget.hasStdExtM())
6784       return SDValue();
6785     LLVM_FALLTHROUGH;
6786   case ISD::ADD:
6787   case ISD::SUB:
6788     break;
6789   }
6790 
6791   // Only handle cases where the result is used by a CopyToReg. That likely
6792   // means the value is a liveout of the basic block. This helps prevent
6793   // infinite combine loops like PR51206.
6794   if (none_of(N->uses(),
6795               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6796     return SDValue();
6797 
6798   SmallVector<SDNode *, 4> SetCCs;
6799   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6800                             UE = Src.getNode()->use_end();
6801        UI != UE; ++UI) {
6802     SDNode *User = *UI;
6803     if (User == N)
6804       continue;
6805     if (UI.getUse().getResNo() != Src.getResNo())
6806       continue;
6807     // All i32 setccs are legalized by sign extending operands.
6808     if (User->getOpcode() == ISD::SETCC) {
6809       SetCCs.push_back(User);
6810       continue;
6811     }
6812     // We don't know if we can extend this user.
6813     break;
6814   }
6815 
6816   // If we don't have any SetCCs, this isn't worthwhile.
6817   if (SetCCs.empty())
6818     return SDValue();
6819 
6820   SDLoc DL(N);
6821   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6822   DCI.CombineTo(N, SExt);
6823 
6824   // Promote all the setccs.
6825   for (SDNode *SetCC : SetCCs) {
6826     SmallVector<SDValue, 4> Ops;
6827 
6828     for (unsigned j = 0; j != 2; ++j) {
6829       SDValue SOp = SetCC->getOperand(j);
6830       if (SOp == Src)
6831         Ops.push_back(SExt);
6832       else
6833         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6834     }
6835 
6836     Ops.push_back(SetCC->getOperand(2));
6837     DCI.CombineTo(SetCC,
6838                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6839   }
6840   return SDValue(N, 0);
6841 }
6842 
6843 // Try to form VWMUL or VWMULU.
6844 // FIXME: Support VWMULSU.
6845 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6846                                     SelectionDAG &DAG) {
6847   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6848   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6849   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6850   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6851     return SDValue();
6852 
6853   SDValue Mask = N->getOperand(2);
6854   SDValue VL = N->getOperand(3);
6855 
6856   // Make sure the mask and VL match.
6857   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6858     return SDValue();
6859 
6860   MVT VT = N->getSimpleValueType(0);
6861 
6862   // Determine the narrow size for a widening multiply.
6863   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6864   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6865                                   VT.getVectorElementCount());
6866 
6867   SDLoc DL(N);
6868 
6869   // See if the other operand is the same opcode.
6870   if (Op0.getOpcode() == Op1.getOpcode()) {
6871     if (!Op1.hasOneUse())
6872       return SDValue();
6873 
6874     // Make sure the mask and VL match.
6875     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6876       return SDValue();
6877 
6878     Op1 = Op1.getOperand(0);
6879   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6880     // The operand is a splat of a scalar.
6881 
6882     // The VL must be the same.
6883     if (Op1.getOperand(1) != VL)
6884       return SDValue();
6885 
6886     // Get the scalar value.
6887     Op1 = Op1.getOperand(0);
6888 
6889     // See if have enough sign bits or zero bits in the scalar to use a
6890     // widening multiply by splatting to smaller element size.
6891     unsigned EltBits = VT.getScalarSizeInBits();
6892     unsigned ScalarBits = Op1.getValueSizeInBits();
6893     // Make sure we're getting all element bits from the scalar register.
6894     // FIXME: Support implicit sign extension of vmv.v.x?
6895     if (ScalarBits < EltBits)
6896       return SDValue();
6897 
6898     if (IsSignExt) {
6899       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6900         return SDValue();
6901     } else {
6902       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6903       if (!DAG.MaskedValueIsZero(Op1, Mask))
6904         return SDValue();
6905     }
6906 
6907     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6908   } else
6909     return SDValue();
6910 
6911   Op0 = Op0.getOperand(0);
6912 
6913   // Re-introduce narrower extends if needed.
6914   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6915   if (Op0.getValueType() != NarrowVT)
6916     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6917   if (Op1.getValueType() != NarrowVT)
6918     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6919 
6920   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6921   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6922 }
6923 
6924 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6925                                                DAGCombinerInfo &DCI) const {
6926   SelectionDAG &DAG = DCI.DAG;
6927 
6928   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6929   // bits are demanded. N will be added to the Worklist if it was not deleted.
6930   // Caller should return SDValue(N, 0) if this returns true.
6931   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6932     SDValue Op = N->getOperand(OpNo);
6933     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6934     if (!SimplifyDemandedBits(Op, Mask, DCI))
6935       return false;
6936 
6937     if (N->getOpcode() != ISD::DELETED_NODE)
6938       DCI.AddToWorklist(N);
6939     return true;
6940   };
6941 
6942   switch (N->getOpcode()) {
6943   default:
6944     break;
6945   case RISCVISD::SplitF64: {
6946     SDValue Op0 = N->getOperand(0);
6947     // If the input to SplitF64 is just BuildPairF64 then the operation is
6948     // redundant. Instead, use BuildPairF64's operands directly.
6949     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6950       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6951 
6952     SDLoc DL(N);
6953 
6954     // It's cheaper to materialise two 32-bit integers than to load a double
6955     // from the constant pool and transfer it to integer registers through the
6956     // stack.
6957     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6958       APInt V = C->getValueAPF().bitcastToAPInt();
6959       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6960       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6961       return DCI.CombineTo(N, Lo, Hi);
6962     }
6963 
6964     // This is a target-specific version of a DAGCombine performed in
6965     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6966     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6967     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6968     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6969         !Op0.getNode()->hasOneUse())
6970       break;
6971     SDValue NewSplitF64 =
6972         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6973                     Op0.getOperand(0));
6974     SDValue Lo = NewSplitF64.getValue(0);
6975     SDValue Hi = NewSplitF64.getValue(1);
6976     APInt SignBit = APInt::getSignMask(32);
6977     if (Op0.getOpcode() == ISD::FNEG) {
6978       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6979                                   DAG.getConstant(SignBit, DL, MVT::i32));
6980       return DCI.CombineTo(N, Lo, NewHi);
6981     }
6982     assert(Op0.getOpcode() == ISD::FABS);
6983     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6984                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6985     return DCI.CombineTo(N, Lo, NewHi);
6986   }
6987   case RISCVISD::SLLW:
6988   case RISCVISD::SRAW:
6989   case RISCVISD::SRLW:
6990   case RISCVISD::ROLW:
6991   case RISCVISD::RORW: {
6992     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6993     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6994         SimplifyDemandedLowBitsHelper(1, 5))
6995       return SDValue(N, 0);
6996     break;
6997   }
6998   case RISCVISD::CLZW:
6999   case RISCVISD::CTZW: {
7000     // Only the lower 32 bits of the first operand are read
7001     if (SimplifyDemandedLowBitsHelper(0, 32))
7002       return SDValue(N, 0);
7003     break;
7004   }
7005   case RISCVISD::FSL:
7006   case RISCVISD::FSR: {
7007     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7008     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7009     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7010     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7011       return SDValue(N, 0);
7012     break;
7013   }
7014   case RISCVISD::FSLW:
7015   case RISCVISD::FSRW: {
7016     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7017     // read.
7018     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7019         SimplifyDemandedLowBitsHelper(1, 32) ||
7020         SimplifyDemandedLowBitsHelper(2, 6))
7021       return SDValue(N, 0);
7022     break;
7023   }
7024   case RISCVISD::GREV:
7025   case RISCVISD::GORC: {
7026     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7027     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7028     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7029     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7030       return SDValue(N, 0);
7031 
7032     return combineGREVI_GORCI(N, DCI.DAG);
7033   }
7034   case RISCVISD::GREVW:
7035   case RISCVISD::GORCW: {
7036     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7037     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7038         SimplifyDemandedLowBitsHelper(1, 5))
7039       return SDValue(N, 0);
7040 
7041     return combineGREVI_GORCI(N, DCI.DAG);
7042   }
7043   case RISCVISD::SHFL:
7044   case RISCVISD::UNSHFL: {
7045     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7046     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7047     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7048     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7049       return SDValue(N, 0);
7050 
7051     break;
7052   }
7053   case RISCVISD::SHFLW:
7054   case RISCVISD::UNSHFLW: {
7055     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7056     SDValue LHS = N->getOperand(0);
7057     SDValue RHS = N->getOperand(1);
7058     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7059     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7060     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7061         SimplifyDemandedLowBitsHelper(1, 4))
7062       return SDValue(N, 0);
7063 
7064     break;
7065   }
7066   case RISCVISD::BCOMPRESSW:
7067   case RISCVISD::BDECOMPRESSW: {
7068     // Only the lower 32 bits of LHS and RHS are read.
7069     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7070         SimplifyDemandedLowBitsHelper(1, 32))
7071       return SDValue(N, 0);
7072 
7073     break;
7074   }
7075   case RISCVISD::FMV_X_ANYEXTH:
7076   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7077     SDLoc DL(N);
7078     SDValue Op0 = N->getOperand(0);
7079     MVT VT = N->getSimpleValueType(0);
7080     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7081     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7082     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7083     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7084          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7085         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7086          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7087       assert(Op0.getOperand(0).getValueType() == VT &&
7088              "Unexpected value type!");
7089       return Op0.getOperand(0);
7090     }
7091 
7092     // This is a target-specific version of a DAGCombine performed in
7093     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7094     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7095     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7096     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7097         !Op0.getNode()->hasOneUse())
7098       break;
7099     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7100     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7101     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7102     if (Op0.getOpcode() == ISD::FNEG)
7103       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7104                          DAG.getConstant(SignBit, DL, VT));
7105 
7106     assert(Op0.getOpcode() == ISD::FABS);
7107     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7108                        DAG.getConstant(~SignBit, DL, VT));
7109   }
7110   case ISD::ADD:
7111     return performADDCombine(N, DAG, Subtarget);
7112   case ISD::SUB:
7113     return performSUBCombine(N, DAG);
7114   case ISD::AND:
7115     return performANDCombine(N, DAG);
7116   case ISD::OR:
7117     return performORCombine(N, DAG, Subtarget);
7118   case ISD::XOR:
7119     return performXORCombine(N, DAG);
7120   case ISD::ANY_EXTEND:
7121     return performANY_EXTENDCombine(N, DCI, Subtarget);
7122   case ISD::ZERO_EXTEND:
7123     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7124     // type legalization. This is safe because fp_to_uint produces poison if
7125     // it overflows.
7126     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
7127         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
7128         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
7129       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7130                          N->getOperand(0).getOperand(0));
7131     return SDValue();
7132   case RISCVISD::SELECT_CC: {
7133     // Transform
7134     SDValue LHS = N->getOperand(0);
7135     SDValue RHS = N->getOperand(1);
7136     SDValue TrueV = N->getOperand(3);
7137     SDValue FalseV = N->getOperand(4);
7138 
7139     // If the True and False values are the same, we don't need a select_cc.
7140     if (TrueV == FalseV)
7141       return TrueV;
7142 
7143     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7144     if (!ISD::isIntEqualitySetCC(CCVal))
7145       break;
7146 
7147     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7148     //      (select_cc X, Y, lt, trueV, falseV)
7149     // Sometimes the setcc is introduced after select_cc has been formed.
7150     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7151         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7152       // If we're looking for eq 0 instead of ne 0, we need to invert the
7153       // condition.
7154       bool Invert = CCVal == ISD::SETEQ;
7155       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7156       if (Invert)
7157         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7158 
7159       SDLoc DL(N);
7160       RHS = LHS.getOperand(1);
7161       LHS = LHS.getOperand(0);
7162       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7163 
7164       SDValue TargetCC = DAG.getCondCode(CCVal);
7165       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7166                          {LHS, RHS, TargetCC, TrueV, FalseV});
7167     }
7168 
7169     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7170     //      (select_cc X, Y, eq/ne, trueV, falseV)
7171     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7172       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7173                          {LHS.getOperand(0), LHS.getOperand(1),
7174                           N->getOperand(2), TrueV, FalseV});
7175     // (select_cc X, 1, setne, trueV, falseV) ->
7176     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7177     // This can occur when legalizing some floating point comparisons.
7178     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7179     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7180       SDLoc DL(N);
7181       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7182       SDValue TargetCC = DAG.getCondCode(CCVal);
7183       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7184       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7185                          {LHS, RHS, TargetCC, TrueV, FalseV});
7186     }
7187 
7188     break;
7189   }
7190   case RISCVISD::BR_CC: {
7191     SDValue LHS = N->getOperand(1);
7192     SDValue RHS = N->getOperand(2);
7193     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7194     if (!ISD::isIntEqualitySetCC(CCVal))
7195       break;
7196 
7197     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7198     //      (br_cc X, Y, lt, dest)
7199     // Sometimes the setcc is introduced after br_cc has been formed.
7200     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7201         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7202       // If we're looking for eq 0 instead of ne 0, we need to invert the
7203       // condition.
7204       bool Invert = CCVal == ISD::SETEQ;
7205       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7206       if (Invert)
7207         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7208 
7209       SDLoc DL(N);
7210       RHS = LHS.getOperand(1);
7211       LHS = LHS.getOperand(0);
7212       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7213 
7214       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7215                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7216                          N->getOperand(4));
7217     }
7218 
7219     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7220     //      (br_cc X, Y, eq/ne, trueV, falseV)
7221     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7222       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7223                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7224                          N->getOperand(3), N->getOperand(4));
7225 
7226     // (br_cc X, 1, setne, br_cc) ->
7227     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7228     // This can occur when legalizing some floating point comparisons.
7229     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7230     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7231       SDLoc DL(N);
7232       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7233       SDValue TargetCC = DAG.getCondCode(CCVal);
7234       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7235       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7236                          N->getOperand(0), LHS, RHS, TargetCC,
7237                          N->getOperand(4));
7238     }
7239     break;
7240   }
7241   case ISD::FCOPYSIGN: {
7242     EVT VT = N->getValueType(0);
7243     if (!VT.isVector())
7244       break;
7245     // There is a form of VFSGNJ which injects the negated sign of its second
7246     // operand. Try and bubble any FNEG up after the extend/round to produce
7247     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7248     // TRUNC=1.
7249     SDValue In2 = N->getOperand(1);
7250     // Avoid cases where the extend/round has multiple uses, as duplicating
7251     // those is typically more expensive than removing a fneg.
7252     if (!In2.hasOneUse())
7253       break;
7254     if (In2.getOpcode() != ISD::FP_EXTEND &&
7255         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7256       break;
7257     In2 = In2.getOperand(0);
7258     if (In2.getOpcode() != ISD::FNEG)
7259       break;
7260     SDLoc DL(N);
7261     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7262     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7263                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7264   }
7265   case ISD::MGATHER:
7266   case ISD::MSCATTER:
7267   case ISD::VP_GATHER:
7268   case ISD::VP_SCATTER: {
7269     if (!DCI.isBeforeLegalize())
7270       break;
7271     SDValue Index, ScaleOp;
7272     bool IsIndexScaled = false;
7273     bool IsIndexSigned = false;
7274     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7275       Index = VPGSN->getIndex();
7276       ScaleOp = VPGSN->getScale();
7277       IsIndexScaled = VPGSN->isIndexScaled();
7278       IsIndexSigned = VPGSN->isIndexSigned();
7279     } else {
7280       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7281       Index = MGSN->getIndex();
7282       ScaleOp = MGSN->getScale();
7283       IsIndexScaled = MGSN->isIndexScaled();
7284       IsIndexSigned = MGSN->isIndexSigned();
7285     }
7286     EVT IndexVT = Index.getValueType();
7287     MVT XLenVT = Subtarget.getXLenVT();
7288     // RISCV indexed loads only support the "unsigned unscaled" addressing
7289     // mode, so anything else must be manually legalized.
7290     bool NeedsIdxLegalization =
7291         IsIndexScaled ||
7292         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7293     if (!NeedsIdxLegalization)
7294       break;
7295 
7296     SDLoc DL(N);
7297 
7298     // Any index legalization should first promote to XLenVT, so we don't lose
7299     // bits when scaling. This may create an illegal index type so we let
7300     // LLVM's legalization take care of the splitting.
7301     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7302     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7303       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7304       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7305                           DL, IndexVT, Index);
7306     }
7307 
7308     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7309     if (IsIndexScaled && Scale != 1) {
7310       // Manually scale the indices by the element size.
7311       // TODO: Sanitize the scale operand here?
7312       // TODO: For VP nodes, should we use VP_SHL here?
7313       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7314       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7315       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7316     }
7317 
7318     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7319     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7320       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7321                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7322                               VPGN->getScale(), VPGN->getMask(),
7323                               VPGN->getVectorLength()},
7324                              VPGN->getMemOperand(), NewIndexTy);
7325     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7326       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7327                               {VPSN->getChain(), VPSN->getValue(),
7328                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7329                                VPSN->getMask(), VPSN->getVectorLength()},
7330                               VPSN->getMemOperand(), NewIndexTy);
7331     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7332       return DAG.getMaskedGather(
7333           N->getVTList(), MGN->getMemoryVT(), DL,
7334           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7335            MGN->getBasePtr(), Index, MGN->getScale()},
7336           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7337     const auto *MSN = cast<MaskedScatterSDNode>(N);
7338     return DAG.getMaskedScatter(
7339         N->getVTList(), MSN->getMemoryVT(), DL,
7340         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7341          Index, MSN->getScale()},
7342         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7343   }
7344   case RISCVISD::SRA_VL:
7345   case RISCVISD::SRL_VL:
7346   case RISCVISD::SHL_VL: {
7347     SDValue ShAmt = N->getOperand(1);
7348     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7349       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7350       SDLoc DL(N);
7351       SDValue VL = N->getOperand(3);
7352       EVT VT = N->getValueType(0);
7353       ShAmt =
7354           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7355       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7356                          N->getOperand(2), N->getOperand(3));
7357     }
7358     break;
7359   }
7360   case ISD::SRA:
7361   case ISD::SRL:
7362   case ISD::SHL: {
7363     SDValue ShAmt = N->getOperand(1);
7364     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7365       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7366       SDLoc DL(N);
7367       EVT VT = N->getValueType(0);
7368       ShAmt =
7369           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7370       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7371     }
7372     break;
7373   }
7374   case RISCVISD::MUL_VL: {
7375     SDValue Op0 = N->getOperand(0);
7376     SDValue Op1 = N->getOperand(1);
7377     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7378       return V;
7379     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7380       return V;
7381     return SDValue();
7382   }
7383   case ISD::STORE: {
7384     auto *Store = cast<StoreSDNode>(N);
7385     SDValue Val = Store->getValue();
7386     // Combine store of vmv.x.s to vse with VL of 1.
7387     // FIXME: Support FP.
7388     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7389       SDValue Src = Val.getOperand(0);
7390       EVT VecVT = Src.getValueType();
7391       EVT MemVT = Store->getMemoryVT();
7392       // The memory VT and the element type must match.
7393       if (VecVT.getVectorElementType() == MemVT) {
7394         SDLoc DL(N);
7395         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7396         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7397                               DAG.getConstant(1, DL, MaskVT),
7398                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7399                               Store->getPointerInfo(),
7400                               Store->getOriginalAlign(),
7401                               Store->getMemOperand()->getFlags());
7402       }
7403     }
7404 
7405     break;
7406   }
7407   }
7408 
7409   return SDValue();
7410 }
7411 
7412 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7413     const SDNode *N, CombineLevel Level) const {
7414   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7415   // materialised in fewer instructions than `(OP _, c1)`:
7416   //
7417   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7418   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7419   SDValue N0 = N->getOperand(0);
7420   EVT Ty = N0.getValueType();
7421   if (Ty.isScalarInteger() &&
7422       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7423     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7424     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7425     if (C1 && C2) {
7426       const APInt &C1Int = C1->getAPIntValue();
7427       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7428 
7429       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7430       // and the combine should happen, to potentially allow further combines
7431       // later.
7432       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7433           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7434         return true;
7435 
7436       // We can materialise `c1` in an add immediate, so it's "free", and the
7437       // combine should be prevented.
7438       if (C1Int.getMinSignedBits() <= 64 &&
7439           isLegalAddImmediate(C1Int.getSExtValue()))
7440         return false;
7441 
7442       // Neither constant will fit into an immediate, so find materialisation
7443       // costs.
7444       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7445                                               Subtarget.getFeatureBits(),
7446                                               /*CompressionCost*/true);
7447       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7448           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7449           /*CompressionCost*/true);
7450 
7451       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7452       // combine should be prevented.
7453       if (C1Cost < ShiftedC1Cost)
7454         return false;
7455     }
7456   }
7457   return true;
7458 }
7459 
7460 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7461     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7462     TargetLoweringOpt &TLO) const {
7463   // Delay this optimization as late as possible.
7464   if (!TLO.LegalOps)
7465     return false;
7466 
7467   EVT VT = Op.getValueType();
7468   if (VT.isVector())
7469     return false;
7470 
7471   // Only handle AND for now.
7472   if (Op.getOpcode() != ISD::AND)
7473     return false;
7474 
7475   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7476   if (!C)
7477     return false;
7478 
7479   const APInt &Mask = C->getAPIntValue();
7480 
7481   // Clear all non-demanded bits initially.
7482   APInt ShrunkMask = Mask & DemandedBits;
7483 
7484   // Try to make a smaller immediate by setting undemanded bits.
7485 
7486   APInt ExpandedMask = Mask | ~DemandedBits;
7487 
7488   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7489     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7490   };
7491   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7492     if (NewMask == Mask)
7493       return true;
7494     SDLoc DL(Op);
7495     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7496     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7497     return TLO.CombineTo(Op, NewOp);
7498   };
7499 
7500   // If the shrunk mask fits in sign extended 12 bits, let the target
7501   // independent code apply it.
7502   if (ShrunkMask.isSignedIntN(12))
7503     return false;
7504 
7505   // Preserve (and X, 0xffff) when zext.h is supported.
7506   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7507     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7508     if (IsLegalMask(NewMask))
7509       return UseMask(NewMask);
7510   }
7511 
7512   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7513   if (VT == MVT::i64) {
7514     APInt NewMask = APInt(64, 0xffffffff);
7515     if (IsLegalMask(NewMask))
7516       return UseMask(NewMask);
7517   }
7518 
7519   // For the remaining optimizations, we need to be able to make a negative
7520   // number through a combination of mask and undemanded bits.
7521   if (!ExpandedMask.isNegative())
7522     return false;
7523 
7524   // What is the fewest number of bits we need to represent the negative number.
7525   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7526 
7527   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7528   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7529   APInt NewMask = ShrunkMask;
7530   if (MinSignedBits <= 12)
7531     NewMask.setBitsFrom(11);
7532   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7533     NewMask.setBitsFrom(31);
7534   else
7535     return false;
7536 
7537   // Check that our new mask is a subset of the demanded mask.
7538   assert(IsLegalMask(NewMask));
7539   return UseMask(NewMask);
7540 }
7541 
7542 static void computeGREV(APInt &Src, unsigned ShAmt) {
7543   ShAmt &= Src.getBitWidth() - 1;
7544   uint64_t x = Src.getZExtValue();
7545   if (ShAmt & 1)
7546     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7547   if (ShAmt & 2)
7548     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7549   if (ShAmt & 4)
7550     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7551   if (ShAmt & 8)
7552     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7553   if (ShAmt & 16)
7554     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7555   if (ShAmt & 32)
7556     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7557   Src = x;
7558 }
7559 
7560 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7561                                                         KnownBits &Known,
7562                                                         const APInt &DemandedElts,
7563                                                         const SelectionDAG &DAG,
7564                                                         unsigned Depth) const {
7565   unsigned BitWidth = Known.getBitWidth();
7566   unsigned Opc = Op.getOpcode();
7567   assert((Opc >= ISD::BUILTIN_OP_END ||
7568           Opc == ISD::INTRINSIC_WO_CHAIN ||
7569           Opc == ISD::INTRINSIC_W_CHAIN ||
7570           Opc == ISD::INTRINSIC_VOID) &&
7571          "Should use MaskedValueIsZero if you don't know whether Op"
7572          " is a target node!");
7573 
7574   Known.resetAll();
7575   switch (Opc) {
7576   default: break;
7577   case RISCVISD::SELECT_CC: {
7578     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7579     // If we don't know any bits, early out.
7580     if (Known.isUnknown())
7581       break;
7582     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7583 
7584     // Only known if known in both the LHS and RHS.
7585     Known = KnownBits::commonBits(Known, Known2);
7586     break;
7587   }
7588   case RISCVISD::REMUW: {
7589     KnownBits Known2;
7590     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7591     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7592     // We only care about the lower 32 bits.
7593     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7594     // Restore the original width by sign extending.
7595     Known = Known.sext(BitWidth);
7596     break;
7597   }
7598   case RISCVISD::DIVUW: {
7599     KnownBits Known2;
7600     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7601     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7602     // We only care about the lower 32 bits.
7603     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7604     // Restore the original width by sign extending.
7605     Known = Known.sext(BitWidth);
7606     break;
7607   }
7608   case RISCVISD::CTZW: {
7609     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7610     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7611     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7612     Known.Zero.setBitsFrom(LowBits);
7613     break;
7614   }
7615   case RISCVISD::CLZW: {
7616     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7617     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7618     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7619     Known.Zero.setBitsFrom(LowBits);
7620     break;
7621   }
7622   case RISCVISD::GREV:
7623   case RISCVISD::GREVW: {
7624     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7625       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7626       if (Opc == RISCVISD::GREVW)
7627         Known = Known.trunc(32);
7628       unsigned ShAmt = C->getZExtValue();
7629       computeGREV(Known.Zero, ShAmt);
7630       computeGREV(Known.One, ShAmt);
7631       if (Opc == RISCVISD::GREVW)
7632         Known = Known.sext(BitWidth);
7633     }
7634     break;
7635   }
7636   case RISCVISD::READ_VLENB:
7637     // We assume VLENB is at least 16 bytes.
7638     Known.Zero.setLowBits(4);
7639     // We assume VLENB is no more than 65536 / 8 bytes.
7640     Known.Zero.setBitsFrom(14);
7641     break;
7642   case ISD::INTRINSIC_W_CHAIN: {
7643     unsigned IntNo = Op.getConstantOperandVal(1);
7644     switch (IntNo) {
7645     default:
7646       // We can't do anything for most intrinsics.
7647       break;
7648     case Intrinsic::riscv_vsetvli:
7649     case Intrinsic::riscv_vsetvlimax:
7650       // Assume that VL output is positive and would fit in an int32_t.
7651       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7652       if (BitWidth >= 32)
7653         Known.Zero.setBitsFrom(31);
7654       break;
7655     }
7656     break;
7657   }
7658   }
7659 }
7660 
7661 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7662     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7663     unsigned Depth) const {
7664   switch (Op.getOpcode()) {
7665   default:
7666     break;
7667   case RISCVISD::SELECT_CC: {
7668     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7669     if (Tmp == 1) return 1;  // Early out.
7670     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7671     return std::min(Tmp, Tmp2);
7672   }
7673   case RISCVISD::SLLW:
7674   case RISCVISD::SRAW:
7675   case RISCVISD::SRLW:
7676   case RISCVISD::DIVW:
7677   case RISCVISD::DIVUW:
7678   case RISCVISD::REMUW:
7679   case RISCVISD::ROLW:
7680   case RISCVISD::RORW:
7681   case RISCVISD::GREVW:
7682   case RISCVISD::GORCW:
7683   case RISCVISD::FSLW:
7684   case RISCVISD::FSRW:
7685   case RISCVISD::SHFLW:
7686   case RISCVISD::UNSHFLW:
7687   case RISCVISD::BCOMPRESSW:
7688   case RISCVISD::BDECOMPRESSW:
7689   case RISCVISD::FCVT_W_RTZ_RV64:
7690   case RISCVISD::FCVT_WU_RTZ_RV64:
7691     // TODO: As the result is sign-extended, this is conservatively correct. A
7692     // more precise answer could be calculated for SRAW depending on known
7693     // bits in the shift amount.
7694     return 33;
7695   case RISCVISD::SHFL:
7696   case RISCVISD::UNSHFL: {
7697     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7698     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7699     // will stay within the upper 32 bits. If there were more than 32 sign bits
7700     // before there will be at least 33 sign bits after.
7701     if (Op.getValueType() == MVT::i64 &&
7702         isa<ConstantSDNode>(Op.getOperand(1)) &&
7703         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7704       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7705       if (Tmp > 32)
7706         return 33;
7707     }
7708     break;
7709   }
7710   case RISCVISD::VMV_X_S:
7711     // The number of sign bits of the scalar result is computed by obtaining the
7712     // element type of the input vector operand, subtracting its width from the
7713     // XLEN, and then adding one (sign bit within the element type). If the
7714     // element type is wider than XLen, the least-significant XLEN bits are
7715     // taken.
7716     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7717       return 1;
7718     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7719   }
7720 
7721   return 1;
7722 }
7723 
7724 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7725                                                   MachineBasicBlock *BB) {
7726   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7727 
7728   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7729   // Should the count have wrapped while it was being read, we need to try
7730   // again.
7731   // ...
7732   // read:
7733   // rdcycleh x3 # load high word of cycle
7734   // rdcycle  x2 # load low word of cycle
7735   // rdcycleh x4 # load high word of cycle
7736   // bne x3, x4, read # check if high word reads match, otherwise try again
7737   // ...
7738 
7739   MachineFunction &MF = *BB->getParent();
7740   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7741   MachineFunction::iterator It = ++BB->getIterator();
7742 
7743   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7744   MF.insert(It, LoopMBB);
7745 
7746   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7747   MF.insert(It, DoneMBB);
7748 
7749   // Transfer the remainder of BB and its successor edges to DoneMBB.
7750   DoneMBB->splice(DoneMBB->begin(), BB,
7751                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7752   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7753 
7754   BB->addSuccessor(LoopMBB);
7755 
7756   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7757   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7758   Register LoReg = MI.getOperand(0).getReg();
7759   Register HiReg = MI.getOperand(1).getReg();
7760   DebugLoc DL = MI.getDebugLoc();
7761 
7762   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7763   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7764       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7765       .addReg(RISCV::X0);
7766   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7767       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7768       .addReg(RISCV::X0);
7769   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7770       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7771       .addReg(RISCV::X0);
7772 
7773   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7774       .addReg(HiReg)
7775       .addReg(ReadAgainReg)
7776       .addMBB(LoopMBB);
7777 
7778   LoopMBB->addSuccessor(LoopMBB);
7779   LoopMBB->addSuccessor(DoneMBB);
7780 
7781   MI.eraseFromParent();
7782 
7783   return DoneMBB;
7784 }
7785 
7786 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7787                                              MachineBasicBlock *BB) {
7788   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7789 
7790   MachineFunction &MF = *BB->getParent();
7791   DebugLoc DL = MI.getDebugLoc();
7792   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7793   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7794   Register LoReg = MI.getOperand(0).getReg();
7795   Register HiReg = MI.getOperand(1).getReg();
7796   Register SrcReg = MI.getOperand(2).getReg();
7797   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7798   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7799 
7800   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7801                           RI);
7802   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7803   MachineMemOperand *MMOLo =
7804       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7805   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7806       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7807   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7808       .addFrameIndex(FI)
7809       .addImm(0)
7810       .addMemOperand(MMOLo);
7811   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7812       .addFrameIndex(FI)
7813       .addImm(4)
7814       .addMemOperand(MMOHi);
7815   MI.eraseFromParent(); // The pseudo instruction is gone now.
7816   return BB;
7817 }
7818 
7819 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7820                                                  MachineBasicBlock *BB) {
7821   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7822          "Unexpected instruction");
7823 
7824   MachineFunction &MF = *BB->getParent();
7825   DebugLoc DL = MI.getDebugLoc();
7826   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7827   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7828   Register DstReg = MI.getOperand(0).getReg();
7829   Register LoReg = MI.getOperand(1).getReg();
7830   Register HiReg = MI.getOperand(2).getReg();
7831   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7832   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7833 
7834   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7835   MachineMemOperand *MMOLo =
7836       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7837   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7838       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7839   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7840       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7841       .addFrameIndex(FI)
7842       .addImm(0)
7843       .addMemOperand(MMOLo);
7844   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7845       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7846       .addFrameIndex(FI)
7847       .addImm(4)
7848       .addMemOperand(MMOHi);
7849   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7850   MI.eraseFromParent(); // The pseudo instruction is gone now.
7851   return BB;
7852 }
7853 
7854 static bool isSelectPseudo(MachineInstr &MI) {
7855   switch (MI.getOpcode()) {
7856   default:
7857     return false;
7858   case RISCV::Select_GPR_Using_CC_GPR:
7859   case RISCV::Select_FPR16_Using_CC_GPR:
7860   case RISCV::Select_FPR32_Using_CC_GPR:
7861   case RISCV::Select_FPR64_Using_CC_GPR:
7862     return true;
7863   }
7864 }
7865 
7866 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7867                                            MachineBasicBlock *BB,
7868                                            const RISCVSubtarget &Subtarget) {
7869   // To "insert" Select_* instructions, we actually have to insert the triangle
7870   // control-flow pattern.  The incoming instructions know the destination vreg
7871   // to set, the condition code register to branch on, the true/false values to
7872   // select between, and the condcode to use to select the appropriate branch.
7873   //
7874   // We produce the following control flow:
7875   //     HeadMBB
7876   //     |  \
7877   //     |  IfFalseMBB
7878   //     | /
7879   //    TailMBB
7880   //
7881   // When we find a sequence of selects we attempt to optimize their emission
7882   // by sharing the control flow. Currently we only handle cases where we have
7883   // multiple selects with the exact same condition (same LHS, RHS and CC).
7884   // The selects may be interleaved with other instructions if the other
7885   // instructions meet some requirements we deem safe:
7886   // - They are debug instructions. Otherwise,
7887   // - They do not have side-effects, do not access memory and their inputs do
7888   //   not depend on the results of the select pseudo-instructions.
7889   // The TrueV/FalseV operands of the selects cannot depend on the result of
7890   // previous selects in the sequence.
7891   // These conditions could be further relaxed. See the X86 target for a
7892   // related approach and more information.
7893   Register LHS = MI.getOperand(1).getReg();
7894   Register RHS = MI.getOperand(2).getReg();
7895   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7896 
7897   SmallVector<MachineInstr *, 4> SelectDebugValues;
7898   SmallSet<Register, 4> SelectDests;
7899   SelectDests.insert(MI.getOperand(0).getReg());
7900 
7901   MachineInstr *LastSelectPseudo = &MI;
7902 
7903   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7904        SequenceMBBI != E; ++SequenceMBBI) {
7905     if (SequenceMBBI->isDebugInstr())
7906       continue;
7907     else if (isSelectPseudo(*SequenceMBBI)) {
7908       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7909           SequenceMBBI->getOperand(2).getReg() != RHS ||
7910           SequenceMBBI->getOperand(3).getImm() != CC ||
7911           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7912           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7913         break;
7914       LastSelectPseudo = &*SequenceMBBI;
7915       SequenceMBBI->collectDebugValues(SelectDebugValues);
7916       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7917     } else {
7918       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7919           SequenceMBBI->mayLoadOrStore())
7920         break;
7921       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7922             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7923           }))
7924         break;
7925     }
7926   }
7927 
7928   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7929   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7930   DebugLoc DL = MI.getDebugLoc();
7931   MachineFunction::iterator I = ++BB->getIterator();
7932 
7933   MachineBasicBlock *HeadMBB = BB;
7934   MachineFunction *F = BB->getParent();
7935   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7936   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7937 
7938   F->insert(I, IfFalseMBB);
7939   F->insert(I, TailMBB);
7940 
7941   // Transfer debug instructions associated with the selects to TailMBB.
7942   for (MachineInstr *DebugInstr : SelectDebugValues) {
7943     TailMBB->push_back(DebugInstr->removeFromParent());
7944   }
7945 
7946   // Move all instructions after the sequence to TailMBB.
7947   TailMBB->splice(TailMBB->end(), HeadMBB,
7948                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7949   // Update machine-CFG edges by transferring all successors of the current
7950   // block to the new block which will contain the Phi nodes for the selects.
7951   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7952   // Set the successors for HeadMBB.
7953   HeadMBB->addSuccessor(IfFalseMBB);
7954   HeadMBB->addSuccessor(TailMBB);
7955 
7956   // Insert appropriate branch.
7957   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7958     .addReg(LHS)
7959     .addReg(RHS)
7960     .addMBB(TailMBB);
7961 
7962   // IfFalseMBB just falls through to TailMBB.
7963   IfFalseMBB->addSuccessor(TailMBB);
7964 
7965   // Create PHIs for all of the select pseudo-instructions.
7966   auto SelectMBBI = MI.getIterator();
7967   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7968   auto InsertionPoint = TailMBB->begin();
7969   while (SelectMBBI != SelectEnd) {
7970     auto Next = std::next(SelectMBBI);
7971     if (isSelectPseudo(*SelectMBBI)) {
7972       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7973       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7974               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7975           .addReg(SelectMBBI->getOperand(4).getReg())
7976           .addMBB(HeadMBB)
7977           .addReg(SelectMBBI->getOperand(5).getReg())
7978           .addMBB(IfFalseMBB);
7979       SelectMBBI->eraseFromParent();
7980     }
7981     SelectMBBI = Next;
7982   }
7983 
7984   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7985   return TailMBB;
7986 }
7987 
7988 MachineBasicBlock *
7989 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7990                                                  MachineBasicBlock *BB) const {
7991   switch (MI.getOpcode()) {
7992   default:
7993     llvm_unreachable("Unexpected instr type to insert");
7994   case RISCV::ReadCycleWide:
7995     assert(!Subtarget.is64Bit() &&
7996            "ReadCycleWrite is only to be used on riscv32");
7997     return emitReadCycleWidePseudo(MI, BB);
7998   case RISCV::Select_GPR_Using_CC_GPR:
7999   case RISCV::Select_FPR16_Using_CC_GPR:
8000   case RISCV::Select_FPR32_Using_CC_GPR:
8001   case RISCV::Select_FPR64_Using_CC_GPR:
8002     return emitSelectPseudo(MI, BB, Subtarget);
8003   case RISCV::BuildPairF64Pseudo:
8004     return emitBuildPairF64Pseudo(MI, BB);
8005   case RISCV::SplitF64Pseudo:
8006     return emitSplitF64Pseudo(MI, BB);
8007   }
8008 }
8009 
8010 // Calling Convention Implementation.
8011 // The expectations for frontend ABI lowering vary from target to target.
8012 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8013 // details, but this is a longer term goal. For now, we simply try to keep the
8014 // role of the frontend as simple and well-defined as possible. The rules can
8015 // be summarised as:
8016 // * Never split up large scalar arguments. We handle them here.
8017 // * If a hardfloat calling convention is being used, and the struct may be
8018 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8019 // available, then pass as two separate arguments. If either the GPRs or FPRs
8020 // are exhausted, then pass according to the rule below.
8021 // * If a struct could never be passed in registers or directly in a stack
8022 // slot (as it is larger than 2*XLEN and the floating point rules don't
8023 // apply), then pass it using a pointer with the byval attribute.
8024 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8025 // word-sized array or a 2*XLEN scalar (depending on alignment).
8026 // * The frontend can determine whether a struct is returned by reference or
8027 // not based on its size and fields. If it will be returned by reference, the
8028 // frontend must modify the prototype so a pointer with the sret annotation is
8029 // passed as the first argument. This is not necessary for large scalar
8030 // returns.
8031 // * Struct return values and varargs should be coerced to structs containing
8032 // register-size fields in the same situations they would be for fixed
8033 // arguments.
8034 
8035 static const MCPhysReg ArgGPRs[] = {
8036   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8037   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8038 };
8039 static const MCPhysReg ArgFPR16s[] = {
8040   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8041   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8042 };
8043 static const MCPhysReg ArgFPR32s[] = {
8044   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8045   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8046 };
8047 static const MCPhysReg ArgFPR64s[] = {
8048   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8049   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8050 };
8051 // This is an interim calling convention and it may be changed in the future.
8052 static const MCPhysReg ArgVRs[] = {
8053     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8054     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8055     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8056 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8057                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8058                                      RISCV::V20M2, RISCV::V22M2};
8059 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8060                                      RISCV::V20M4};
8061 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8062 
8063 // Pass a 2*XLEN argument that has been split into two XLEN values through
8064 // registers or the stack as necessary.
8065 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8066                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8067                                 MVT ValVT2, MVT LocVT2,
8068                                 ISD::ArgFlagsTy ArgFlags2) {
8069   unsigned XLenInBytes = XLen / 8;
8070   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8071     // At least one half can be passed via register.
8072     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8073                                      VA1.getLocVT(), CCValAssign::Full));
8074   } else {
8075     // Both halves must be passed on the stack, with proper alignment.
8076     Align StackAlign =
8077         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8078     State.addLoc(
8079         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8080                             State.AllocateStack(XLenInBytes, StackAlign),
8081                             VA1.getLocVT(), CCValAssign::Full));
8082     State.addLoc(CCValAssign::getMem(
8083         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8084         LocVT2, CCValAssign::Full));
8085     return false;
8086   }
8087 
8088   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8089     // The second half can also be passed via register.
8090     State.addLoc(
8091         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8092   } else {
8093     // The second half is passed via the stack, without additional alignment.
8094     State.addLoc(CCValAssign::getMem(
8095         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8096         LocVT2, CCValAssign::Full));
8097   }
8098 
8099   return false;
8100 }
8101 
8102 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8103                                Optional<unsigned> FirstMaskArgument,
8104                                CCState &State, const RISCVTargetLowering &TLI) {
8105   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8106   if (RC == &RISCV::VRRegClass) {
8107     // Assign the first mask argument to V0.
8108     // This is an interim calling convention and it may be changed in the
8109     // future.
8110     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8111       return State.AllocateReg(RISCV::V0);
8112     return State.AllocateReg(ArgVRs);
8113   }
8114   if (RC == &RISCV::VRM2RegClass)
8115     return State.AllocateReg(ArgVRM2s);
8116   if (RC == &RISCV::VRM4RegClass)
8117     return State.AllocateReg(ArgVRM4s);
8118   if (RC == &RISCV::VRM8RegClass)
8119     return State.AllocateReg(ArgVRM8s);
8120   llvm_unreachable("Unhandled register class for ValueType");
8121 }
8122 
8123 // Implements the RISC-V calling convention. Returns true upon failure.
8124 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8125                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8126                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8127                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8128                      Optional<unsigned> FirstMaskArgument) {
8129   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8130   assert(XLen == 32 || XLen == 64);
8131   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8132 
8133   // Any return value split in to more than two values can't be returned
8134   // directly. Vectors are returned via the available vector registers.
8135   if (!LocVT.isVector() && IsRet && ValNo > 1)
8136     return true;
8137 
8138   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8139   // variadic argument, or if no F16/F32 argument registers are available.
8140   bool UseGPRForF16_F32 = true;
8141   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8142   // variadic argument, or if no F64 argument registers are available.
8143   bool UseGPRForF64 = true;
8144 
8145   switch (ABI) {
8146   default:
8147     llvm_unreachable("Unexpected ABI");
8148   case RISCVABI::ABI_ILP32:
8149   case RISCVABI::ABI_LP64:
8150     break;
8151   case RISCVABI::ABI_ILP32F:
8152   case RISCVABI::ABI_LP64F:
8153     UseGPRForF16_F32 = !IsFixed;
8154     break;
8155   case RISCVABI::ABI_ILP32D:
8156   case RISCVABI::ABI_LP64D:
8157     UseGPRForF16_F32 = !IsFixed;
8158     UseGPRForF64 = !IsFixed;
8159     break;
8160   }
8161 
8162   // FPR16, FPR32, and FPR64 alias each other.
8163   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8164     UseGPRForF16_F32 = true;
8165     UseGPRForF64 = true;
8166   }
8167 
8168   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8169   // similar local variables rather than directly checking against the target
8170   // ABI.
8171 
8172   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8173     LocVT = XLenVT;
8174     LocInfo = CCValAssign::BCvt;
8175   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8176     LocVT = MVT::i64;
8177     LocInfo = CCValAssign::BCvt;
8178   }
8179 
8180   // If this is a variadic argument, the RISC-V calling convention requires
8181   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8182   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8183   // be used regardless of whether the original argument was split during
8184   // legalisation or not. The argument will not be passed by registers if the
8185   // original type is larger than 2*XLEN, so the register alignment rule does
8186   // not apply.
8187   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8188   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8189       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8190     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8191     // Skip 'odd' register if necessary.
8192     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8193       State.AllocateReg(ArgGPRs);
8194   }
8195 
8196   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8197   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8198       State.getPendingArgFlags();
8199 
8200   assert(PendingLocs.size() == PendingArgFlags.size() &&
8201          "PendingLocs and PendingArgFlags out of sync");
8202 
8203   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8204   // registers are exhausted.
8205   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8206     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8207            "Can't lower f64 if it is split");
8208     // Depending on available argument GPRS, f64 may be passed in a pair of
8209     // GPRs, split between a GPR and the stack, or passed completely on the
8210     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8211     // cases.
8212     Register Reg = State.AllocateReg(ArgGPRs);
8213     LocVT = MVT::i32;
8214     if (!Reg) {
8215       unsigned StackOffset = State.AllocateStack(8, Align(8));
8216       State.addLoc(
8217           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8218       return false;
8219     }
8220     if (!State.AllocateReg(ArgGPRs))
8221       State.AllocateStack(4, Align(4));
8222     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8223     return false;
8224   }
8225 
8226   // Fixed-length vectors are located in the corresponding scalable-vector
8227   // container types.
8228   if (ValVT.isFixedLengthVector())
8229     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8230 
8231   // Split arguments might be passed indirectly, so keep track of the pending
8232   // values. Split vectors are passed via a mix of registers and indirectly, so
8233   // treat them as we would any other argument.
8234   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8235     LocVT = XLenVT;
8236     LocInfo = CCValAssign::Indirect;
8237     PendingLocs.push_back(
8238         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8239     PendingArgFlags.push_back(ArgFlags);
8240     if (!ArgFlags.isSplitEnd()) {
8241       return false;
8242     }
8243   }
8244 
8245   // If the split argument only had two elements, it should be passed directly
8246   // in registers or on the stack.
8247   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8248       PendingLocs.size() <= 2) {
8249     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8250     // Apply the normal calling convention rules to the first half of the
8251     // split argument.
8252     CCValAssign VA = PendingLocs[0];
8253     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8254     PendingLocs.clear();
8255     PendingArgFlags.clear();
8256     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8257                                ArgFlags);
8258   }
8259 
8260   // Allocate to a register if possible, or else a stack slot.
8261   Register Reg;
8262   unsigned StoreSizeBytes = XLen / 8;
8263   Align StackAlign = Align(XLen / 8);
8264 
8265   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8266     Reg = State.AllocateReg(ArgFPR16s);
8267   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8268     Reg = State.AllocateReg(ArgFPR32s);
8269   else if (ValVT == MVT::f64 && !UseGPRForF64)
8270     Reg = State.AllocateReg(ArgFPR64s);
8271   else if (ValVT.isVector()) {
8272     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8273     if (!Reg) {
8274       // For return values, the vector must be passed fully via registers or
8275       // via the stack.
8276       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8277       // but we're using all of them.
8278       if (IsRet)
8279         return true;
8280       // Try using a GPR to pass the address
8281       if ((Reg = State.AllocateReg(ArgGPRs))) {
8282         LocVT = XLenVT;
8283         LocInfo = CCValAssign::Indirect;
8284       } else if (ValVT.isScalableVector()) {
8285         report_fatal_error("Unable to pass scalable vector types on the stack");
8286       } else {
8287         // Pass fixed-length vectors on the stack.
8288         LocVT = ValVT;
8289         StoreSizeBytes = ValVT.getStoreSize();
8290         // Align vectors to their element sizes, being careful for vXi1
8291         // vectors.
8292         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8293       }
8294     }
8295   } else {
8296     Reg = State.AllocateReg(ArgGPRs);
8297   }
8298 
8299   unsigned StackOffset =
8300       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8301 
8302   // If we reach this point and PendingLocs is non-empty, we must be at the
8303   // end of a split argument that must be passed indirectly.
8304   if (!PendingLocs.empty()) {
8305     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8306     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8307 
8308     for (auto &It : PendingLocs) {
8309       if (Reg)
8310         It.convertToReg(Reg);
8311       else
8312         It.convertToMem(StackOffset);
8313       State.addLoc(It);
8314     }
8315     PendingLocs.clear();
8316     PendingArgFlags.clear();
8317     return false;
8318   }
8319 
8320   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8321           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8322          "Expected an XLenVT or vector types at this stage");
8323 
8324   if (Reg) {
8325     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8326     return false;
8327   }
8328 
8329   // When a floating-point value is passed on the stack, no bit-conversion is
8330   // needed.
8331   if (ValVT.isFloatingPoint()) {
8332     LocVT = ValVT;
8333     LocInfo = CCValAssign::Full;
8334   }
8335   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8336   return false;
8337 }
8338 
8339 template <typename ArgTy>
8340 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8341   for (const auto &ArgIdx : enumerate(Args)) {
8342     MVT ArgVT = ArgIdx.value().VT;
8343     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8344       return ArgIdx.index();
8345   }
8346   return None;
8347 }
8348 
8349 void RISCVTargetLowering::analyzeInputArgs(
8350     MachineFunction &MF, CCState &CCInfo,
8351     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8352     RISCVCCAssignFn Fn) const {
8353   unsigned NumArgs = Ins.size();
8354   FunctionType *FType = MF.getFunction().getFunctionType();
8355 
8356   Optional<unsigned> FirstMaskArgument;
8357   if (Subtarget.hasVInstructions())
8358     FirstMaskArgument = preAssignMask(Ins);
8359 
8360   for (unsigned i = 0; i != NumArgs; ++i) {
8361     MVT ArgVT = Ins[i].VT;
8362     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8363 
8364     Type *ArgTy = nullptr;
8365     if (IsRet)
8366       ArgTy = FType->getReturnType();
8367     else if (Ins[i].isOrigArg())
8368       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8369 
8370     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8371     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8372            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8373            FirstMaskArgument)) {
8374       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8375                         << EVT(ArgVT).getEVTString() << '\n');
8376       llvm_unreachable(nullptr);
8377     }
8378   }
8379 }
8380 
8381 void RISCVTargetLowering::analyzeOutputArgs(
8382     MachineFunction &MF, CCState &CCInfo,
8383     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8384     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8385   unsigned NumArgs = Outs.size();
8386 
8387   Optional<unsigned> FirstMaskArgument;
8388   if (Subtarget.hasVInstructions())
8389     FirstMaskArgument = preAssignMask(Outs);
8390 
8391   for (unsigned i = 0; i != NumArgs; i++) {
8392     MVT ArgVT = Outs[i].VT;
8393     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8394     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8395 
8396     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8397     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8398            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8399            FirstMaskArgument)) {
8400       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8401                         << EVT(ArgVT).getEVTString() << "\n");
8402       llvm_unreachable(nullptr);
8403     }
8404   }
8405 }
8406 
8407 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8408 // values.
8409 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8410                                    const CCValAssign &VA, const SDLoc &DL,
8411                                    const RISCVSubtarget &Subtarget) {
8412   switch (VA.getLocInfo()) {
8413   default:
8414     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8415   case CCValAssign::Full:
8416     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8417       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8418     break;
8419   case CCValAssign::BCvt:
8420     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8421       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8422     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8423       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8424     else
8425       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8426     break;
8427   }
8428   return Val;
8429 }
8430 
8431 // The caller is responsible for loading the full value if the argument is
8432 // passed with CCValAssign::Indirect.
8433 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8434                                 const CCValAssign &VA, const SDLoc &DL,
8435                                 const RISCVTargetLowering &TLI) {
8436   MachineFunction &MF = DAG.getMachineFunction();
8437   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8438   EVT LocVT = VA.getLocVT();
8439   SDValue Val;
8440   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8441   Register VReg = RegInfo.createVirtualRegister(RC);
8442   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8443   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8444 
8445   if (VA.getLocInfo() == CCValAssign::Indirect)
8446     return Val;
8447 
8448   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8449 }
8450 
8451 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8452                                    const CCValAssign &VA, const SDLoc &DL,
8453                                    const RISCVSubtarget &Subtarget) {
8454   EVT LocVT = VA.getLocVT();
8455 
8456   switch (VA.getLocInfo()) {
8457   default:
8458     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8459   case CCValAssign::Full:
8460     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8461       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8462     break;
8463   case CCValAssign::BCvt:
8464     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8465       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8466     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8467       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8468     else
8469       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8470     break;
8471   }
8472   return Val;
8473 }
8474 
8475 // The caller is responsible for loading the full value if the argument is
8476 // passed with CCValAssign::Indirect.
8477 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8478                                 const CCValAssign &VA, const SDLoc &DL) {
8479   MachineFunction &MF = DAG.getMachineFunction();
8480   MachineFrameInfo &MFI = MF.getFrameInfo();
8481   EVT LocVT = VA.getLocVT();
8482   EVT ValVT = VA.getValVT();
8483   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8484   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8485                                  /*Immutable=*/true);
8486   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8487   SDValue Val;
8488 
8489   ISD::LoadExtType ExtType;
8490   switch (VA.getLocInfo()) {
8491   default:
8492     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8493   case CCValAssign::Full:
8494   case CCValAssign::Indirect:
8495   case CCValAssign::BCvt:
8496     ExtType = ISD::NON_EXTLOAD;
8497     break;
8498   }
8499   Val = DAG.getExtLoad(
8500       ExtType, DL, LocVT, Chain, FIN,
8501       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8502   return Val;
8503 }
8504 
8505 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8506                                        const CCValAssign &VA, const SDLoc &DL) {
8507   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8508          "Unexpected VA");
8509   MachineFunction &MF = DAG.getMachineFunction();
8510   MachineFrameInfo &MFI = MF.getFrameInfo();
8511   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8512 
8513   if (VA.isMemLoc()) {
8514     // f64 is passed on the stack.
8515     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8516     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8517     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8518                        MachinePointerInfo::getFixedStack(MF, FI));
8519   }
8520 
8521   assert(VA.isRegLoc() && "Expected register VA assignment");
8522 
8523   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8524   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8525   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8526   SDValue Hi;
8527   if (VA.getLocReg() == RISCV::X17) {
8528     // Second half of f64 is passed on the stack.
8529     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8530     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8531     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8532                      MachinePointerInfo::getFixedStack(MF, FI));
8533   } else {
8534     // Second half of f64 is passed in another GPR.
8535     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8536     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8537     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8538   }
8539   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8540 }
8541 
8542 // FastCC has less than 1% performance improvement for some particular
8543 // benchmark. But theoretically, it may has benenfit for some cases.
8544 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8545                             unsigned ValNo, MVT ValVT, MVT LocVT,
8546                             CCValAssign::LocInfo LocInfo,
8547                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8548                             bool IsFixed, bool IsRet, Type *OrigTy,
8549                             const RISCVTargetLowering &TLI,
8550                             Optional<unsigned> FirstMaskArgument) {
8551 
8552   // X5 and X6 might be used for save-restore libcall.
8553   static const MCPhysReg GPRList[] = {
8554       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8555       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8556       RISCV::X29, RISCV::X30, RISCV::X31};
8557 
8558   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8559     if (unsigned Reg = State.AllocateReg(GPRList)) {
8560       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8561       return false;
8562     }
8563   }
8564 
8565   if (LocVT == MVT::f16) {
8566     static const MCPhysReg FPR16List[] = {
8567         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8568         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8569         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8570         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8571     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8572       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8573       return false;
8574     }
8575   }
8576 
8577   if (LocVT == MVT::f32) {
8578     static const MCPhysReg FPR32List[] = {
8579         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8580         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8581         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8582         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8583     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8584       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8585       return false;
8586     }
8587   }
8588 
8589   if (LocVT == MVT::f64) {
8590     static const MCPhysReg FPR64List[] = {
8591         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8592         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8593         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8594         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8595     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8596       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8597       return false;
8598     }
8599   }
8600 
8601   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8602     unsigned Offset4 = State.AllocateStack(4, Align(4));
8603     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8604     return false;
8605   }
8606 
8607   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8608     unsigned Offset5 = State.AllocateStack(8, Align(8));
8609     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8610     return false;
8611   }
8612 
8613   if (LocVT.isVector()) {
8614     if (unsigned Reg =
8615             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8616       // Fixed-length vectors are located in the corresponding scalable-vector
8617       // container types.
8618       if (ValVT.isFixedLengthVector())
8619         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8620       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8621     } else {
8622       // Try and pass the address via a "fast" GPR.
8623       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8624         LocInfo = CCValAssign::Indirect;
8625         LocVT = TLI.getSubtarget().getXLenVT();
8626         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8627       } else if (ValVT.isFixedLengthVector()) {
8628         auto StackAlign =
8629             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8630         unsigned StackOffset =
8631             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8632         State.addLoc(
8633             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8634       } else {
8635         // Can't pass scalable vectors on the stack.
8636         return true;
8637       }
8638     }
8639 
8640     return false;
8641   }
8642 
8643   return true; // CC didn't match.
8644 }
8645 
8646 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8647                          CCValAssign::LocInfo LocInfo,
8648                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8649 
8650   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8651     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8652     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8653     static const MCPhysReg GPRList[] = {
8654         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8655         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8656     if (unsigned Reg = State.AllocateReg(GPRList)) {
8657       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8658       return false;
8659     }
8660   }
8661 
8662   if (LocVT == MVT::f32) {
8663     // Pass in STG registers: F1, ..., F6
8664     //                        fs0 ... fs5
8665     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8666                                           RISCV::F18_F, RISCV::F19_F,
8667                                           RISCV::F20_F, RISCV::F21_F};
8668     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8669       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8670       return false;
8671     }
8672   }
8673 
8674   if (LocVT == MVT::f64) {
8675     // Pass in STG registers: D1, ..., D6
8676     //                        fs6 ... fs11
8677     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8678                                           RISCV::F24_D, RISCV::F25_D,
8679                                           RISCV::F26_D, RISCV::F27_D};
8680     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8681       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8682       return false;
8683     }
8684   }
8685 
8686   report_fatal_error("No registers left in GHC calling convention");
8687   return true;
8688 }
8689 
8690 // Transform physical registers into virtual registers.
8691 SDValue RISCVTargetLowering::LowerFormalArguments(
8692     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8693     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8694     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8695 
8696   MachineFunction &MF = DAG.getMachineFunction();
8697 
8698   switch (CallConv) {
8699   default:
8700     report_fatal_error("Unsupported calling convention");
8701   case CallingConv::C:
8702   case CallingConv::Fast:
8703     break;
8704   case CallingConv::GHC:
8705     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8706         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8707       report_fatal_error(
8708         "GHC calling convention requires the F and D instruction set extensions");
8709   }
8710 
8711   const Function &Func = MF.getFunction();
8712   if (Func.hasFnAttribute("interrupt")) {
8713     if (!Func.arg_empty())
8714       report_fatal_error(
8715         "Functions with the interrupt attribute cannot have arguments!");
8716 
8717     StringRef Kind =
8718       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8719 
8720     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8721       report_fatal_error(
8722         "Function interrupt attribute argument not supported!");
8723   }
8724 
8725   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8726   MVT XLenVT = Subtarget.getXLenVT();
8727   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8728   // Used with vargs to acumulate store chains.
8729   std::vector<SDValue> OutChains;
8730 
8731   // Assign locations to all of the incoming arguments.
8732   SmallVector<CCValAssign, 16> ArgLocs;
8733   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8734 
8735   if (CallConv == CallingConv::GHC)
8736     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8737   else
8738     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8739                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8740                                                    : CC_RISCV);
8741 
8742   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8743     CCValAssign &VA = ArgLocs[i];
8744     SDValue ArgValue;
8745     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8746     // case.
8747     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8748       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8749     else if (VA.isRegLoc())
8750       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8751     else
8752       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8753 
8754     if (VA.getLocInfo() == CCValAssign::Indirect) {
8755       // If the original argument was split and passed by reference (e.g. i128
8756       // on RV32), we need to load all parts of it here (using the same
8757       // address). Vectors may be partly split to registers and partly to the
8758       // stack, in which case the base address is partly offset and subsequent
8759       // stores are relative to that.
8760       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8761                                    MachinePointerInfo()));
8762       unsigned ArgIndex = Ins[i].OrigArgIndex;
8763       unsigned ArgPartOffset = Ins[i].PartOffset;
8764       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8765       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8766         CCValAssign &PartVA = ArgLocs[i + 1];
8767         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8768         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8769         if (PartVA.getValVT().isScalableVector())
8770           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8771         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8772         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8773                                      MachinePointerInfo()));
8774         ++i;
8775       }
8776       continue;
8777     }
8778     InVals.push_back(ArgValue);
8779   }
8780 
8781   if (IsVarArg) {
8782     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8783     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8784     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8785     MachineFrameInfo &MFI = MF.getFrameInfo();
8786     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8787     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8788 
8789     // Offset of the first variable argument from stack pointer, and size of
8790     // the vararg save area. For now, the varargs save area is either zero or
8791     // large enough to hold a0-a7.
8792     int VaArgOffset, VarArgsSaveSize;
8793 
8794     // If all registers are allocated, then all varargs must be passed on the
8795     // stack and we don't need to save any argregs.
8796     if (ArgRegs.size() == Idx) {
8797       VaArgOffset = CCInfo.getNextStackOffset();
8798       VarArgsSaveSize = 0;
8799     } else {
8800       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8801       VaArgOffset = -VarArgsSaveSize;
8802     }
8803 
8804     // Record the frame index of the first variable argument
8805     // which is a value necessary to VASTART.
8806     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8807     RVFI->setVarArgsFrameIndex(FI);
8808 
8809     // If saving an odd number of registers then create an extra stack slot to
8810     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8811     // offsets to even-numbered registered remain 2*XLEN-aligned.
8812     if (Idx % 2) {
8813       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8814       VarArgsSaveSize += XLenInBytes;
8815     }
8816 
8817     // Copy the integer registers that may have been used for passing varargs
8818     // to the vararg save area.
8819     for (unsigned I = Idx; I < ArgRegs.size();
8820          ++I, VaArgOffset += XLenInBytes) {
8821       const Register Reg = RegInfo.createVirtualRegister(RC);
8822       RegInfo.addLiveIn(ArgRegs[I], Reg);
8823       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8824       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8825       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8826       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8827                                    MachinePointerInfo::getFixedStack(MF, FI));
8828       cast<StoreSDNode>(Store.getNode())
8829           ->getMemOperand()
8830           ->setValue((Value *)nullptr);
8831       OutChains.push_back(Store);
8832     }
8833     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8834   }
8835 
8836   // All stores are grouped in one node to allow the matching between
8837   // the size of Ins and InVals. This only happens for vararg functions.
8838   if (!OutChains.empty()) {
8839     OutChains.push_back(Chain);
8840     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8841   }
8842 
8843   return Chain;
8844 }
8845 
8846 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8847 /// for tail call optimization.
8848 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8849 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8850     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8851     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8852 
8853   auto &Callee = CLI.Callee;
8854   auto CalleeCC = CLI.CallConv;
8855   auto &Outs = CLI.Outs;
8856   auto &Caller = MF.getFunction();
8857   auto CallerCC = Caller.getCallingConv();
8858 
8859   // Exception-handling functions need a special set of instructions to
8860   // indicate a return to the hardware. Tail-calling another function would
8861   // probably break this.
8862   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8863   // should be expanded as new function attributes are introduced.
8864   if (Caller.hasFnAttribute("interrupt"))
8865     return false;
8866 
8867   // Do not tail call opt if the stack is used to pass parameters.
8868   if (CCInfo.getNextStackOffset() != 0)
8869     return false;
8870 
8871   // Do not tail call opt if any parameters need to be passed indirectly.
8872   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8873   // passed indirectly. So the address of the value will be passed in a
8874   // register, or if not available, then the address is put on the stack. In
8875   // order to pass indirectly, space on the stack often needs to be allocated
8876   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8877   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8878   // are passed CCValAssign::Indirect.
8879   for (auto &VA : ArgLocs)
8880     if (VA.getLocInfo() == CCValAssign::Indirect)
8881       return false;
8882 
8883   // Do not tail call opt if either caller or callee uses struct return
8884   // semantics.
8885   auto IsCallerStructRet = Caller.hasStructRetAttr();
8886   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8887   if (IsCallerStructRet || IsCalleeStructRet)
8888     return false;
8889 
8890   // Externally-defined functions with weak linkage should not be
8891   // tail-called. The behaviour of branch instructions in this situation (as
8892   // used for tail calls) is implementation-defined, so we cannot rely on the
8893   // linker replacing the tail call with a return.
8894   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8895     const GlobalValue *GV = G->getGlobal();
8896     if (GV->hasExternalWeakLinkage())
8897       return false;
8898   }
8899 
8900   // The callee has to preserve all registers the caller needs to preserve.
8901   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8902   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8903   if (CalleeCC != CallerCC) {
8904     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8905     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8906       return false;
8907   }
8908 
8909   // Byval parameters hand the function a pointer directly into the stack area
8910   // we want to reuse during a tail call. Working around this *is* possible
8911   // but less efficient and uglier in LowerCall.
8912   for (auto &Arg : Outs)
8913     if (Arg.Flags.isByVal())
8914       return false;
8915 
8916   return true;
8917 }
8918 
8919 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8920   return DAG.getDataLayout().getPrefTypeAlign(
8921       VT.getTypeForEVT(*DAG.getContext()));
8922 }
8923 
8924 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8925 // and output parameter nodes.
8926 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8927                                        SmallVectorImpl<SDValue> &InVals) const {
8928   SelectionDAG &DAG = CLI.DAG;
8929   SDLoc &DL = CLI.DL;
8930   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8931   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8932   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8933   SDValue Chain = CLI.Chain;
8934   SDValue Callee = CLI.Callee;
8935   bool &IsTailCall = CLI.IsTailCall;
8936   CallingConv::ID CallConv = CLI.CallConv;
8937   bool IsVarArg = CLI.IsVarArg;
8938   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8939   MVT XLenVT = Subtarget.getXLenVT();
8940 
8941   MachineFunction &MF = DAG.getMachineFunction();
8942 
8943   // Analyze the operands of the call, assigning locations to each operand.
8944   SmallVector<CCValAssign, 16> ArgLocs;
8945   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8946 
8947   if (CallConv == CallingConv::GHC)
8948     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8949   else
8950     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8951                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8952                                                     : CC_RISCV);
8953 
8954   // Check if it's really possible to do a tail call.
8955   if (IsTailCall)
8956     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8957 
8958   if (IsTailCall)
8959     ++NumTailCalls;
8960   else if (CLI.CB && CLI.CB->isMustTailCall())
8961     report_fatal_error("failed to perform tail call elimination on a call "
8962                        "site marked musttail");
8963 
8964   // Get a count of how many bytes are to be pushed on the stack.
8965   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8966 
8967   // Create local copies for byval args
8968   SmallVector<SDValue, 8> ByValArgs;
8969   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8970     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8971     if (!Flags.isByVal())
8972       continue;
8973 
8974     SDValue Arg = OutVals[i];
8975     unsigned Size = Flags.getByValSize();
8976     Align Alignment = Flags.getNonZeroByValAlign();
8977 
8978     int FI =
8979         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8980     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8981     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8982 
8983     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8984                           /*IsVolatile=*/false,
8985                           /*AlwaysInline=*/false, IsTailCall,
8986                           MachinePointerInfo(), MachinePointerInfo());
8987     ByValArgs.push_back(FIPtr);
8988   }
8989 
8990   if (!IsTailCall)
8991     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8992 
8993   // Copy argument values to their designated locations.
8994   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8995   SmallVector<SDValue, 8> MemOpChains;
8996   SDValue StackPtr;
8997   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8998     CCValAssign &VA = ArgLocs[i];
8999     SDValue ArgValue = OutVals[i];
9000     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9001 
9002     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9003     bool IsF64OnRV32DSoftABI =
9004         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9005     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9006       SDValue SplitF64 = DAG.getNode(
9007           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9008       SDValue Lo = SplitF64.getValue(0);
9009       SDValue Hi = SplitF64.getValue(1);
9010 
9011       Register RegLo = VA.getLocReg();
9012       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9013 
9014       if (RegLo == RISCV::X17) {
9015         // Second half of f64 is passed on the stack.
9016         // Work out the address of the stack slot.
9017         if (!StackPtr.getNode())
9018           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9019         // Emit the store.
9020         MemOpChains.push_back(
9021             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9022       } else {
9023         // Second half of f64 is passed in another GPR.
9024         assert(RegLo < RISCV::X31 && "Invalid register pair");
9025         Register RegHigh = RegLo + 1;
9026         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9027       }
9028       continue;
9029     }
9030 
9031     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9032     // as any other MemLoc.
9033 
9034     // Promote the value if needed.
9035     // For now, only handle fully promoted and indirect arguments.
9036     if (VA.getLocInfo() == CCValAssign::Indirect) {
9037       // Store the argument in a stack slot and pass its address.
9038       Align StackAlign =
9039           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9040                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9041       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9042       // If the original argument was split (e.g. i128), we need
9043       // to store the required parts of it here (and pass just one address).
9044       // Vectors may be partly split to registers and partly to the stack, in
9045       // which case the base address is partly offset and subsequent stores are
9046       // relative to that.
9047       unsigned ArgIndex = Outs[i].OrigArgIndex;
9048       unsigned ArgPartOffset = Outs[i].PartOffset;
9049       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9050       // Calculate the total size to store. We don't have access to what we're
9051       // actually storing other than performing the loop and collecting the
9052       // info.
9053       SmallVector<std::pair<SDValue, SDValue>> Parts;
9054       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9055         SDValue PartValue = OutVals[i + 1];
9056         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9057         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9058         EVT PartVT = PartValue.getValueType();
9059         if (PartVT.isScalableVector())
9060           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9061         StoredSize += PartVT.getStoreSize();
9062         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9063         Parts.push_back(std::make_pair(PartValue, Offset));
9064         ++i;
9065       }
9066       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9067       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9068       MemOpChains.push_back(
9069           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9070                        MachinePointerInfo::getFixedStack(MF, FI)));
9071       for (const auto &Part : Parts) {
9072         SDValue PartValue = Part.first;
9073         SDValue PartOffset = Part.second;
9074         SDValue Address =
9075             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9076         MemOpChains.push_back(
9077             DAG.getStore(Chain, DL, PartValue, Address,
9078                          MachinePointerInfo::getFixedStack(MF, FI)));
9079       }
9080       ArgValue = SpillSlot;
9081     } else {
9082       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9083     }
9084 
9085     // Use local copy if it is a byval arg.
9086     if (Flags.isByVal())
9087       ArgValue = ByValArgs[j++];
9088 
9089     if (VA.isRegLoc()) {
9090       // Queue up the argument copies and emit them at the end.
9091       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9092     } else {
9093       assert(VA.isMemLoc() && "Argument not register or memory");
9094       assert(!IsTailCall && "Tail call not allowed if stack is used "
9095                             "for passing parameters");
9096 
9097       // Work out the address of the stack slot.
9098       if (!StackPtr.getNode())
9099         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9100       SDValue Address =
9101           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9102                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9103 
9104       // Emit the store.
9105       MemOpChains.push_back(
9106           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9107     }
9108   }
9109 
9110   // Join the stores, which are independent of one another.
9111   if (!MemOpChains.empty())
9112     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9113 
9114   SDValue Glue;
9115 
9116   // Build a sequence of copy-to-reg nodes, chained and glued together.
9117   for (auto &Reg : RegsToPass) {
9118     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9119     Glue = Chain.getValue(1);
9120   }
9121 
9122   // Validate that none of the argument registers have been marked as
9123   // reserved, if so report an error. Do the same for the return address if this
9124   // is not a tailcall.
9125   validateCCReservedRegs(RegsToPass, MF);
9126   if (!IsTailCall &&
9127       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9128     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9129         MF.getFunction(),
9130         "Return address register required, but has been reserved."});
9131 
9132   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9133   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9134   // split it and then direct call can be matched by PseudoCALL.
9135   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9136     const GlobalValue *GV = S->getGlobal();
9137 
9138     unsigned OpFlags = RISCVII::MO_CALL;
9139     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9140       OpFlags = RISCVII::MO_PLT;
9141 
9142     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9143   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9144     unsigned OpFlags = RISCVII::MO_CALL;
9145 
9146     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9147                                                  nullptr))
9148       OpFlags = RISCVII::MO_PLT;
9149 
9150     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9151   }
9152 
9153   // The first call operand is the chain and the second is the target address.
9154   SmallVector<SDValue, 8> Ops;
9155   Ops.push_back(Chain);
9156   Ops.push_back(Callee);
9157 
9158   // Add argument registers to the end of the list so that they are
9159   // known live into the call.
9160   for (auto &Reg : RegsToPass)
9161     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9162 
9163   if (!IsTailCall) {
9164     // Add a register mask operand representing the call-preserved registers.
9165     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9166     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9167     assert(Mask && "Missing call preserved mask for calling convention");
9168     Ops.push_back(DAG.getRegisterMask(Mask));
9169   }
9170 
9171   // Glue the call to the argument copies, if any.
9172   if (Glue.getNode())
9173     Ops.push_back(Glue);
9174 
9175   // Emit the call.
9176   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9177 
9178   if (IsTailCall) {
9179     MF.getFrameInfo().setHasTailCall();
9180     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9181   }
9182 
9183   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9184   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9185   Glue = Chain.getValue(1);
9186 
9187   // Mark the end of the call, which is glued to the call itself.
9188   Chain = DAG.getCALLSEQ_END(Chain,
9189                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9190                              DAG.getConstant(0, DL, PtrVT, true),
9191                              Glue, DL);
9192   Glue = Chain.getValue(1);
9193 
9194   // Assign locations to each value returned by this call.
9195   SmallVector<CCValAssign, 16> RVLocs;
9196   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9197   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9198 
9199   // Copy all of the result registers out of their specified physreg.
9200   for (auto &VA : RVLocs) {
9201     // Copy the value out
9202     SDValue RetValue =
9203         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9204     // Glue the RetValue to the end of the call sequence
9205     Chain = RetValue.getValue(1);
9206     Glue = RetValue.getValue(2);
9207 
9208     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9209       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9210       SDValue RetValue2 =
9211           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9212       Chain = RetValue2.getValue(1);
9213       Glue = RetValue2.getValue(2);
9214       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9215                              RetValue2);
9216     }
9217 
9218     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9219 
9220     InVals.push_back(RetValue);
9221   }
9222 
9223   return Chain;
9224 }
9225 
9226 bool RISCVTargetLowering::CanLowerReturn(
9227     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9228     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9229   SmallVector<CCValAssign, 16> RVLocs;
9230   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9231 
9232   Optional<unsigned> FirstMaskArgument;
9233   if (Subtarget.hasVInstructions())
9234     FirstMaskArgument = preAssignMask(Outs);
9235 
9236   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9237     MVT VT = Outs[i].VT;
9238     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9239     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9240     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9241                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9242                  *this, FirstMaskArgument))
9243       return false;
9244   }
9245   return true;
9246 }
9247 
9248 SDValue
9249 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9250                                  bool IsVarArg,
9251                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9252                                  const SmallVectorImpl<SDValue> &OutVals,
9253                                  const SDLoc &DL, SelectionDAG &DAG) const {
9254   const MachineFunction &MF = DAG.getMachineFunction();
9255   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9256 
9257   // Stores the assignment of the return value to a location.
9258   SmallVector<CCValAssign, 16> RVLocs;
9259 
9260   // Info about the registers and stack slot.
9261   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9262                  *DAG.getContext());
9263 
9264   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9265                     nullptr, CC_RISCV);
9266 
9267   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9268     report_fatal_error("GHC functions return void only");
9269 
9270   SDValue Glue;
9271   SmallVector<SDValue, 4> RetOps(1, Chain);
9272 
9273   // Copy the result values into the output registers.
9274   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9275     SDValue Val = OutVals[i];
9276     CCValAssign &VA = RVLocs[i];
9277     assert(VA.isRegLoc() && "Can only return in registers!");
9278 
9279     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9280       // Handle returning f64 on RV32D with a soft float ABI.
9281       assert(VA.isRegLoc() && "Expected return via registers");
9282       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9283                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9284       SDValue Lo = SplitF64.getValue(0);
9285       SDValue Hi = SplitF64.getValue(1);
9286       Register RegLo = VA.getLocReg();
9287       assert(RegLo < RISCV::X31 && "Invalid register pair");
9288       Register RegHi = RegLo + 1;
9289 
9290       if (STI.isRegisterReservedByUser(RegLo) ||
9291           STI.isRegisterReservedByUser(RegHi))
9292         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9293             MF.getFunction(),
9294             "Return value register required, but has been reserved."});
9295 
9296       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9297       Glue = Chain.getValue(1);
9298       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9299       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9300       Glue = Chain.getValue(1);
9301       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9302     } else {
9303       // Handle a 'normal' return.
9304       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9305       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9306 
9307       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9308         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9309             MF.getFunction(),
9310             "Return value register required, but has been reserved."});
9311 
9312       // Guarantee that all emitted copies are stuck together.
9313       Glue = Chain.getValue(1);
9314       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9315     }
9316   }
9317 
9318   RetOps[0] = Chain; // Update chain.
9319 
9320   // Add the glue node if we have it.
9321   if (Glue.getNode()) {
9322     RetOps.push_back(Glue);
9323   }
9324 
9325   unsigned RetOpc = RISCVISD::RET_FLAG;
9326   // Interrupt service routines use different return instructions.
9327   const Function &Func = DAG.getMachineFunction().getFunction();
9328   if (Func.hasFnAttribute("interrupt")) {
9329     if (!Func.getReturnType()->isVoidTy())
9330       report_fatal_error(
9331           "Functions with the interrupt attribute must have void return type!");
9332 
9333     MachineFunction &MF = DAG.getMachineFunction();
9334     StringRef Kind =
9335       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9336 
9337     if (Kind == "user")
9338       RetOpc = RISCVISD::URET_FLAG;
9339     else if (Kind == "supervisor")
9340       RetOpc = RISCVISD::SRET_FLAG;
9341     else
9342       RetOpc = RISCVISD::MRET_FLAG;
9343   }
9344 
9345   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9346 }
9347 
9348 void RISCVTargetLowering::validateCCReservedRegs(
9349     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9350     MachineFunction &MF) const {
9351   const Function &F = MF.getFunction();
9352   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9353 
9354   if (llvm::any_of(Regs, [&STI](auto Reg) {
9355         return STI.isRegisterReservedByUser(Reg.first);
9356       }))
9357     F.getContext().diagnose(DiagnosticInfoUnsupported{
9358         F, "Argument register required, but has been reserved."});
9359 }
9360 
9361 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9362   return CI->isTailCall();
9363 }
9364 
9365 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9366 #define NODE_NAME_CASE(NODE)                                                   \
9367   case RISCVISD::NODE:                                                         \
9368     return "RISCVISD::" #NODE;
9369   // clang-format off
9370   switch ((RISCVISD::NodeType)Opcode) {
9371   case RISCVISD::FIRST_NUMBER:
9372     break;
9373   NODE_NAME_CASE(RET_FLAG)
9374   NODE_NAME_CASE(URET_FLAG)
9375   NODE_NAME_CASE(SRET_FLAG)
9376   NODE_NAME_CASE(MRET_FLAG)
9377   NODE_NAME_CASE(CALL)
9378   NODE_NAME_CASE(SELECT_CC)
9379   NODE_NAME_CASE(BR_CC)
9380   NODE_NAME_CASE(BuildPairF64)
9381   NODE_NAME_CASE(SplitF64)
9382   NODE_NAME_CASE(TAIL)
9383   NODE_NAME_CASE(MULHSU)
9384   NODE_NAME_CASE(SLLW)
9385   NODE_NAME_CASE(SRAW)
9386   NODE_NAME_CASE(SRLW)
9387   NODE_NAME_CASE(DIVW)
9388   NODE_NAME_CASE(DIVUW)
9389   NODE_NAME_CASE(REMUW)
9390   NODE_NAME_CASE(ROLW)
9391   NODE_NAME_CASE(RORW)
9392   NODE_NAME_CASE(CLZW)
9393   NODE_NAME_CASE(CTZW)
9394   NODE_NAME_CASE(FSLW)
9395   NODE_NAME_CASE(FSRW)
9396   NODE_NAME_CASE(FSL)
9397   NODE_NAME_CASE(FSR)
9398   NODE_NAME_CASE(FMV_H_X)
9399   NODE_NAME_CASE(FMV_X_ANYEXTH)
9400   NODE_NAME_CASE(FMV_W_X_RV64)
9401   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9402   NODE_NAME_CASE(FCVT_X_RTZ)
9403   NODE_NAME_CASE(FCVT_XU_RTZ)
9404   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9405   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9406   NODE_NAME_CASE(READ_CYCLE_WIDE)
9407   NODE_NAME_CASE(GREV)
9408   NODE_NAME_CASE(GREVW)
9409   NODE_NAME_CASE(GORC)
9410   NODE_NAME_CASE(GORCW)
9411   NODE_NAME_CASE(SHFL)
9412   NODE_NAME_CASE(SHFLW)
9413   NODE_NAME_CASE(UNSHFL)
9414   NODE_NAME_CASE(UNSHFLW)
9415   NODE_NAME_CASE(BCOMPRESS)
9416   NODE_NAME_CASE(BCOMPRESSW)
9417   NODE_NAME_CASE(BDECOMPRESS)
9418   NODE_NAME_CASE(BDECOMPRESSW)
9419   NODE_NAME_CASE(VMV_V_X_VL)
9420   NODE_NAME_CASE(VFMV_V_F_VL)
9421   NODE_NAME_CASE(VMV_X_S)
9422   NODE_NAME_CASE(VMV_S_X_VL)
9423   NODE_NAME_CASE(VFMV_S_F_VL)
9424   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9425   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9426   NODE_NAME_CASE(READ_VLENB)
9427   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9428   NODE_NAME_CASE(VSLIDEUP_VL)
9429   NODE_NAME_CASE(VSLIDE1UP_VL)
9430   NODE_NAME_CASE(VSLIDEDOWN_VL)
9431   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9432   NODE_NAME_CASE(VID_VL)
9433   NODE_NAME_CASE(VFNCVT_ROD_VL)
9434   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9435   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9436   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9437   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9438   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9439   NODE_NAME_CASE(VECREDUCE_AND_VL)
9440   NODE_NAME_CASE(VECREDUCE_OR_VL)
9441   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9442   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9443   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9444   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9445   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9446   NODE_NAME_CASE(ADD_VL)
9447   NODE_NAME_CASE(AND_VL)
9448   NODE_NAME_CASE(MUL_VL)
9449   NODE_NAME_CASE(OR_VL)
9450   NODE_NAME_CASE(SDIV_VL)
9451   NODE_NAME_CASE(SHL_VL)
9452   NODE_NAME_CASE(SREM_VL)
9453   NODE_NAME_CASE(SRA_VL)
9454   NODE_NAME_CASE(SRL_VL)
9455   NODE_NAME_CASE(SUB_VL)
9456   NODE_NAME_CASE(UDIV_VL)
9457   NODE_NAME_CASE(UREM_VL)
9458   NODE_NAME_CASE(XOR_VL)
9459   NODE_NAME_CASE(SADDSAT_VL)
9460   NODE_NAME_CASE(UADDSAT_VL)
9461   NODE_NAME_CASE(SSUBSAT_VL)
9462   NODE_NAME_CASE(USUBSAT_VL)
9463   NODE_NAME_CASE(FADD_VL)
9464   NODE_NAME_CASE(FSUB_VL)
9465   NODE_NAME_CASE(FMUL_VL)
9466   NODE_NAME_CASE(FDIV_VL)
9467   NODE_NAME_CASE(FNEG_VL)
9468   NODE_NAME_CASE(FABS_VL)
9469   NODE_NAME_CASE(FSQRT_VL)
9470   NODE_NAME_CASE(FMA_VL)
9471   NODE_NAME_CASE(FCOPYSIGN_VL)
9472   NODE_NAME_CASE(SMIN_VL)
9473   NODE_NAME_CASE(SMAX_VL)
9474   NODE_NAME_CASE(UMIN_VL)
9475   NODE_NAME_CASE(UMAX_VL)
9476   NODE_NAME_CASE(FMINNUM_VL)
9477   NODE_NAME_CASE(FMAXNUM_VL)
9478   NODE_NAME_CASE(MULHS_VL)
9479   NODE_NAME_CASE(MULHU_VL)
9480   NODE_NAME_CASE(FP_TO_SINT_VL)
9481   NODE_NAME_CASE(FP_TO_UINT_VL)
9482   NODE_NAME_CASE(SINT_TO_FP_VL)
9483   NODE_NAME_CASE(UINT_TO_FP_VL)
9484   NODE_NAME_CASE(FP_EXTEND_VL)
9485   NODE_NAME_CASE(FP_ROUND_VL)
9486   NODE_NAME_CASE(VWMUL_VL)
9487   NODE_NAME_CASE(VWMULU_VL)
9488   NODE_NAME_CASE(SETCC_VL)
9489   NODE_NAME_CASE(VSELECT_VL)
9490   NODE_NAME_CASE(VMAND_VL)
9491   NODE_NAME_CASE(VMOR_VL)
9492   NODE_NAME_CASE(VMXOR_VL)
9493   NODE_NAME_CASE(VMCLR_VL)
9494   NODE_NAME_CASE(VMSET_VL)
9495   NODE_NAME_CASE(VRGATHER_VX_VL)
9496   NODE_NAME_CASE(VRGATHER_VV_VL)
9497   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9498   NODE_NAME_CASE(VSEXT_VL)
9499   NODE_NAME_CASE(VZEXT_VL)
9500   NODE_NAME_CASE(VCPOP_VL)
9501   NODE_NAME_CASE(VLE_VL)
9502   NODE_NAME_CASE(VSE_VL)
9503   NODE_NAME_CASE(READ_CSR)
9504   NODE_NAME_CASE(WRITE_CSR)
9505   NODE_NAME_CASE(SWAP_CSR)
9506   }
9507   // clang-format on
9508   return nullptr;
9509 #undef NODE_NAME_CASE
9510 }
9511 
9512 /// getConstraintType - Given a constraint letter, return the type of
9513 /// constraint it is for this target.
9514 RISCVTargetLowering::ConstraintType
9515 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9516   if (Constraint.size() == 1) {
9517     switch (Constraint[0]) {
9518     default:
9519       break;
9520     case 'f':
9521       return C_RegisterClass;
9522     case 'I':
9523     case 'J':
9524     case 'K':
9525       return C_Immediate;
9526     case 'A':
9527       return C_Memory;
9528     case 'S': // A symbolic address
9529       return C_Other;
9530     }
9531   } else {
9532     if (Constraint == "vr" || Constraint == "vm")
9533       return C_RegisterClass;
9534   }
9535   return TargetLowering::getConstraintType(Constraint);
9536 }
9537 
9538 std::pair<unsigned, const TargetRegisterClass *>
9539 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9540                                                   StringRef Constraint,
9541                                                   MVT VT) const {
9542   // First, see if this is a constraint that directly corresponds to a
9543   // RISCV register class.
9544   if (Constraint.size() == 1) {
9545     switch (Constraint[0]) {
9546     case 'r':
9547       return std::make_pair(0U, &RISCV::GPRRegClass);
9548     case 'f':
9549       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9550         return std::make_pair(0U, &RISCV::FPR16RegClass);
9551       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9552         return std::make_pair(0U, &RISCV::FPR32RegClass);
9553       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9554         return std::make_pair(0U, &RISCV::FPR64RegClass);
9555       break;
9556     default:
9557       break;
9558     }
9559   } else {
9560     if (Constraint == "vr") {
9561       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9562                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9563         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9564           return std::make_pair(0U, RC);
9565       }
9566     } else if (Constraint == "vm") {
9567       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9568         return std::make_pair(0U, &RISCV::VMRegClass);
9569     }
9570   }
9571 
9572   // Clang will correctly decode the usage of register name aliases into their
9573   // official names. However, other frontends like `rustc` do not. This allows
9574   // users of these frontends to use the ABI names for registers in LLVM-style
9575   // register constraints.
9576   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9577                                .Case("{zero}", RISCV::X0)
9578                                .Case("{ra}", RISCV::X1)
9579                                .Case("{sp}", RISCV::X2)
9580                                .Case("{gp}", RISCV::X3)
9581                                .Case("{tp}", RISCV::X4)
9582                                .Case("{t0}", RISCV::X5)
9583                                .Case("{t1}", RISCV::X6)
9584                                .Case("{t2}", RISCV::X7)
9585                                .Cases("{s0}", "{fp}", RISCV::X8)
9586                                .Case("{s1}", RISCV::X9)
9587                                .Case("{a0}", RISCV::X10)
9588                                .Case("{a1}", RISCV::X11)
9589                                .Case("{a2}", RISCV::X12)
9590                                .Case("{a3}", RISCV::X13)
9591                                .Case("{a4}", RISCV::X14)
9592                                .Case("{a5}", RISCV::X15)
9593                                .Case("{a6}", RISCV::X16)
9594                                .Case("{a7}", RISCV::X17)
9595                                .Case("{s2}", RISCV::X18)
9596                                .Case("{s3}", RISCV::X19)
9597                                .Case("{s4}", RISCV::X20)
9598                                .Case("{s5}", RISCV::X21)
9599                                .Case("{s6}", RISCV::X22)
9600                                .Case("{s7}", RISCV::X23)
9601                                .Case("{s8}", RISCV::X24)
9602                                .Case("{s9}", RISCV::X25)
9603                                .Case("{s10}", RISCV::X26)
9604                                .Case("{s11}", RISCV::X27)
9605                                .Case("{t3}", RISCV::X28)
9606                                .Case("{t4}", RISCV::X29)
9607                                .Case("{t5}", RISCV::X30)
9608                                .Case("{t6}", RISCV::X31)
9609                                .Default(RISCV::NoRegister);
9610   if (XRegFromAlias != RISCV::NoRegister)
9611     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9612 
9613   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9614   // TableGen record rather than the AsmName to choose registers for InlineAsm
9615   // constraints, plus we want to match those names to the widest floating point
9616   // register type available, manually select floating point registers here.
9617   //
9618   // The second case is the ABI name of the register, so that frontends can also
9619   // use the ABI names in register constraint lists.
9620   if (Subtarget.hasStdExtF()) {
9621     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9622                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9623                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9624                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9625                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9626                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9627                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9628                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9629                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9630                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9631                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9632                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9633                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9634                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9635                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9636                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9637                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9638                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9639                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9640                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9641                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9642                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9643                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9644                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9645                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9646                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9647                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9648                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9649                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9650                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9651                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9652                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9653                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9654                         .Default(RISCV::NoRegister);
9655     if (FReg != RISCV::NoRegister) {
9656       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9657       if (Subtarget.hasStdExtD()) {
9658         unsigned RegNo = FReg - RISCV::F0_F;
9659         unsigned DReg = RISCV::F0_D + RegNo;
9660         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9661       }
9662       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9663     }
9664   }
9665 
9666   if (Subtarget.hasVInstructions()) {
9667     Register VReg = StringSwitch<Register>(Constraint.lower())
9668                         .Case("{v0}", RISCV::V0)
9669                         .Case("{v1}", RISCV::V1)
9670                         .Case("{v2}", RISCV::V2)
9671                         .Case("{v3}", RISCV::V3)
9672                         .Case("{v4}", RISCV::V4)
9673                         .Case("{v5}", RISCV::V5)
9674                         .Case("{v6}", RISCV::V6)
9675                         .Case("{v7}", RISCV::V7)
9676                         .Case("{v8}", RISCV::V8)
9677                         .Case("{v9}", RISCV::V9)
9678                         .Case("{v10}", RISCV::V10)
9679                         .Case("{v11}", RISCV::V11)
9680                         .Case("{v12}", RISCV::V12)
9681                         .Case("{v13}", RISCV::V13)
9682                         .Case("{v14}", RISCV::V14)
9683                         .Case("{v15}", RISCV::V15)
9684                         .Case("{v16}", RISCV::V16)
9685                         .Case("{v17}", RISCV::V17)
9686                         .Case("{v18}", RISCV::V18)
9687                         .Case("{v19}", RISCV::V19)
9688                         .Case("{v20}", RISCV::V20)
9689                         .Case("{v21}", RISCV::V21)
9690                         .Case("{v22}", RISCV::V22)
9691                         .Case("{v23}", RISCV::V23)
9692                         .Case("{v24}", RISCV::V24)
9693                         .Case("{v25}", RISCV::V25)
9694                         .Case("{v26}", RISCV::V26)
9695                         .Case("{v27}", RISCV::V27)
9696                         .Case("{v28}", RISCV::V28)
9697                         .Case("{v29}", RISCV::V29)
9698                         .Case("{v30}", RISCV::V30)
9699                         .Case("{v31}", RISCV::V31)
9700                         .Default(RISCV::NoRegister);
9701     if (VReg != RISCV::NoRegister) {
9702       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9703         return std::make_pair(VReg, &RISCV::VMRegClass);
9704       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9705         return std::make_pair(VReg, &RISCV::VRRegClass);
9706       for (const auto *RC :
9707            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9708         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9709           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9710           return std::make_pair(VReg, RC);
9711         }
9712       }
9713     }
9714   }
9715 
9716   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9717 }
9718 
9719 unsigned
9720 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9721   // Currently only support length 1 constraints.
9722   if (ConstraintCode.size() == 1) {
9723     switch (ConstraintCode[0]) {
9724     case 'A':
9725       return InlineAsm::Constraint_A;
9726     default:
9727       break;
9728     }
9729   }
9730 
9731   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9732 }
9733 
9734 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9735     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9736     SelectionDAG &DAG) const {
9737   // Currently only support length 1 constraints.
9738   if (Constraint.length() == 1) {
9739     switch (Constraint[0]) {
9740     case 'I':
9741       // Validate & create a 12-bit signed immediate operand.
9742       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9743         uint64_t CVal = C->getSExtValue();
9744         if (isInt<12>(CVal))
9745           Ops.push_back(
9746               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9747       }
9748       return;
9749     case 'J':
9750       // Validate & create an integer zero operand.
9751       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9752         if (C->getZExtValue() == 0)
9753           Ops.push_back(
9754               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9755       return;
9756     case 'K':
9757       // Validate & create a 5-bit unsigned immediate operand.
9758       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9759         uint64_t CVal = C->getZExtValue();
9760         if (isUInt<5>(CVal))
9761           Ops.push_back(
9762               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9763       }
9764       return;
9765     case 'S':
9766       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9767         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9768                                                  GA->getValueType(0)));
9769       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9770         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9771                                                 BA->getValueType(0)));
9772       }
9773       return;
9774     default:
9775       break;
9776     }
9777   }
9778   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9779 }
9780 
9781 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9782                                                    Instruction *Inst,
9783                                                    AtomicOrdering Ord) const {
9784   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9785     return Builder.CreateFence(Ord);
9786   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9787     return Builder.CreateFence(AtomicOrdering::Release);
9788   return nullptr;
9789 }
9790 
9791 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9792                                                     Instruction *Inst,
9793                                                     AtomicOrdering Ord) const {
9794   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9795     return Builder.CreateFence(AtomicOrdering::Acquire);
9796   return nullptr;
9797 }
9798 
9799 TargetLowering::AtomicExpansionKind
9800 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9801   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9802   // point operations can't be used in an lr/sc sequence without breaking the
9803   // forward-progress guarantee.
9804   if (AI->isFloatingPointOperation())
9805     return AtomicExpansionKind::CmpXChg;
9806 
9807   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9808   if (Size == 8 || Size == 16)
9809     return AtomicExpansionKind::MaskedIntrinsic;
9810   return AtomicExpansionKind::None;
9811 }
9812 
9813 static Intrinsic::ID
9814 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9815   if (XLen == 32) {
9816     switch (BinOp) {
9817     default:
9818       llvm_unreachable("Unexpected AtomicRMW BinOp");
9819     case AtomicRMWInst::Xchg:
9820       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9821     case AtomicRMWInst::Add:
9822       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9823     case AtomicRMWInst::Sub:
9824       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9825     case AtomicRMWInst::Nand:
9826       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9827     case AtomicRMWInst::Max:
9828       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9829     case AtomicRMWInst::Min:
9830       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9831     case AtomicRMWInst::UMax:
9832       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9833     case AtomicRMWInst::UMin:
9834       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9835     }
9836   }
9837 
9838   if (XLen == 64) {
9839     switch (BinOp) {
9840     default:
9841       llvm_unreachable("Unexpected AtomicRMW BinOp");
9842     case AtomicRMWInst::Xchg:
9843       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9844     case AtomicRMWInst::Add:
9845       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9846     case AtomicRMWInst::Sub:
9847       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9848     case AtomicRMWInst::Nand:
9849       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9850     case AtomicRMWInst::Max:
9851       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9852     case AtomicRMWInst::Min:
9853       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9854     case AtomicRMWInst::UMax:
9855       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9856     case AtomicRMWInst::UMin:
9857       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9858     }
9859   }
9860 
9861   llvm_unreachable("Unexpected XLen\n");
9862 }
9863 
9864 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9865     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9866     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9867   unsigned XLen = Subtarget.getXLen();
9868   Value *Ordering =
9869       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9870   Type *Tys[] = {AlignedAddr->getType()};
9871   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9872       AI->getModule(),
9873       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9874 
9875   if (XLen == 64) {
9876     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9877     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9878     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9879   }
9880 
9881   Value *Result;
9882 
9883   // Must pass the shift amount needed to sign extend the loaded value prior
9884   // to performing a signed comparison for min/max. ShiftAmt is the number of
9885   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9886   // is the number of bits to left+right shift the value in order to
9887   // sign-extend.
9888   if (AI->getOperation() == AtomicRMWInst::Min ||
9889       AI->getOperation() == AtomicRMWInst::Max) {
9890     const DataLayout &DL = AI->getModule()->getDataLayout();
9891     unsigned ValWidth =
9892         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9893     Value *SextShamt =
9894         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9895     Result = Builder.CreateCall(LrwOpScwLoop,
9896                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9897   } else {
9898     Result =
9899         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9900   }
9901 
9902   if (XLen == 64)
9903     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9904   return Result;
9905 }
9906 
9907 TargetLowering::AtomicExpansionKind
9908 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9909     AtomicCmpXchgInst *CI) const {
9910   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9911   if (Size == 8 || Size == 16)
9912     return AtomicExpansionKind::MaskedIntrinsic;
9913   return AtomicExpansionKind::None;
9914 }
9915 
9916 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9917     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9918     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9919   unsigned XLen = Subtarget.getXLen();
9920   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9921   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9922   if (XLen == 64) {
9923     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9924     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9925     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9926     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9927   }
9928   Type *Tys[] = {AlignedAddr->getType()};
9929   Function *MaskedCmpXchg =
9930       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9931   Value *Result = Builder.CreateCall(
9932       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9933   if (XLen == 64)
9934     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9935   return Result;
9936 }
9937 
9938 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9939   return false;
9940 }
9941 
9942 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
9943                                                EVT VT) const {
9944   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
9945     return false;
9946 
9947   switch (FPVT.getSimpleVT().SimpleTy) {
9948   case MVT::f16:
9949     return Subtarget.hasStdExtZfh();
9950   case MVT::f32:
9951     return Subtarget.hasStdExtF();
9952   case MVT::f64:
9953     return Subtarget.hasStdExtD();
9954   default:
9955     return false;
9956   }
9957 }
9958 
9959 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9960                                                      EVT VT) const {
9961   VT = VT.getScalarType();
9962 
9963   if (!VT.isSimple())
9964     return false;
9965 
9966   switch (VT.getSimpleVT().SimpleTy) {
9967   case MVT::f16:
9968     return Subtarget.hasStdExtZfh();
9969   case MVT::f32:
9970     return Subtarget.hasStdExtF();
9971   case MVT::f64:
9972     return Subtarget.hasStdExtD();
9973   default:
9974     break;
9975   }
9976 
9977   return false;
9978 }
9979 
9980 Register RISCVTargetLowering::getExceptionPointerRegister(
9981     const Constant *PersonalityFn) const {
9982   return RISCV::X10;
9983 }
9984 
9985 Register RISCVTargetLowering::getExceptionSelectorRegister(
9986     const Constant *PersonalityFn) const {
9987   return RISCV::X11;
9988 }
9989 
9990 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9991   // Return false to suppress the unnecessary extensions if the LibCall
9992   // arguments or return value is f32 type for LP64 ABI.
9993   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9994   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9995     return false;
9996 
9997   return true;
9998 }
9999 
10000 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10001   if (Subtarget.is64Bit() && Type == MVT::i32)
10002     return true;
10003 
10004   return IsSigned;
10005 }
10006 
10007 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10008                                                  SDValue C) const {
10009   // Check integral scalar types.
10010   if (VT.isScalarInteger()) {
10011     // Omit the optimization if the sub target has the M extension and the data
10012     // size exceeds XLen.
10013     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10014       return false;
10015     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10016       // Break the MUL to a SLLI and an ADD/SUB.
10017       const APInt &Imm = ConstNode->getAPIntValue();
10018       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10019           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10020         return true;
10021       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10022       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10023           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10024            (Imm - 8).isPowerOf2()))
10025         return true;
10026       // Omit the following optimization if the sub target has the M extension
10027       // and the data size >= XLen.
10028       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10029         return false;
10030       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10031       // a pair of LUI/ADDI.
10032       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10033         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10034         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10035             (1 - ImmS).isPowerOf2())
10036         return true;
10037       }
10038     }
10039   }
10040 
10041   return false;
10042 }
10043 
10044 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10045     const SDValue &AddNode, const SDValue &ConstNode) const {
10046   // Let the DAGCombiner decide for vectors.
10047   EVT VT = AddNode.getValueType();
10048   if (VT.isVector())
10049     return true;
10050 
10051   // Let the DAGCombiner decide for larger types.
10052   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10053     return true;
10054 
10055   // It is worse if c1 is simm12 while c1*c2 is not.
10056   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10057   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10058   const APInt &C1 = C1Node->getAPIntValue();
10059   const APInt &C2 = C2Node->getAPIntValue();
10060   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10061     return false;
10062 
10063   // Default to true and let the DAGCombiner decide.
10064   return true;
10065 }
10066 
10067 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10068     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10069     bool *Fast) const {
10070   if (!VT.isVector())
10071     return false;
10072 
10073   EVT ElemVT = VT.getVectorElementType();
10074   if (Alignment >= ElemVT.getStoreSize()) {
10075     if (Fast)
10076       *Fast = true;
10077     return true;
10078   }
10079 
10080   return false;
10081 }
10082 
10083 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10084     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10085     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10086   bool IsABIRegCopy = CC.hasValue();
10087   EVT ValueVT = Val.getValueType();
10088   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10089     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10090     // and cast to f32.
10091     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10092     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10093     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10094                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10095     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10096     Parts[0] = Val;
10097     return true;
10098   }
10099 
10100   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10101     LLVMContext &Context = *DAG.getContext();
10102     EVT ValueEltVT = ValueVT.getVectorElementType();
10103     EVT PartEltVT = PartVT.getVectorElementType();
10104     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10105     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10106     if (PartVTBitSize % ValueVTBitSize == 0) {
10107       // If the element types are different, bitcast to the same element type of
10108       // PartVT first.
10109       if (ValueEltVT != PartEltVT) {
10110         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
10111         assert(Count != 0 && "The number of element should not be zero.");
10112         EVT SameEltTypeVT =
10113             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
10114         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10115       }
10116       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10117                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
10118       Parts[0] = Val;
10119       return true;
10120     }
10121   }
10122   return false;
10123 }
10124 
10125 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10126     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10127     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10128   bool IsABIRegCopy = CC.hasValue();
10129   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10130     SDValue Val = Parts[0];
10131 
10132     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10133     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10134     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10135     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10136     return Val;
10137   }
10138 
10139   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10140     LLVMContext &Context = *DAG.getContext();
10141     SDValue Val = Parts[0];
10142     EVT ValueEltVT = ValueVT.getVectorElementType();
10143     EVT PartEltVT = PartVT.getVectorElementType();
10144     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10145     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10146     if (PartVTBitSize % ValueVTBitSize == 0) {
10147       EVT SameEltTypeVT = ValueVT;
10148       // If the element types are different, convert it to the same element type
10149       // of PartVT.
10150       if (ValueEltVT != PartEltVT) {
10151         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
10152         assert(Count != 0 && "The number of element should not be zero.");
10153         SameEltTypeVT =
10154             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
10155       }
10156       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
10157                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
10158       if (ValueEltVT != PartEltVT)
10159         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
10160       return Val;
10161     }
10162   }
10163   return SDValue();
10164 }
10165 
10166 #define GET_REGISTER_MATCHER
10167 #include "RISCVGenAsmMatcher.inc"
10168 
10169 Register
10170 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10171                                        const MachineFunction &MF) const {
10172   Register Reg = MatchRegisterAltName(RegName);
10173   if (Reg == RISCV::NoRegister)
10174     Reg = MatchRegisterName(RegName);
10175   if (Reg == RISCV::NoRegister)
10176     report_fatal_error(
10177         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10178   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10179   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10180     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10181                              StringRef(RegName) + "\"."));
10182   return Reg;
10183 }
10184 
10185 namespace llvm {
10186 namespace RISCVVIntrinsicsTable {
10187 
10188 #define GET_RISCVVIntrinsicsTable_IMPL
10189 #include "RISCVGenSearchableTables.inc"
10190 
10191 } // namespace RISCVVIntrinsicsTable
10192 
10193 } // namespace llvm
10194