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     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
339     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
344     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
345     for (auto CC : FPCCToExpand)
346       setCondCodeAction(CC, MVT::f16, Expand);
347     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
348     setOperationAction(ISD::SELECT, MVT::f16, Custom);
349     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
350 
351     setOperationAction(ISD::FREM,       MVT::f16, Promote);
352     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
353     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
354     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
355     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
356     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
357     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
358     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
359     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
360     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
361     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
362     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
363     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
364     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
365     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
366     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
367     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
368     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
369 
370     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
371     // complete support for all operations in LegalizeDAG.
372 
373     // We need to custom promote this.
374     if (Subtarget.is64Bit())
375       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
376   }
377 
378   if (Subtarget.hasStdExtF()) {
379     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
380     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
381     setOperationAction(ISD::LRINT, MVT::f32, Legal);
382     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
383     setOperationAction(ISD::LROUND, MVT::f32, Legal);
384     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
385     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
386     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
387     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
388     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
389     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
390     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
391     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
392     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
393     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
395     for (auto CC : FPCCToExpand)
396       setCondCodeAction(CC, MVT::f32, Expand);
397     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
398     setOperationAction(ISD::SELECT, MVT::f32, Custom);
399     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
400     for (auto Op : FPOpToExpand)
401       setOperationAction(Op, MVT::f32, Expand);
402     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
403     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
404   }
405 
406   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
407     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
408 
409   if (Subtarget.hasStdExtD()) {
410     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
411     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
412     setOperationAction(ISD::LRINT, MVT::f64, Legal);
413     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
414     setOperationAction(ISD::LROUND, MVT::f64, Legal);
415     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
416     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
417     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
418     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
419     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
420     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
421     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
422     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
423     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
424     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
425     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
426     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
428     for (auto CC : FPCCToExpand)
429       setCondCodeAction(CC, MVT::f64, Expand);
430     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
431     setOperationAction(ISD::SELECT, MVT::f64, Custom);
432     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
433     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
434     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
435     for (auto Op : FPOpToExpand)
436       setOperationAction(Op, MVT::f64, Expand);
437     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
438     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
439   }
440 
441   if (Subtarget.is64Bit()) {
442     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
443     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
444     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
445     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
446   }
447 
448   if (Subtarget.hasStdExtF()) {
449     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
450     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
451 
452     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
453     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
454     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
455     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
456 
457     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
458     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
459   }
460 
461   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
462   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
463   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
464   setOperationAction(ISD::JumpTable, XLenVT, Custom);
465 
466   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
467 
468   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
469   // Unfortunately this can't be determined just from the ISA naming string.
470   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
471                      Subtarget.is64Bit() ? Legal : Custom);
472 
473   setOperationAction(ISD::TRAP, MVT::Other, Legal);
474   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
475   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
476   if (Subtarget.is64Bit())
477     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
478 
479   if (Subtarget.hasStdExtA()) {
480     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
481     setMinCmpXchgSizeInBits(32);
482   } else {
483     setMaxAtomicSizeInBitsSupported(0);
484   }
485 
486   setBooleanContents(ZeroOrOneBooleanContent);
487 
488   if (Subtarget.hasVInstructions()) {
489     setBooleanVectorContents(ZeroOrOneBooleanContent);
490 
491     setOperationAction(ISD::VSCALE, XLenVT, Custom);
492 
493     // RVV intrinsics may have illegal operands.
494     // We also need to custom legalize vmv.x.s.
495     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
496     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
497     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
498     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
499     if (Subtarget.is64Bit()) {
500       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
501     } else {
502       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
503       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
504     }
505 
506     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
507     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
508 
509     static const unsigned IntegerVPOps[] = {
510         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
511         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
512         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
513         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
514         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
515         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
516         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
517         ISD::VP_SELECT};
518 
519     static const unsigned FloatingPointVPOps[] = {
520         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
521         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
522         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
523 
524     if (!Subtarget.is64Bit()) {
525       // We must custom-lower certain vXi64 operations on RV32 due to the vector
526       // element type being illegal.
527       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
528       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
529 
530       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
531       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
532       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
533       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
534       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
535       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
536       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
537       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
538 
539       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
540       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
541       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
542       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
543       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
544       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
545       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
546       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
547     }
548 
549     for (MVT VT : BoolVecVTs) {
550       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
551 
552       // Mask VTs are custom-expanded into a series of standard nodes
553       setOperationAction(ISD::TRUNCATE, VT, Custom);
554       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
555       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
556       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
557 
558       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
559       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
560 
561       setOperationAction(ISD::SELECT, VT, Custom);
562       setOperationAction(ISD::SELECT_CC, VT, Expand);
563       setOperationAction(ISD::VSELECT, VT, Expand);
564       setOperationAction(ISD::VP_SELECT, VT, Expand);
565 
566       setOperationAction(ISD::VP_AND, VT, Custom);
567       setOperationAction(ISD::VP_OR, VT, Custom);
568       setOperationAction(ISD::VP_XOR, VT, Custom);
569 
570       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
571       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
572       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
573 
574       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
575       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
576       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
577 
578       // RVV has native int->float & float->int conversions where the
579       // element type sizes are within one power-of-two of each other. Any
580       // wider distances between type sizes have to be lowered as sequences
581       // which progressively narrow the gap in stages.
582       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
583       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
584       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
585       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
586 
587       // Expand all extending loads to types larger than this, and truncating
588       // stores from types larger than this.
589       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
590         setTruncStoreAction(OtherVT, VT, Expand);
591         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
592         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
593         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
594       }
595     }
596 
597     for (MVT VT : IntVecVTs) {
598       if (VT.getVectorElementType() == MVT::i64 &&
599           !Subtarget.hasVInstructionsI64())
600         continue;
601 
602       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
603       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
604 
605       // Vectors implement MULHS/MULHU.
606       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
607       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
608 
609       setOperationAction(ISD::SMIN, VT, Legal);
610       setOperationAction(ISD::SMAX, VT, Legal);
611       setOperationAction(ISD::UMIN, VT, Legal);
612       setOperationAction(ISD::UMAX, VT, Legal);
613 
614       setOperationAction(ISD::ROTL, VT, Expand);
615       setOperationAction(ISD::ROTR, VT, Expand);
616 
617       setOperationAction(ISD::CTTZ, VT, Expand);
618       setOperationAction(ISD::CTLZ, VT, Expand);
619       setOperationAction(ISD::CTPOP, VT, Expand);
620 
621       setOperationAction(ISD::BSWAP, VT, Expand);
622 
623       // Custom-lower extensions and truncations from/to mask types.
624       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
625       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
626       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
627 
628       // RVV has native int->float & float->int conversions where the
629       // element type sizes are within one power-of-two of each other. Any
630       // wider distances between type sizes have to be lowered as sequences
631       // which progressively narrow the gap in stages.
632       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
633       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
634       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
635       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
636 
637       setOperationAction(ISD::SADDSAT, VT, Legal);
638       setOperationAction(ISD::UADDSAT, VT, Legal);
639       setOperationAction(ISD::SSUBSAT, VT, Legal);
640       setOperationAction(ISD::USUBSAT, VT, Legal);
641 
642       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
643       // nodes which truncate by one power of two at a time.
644       setOperationAction(ISD::TRUNCATE, VT, Custom);
645 
646       // Custom-lower insert/extract operations to simplify patterns.
647       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
648       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
649 
650       // Custom-lower reduction operations to set up the corresponding custom
651       // nodes' operands.
652       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
653       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
654       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
655       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
656       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
657       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
658       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
659       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
660 
661       for (unsigned VPOpc : IntegerVPOps)
662         setOperationAction(VPOpc, VT, Custom);
663 
664       setOperationAction(ISD::LOAD, VT, Custom);
665       setOperationAction(ISD::STORE, VT, Custom);
666 
667       setOperationAction(ISD::MLOAD, VT, Custom);
668       setOperationAction(ISD::MSTORE, VT, Custom);
669       setOperationAction(ISD::MGATHER, VT, Custom);
670       setOperationAction(ISD::MSCATTER, VT, Custom);
671 
672       setOperationAction(ISD::VP_LOAD, VT, Custom);
673       setOperationAction(ISD::VP_STORE, VT, Custom);
674       setOperationAction(ISD::VP_GATHER, VT, Custom);
675       setOperationAction(ISD::VP_SCATTER, VT, Custom);
676 
677       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
678       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
679       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
680 
681       setOperationAction(ISD::SELECT, VT, Custom);
682       setOperationAction(ISD::SELECT_CC, VT, Expand);
683 
684       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
685       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
686 
687       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
688         setTruncStoreAction(VT, OtherVT, Expand);
689         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
690         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
691         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
692       }
693 
694       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
695       // type that can represent the value exactly.
696       if (VT.getVectorElementType() != MVT::i64) {
697         MVT FloatEltVT =
698             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
699         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
700         if (isTypeLegal(FloatVT)) {
701           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
702           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
703         }
704       }
705     }
706 
707     // Expand various CCs to best match the RVV ISA, which natively supports UNE
708     // but no other unordered comparisons, and supports all ordered comparisons
709     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
710     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
711     // and we pattern-match those back to the "original", swapping operands once
712     // more. This way we catch both operations and both "vf" and "fv" forms with
713     // fewer patterns.
714     static const ISD::CondCode VFPCCToExpand[] = {
715         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
716         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
717         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
718     };
719 
720     // Sets common operation actions on RVV floating-point vector types.
721     const auto SetCommonVFPActions = [&](MVT VT) {
722       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
723       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
724       // sizes are within one power-of-two of each other. Therefore conversions
725       // between vXf16 and vXf64 must be lowered as sequences which convert via
726       // vXf32.
727       setOperationAction(ISD::FP_ROUND, VT, Custom);
728       setOperationAction(ISD::FP_EXTEND, VT, Custom);
729       // Custom-lower insert/extract operations to simplify patterns.
730       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
731       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
732       // Expand various condition codes (explained above).
733       for (auto CC : VFPCCToExpand)
734         setCondCodeAction(CC, VT, Expand);
735 
736       setOperationAction(ISD::FMINNUM, VT, Legal);
737       setOperationAction(ISD::FMAXNUM, VT, Legal);
738 
739       setOperationAction(ISD::FTRUNC, VT, Custom);
740       setOperationAction(ISD::FCEIL, VT, Custom);
741       setOperationAction(ISD::FFLOOR, VT, Custom);
742 
743       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
744       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
745       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
746       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
747 
748       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
749 
750       setOperationAction(ISD::LOAD, VT, Custom);
751       setOperationAction(ISD::STORE, VT, Custom);
752 
753       setOperationAction(ISD::MLOAD, VT, Custom);
754       setOperationAction(ISD::MSTORE, VT, Custom);
755       setOperationAction(ISD::MGATHER, VT, Custom);
756       setOperationAction(ISD::MSCATTER, VT, Custom);
757 
758       setOperationAction(ISD::VP_LOAD, VT, Custom);
759       setOperationAction(ISD::VP_STORE, VT, Custom);
760       setOperationAction(ISD::VP_GATHER, VT, Custom);
761       setOperationAction(ISD::VP_SCATTER, VT, Custom);
762 
763       setOperationAction(ISD::SELECT, VT, Custom);
764       setOperationAction(ISD::SELECT_CC, VT, Expand);
765 
766       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
767       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
768       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
769 
770       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
771 
772       for (unsigned VPOpc : FloatingPointVPOps)
773         setOperationAction(VPOpc, VT, Custom);
774     };
775 
776     // Sets common extload/truncstore actions on RVV floating-point vector
777     // types.
778     const auto SetCommonVFPExtLoadTruncStoreActions =
779         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
780           for (auto SmallVT : SmallerVTs) {
781             setTruncStoreAction(VT, SmallVT, Expand);
782             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
783           }
784         };
785 
786     if (Subtarget.hasVInstructionsF16())
787       for (MVT VT : F16VecVTs)
788         SetCommonVFPActions(VT);
789 
790     for (MVT VT : F32VecVTs) {
791       if (Subtarget.hasVInstructionsF32())
792         SetCommonVFPActions(VT);
793       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
794     }
795 
796     for (MVT VT : F64VecVTs) {
797       if (Subtarget.hasVInstructionsF64())
798         SetCommonVFPActions(VT);
799       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
800       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
801     }
802 
803     if (Subtarget.useRVVForFixedLengthVectors()) {
804       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
805         if (!useRVVForFixedLengthVectorVT(VT))
806           continue;
807 
808         // By default everything must be expanded.
809         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
810           setOperationAction(Op, VT, Expand);
811         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
812           setTruncStoreAction(VT, OtherVT, Expand);
813           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
814           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
815           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
816         }
817 
818         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
819         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
820         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
821 
822         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
823         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
824 
825         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
826         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
827 
828         setOperationAction(ISD::LOAD, VT, Custom);
829         setOperationAction(ISD::STORE, VT, Custom);
830 
831         setOperationAction(ISD::SETCC, VT, Custom);
832 
833         setOperationAction(ISD::SELECT, VT, Custom);
834 
835         setOperationAction(ISD::TRUNCATE, VT, Custom);
836 
837         setOperationAction(ISD::BITCAST, VT, Custom);
838 
839         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
840         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
841         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
842 
843         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
844         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
845         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
846 
847         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
848         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
849         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
850         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
851 
852         // Operations below are different for between masks and other vectors.
853         if (VT.getVectorElementType() == MVT::i1) {
854           setOperationAction(ISD::VP_AND, VT, Custom);
855           setOperationAction(ISD::VP_OR, VT, Custom);
856           setOperationAction(ISD::VP_XOR, VT, Custom);
857           setOperationAction(ISD::AND, VT, Custom);
858           setOperationAction(ISD::OR, VT, Custom);
859           setOperationAction(ISD::XOR, VT, Custom);
860           continue;
861         }
862 
863         // Use SPLAT_VECTOR to prevent type legalization from destroying the
864         // splats when type legalizing i64 scalar on RV32.
865         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
866         // improvements first.
867         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
868           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
869           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
870         }
871 
872         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
873         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
874 
875         setOperationAction(ISD::MLOAD, VT, Custom);
876         setOperationAction(ISD::MSTORE, VT, Custom);
877         setOperationAction(ISD::MGATHER, VT, Custom);
878         setOperationAction(ISD::MSCATTER, VT, Custom);
879 
880         setOperationAction(ISD::VP_LOAD, VT, Custom);
881         setOperationAction(ISD::VP_STORE, VT, Custom);
882         setOperationAction(ISD::VP_GATHER, VT, Custom);
883         setOperationAction(ISD::VP_SCATTER, VT, Custom);
884 
885         setOperationAction(ISD::ADD, VT, Custom);
886         setOperationAction(ISD::MUL, VT, Custom);
887         setOperationAction(ISD::SUB, VT, Custom);
888         setOperationAction(ISD::AND, VT, Custom);
889         setOperationAction(ISD::OR, VT, Custom);
890         setOperationAction(ISD::XOR, VT, Custom);
891         setOperationAction(ISD::SDIV, VT, Custom);
892         setOperationAction(ISD::SREM, VT, Custom);
893         setOperationAction(ISD::UDIV, VT, Custom);
894         setOperationAction(ISD::UREM, VT, Custom);
895         setOperationAction(ISD::SHL, VT, Custom);
896         setOperationAction(ISD::SRA, VT, Custom);
897         setOperationAction(ISD::SRL, VT, Custom);
898 
899         setOperationAction(ISD::SMIN, VT, Custom);
900         setOperationAction(ISD::SMAX, VT, Custom);
901         setOperationAction(ISD::UMIN, VT, Custom);
902         setOperationAction(ISD::UMAX, VT, Custom);
903         setOperationAction(ISD::ABS,  VT, Custom);
904 
905         setOperationAction(ISD::MULHS, VT, Custom);
906         setOperationAction(ISD::MULHU, VT, Custom);
907 
908         setOperationAction(ISD::SADDSAT, VT, Custom);
909         setOperationAction(ISD::UADDSAT, VT, Custom);
910         setOperationAction(ISD::SSUBSAT, VT, Custom);
911         setOperationAction(ISD::USUBSAT, VT, Custom);
912 
913         setOperationAction(ISD::VSELECT, VT, Custom);
914         setOperationAction(ISD::SELECT_CC, VT, Expand);
915 
916         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
917         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
918         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
919 
920         // Custom-lower reduction operations to set up the corresponding custom
921         // nodes' operands.
922         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
923         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
924         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
925         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
926         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
927 
928         for (unsigned VPOpc : IntegerVPOps)
929           setOperationAction(VPOpc, VT, Custom);
930 
931         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
932         // type that can represent the value exactly.
933         if (VT.getVectorElementType() != MVT::i64) {
934           MVT FloatEltVT =
935               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
936           EVT FloatVT =
937               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
938           if (isTypeLegal(FloatVT)) {
939             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
940             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
941           }
942         }
943       }
944 
945       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
946         if (!useRVVForFixedLengthVectorVT(VT))
947           continue;
948 
949         // By default everything must be expanded.
950         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
951           setOperationAction(Op, VT, Expand);
952         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
953           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
954           setTruncStoreAction(VT, OtherVT, Expand);
955         }
956 
957         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
958         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
959         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
960 
961         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
962         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
963         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
964         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
965         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
966 
967         setOperationAction(ISD::LOAD, VT, Custom);
968         setOperationAction(ISD::STORE, VT, Custom);
969         setOperationAction(ISD::MLOAD, VT, Custom);
970         setOperationAction(ISD::MSTORE, VT, Custom);
971         setOperationAction(ISD::MGATHER, VT, Custom);
972         setOperationAction(ISD::MSCATTER, VT, Custom);
973 
974         setOperationAction(ISD::VP_LOAD, VT, Custom);
975         setOperationAction(ISD::VP_STORE, VT, Custom);
976         setOperationAction(ISD::VP_GATHER, VT, Custom);
977         setOperationAction(ISD::VP_SCATTER, VT, Custom);
978 
979         setOperationAction(ISD::FADD, VT, Custom);
980         setOperationAction(ISD::FSUB, VT, Custom);
981         setOperationAction(ISD::FMUL, VT, Custom);
982         setOperationAction(ISD::FDIV, VT, Custom);
983         setOperationAction(ISD::FNEG, VT, Custom);
984         setOperationAction(ISD::FABS, VT, Custom);
985         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
986         setOperationAction(ISD::FSQRT, VT, Custom);
987         setOperationAction(ISD::FMA, VT, Custom);
988         setOperationAction(ISD::FMINNUM, VT, Custom);
989         setOperationAction(ISD::FMAXNUM, VT, Custom);
990 
991         setOperationAction(ISD::FP_ROUND, VT, Custom);
992         setOperationAction(ISD::FP_EXTEND, VT, Custom);
993 
994         setOperationAction(ISD::FTRUNC, VT, Custom);
995         setOperationAction(ISD::FCEIL, VT, Custom);
996         setOperationAction(ISD::FFLOOR, VT, Custom);
997 
998         for (auto CC : VFPCCToExpand)
999           setCondCodeAction(CC, VT, Expand);
1000 
1001         setOperationAction(ISD::VSELECT, VT, Custom);
1002         setOperationAction(ISD::SELECT, VT, Custom);
1003         setOperationAction(ISD::SELECT_CC, VT, Expand);
1004 
1005         setOperationAction(ISD::BITCAST, VT, Custom);
1006 
1007         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1008         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1009         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1010         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1011 
1012         for (unsigned VPOpc : FloatingPointVPOps)
1013           setOperationAction(VPOpc, VT, Custom);
1014       }
1015 
1016       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1017       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1018       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1019       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1020       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1021       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1022       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1023       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1024     }
1025   }
1026 
1027   // Function alignments.
1028   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1029   setMinFunctionAlignment(FunctionAlignment);
1030   setPrefFunctionAlignment(FunctionAlignment);
1031 
1032   setMinimumJumpTableEntries(5);
1033 
1034   // Jumps are expensive, compared to logic
1035   setJumpIsExpensive();
1036 
1037   setTargetDAGCombine(ISD::ADD);
1038   setTargetDAGCombine(ISD::SUB);
1039   setTargetDAGCombine(ISD::AND);
1040   setTargetDAGCombine(ISD::OR);
1041   setTargetDAGCombine(ISD::XOR);
1042   setTargetDAGCombine(ISD::ANY_EXTEND);
1043   setTargetDAGCombine(ISD::ZERO_EXTEND);
1044   if (Subtarget.hasVInstructions()) {
1045     setTargetDAGCombine(ISD::FCOPYSIGN);
1046     setTargetDAGCombine(ISD::MGATHER);
1047     setTargetDAGCombine(ISD::MSCATTER);
1048     setTargetDAGCombine(ISD::VP_GATHER);
1049     setTargetDAGCombine(ISD::VP_SCATTER);
1050     setTargetDAGCombine(ISD::SRA);
1051     setTargetDAGCombine(ISD::SRL);
1052     setTargetDAGCombine(ISD::SHL);
1053     setTargetDAGCombine(ISD::STORE);
1054   }
1055 }
1056 
1057 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1058                                             LLVMContext &Context,
1059                                             EVT VT) const {
1060   if (!VT.isVector())
1061     return getPointerTy(DL);
1062   if (Subtarget.hasVInstructions() &&
1063       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1064     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1065   return VT.changeVectorElementTypeToInteger();
1066 }
1067 
1068 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1069   return Subtarget.getXLenVT();
1070 }
1071 
1072 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1073                                              const CallInst &I,
1074                                              MachineFunction &MF,
1075                                              unsigned Intrinsic) const {
1076   auto &DL = I.getModule()->getDataLayout();
1077   switch (Intrinsic) {
1078   default:
1079     return false;
1080   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1081   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1082   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1083   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1084   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1085   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1086   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1087   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1088   case Intrinsic::riscv_masked_cmpxchg_i32: {
1089     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1090     Info.opc = ISD::INTRINSIC_W_CHAIN;
1091     Info.memVT = MVT::getVT(PtrTy->getElementType());
1092     Info.ptrVal = I.getArgOperand(0);
1093     Info.offset = 0;
1094     Info.align = Align(4);
1095     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1096                  MachineMemOperand::MOVolatile;
1097     return true;
1098   }
1099   case Intrinsic::riscv_masked_strided_load:
1100     Info.opc = ISD::INTRINSIC_W_CHAIN;
1101     Info.ptrVal = I.getArgOperand(1);
1102     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1103     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1104     Info.size = MemoryLocation::UnknownSize;
1105     Info.flags |= MachineMemOperand::MOLoad;
1106     return true;
1107   case Intrinsic::riscv_masked_strided_store:
1108     Info.opc = ISD::INTRINSIC_VOID;
1109     Info.ptrVal = I.getArgOperand(1);
1110     Info.memVT =
1111         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1112     Info.align = Align(
1113         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1114         8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOStore;
1117     return true;
1118   }
1119 }
1120 
1121 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1122                                                 const AddrMode &AM, Type *Ty,
1123                                                 unsigned AS,
1124                                                 Instruction *I) const {
1125   // No global is ever allowed as a base.
1126   if (AM.BaseGV)
1127     return false;
1128 
1129   // Require a 12-bit signed offset.
1130   if (!isInt<12>(AM.BaseOffs))
1131     return false;
1132 
1133   switch (AM.Scale) {
1134   case 0: // "r+i" or just "i", depending on HasBaseReg.
1135     break;
1136   case 1:
1137     if (!AM.HasBaseReg) // allow "r+i".
1138       break;
1139     return false; // disallow "r+r" or "r+r+i".
1140   default:
1141     return false;
1142   }
1143 
1144   return true;
1145 }
1146 
1147 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1148   return isInt<12>(Imm);
1149 }
1150 
1151 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1152   return isInt<12>(Imm);
1153 }
1154 
1155 // On RV32, 64-bit integers are split into their high and low parts and held
1156 // in two different registers, so the trunc is free since the low register can
1157 // just be used.
1158 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1159   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1160     return false;
1161   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1162   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1163   return (SrcBits == 64 && DestBits == 32);
1164 }
1165 
1166 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1167   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1168       !SrcVT.isInteger() || !DstVT.isInteger())
1169     return false;
1170   unsigned SrcBits = SrcVT.getSizeInBits();
1171   unsigned DestBits = DstVT.getSizeInBits();
1172   return (SrcBits == 64 && DestBits == 32);
1173 }
1174 
1175 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1176   // Zexts are free if they can be combined with a load.
1177   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1178     EVT MemVT = LD->getMemoryVT();
1179     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1180          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1181         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1182          LD->getExtensionType() == ISD::ZEXTLOAD))
1183       return true;
1184   }
1185 
1186   return TargetLowering::isZExtFree(Val, VT2);
1187 }
1188 
1189 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1190   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1191 }
1192 
1193 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1194   return Subtarget.hasStdExtZbb();
1195 }
1196 
1197 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1198   return Subtarget.hasStdExtZbb();
1199 }
1200 
1201 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1202   EVT VT = Y.getValueType();
1203 
1204   // FIXME: Support vectors once we have tests.
1205   if (VT.isVector())
1206     return false;
1207 
1208   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1209 }
1210 
1211 /// Check if sinking \p I's operands to I's basic block is profitable, because
1212 /// the operands can be folded into a target instruction, e.g.
1213 /// splats of scalars can fold into vector instructions.
1214 bool RISCVTargetLowering::shouldSinkOperands(
1215     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1216   using namespace llvm::PatternMatch;
1217 
1218   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1219     return false;
1220 
1221   auto IsSinker = [&](Instruction *I, int Operand) {
1222     switch (I->getOpcode()) {
1223     case Instruction::Add:
1224     case Instruction::Sub:
1225     case Instruction::Mul:
1226     case Instruction::And:
1227     case Instruction::Or:
1228     case Instruction::Xor:
1229     case Instruction::FAdd:
1230     case Instruction::FSub:
1231     case Instruction::FMul:
1232     case Instruction::FDiv:
1233     case Instruction::ICmp:
1234     case Instruction::FCmp:
1235       return true;
1236     case Instruction::Shl:
1237     case Instruction::LShr:
1238     case Instruction::AShr:
1239     case Instruction::UDiv:
1240     case Instruction::SDiv:
1241     case Instruction::URem:
1242     case Instruction::SRem:
1243       return Operand == 1;
1244     case Instruction::Call:
1245       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1246         switch (II->getIntrinsicID()) {
1247         case Intrinsic::fma:
1248           return Operand == 0 || Operand == 1;
1249         default:
1250           return false;
1251         }
1252       }
1253       return false;
1254     default:
1255       return false;
1256     }
1257   };
1258 
1259   for (auto OpIdx : enumerate(I->operands())) {
1260     if (!IsSinker(I, OpIdx.index()))
1261       continue;
1262 
1263     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1264     // Make sure we are not already sinking this operand
1265     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1266       continue;
1267 
1268     // We are looking for a splat that can be sunk.
1269     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1270                              m_Undef(), m_ZeroMask())))
1271       continue;
1272 
1273     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1274     // and vector registers
1275     for (Use &U : Op->uses()) {
1276       Instruction *Insn = cast<Instruction>(U.getUser());
1277       if (!IsSinker(Insn, U.getOperandNo()))
1278         return false;
1279     }
1280 
1281     Ops.push_back(&Op->getOperandUse(0));
1282     Ops.push_back(&OpIdx.value());
1283   }
1284   return true;
1285 }
1286 
1287 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1288                                        bool ForCodeSize) const {
1289   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1290   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1291     return false;
1292   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1293     return false;
1294   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1295     return false;
1296   if (Imm.isNegZero())
1297     return false;
1298   return Imm.isZero();
1299 }
1300 
1301 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1302   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1303          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1304          (VT == MVT::f64 && Subtarget.hasStdExtD());
1305 }
1306 
1307 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1308                                                       CallingConv::ID CC,
1309                                                       EVT VT) const {
1310   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1311   // We might still end up using a GPR but that will be decided based on ABI.
1312   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1313   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1314     return MVT::f32;
1315 
1316   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1317 }
1318 
1319 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1320                                                            CallingConv::ID CC,
1321                                                            EVT VT) const {
1322   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1323   // We might still end up using a GPR but that will be decided based on ABI.
1324   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1325   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1326     return 1;
1327 
1328   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1329 }
1330 
1331 // Changes the condition code and swaps operands if necessary, so the SetCC
1332 // operation matches one of the comparisons supported directly by branches
1333 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1334 // with 1/-1.
1335 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1336                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1337   // Convert X > -1 to X >= 0.
1338   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1339     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1340     CC = ISD::SETGE;
1341     return;
1342   }
1343   // Convert X < 1 to 0 >= X.
1344   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1345     RHS = LHS;
1346     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1347     CC = ISD::SETGE;
1348     return;
1349   }
1350 
1351   switch (CC) {
1352   default:
1353     break;
1354   case ISD::SETGT:
1355   case ISD::SETLE:
1356   case ISD::SETUGT:
1357   case ISD::SETULE:
1358     CC = ISD::getSetCCSwappedOperands(CC);
1359     std::swap(LHS, RHS);
1360     break;
1361   }
1362 }
1363 
1364 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1365   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1366   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1367   if (VT.getVectorElementType() == MVT::i1)
1368     KnownSize *= 8;
1369 
1370   switch (KnownSize) {
1371   default:
1372     llvm_unreachable("Invalid LMUL.");
1373   case 8:
1374     return RISCVII::VLMUL::LMUL_F8;
1375   case 16:
1376     return RISCVII::VLMUL::LMUL_F4;
1377   case 32:
1378     return RISCVII::VLMUL::LMUL_F2;
1379   case 64:
1380     return RISCVII::VLMUL::LMUL_1;
1381   case 128:
1382     return RISCVII::VLMUL::LMUL_2;
1383   case 256:
1384     return RISCVII::VLMUL::LMUL_4;
1385   case 512:
1386     return RISCVII::VLMUL::LMUL_8;
1387   }
1388 }
1389 
1390 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1391   switch (LMul) {
1392   default:
1393     llvm_unreachable("Invalid LMUL.");
1394   case RISCVII::VLMUL::LMUL_F8:
1395   case RISCVII::VLMUL::LMUL_F4:
1396   case RISCVII::VLMUL::LMUL_F2:
1397   case RISCVII::VLMUL::LMUL_1:
1398     return RISCV::VRRegClassID;
1399   case RISCVII::VLMUL::LMUL_2:
1400     return RISCV::VRM2RegClassID;
1401   case RISCVII::VLMUL::LMUL_4:
1402     return RISCV::VRM4RegClassID;
1403   case RISCVII::VLMUL::LMUL_8:
1404     return RISCV::VRM8RegClassID;
1405   }
1406 }
1407 
1408 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1409   RISCVII::VLMUL LMUL = getLMUL(VT);
1410   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1411       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1412       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1413       LMUL == RISCVII::VLMUL::LMUL_1) {
1414     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1415                   "Unexpected subreg numbering");
1416     return RISCV::sub_vrm1_0 + Index;
1417   }
1418   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1419     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1420                   "Unexpected subreg numbering");
1421     return RISCV::sub_vrm2_0 + Index;
1422   }
1423   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1424     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1425                   "Unexpected subreg numbering");
1426     return RISCV::sub_vrm4_0 + Index;
1427   }
1428   llvm_unreachable("Invalid vector type.");
1429 }
1430 
1431 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1432   if (VT.getVectorElementType() == MVT::i1)
1433     return RISCV::VRRegClassID;
1434   return getRegClassIDForLMUL(getLMUL(VT));
1435 }
1436 
1437 // Attempt to decompose a subvector insert/extract between VecVT and
1438 // SubVecVT via subregister indices. Returns the subregister index that
1439 // can perform the subvector insert/extract with the given element index, as
1440 // well as the index corresponding to any leftover subvectors that must be
1441 // further inserted/extracted within the register class for SubVecVT.
1442 std::pair<unsigned, unsigned>
1443 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1444     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1445     const RISCVRegisterInfo *TRI) {
1446   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1447                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1448                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1449                 "Register classes not ordered");
1450   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1451   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1452   // Try to compose a subregister index that takes us from the incoming
1453   // LMUL>1 register class down to the outgoing one. At each step we half
1454   // the LMUL:
1455   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1456   // Note that this is not guaranteed to find a subregister index, such as
1457   // when we are extracting from one VR type to another.
1458   unsigned SubRegIdx = RISCV::NoSubRegister;
1459   for (const unsigned RCID :
1460        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1461     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1462       VecVT = VecVT.getHalfNumVectorElementsVT();
1463       bool IsHi =
1464           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1465       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1466                                             getSubregIndexByMVT(VecVT, IsHi));
1467       if (IsHi)
1468         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1469     }
1470   return {SubRegIdx, InsertExtractIdx};
1471 }
1472 
1473 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1474 // stores for those types.
1475 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1476   return !Subtarget.useRVVForFixedLengthVectors() ||
1477          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1478 }
1479 
1480 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1481   if (ScalarTy->isPointerTy())
1482     return true;
1483 
1484   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1485       ScalarTy->isIntegerTy(32))
1486     return true;
1487 
1488   if (ScalarTy->isIntegerTy(64))
1489     return Subtarget.hasVInstructionsI64();
1490 
1491   if (ScalarTy->isHalfTy())
1492     return Subtarget.hasVInstructionsF16();
1493   if (ScalarTy->isFloatTy())
1494     return Subtarget.hasVInstructionsF32();
1495   if (ScalarTy->isDoubleTy())
1496     return Subtarget.hasVInstructionsF64();
1497 
1498   return false;
1499 }
1500 
1501 static bool useRVVForFixedLengthVectorVT(MVT VT,
1502                                          const RISCVSubtarget &Subtarget) {
1503   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1504   if (!Subtarget.useRVVForFixedLengthVectors())
1505     return false;
1506 
1507   // We only support a set of vector types with a consistent maximum fixed size
1508   // across all supported vector element types to avoid legalization issues.
1509   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1510   // fixed-length vector type we support is 1024 bytes.
1511   if (VT.getFixedSizeInBits() > 1024 * 8)
1512     return false;
1513 
1514   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1515 
1516   MVT EltVT = VT.getVectorElementType();
1517 
1518   // Don't use RVV for vectors we cannot scalarize if required.
1519   switch (EltVT.SimpleTy) {
1520   // i1 is supported but has different rules.
1521   default:
1522     return false;
1523   case MVT::i1:
1524     // Masks can only use a single register.
1525     if (VT.getVectorNumElements() > MinVLen)
1526       return false;
1527     MinVLen /= 8;
1528     break;
1529   case MVT::i8:
1530   case MVT::i16:
1531   case MVT::i32:
1532     break;
1533   case MVT::i64:
1534     if (!Subtarget.hasVInstructionsI64())
1535       return false;
1536     break;
1537   case MVT::f16:
1538     if (!Subtarget.hasVInstructionsF16())
1539       return false;
1540     break;
1541   case MVT::f32:
1542     if (!Subtarget.hasVInstructionsF32())
1543       return false;
1544     break;
1545   case MVT::f64:
1546     if (!Subtarget.hasVInstructionsF64())
1547       return false;
1548     break;
1549   }
1550 
1551   // Reject elements larger than ELEN.
1552   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1553     return false;
1554 
1555   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1556   // Don't use RVV for types that don't fit.
1557   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1558     return false;
1559 
1560   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1561   // the base fixed length RVV support in place.
1562   if (!VT.isPow2VectorType())
1563     return false;
1564 
1565   return true;
1566 }
1567 
1568 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1569   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1570 }
1571 
1572 // Return the largest legal scalable vector type that matches VT's element type.
1573 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1574                                             const RISCVSubtarget &Subtarget) {
1575   // This may be called before legal types are setup.
1576   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1577           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1578          "Expected legal fixed length vector!");
1579 
1580   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1581   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1582 
1583   MVT EltVT = VT.getVectorElementType();
1584   switch (EltVT.SimpleTy) {
1585   default:
1586     llvm_unreachable("unexpected element type for RVV container");
1587   case MVT::i1:
1588   case MVT::i8:
1589   case MVT::i16:
1590   case MVT::i32:
1591   case MVT::i64:
1592   case MVT::f16:
1593   case MVT::f32:
1594   case MVT::f64: {
1595     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1596     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1597     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1598     unsigned NumElts =
1599         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1600     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1601     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1602     return MVT::getScalableVectorVT(EltVT, NumElts);
1603   }
1604   }
1605 }
1606 
1607 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1608                                             const RISCVSubtarget &Subtarget) {
1609   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1610                                           Subtarget);
1611 }
1612 
1613 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1614   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1615 }
1616 
1617 // Grow V to consume an entire RVV register.
1618 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1619                                        const RISCVSubtarget &Subtarget) {
1620   assert(VT.isScalableVector() &&
1621          "Expected to convert into a scalable vector!");
1622   assert(V.getValueType().isFixedLengthVector() &&
1623          "Expected a fixed length vector operand!");
1624   SDLoc DL(V);
1625   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1626   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1627 }
1628 
1629 // Shrink V so it's just big enough to maintain a VT's worth of data.
1630 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1631                                          const RISCVSubtarget &Subtarget) {
1632   assert(VT.isFixedLengthVector() &&
1633          "Expected to convert into a fixed length vector!");
1634   assert(V.getValueType().isScalableVector() &&
1635          "Expected a scalable vector operand!");
1636   SDLoc DL(V);
1637   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1638   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1639 }
1640 
1641 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1642 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1643 // the vector type that it is contained in.
1644 static std::pair<SDValue, SDValue>
1645 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1646                 const RISCVSubtarget &Subtarget) {
1647   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1648   MVT XLenVT = Subtarget.getXLenVT();
1649   SDValue VL = VecVT.isFixedLengthVector()
1650                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1651                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1652   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1653   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1654   return {Mask, VL};
1655 }
1656 
1657 // As above but assuming the given type is a scalable vector type.
1658 static std::pair<SDValue, SDValue>
1659 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1660                         const RISCVSubtarget &Subtarget) {
1661   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1662   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1663 }
1664 
1665 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1666 // of either is (currently) supported. This can get us into an infinite loop
1667 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1668 // as a ..., etc.
1669 // Until either (or both) of these can reliably lower any node, reporting that
1670 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1671 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1672 // which is not desirable.
1673 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1674     EVT VT, unsigned DefinedValues) const {
1675   return false;
1676 }
1677 
1678 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1679   // Only splats are currently supported.
1680   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1681     return true;
1682 
1683   return false;
1684 }
1685 
1686 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1687   // RISCV FP-to-int conversions saturate to the destination register size, but
1688   // don't produce 0 for nan. We can use a conversion instruction and fix the
1689   // nan case with a compare and a select.
1690   SDValue Src = Op.getOperand(0);
1691 
1692   EVT DstVT = Op.getValueType();
1693   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1694 
1695   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1696   unsigned Opc;
1697   if (SatVT == DstVT)
1698     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1699   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1700     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1701   else
1702     return SDValue();
1703   // FIXME: Support other SatVTs by clamping before or after the conversion.
1704 
1705   SDLoc DL(Op);
1706   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1707 
1708   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1709   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1710 }
1711 
1712 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1713 // and back. Taking care to avoid converting values that are nan or already
1714 // correct.
1715 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1716 // have FRM dependencies modeled yet.
1717 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1718   MVT VT = Op.getSimpleValueType();
1719   assert(VT.isVector() && "Unexpected type");
1720 
1721   SDLoc DL(Op);
1722 
1723   // Freeze the source since we are increasing the number of uses.
1724   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1725 
1726   // Truncate to integer and convert back to FP.
1727   MVT IntVT = VT.changeVectorElementTypeToInteger();
1728   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1729   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1730 
1731   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1732 
1733   if (Op.getOpcode() == ISD::FCEIL) {
1734     // If the truncated value is the greater than or equal to the original
1735     // value, we've computed the ceil. Otherwise, we went the wrong way and
1736     // need to increase by 1.
1737     // FIXME: This should use a masked operation. Handle here or in isel?
1738     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1739                                  DAG.getConstantFP(1.0, DL, VT));
1740     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1741     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1742   } else if (Op.getOpcode() == ISD::FFLOOR) {
1743     // If the truncated value is the less than or equal to the original value,
1744     // we've computed the floor. Otherwise, we went the wrong way and need to
1745     // decrease by 1.
1746     // FIXME: This should use a masked operation. Handle here or in isel?
1747     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1748                                  DAG.getConstantFP(1.0, DL, VT));
1749     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1750     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1751   }
1752 
1753   // Restore the original sign so that -0.0 is preserved.
1754   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1755 
1756   // Determine the largest integer that can be represented exactly. This and
1757   // values larger than it don't have any fractional bits so don't need to
1758   // be converted.
1759   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1760   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1761   APFloat MaxVal = APFloat(FltSem);
1762   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1763                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1764   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1765 
1766   // If abs(Src) was larger than MaxVal or nan, keep it.
1767   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1768   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1769   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1770 }
1771 
1772 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1773                                  const RISCVSubtarget &Subtarget) {
1774   MVT VT = Op.getSimpleValueType();
1775   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1776 
1777   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1778 
1779   SDLoc DL(Op);
1780   SDValue Mask, VL;
1781   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1782 
1783   unsigned Opc =
1784       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1785   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1786   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1787 }
1788 
1789 struct VIDSequence {
1790   int64_t StepNumerator;
1791   unsigned StepDenominator;
1792   int64_t Addend;
1793 };
1794 
1795 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1796 // to the (non-zero) step S and start value X. This can be then lowered as the
1797 // RVV sequence (VID * S) + X, for example.
1798 // The step S is represented as an integer numerator divided by a positive
1799 // denominator. Note that the implementation currently only identifies
1800 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1801 // cannot detect 2/3, for example.
1802 // Note that this method will also match potentially unappealing index
1803 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1804 // determine whether this is worth generating code for.
1805 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1806   unsigned NumElts = Op.getNumOperands();
1807   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1808   if (!Op.getValueType().isInteger())
1809     return None;
1810 
1811   Optional<unsigned> SeqStepDenom;
1812   Optional<int64_t> SeqStepNum, SeqAddend;
1813   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1814   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1815   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1816     // Assume undef elements match the sequence; we just have to be careful
1817     // when interpolating across them.
1818     if (Op.getOperand(Idx).isUndef())
1819       continue;
1820     // The BUILD_VECTOR must be all constants.
1821     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1822       return None;
1823 
1824     uint64_t Val = Op.getConstantOperandVal(Idx) &
1825                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1826 
1827     if (PrevElt) {
1828       // Calculate the step since the last non-undef element, and ensure
1829       // it's consistent across the entire sequence.
1830       unsigned IdxDiff = Idx - PrevElt->second;
1831       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1832 
1833       // A zero-value value difference means that we're somewhere in the middle
1834       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1835       // step change before evaluating the sequence.
1836       if (ValDiff != 0) {
1837         int64_t Remainder = ValDiff % IdxDiff;
1838         // Normalize the step if it's greater than 1.
1839         if (Remainder != ValDiff) {
1840           // The difference must cleanly divide the element span.
1841           if (Remainder != 0)
1842             return None;
1843           ValDiff /= IdxDiff;
1844           IdxDiff = 1;
1845         }
1846 
1847         if (!SeqStepNum)
1848           SeqStepNum = ValDiff;
1849         else if (ValDiff != SeqStepNum)
1850           return None;
1851 
1852         if (!SeqStepDenom)
1853           SeqStepDenom = IdxDiff;
1854         else if (IdxDiff != *SeqStepDenom)
1855           return None;
1856       }
1857     }
1858 
1859     // Record and/or check any addend.
1860     if (SeqStepNum && SeqStepDenom) {
1861       uint64_t ExpectedVal =
1862           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1863       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1864       if (!SeqAddend)
1865         SeqAddend = Addend;
1866       else if (SeqAddend != Addend)
1867         return None;
1868     }
1869 
1870     // Record this non-undef element for later.
1871     if (!PrevElt || PrevElt->first != Val)
1872       PrevElt = std::make_pair(Val, Idx);
1873   }
1874   // We need to have logged both a step and an addend for this to count as
1875   // a legal index sequence.
1876   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1877     return None;
1878 
1879   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1880 }
1881 
1882 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1883                                  const RISCVSubtarget &Subtarget) {
1884   MVT VT = Op.getSimpleValueType();
1885   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1886 
1887   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1888 
1889   SDLoc DL(Op);
1890   SDValue Mask, VL;
1891   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1892 
1893   MVT XLenVT = Subtarget.getXLenVT();
1894   unsigned NumElts = Op.getNumOperands();
1895 
1896   if (VT.getVectorElementType() == MVT::i1) {
1897     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1898       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1899       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1900     }
1901 
1902     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1903       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1904       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1905     }
1906 
1907     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1908     // scalar integer chunks whose bit-width depends on the number of mask
1909     // bits and XLEN.
1910     // First, determine the most appropriate scalar integer type to use. This
1911     // is at most XLenVT, but may be shrunk to a smaller vector element type
1912     // according to the size of the final vector - use i8 chunks rather than
1913     // XLenVT if we're producing a v8i1. This results in more consistent
1914     // codegen across RV32 and RV64.
1915     unsigned NumViaIntegerBits =
1916         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1917     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1918       // If we have to use more than one INSERT_VECTOR_ELT then this
1919       // optimization is likely to increase code size; avoid peforming it in
1920       // such a case. We can use a load from a constant pool in this case.
1921       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1922         return SDValue();
1923       // Now we can create our integer vector type. Note that it may be larger
1924       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1925       MVT IntegerViaVecVT =
1926           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1927                            divideCeil(NumElts, NumViaIntegerBits));
1928 
1929       uint64_t Bits = 0;
1930       unsigned BitPos = 0, IntegerEltIdx = 0;
1931       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1932 
1933       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1934         // Once we accumulate enough bits to fill our scalar type, insert into
1935         // our vector and clear our accumulated data.
1936         if (I != 0 && I % NumViaIntegerBits == 0) {
1937           if (NumViaIntegerBits <= 32)
1938             Bits = SignExtend64(Bits, 32);
1939           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1940           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1941                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1942           Bits = 0;
1943           BitPos = 0;
1944           IntegerEltIdx++;
1945         }
1946         SDValue V = Op.getOperand(I);
1947         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1948         Bits |= ((uint64_t)BitValue << BitPos);
1949       }
1950 
1951       // Insert the (remaining) scalar value into position in our integer
1952       // vector type.
1953       if (NumViaIntegerBits <= 32)
1954         Bits = SignExtend64(Bits, 32);
1955       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1956       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1957                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1958 
1959       if (NumElts < NumViaIntegerBits) {
1960         // If we're producing a smaller vector than our minimum legal integer
1961         // type, bitcast to the equivalent (known-legal) mask type, and extract
1962         // our final mask.
1963         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1964         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1965         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1966                           DAG.getConstant(0, DL, XLenVT));
1967       } else {
1968         // Else we must have produced an integer type with the same size as the
1969         // mask type; bitcast for the final result.
1970         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1971         Vec = DAG.getBitcast(VT, Vec);
1972       }
1973 
1974       return Vec;
1975     }
1976 
1977     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1978     // vector type, we have a legal equivalently-sized i8 type, so we can use
1979     // that.
1980     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1981     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1982 
1983     SDValue WideVec;
1984     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1985       // For a splat, perform a scalar truncate before creating the wider
1986       // vector.
1987       assert(Splat.getValueType() == XLenVT &&
1988              "Unexpected type for i1 splat value");
1989       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1990                           DAG.getConstant(1, DL, XLenVT));
1991       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1992     } else {
1993       SmallVector<SDValue, 8> Ops(Op->op_values());
1994       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1995       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1996       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1997     }
1998 
1999     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2000   }
2001 
2002   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2003     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2004                                         : RISCVISD::VMV_V_X_VL;
2005     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2006     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2007   }
2008 
2009   // Try and match index sequences, which we can lower to the vid instruction
2010   // with optional modifications. An all-undef vector is matched by
2011   // getSplatValue, above.
2012   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2013     int64_t StepNumerator = SimpleVID->StepNumerator;
2014     unsigned StepDenominator = SimpleVID->StepDenominator;
2015     int64_t Addend = SimpleVID->Addend;
2016 
2017     assert(StepNumerator != 0 && "Invalid step");
2018     bool Negate = false;
2019     int64_t SplatStepVal = StepNumerator;
2020     unsigned StepOpcode = ISD::MUL;
2021     if (StepNumerator != 1) {
2022       if (isPowerOf2_64(std::abs(StepNumerator))) {
2023         Negate = StepNumerator < 0;
2024         StepOpcode = ISD::SHL;
2025         SplatStepVal = Log2_64(std::abs(StepNumerator));
2026       }
2027     }
2028 
2029     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2030     // threshold since it's the immediate value many RVV instructions accept.
2031     // There is no vmul.vi instruction so ensure multiply constant can fit in
2032     // a single addi instruction.
2033     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2034          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2035         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2036       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2037       // Convert right out of the scalable type so we can use standard ISD
2038       // nodes for the rest of the computation. If we used scalable types with
2039       // these, we'd lose the fixed-length vector info and generate worse
2040       // vsetvli code.
2041       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2042       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2043           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2044         SDValue SplatStep = DAG.getSplatVector(
2045             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2046         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2047       }
2048       if (StepDenominator != 1) {
2049         SDValue SplatStep = DAG.getSplatVector(
2050             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2051         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2052       }
2053       if (Addend != 0 || Negate) {
2054         SDValue SplatAddend =
2055             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2056         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2057       }
2058       return VID;
2059     }
2060   }
2061 
2062   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2063   // when re-interpreted as a vector with a larger element type. For example,
2064   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2065   // could be instead splat as
2066   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2067   // TODO: This optimization could also work on non-constant splats, but it
2068   // would require bit-manipulation instructions to construct the splat value.
2069   SmallVector<SDValue> Sequence;
2070   unsigned EltBitSize = VT.getScalarSizeInBits();
2071   const auto *BV = cast<BuildVectorSDNode>(Op);
2072   if (VT.isInteger() && EltBitSize < 64 &&
2073       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2074       BV->getRepeatedSequence(Sequence) &&
2075       (Sequence.size() * EltBitSize) <= 64) {
2076     unsigned SeqLen = Sequence.size();
2077     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2078     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2079     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2080             ViaIntVT == MVT::i64) &&
2081            "Unexpected sequence type");
2082 
2083     unsigned EltIdx = 0;
2084     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2085     uint64_t SplatValue = 0;
2086     // Construct the amalgamated value which can be splatted as this larger
2087     // vector type.
2088     for (const auto &SeqV : Sequence) {
2089       if (!SeqV.isUndef())
2090         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2091                        << (EltIdx * EltBitSize));
2092       EltIdx++;
2093     }
2094 
2095     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2096     // achieve better constant materializion.
2097     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2098       SplatValue = SignExtend64(SplatValue, 32);
2099 
2100     // Since we can't introduce illegal i64 types at this stage, we can only
2101     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2102     // way we can use RVV instructions to splat.
2103     assert((ViaIntVT.bitsLE(XLenVT) ||
2104             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2105            "Unexpected bitcast sequence");
2106     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2107       SDValue ViaVL =
2108           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2109       MVT ViaContainerVT =
2110           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2111       SDValue Splat =
2112           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2113                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2114       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2115       return DAG.getBitcast(VT, Splat);
2116     }
2117   }
2118 
2119   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2120   // which constitute a large proportion of the elements. In such cases we can
2121   // splat a vector with the dominant element and make up the shortfall with
2122   // INSERT_VECTOR_ELTs.
2123   // Note that this includes vectors of 2 elements by association. The
2124   // upper-most element is the "dominant" one, allowing us to use a splat to
2125   // "insert" the upper element, and an insert of the lower element at position
2126   // 0, which improves codegen.
2127   SDValue DominantValue;
2128   unsigned MostCommonCount = 0;
2129   DenseMap<SDValue, unsigned> ValueCounts;
2130   unsigned NumUndefElts =
2131       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2132 
2133   // Track the number of scalar loads we know we'd be inserting, estimated as
2134   // any non-zero floating-point constant. Other kinds of element are either
2135   // already in registers or are materialized on demand. The threshold at which
2136   // a vector load is more desirable than several scalar materializion and
2137   // vector-insertion instructions is not known.
2138   unsigned NumScalarLoads = 0;
2139 
2140   for (SDValue V : Op->op_values()) {
2141     if (V.isUndef())
2142       continue;
2143 
2144     ValueCounts.insert(std::make_pair(V, 0));
2145     unsigned &Count = ValueCounts[V];
2146 
2147     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2148       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2149 
2150     // Is this value dominant? In case of a tie, prefer the highest element as
2151     // it's cheaper to insert near the beginning of a vector than it is at the
2152     // end.
2153     if (++Count >= MostCommonCount) {
2154       DominantValue = V;
2155       MostCommonCount = Count;
2156     }
2157   }
2158 
2159   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2160   unsigned NumDefElts = NumElts - NumUndefElts;
2161   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2162 
2163   // Don't perform this optimization when optimizing for size, since
2164   // materializing elements and inserting them tends to cause code bloat.
2165   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2166       ((MostCommonCount > DominantValueCountThreshold) ||
2167        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2168     // Start by splatting the most common element.
2169     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2170 
2171     DenseSet<SDValue> Processed{DominantValue};
2172     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2173     for (const auto &OpIdx : enumerate(Op->ops())) {
2174       const SDValue &V = OpIdx.value();
2175       if (V.isUndef() || !Processed.insert(V).second)
2176         continue;
2177       if (ValueCounts[V] == 1) {
2178         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2179                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2180       } else {
2181         // Blend in all instances of this value using a VSELECT, using a
2182         // mask where each bit signals whether that element is the one
2183         // we're after.
2184         SmallVector<SDValue> Ops;
2185         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2186           return DAG.getConstant(V == V1, DL, XLenVT);
2187         });
2188         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2189                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2190                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2191       }
2192     }
2193 
2194     return Vec;
2195   }
2196 
2197   return SDValue();
2198 }
2199 
2200 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2201                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2202   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2203     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2204     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2205     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2206     // node in order to try and match RVV vector/scalar instructions.
2207     if ((LoC >> 31) == HiC)
2208       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2209   }
2210 
2211   // Fall back to a stack store and stride x0 vector load.
2212   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2213 }
2214 
2215 // Called by type legalization to handle splat of i64 on RV32.
2216 // FIXME: We can optimize this when the type has sign or zero bits in one
2217 // of the halves.
2218 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2219                                    SDValue VL, SelectionDAG &DAG) {
2220   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2221   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2222                            DAG.getConstant(0, DL, MVT::i32));
2223   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2224                            DAG.getConstant(1, DL, MVT::i32));
2225   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2226 }
2227 
2228 // This function lowers a splat of a scalar operand Splat with the vector
2229 // length VL. It ensures the final sequence is type legal, which is useful when
2230 // lowering a splat after type legalization.
2231 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2232                                 SelectionDAG &DAG,
2233                                 const RISCVSubtarget &Subtarget) {
2234   if (VT.isFloatingPoint())
2235     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2236 
2237   MVT XLenVT = Subtarget.getXLenVT();
2238 
2239   // Simplest case is that the operand needs to be promoted to XLenVT.
2240   if (Scalar.getValueType().bitsLE(XLenVT)) {
2241     // If the operand is a constant, sign extend to increase our chances
2242     // of being able to use a .vi instruction. ANY_EXTEND would become a
2243     // a zero extend and the simm5 check in isel would fail.
2244     // FIXME: Should we ignore the upper bits in isel instead?
2245     unsigned ExtOpc =
2246         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2247     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2248     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2249   }
2250 
2251   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2252          "Unexpected scalar for splat lowering!");
2253 
2254   // Otherwise use the more complicated splatting algorithm.
2255   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2256 }
2257 
2258 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2259                                    const RISCVSubtarget &Subtarget) {
2260   SDValue V1 = Op.getOperand(0);
2261   SDValue V2 = Op.getOperand(1);
2262   SDLoc DL(Op);
2263   MVT XLenVT = Subtarget.getXLenVT();
2264   MVT VT = Op.getSimpleValueType();
2265   unsigned NumElts = VT.getVectorNumElements();
2266   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2267 
2268   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2269 
2270   SDValue TrueMask, VL;
2271   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2272 
2273   if (SVN->isSplat()) {
2274     const int Lane = SVN->getSplatIndex();
2275     if (Lane >= 0) {
2276       MVT SVT = VT.getVectorElementType();
2277 
2278       // Turn splatted vector load into a strided load with an X0 stride.
2279       SDValue V = V1;
2280       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2281       // with undef.
2282       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2283       int Offset = Lane;
2284       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2285         int OpElements =
2286             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2287         V = V.getOperand(Offset / OpElements);
2288         Offset %= OpElements;
2289       }
2290 
2291       // We need to ensure the load isn't atomic or volatile.
2292       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2293         auto *Ld = cast<LoadSDNode>(V);
2294         Offset *= SVT.getStoreSize();
2295         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2296                                                    TypeSize::Fixed(Offset), DL);
2297 
2298         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2299         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2300           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2301           SDValue IntID =
2302               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2303           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2304                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2305           SDValue NewLoad = DAG.getMemIntrinsicNode(
2306               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2307               DAG.getMachineFunction().getMachineMemOperand(
2308                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2309           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2310           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2311         }
2312 
2313         // Otherwise use a scalar load and splat. This will give the best
2314         // opportunity to fold a splat into the operation. ISel can turn it into
2315         // the x0 strided load if we aren't able to fold away the select.
2316         if (SVT.isFloatingPoint())
2317           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2318                           Ld->getPointerInfo().getWithOffset(Offset),
2319                           Ld->getOriginalAlign(),
2320                           Ld->getMemOperand()->getFlags());
2321         else
2322           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2323                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2324                              Ld->getOriginalAlign(),
2325                              Ld->getMemOperand()->getFlags());
2326         DAG.makeEquivalentMemoryOrdering(Ld, V);
2327 
2328         unsigned Opc =
2329             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2330         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2331         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2332       }
2333 
2334       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2335       assert(Lane < (int)NumElts && "Unexpected lane!");
2336       SDValue Gather =
2337           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2338                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2339       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2340     }
2341   }
2342 
2343   // Detect shuffles which can be re-expressed as vector selects; these are
2344   // shuffles in which each element in the destination is taken from an element
2345   // at the corresponding index in either source vectors.
2346   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2347     int MaskIndex = MaskIdx.value();
2348     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2349   });
2350 
2351   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2352 
2353   SmallVector<SDValue> MaskVals;
2354   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2355   // merged with a second vrgather.
2356   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2357 
2358   // By default we preserve the original operand order, and use a mask to
2359   // select LHS as true and RHS as false. However, since RVV vector selects may
2360   // feature splats but only on the LHS, we may choose to invert our mask and
2361   // instead select between RHS and LHS.
2362   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2363   bool InvertMask = IsSelect == SwapOps;
2364 
2365   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2366   // half.
2367   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2368 
2369   // Now construct the mask that will be used by the vselect or blended
2370   // vrgather operation. For vrgathers, construct the appropriate indices into
2371   // each vector.
2372   for (int MaskIndex : SVN->getMask()) {
2373     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2374     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2375     if (!IsSelect) {
2376       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2377       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2378                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2379                                      : DAG.getUNDEF(XLenVT));
2380       GatherIndicesRHS.push_back(
2381           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2382                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2383       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2384         ++LHSIndexCounts[MaskIndex];
2385       if (!IsLHSOrUndefIndex)
2386         ++RHSIndexCounts[MaskIndex - NumElts];
2387     }
2388   }
2389 
2390   if (SwapOps) {
2391     std::swap(V1, V2);
2392     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2393   }
2394 
2395   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2396   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2397   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2398 
2399   if (IsSelect)
2400     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2401 
2402   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2403     // On such a large vector we're unable to use i8 as the index type.
2404     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2405     // may involve vector splitting if we're already at LMUL=8, or our
2406     // user-supplied maximum fixed-length LMUL.
2407     return SDValue();
2408   }
2409 
2410   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2411   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2412   MVT IndexVT = VT.changeTypeToInteger();
2413   // Since we can't introduce illegal index types at this stage, use i16 and
2414   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2415   // than XLenVT.
2416   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2417     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2418     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2419   }
2420 
2421   MVT IndexContainerVT =
2422       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2423 
2424   SDValue Gather;
2425   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2426   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2427   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2428     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2429   } else {
2430     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2431     // If only one index is used, we can use a "splat" vrgather.
2432     // TODO: We can splat the most-common index and fix-up any stragglers, if
2433     // that's beneficial.
2434     if (LHSIndexCounts.size() == 1) {
2435       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2436       Gather =
2437           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2438                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2439     } else {
2440       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2441       LHSIndices =
2442           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2443 
2444       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2445                            TrueMask, VL);
2446     }
2447   }
2448 
2449   // If a second vector operand is used by this shuffle, blend it in with an
2450   // additional vrgather.
2451   if (!V2.isUndef()) {
2452     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2453     // If only one index is used, we can use a "splat" vrgather.
2454     // TODO: We can splat the most-common index and fix-up any stragglers, if
2455     // that's beneficial.
2456     if (RHSIndexCounts.size() == 1) {
2457       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2458       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2459                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2460     } else {
2461       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2462       RHSIndices =
2463           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2464       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2465                        VL);
2466     }
2467 
2468     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2469     SelectMask =
2470         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2471 
2472     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2473                          Gather, VL);
2474   }
2475 
2476   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2477 }
2478 
2479 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2480                                      SDLoc DL, SelectionDAG &DAG,
2481                                      const RISCVSubtarget &Subtarget) {
2482   if (VT.isScalableVector())
2483     return DAG.getFPExtendOrRound(Op, DL, VT);
2484   assert(VT.isFixedLengthVector() &&
2485          "Unexpected value type for RVV FP extend/round lowering");
2486   SDValue Mask, VL;
2487   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2488   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2489                         ? RISCVISD::FP_EXTEND_VL
2490                         : RISCVISD::FP_ROUND_VL;
2491   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2492 }
2493 
2494 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2495 // the exponent.
2496 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2497   MVT VT = Op.getSimpleValueType();
2498   unsigned EltSize = VT.getScalarSizeInBits();
2499   SDValue Src = Op.getOperand(0);
2500   SDLoc DL(Op);
2501 
2502   // We need a FP type that can represent the value.
2503   // TODO: Use f16 for i8 when possible?
2504   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2505   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2506 
2507   // Legal types should have been checked in the RISCVTargetLowering
2508   // constructor.
2509   // TODO: Splitting may make sense in some cases.
2510   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2511          "Expected legal float type!");
2512 
2513   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2514   // The trailing zero count is equal to log2 of this single bit value.
2515   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2516     SDValue Neg =
2517         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2518     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2519   }
2520 
2521   // We have a legal FP type, convert to it.
2522   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2523   // Bitcast to integer and shift the exponent to the LSB.
2524   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2525   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2526   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2527   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2528                               DAG.getConstant(ShiftAmt, DL, IntVT));
2529   // Truncate back to original type to allow vnsrl.
2530   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2531   // The exponent contains log2 of the value in biased form.
2532   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2533 
2534   // For trailing zeros, we just need to subtract the bias.
2535   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2536     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2537                        DAG.getConstant(ExponentBias, DL, VT));
2538 
2539   // For leading zeros, we need to remove the bias and convert from log2 to
2540   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2541   unsigned Adjust = ExponentBias + (EltSize - 1);
2542   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2543 }
2544 
2545 // While RVV has alignment restrictions, we should always be able to load as a
2546 // legal equivalently-sized byte-typed vector instead. This method is
2547 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2548 // the load is already correctly-aligned, it returns SDValue().
2549 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2550                                                     SelectionDAG &DAG) const {
2551   auto *Load = cast<LoadSDNode>(Op);
2552   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2553 
2554   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2555                                      Load->getMemoryVT(),
2556                                      *Load->getMemOperand()))
2557     return SDValue();
2558 
2559   SDLoc DL(Op);
2560   MVT VT = Op.getSimpleValueType();
2561   unsigned EltSizeBits = VT.getScalarSizeInBits();
2562   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2563          "Unexpected unaligned RVV load type");
2564   MVT NewVT =
2565       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2566   assert(NewVT.isValid() &&
2567          "Expecting equally-sized RVV vector types to be legal");
2568   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2569                           Load->getPointerInfo(), Load->getOriginalAlign(),
2570                           Load->getMemOperand()->getFlags());
2571   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2572 }
2573 
2574 // While RVV has alignment restrictions, we should always be able to store as a
2575 // legal equivalently-sized byte-typed vector instead. This method is
2576 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2577 // returns SDValue() if the store is already correctly aligned.
2578 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2579                                                      SelectionDAG &DAG) const {
2580   auto *Store = cast<StoreSDNode>(Op);
2581   assert(Store && Store->getValue().getValueType().isVector() &&
2582          "Expected vector store");
2583 
2584   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2585                                      Store->getMemoryVT(),
2586                                      *Store->getMemOperand()))
2587     return SDValue();
2588 
2589   SDLoc DL(Op);
2590   SDValue StoredVal = Store->getValue();
2591   MVT VT = StoredVal.getSimpleValueType();
2592   unsigned EltSizeBits = VT.getScalarSizeInBits();
2593   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2594          "Unexpected unaligned RVV store type");
2595   MVT NewVT =
2596       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2597   assert(NewVT.isValid() &&
2598          "Expecting equally-sized RVV vector types to be legal");
2599   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2600   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2601                       Store->getPointerInfo(), Store->getOriginalAlign(),
2602                       Store->getMemOperand()->getFlags());
2603 }
2604 
2605 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2606                                             SelectionDAG &DAG) const {
2607   switch (Op.getOpcode()) {
2608   default:
2609     report_fatal_error("unimplemented operand");
2610   case ISD::GlobalAddress:
2611     return lowerGlobalAddress(Op, DAG);
2612   case ISD::BlockAddress:
2613     return lowerBlockAddress(Op, DAG);
2614   case ISD::ConstantPool:
2615     return lowerConstantPool(Op, DAG);
2616   case ISD::JumpTable:
2617     return lowerJumpTable(Op, DAG);
2618   case ISD::GlobalTLSAddress:
2619     return lowerGlobalTLSAddress(Op, DAG);
2620   case ISD::SELECT:
2621     return lowerSELECT(Op, DAG);
2622   case ISD::BRCOND:
2623     return lowerBRCOND(Op, DAG);
2624   case ISD::VASTART:
2625     return lowerVASTART(Op, DAG);
2626   case ISD::FRAMEADDR:
2627     return lowerFRAMEADDR(Op, DAG);
2628   case ISD::RETURNADDR:
2629     return lowerRETURNADDR(Op, DAG);
2630   case ISD::SHL_PARTS:
2631     return lowerShiftLeftParts(Op, DAG);
2632   case ISD::SRA_PARTS:
2633     return lowerShiftRightParts(Op, DAG, true);
2634   case ISD::SRL_PARTS:
2635     return lowerShiftRightParts(Op, DAG, false);
2636   case ISD::BITCAST: {
2637     SDLoc DL(Op);
2638     EVT VT = Op.getValueType();
2639     SDValue Op0 = Op.getOperand(0);
2640     EVT Op0VT = Op0.getValueType();
2641     MVT XLenVT = Subtarget.getXLenVT();
2642     if (VT.isFixedLengthVector()) {
2643       // We can handle fixed length vector bitcasts with a simple replacement
2644       // in isel.
2645       if (Op0VT.isFixedLengthVector())
2646         return Op;
2647       // When bitcasting from scalar to fixed-length vector, insert the scalar
2648       // into a one-element vector of the result type, and perform a vector
2649       // bitcast.
2650       if (!Op0VT.isVector()) {
2651         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2652         if (!isTypeLegal(BVT))
2653           return SDValue();
2654         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2655                                               DAG.getUNDEF(BVT), Op0,
2656                                               DAG.getConstant(0, DL, XLenVT)));
2657       }
2658       return SDValue();
2659     }
2660     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2661     // thus: bitcast the vector to a one-element vector type whose element type
2662     // is the same as the result type, and extract the first element.
2663     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2664       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2665       if (!isTypeLegal(BVT))
2666         return SDValue();
2667       SDValue BVec = DAG.getBitcast(BVT, Op0);
2668       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2669                          DAG.getConstant(0, DL, XLenVT));
2670     }
2671     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2672       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2673       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2674       return FPConv;
2675     }
2676     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2677         Subtarget.hasStdExtF()) {
2678       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2679       SDValue FPConv =
2680           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2681       return FPConv;
2682     }
2683     return SDValue();
2684   }
2685   case ISD::INTRINSIC_WO_CHAIN:
2686     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2687   case ISD::INTRINSIC_W_CHAIN:
2688     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2689   case ISD::INTRINSIC_VOID:
2690     return LowerINTRINSIC_VOID(Op, DAG);
2691   case ISD::BSWAP:
2692   case ISD::BITREVERSE: {
2693     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2694     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2695     MVT VT = Op.getSimpleValueType();
2696     SDLoc DL(Op);
2697     // Start with the maximum immediate value which is the bitwidth - 1.
2698     unsigned Imm = VT.getSizeInBits() - 1;
2699     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2700     if (Op.getOpcode() == ISD::BSWAP)
2701       Imm &= ~0x7U;
2702     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2703                        DAG.getConstant(Imm, DL, VT));
2704   }
2705   case ISD::FSHL:
2706   case ISD::FSHR: {
2707     MVT VT = Op.getSimpleValueType();
2708     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2709     SDLoc DL(Op);
2710     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2711       return Op;
2712     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2713     // use log(XLen) bits. Mask the shift amount accordingly.
2714     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2715     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2716                                 DAG.getConstant(ShAmtWidth, DL, VT));
2717     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2718     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2719   }
2720   case ISD::TRUNCATE: {
2721     SDLoc DL(Op);
2722     MVT VT = Op.getSimpleValueType();
2723     // Only custom-lower vector truncates
2724     if (!VT.isVector())
2725       return Op;
2726 
2727     // Truncates to mask types are handled differently
2728     if (VT.getVectorElementType() == MVT::i1)
2729       return lowerVectorMaskTrunc(Op, DAG);
2730 
2731     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2732     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2733     // truncate by one power of two at a time.
2734     MVT DstEltVT = VT.getVectorElementType();
2735 
2736     SDValue Src = Op.getOperand(0);
2737     MVT SrcVT = Src.getSimpleValueType();
2738     MVT SrcEltVT = SrcVT.getVectorElementType();
2739 
2740     assert(DstEltVT.bitsLT(SrcEltVT) &&
2741            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2742            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2743            "Unexpected vector truncate lowering");
2744 
2745     MVT ContainerVT = SrcVT;
2746     if (SrcVT.isFixedLengthVector()) {
2747       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2748       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2749     }
2750 
2751     SDValue Result = Src;
2752     SDValue Mask, VL;
2753     std::tie(Mask, VL) =
2754         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2755     LLVMContext &Context = *DAG.getContext();
2756     const ElementCount Count = ContainerVT.getVectorElementCount();
2757     do {
2758       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2759       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2760       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2761                            Mask, VL);
2762     } while (SrcEltVT != DstEltVT);
2763 
2764     if (SrcVT.isFixedLengthVector())
2765       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2766 
2767     return Result;
2768   }
2769   case ISD::ANY_EXTEND:
2770   case ISD::ZERO_EXTEND:
2771     if (Op.getOperand(0).getValueType().isVector() &&
2772         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2773       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2774     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2775   case ISD::SIGN_EXTEND:
2776     if (Op.getOperand(0).getValueType().isVector() &&
2777         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2778       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2779     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2780   case ISD::SPLAT_VECTOR_PARTS:
2781     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2782   case ISD::INSERT_VECTOR_ELT:
2783     return lowerINSERT_VECTOR_ELT(Op, DAG);
2784   case ISD::EXTRACT_VECTOR_ELT:
2785     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2786   case ISD::VSCALE: {
2787     MVT VT = Op.getSimpleValueType();
2788     SDLoc DL(Op);
2789     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2790     // We define our scalable vector types for lmul=1 to use a 64 bit known
2791     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2792     // vscale as VLENB / 8.
2793     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
2794     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2795       // We assume VLENB is a multiple of 8. We manually choose the best shift
2796       // here because SimplifyDemandedBits isn't always able to simplify it.
2797       uint64_t Val = Op.getConstantOperandVal(0);
2798       if (isPowerOf2_64(Val)) {
2799         uint64_t Log2 = Log2_64(Val);
2800         if (Log2 < 3)
2801           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2802                              DAG.getConstant(3 - Log2, DL, VT));
2803         if (Log2 > 3)
2804           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2805                              DAG.getConstant(Log2 - 3, DL, VT));
2806         return VLENB;
2807       }
2808       // If the multiplier is a multiple of 8, scale it down to avoid needing
2809       // to shift the VLENB value.
2810       if ((Val % 8) == 0)
2811         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2812                            DAG.getConstant(Val / 8, DL, VT));
2813     }
2814 
2815     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2816                                  DAG.getConstant(3, DL, VT));
2817     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2818   }
2819   case ISD::FPOWI: {
2820     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2821     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2822     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2823         Op.getOperand(1).getValueType() == MVT::i32) {
2824       SDLoc DL(Op);
2825       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2826       SDValue Powi =
2827           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2828       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2829                          DAG.getIntPtrConstant(0, DL));
2830     }
2831     return SDValue();
2832   }
2833   case ISD::FP_EXTEND: {
2834     // RVV can only do fp_extend to types double the size as the source. We
2835     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2836     // via f32.
2837     SDLoc DL(Op);
2838     MVT VT = Op.getSimpleValueType();
2839     SDValue Src = Op.getOperand(0);
2840     MVT SrcVT = Src.getSimpleValueType();
2841 
2842     // Prepare any fixed-length vector operands.
2843     MVT ContainerVT = VT;
2844     if (SrcVT.isFixedLengthVector()) {
2845       ContainerVT = getContainerForFixedLengthVector(VT);
2846       MVT SrcContainerVT =
2847           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2848       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2849     }
2850 
2851     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2852         SrcVT.getVectorElementType() != MVT::f16) {
2853       // For scalable vectors, we only need to close the gap between
2854       // vXf16->vXf64.
2855       if (!VT.isFixedLengthVector())
2856         return Op;
2857       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2858       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2859       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2860     }
2861 
2862     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2863     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2864     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2865         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2866 
2867     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2868                                            DL, DAG, Subtarget);
2869     if (VT.isFixedLengthVector())
2870       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2871     return Extend;
2872   }
2873   case ISD::FP_ROUND: {
2874     // RVV can only do fp_round to types half the size as the source. We
2875     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2876     // conversion instruction.
2877     SDLoc DL(Op);
2878     MVT VT = Op.getSimpleValueType();
2879     SDValue Src = Op.getOperand(0);
2880     MVT SrcVT = Src.getSimpleValueType();
2881 
2882     // Prepare any fixed-length vector operands.
2883     MVT ContainerVT = VT;
2884     if (VT.isFixedLengthVector()) {
2885       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2886       ContainerVT =
2887           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2888       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2889     }
2890 
2891     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2892         SrcVT.getVectorElementType() != MVT::f64) {
2893       // For scalable vectors, we only need to close the gap between
2894       // vXf64<->vXf16.
2895       if (!VT.isFixedLengthVector())
2896         return Op;
2897       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2898       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2899       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2900     }
2901 
2902     SDValue Mask, VL;
2903     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2904 
2905     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2906     SDValue IntermediateRound =
2907         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2908     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2909                                           DL, DAG, Subtarget);
2910 
2911     if (VT.isFixedLengthVector())
2912       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2913     return Round;
2914   }
2915   case ISD::FP_TO_SINT:
2916   case ISD::FP_TO_UINT:
2917   case ISD::SINT_TO_FP:
2918   case ISD::UINT_TO_FP: {
2919     // RVV can only do fp<->int conversions to types half/double the size as
2920     // the source. We custom-lower any conversions that do two hops into
2921     // sequences.
2922     MVT VT = Op.getSimpleValueType();
2923     if (!VT.isVector())
2924       return Op;
2925     SDLoc DL(Op);
2926     SDValue Src = Op.getOperand(0);
2927     MVT EltVT = VT.getVectorElementType();
2928     MVT SrcVT = Src.getSimpleValueType();
2929     MVT SrcEltVT = SrcVT.getVectorElementType();
2930     unsigned EltSize = EltVT.getSizeInBits();
2931     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2932     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2933            "Unexpected vector element types");
2934 
2935     bool IsInt2FP = SrcEltVT.isInteger();
2936     // Widening conversions
2937     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2938       if (IsInt2FP) {
2939         // Do a regular integer sign/zero extension then convert to float.
2940         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2941                                       VT.getVectorElementCount());
2942         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2943                                  ? ISD::ZERO_EXTEND
2944                                  : ISD::SIGN_EXTEND;
2945         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2946         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2947       }
2948       // FP2Int
2949       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2950       // Do one doubling fp_extend then complete the operation by converting
2951       // to int.
2952       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2953       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2954       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2955     }
2956 
2957     // Narrowing conversions
2958     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2959       if (IsInt2FP) {
2960         // One narrowing int_to_fp, then an fp_round.
2961         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2962         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2963         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2964         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2965       }
2966       // FP2Int
2967       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2968       // representable by the integer, the result is poison.
2969       MVT IVecVT =
2970           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2971                            VT.getVectorElementCount());
2972       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2973       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2974     }
2975 
2976     // Scalable vectors can exit here. Patterns will handle equally-sized
2977     // conversions halving/doubling ones.
2978     if (!VT.isFixedLengthVector())
2979       return Op;
2980 
2981     // For fixed-length vectors we lower to a custom "VL" node.
2982     unsigned RVVOpc = 0;
2983     switch (Op.getOpcode()) {
2984     default:
2985       llvm_unreachable("Impossible opcode");
2986     case ISD::FP_TO_SINT:
2987       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2988       break;
2989     case ISD::FP_TO_UINT:
2990       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2991       break;
2992     case ISD::SINT_TO_FP:
2993       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2994       break;
2995     case ISD::UINT_TO_FP:
2996       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2997       break;
2998     }
2999 
3000     MVT ContainerVT, SrcContainerVT;
3001     // Derive the reference container type from the larger vector type.
3002     if (SrcEltSize > EltSize) {
3003       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3004       ContainerVT =
3005           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3006     } else {
3007       ContainerVT = getContainerForFixedLengthVector(VT);
3008       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3009     }
3010 
3011     SDValue Mask, VL;
3012     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3013 
3014     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3015     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3016     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3017   }
3018   case ISD::FP_TO_SINT_SAT:
3019   case ISD::FP_TO_UINT_SAT:
3020     return lowerFP_TO_INT_SAT(Op, DAG);
3021   case ISD::FTRUNC:
3022   case ISD::FCEIL:
3023   case ISD::FFLOOR:
3024     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3025   case ISD::VECREDUCE_ADD:
3026   case ISD::VECREDUCE_UMAX:
3027   case ISD::VECREDUCE_SMAX:
3028   case ISD::VECREDUCE_UMIN:
3029   case ISD::VECREDUCE_SMIN:
3030     return lowerVECREDUCE(Op, DAG);
3031   case ISD::VECREDUCE_AND:
3032   case ISD::VECREDUCE_OR:
3033   case ISD::VECREDUCE_XOR:
3034     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3035       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3036     return lowerVECREDUCE(Op, DAG);
3037   case ISD::VECREDUCE_FADD:
3038   case ISD::VECREDUCE_SEQ_FADD:
3039   case ISD::VECREDUCE_FMIN:
3040   case ISD::VECREDUCE_FMAX:
3041     return lowerFPVECREDUCE(Op, DAG);
3042   case ISD::VP_REDUCE_ADD:
3043   case ISD::VP_REDUCE_UMAX:
3044   case ISD::VP_REDUCE_SMAX:
3045   case ISD::VP_REDUCE_UMIN:
3046   case ISD::VP_REDUCE_SMIN:
3047   case ISD::VP_REDUCE_FADD:
3048   case ISD::VP_REDUCE_SEQ_FADD:
3049   case ISD::VP_REDUCE_FMIN:
3050   case ISD::VP_REDUCE_FMAX:
3051     return lowerVPREDUCE(Op, DAG);
3052   case ISD::VP_REDUCE_AND:
3053   case ISD::VP_REDUCE_OR:
3054   case ISD::VP_REDUCE_XOR:
3055     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3056       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3057     return lowerVPREDUCE(Op, DAG);
3058   case ISD::INSERT_SUBVECTOR:
3059     return lowerINSERT_SUBVECTOR(Op, DAG);
3060   case ISD::EXTRACT_SUBVECTOR:
3061     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3062   case ISD::STEP_VECTOR:
3063     return lowerSTEP_VECTOR(Op, DAG);
3064   case ISD::VECTOR_REVERSE:
3065     return lowerVECTOR_REVERSE(Op, DAG);
3066   case ISD::BUILD_VECTOR:
3067     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3068   case ISD::SPLAT_VECTOR:
3069     if (Op.getValueType().getVectorElementType() == MVT::i1)
3070       return lowerVectorMaskSplat(Op, DAG);
3071     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3072   case ISD::VECTOR_SHUFFLE:
3073     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3074   case ISD::CONCAT_VECTORS: {
3075     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3076     // better than going through the stack, as the default expansion does.
3077     SDLoc DL(Op);
3078     MVT VT = Op.getSimpleValueType();
3079     unsigned NumOpElts =
3080         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3081     SDValue Vec = DAG.getUNDEF(VT);
3082     for (const auto &OpIdx : enumerate(Op->ops()))
3083       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3084                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3085     return Vec;
3086   }
3087   case ISD::LOAD:
3088     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3089       return V;
3090     if (Op.getValueType().isFixedLengthVector())
3091       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3092     return Op;
3093   case ISD::STORE:
3094     if (auto V = expandUnalignedRVVStore(Op, DAG))
3095       return V;
3096     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3097       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3098     return Op;
3099   case ISD::MLOAD:
3100   case ISD::VP_LOAD:
3101     return lowerMaskedLoad(Op, DAG);
3102   case ISD::MSTORE:
3103   case ISD::VP_STORE:
3104     return lowerMaskedStore(Op, DAG);
3105   case ISD::SETCC:
3106     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3107   case ISD::ADD:
3108     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3109   case ISD::SUB:
3110     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3111   case ISD::MUL:
3112     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3113   case ISD::MULHS:
3114     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3115   case ISD::MULHU:
3116     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3117   case ISD::AND:
3118     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3119                                               RISCVISD::AND_VL);
3120   case ISD::OR:
3121     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3122                                               RISCVISD::OR_VL);
3123   case ISD::XOR:
3124     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3125                                               RISCVISD::XOR_VL);
3126   case ISD::SDIV:
3127     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3128   case ISD::SREM:
3129     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3130   case ISD::UDIV:
3131     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3132   case ISD::UREM:
3133     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3134   case ISD::SHL:
3135   case ISD::SRA:
3136   case ISD::SRL:
3137     if (Op.getSimpleValueType().isFixedLengthVector())
3138       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3139     // This can be called for an i32 shift amount that needs to be promoted.
3140     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3141            "Unexpected custom legalisation");
3142     return SDValue();
3143   case ISD::SADDSAT:
3144     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3145   case ISD::UADDSAT:
3146     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3147   case ISD::SSUBSAT:
3148     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3149   case ISD::USUBSAT:
3150     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3151   case ISD::FADD:
3152     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3153   case ISD::FSUB:
3154     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3155   case ISD::FMUL:
3156     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3157   case ISD::FDIV:
3158     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3159   case ISD::FNEG:
3160     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3161   case ISD::FABS:
3162     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3163   case ISD::FSQRT:
3164     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3165   case ISD::FMA:
3166     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3167   case ISD::SMIN:
3168     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3169   case ISD::SMAX:
3170     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3171   case ISD::UMIN:
3172     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3173   case ISD::UMAX:
3174     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3175   case ISD::FMINNUM:
3176     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3177   case ISD::FMAXNUM:
3178     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3179   case ISD::ABS:
3180     return lowerABS(Op, DAG);
3181   case ISD::CTLZ_ZERO_UNDEF:
3182   case ISD::CTTZ_ZERO_UNDEF:
3183     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3184   case ISD::VSELECT:
3185     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3186   case ISD::FCOPYSIGN:
3187     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3188   case ISD::MGATHER:
3189   case ISD::VP_GATHER:
3190     return lowerMaskedGather(Op, DAG);
3191   case ISD::MSCATTER:
3192   case ISD::VP_SCATTER:
3193     return lowerMaskedScatter(Op, DAG);
3194   case ISD::FLT_ROUNDS_:
3195     return lowerGET_ROUNDING(Op, DAG);
3196   case ISD::SET_ROUNDING:
3197     return lowerSET_ROUNDING(Op, DAG);
3198   case ISD::VP_SELECT:
3199     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3200   case ISD::VP_ADD:
3201     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3202   case ISD::VP_SUB:
3203     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3204   case ISD::VP_MUL:
3205     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3206   case ISD::VP_SDIV:
3207     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3208   case ISD::VP_UDIV:
3209     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3210   case ISD::VP_SREM:
3211     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3212   case ISD::VP_UREM:
3213     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3214   case ISD::VP_AND:
3215     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3216   case ISD::VP_OR:
3217     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3218   case ISD::VP_XOR:
3219     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3220   case ISD::VP_ASHR:
3221     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3222   case ISD::VP_LSHR:
3223     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3224   case ISD::VP_SHL:
3225     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3226   case ISD::VP_FADD:
3227     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3228   case ISD::VP_FSUB:
3229     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3230   case ISD::VP_FMUL:
3231     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3232   case ISD::VP_FDIV:
3233     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3234   }
3235 }
3236 
3237 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3238                              SelectionDAG &DAG, unsigned Flags) {
3239   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3240 }
3241 
3242 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3243                              SelectionDAG &DAG, unsigned Flags) {
3244   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3245                                    Flags);
3246 }
3247 
3248 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3249                              SelectionDAG &DAG, unsigned Flags) {
3250   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3251                                    N->getOffset(), Flags);
3252 }
3253 
3254 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3255                              SelectionDAG &DAG, unsigned Flags) {
3256   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3257 }
3258 
3259 template <class NodeTy>
3260 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3261                                      bool IsLocal) const {
3262   SDLoc DL(N);
3263   EVT Ty = getPointerTy(DAG.getDataLayout());
3264 
3265   if (isPositionIndependent()) {
3266     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3267     if (IsLocal)
3268       // Use PC-relative addressing to access the symbol. This generates the
3269       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3270       // %pcrel_lo(auipc)).
3271       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3272 
3273     // Use PC-relative addressing to access the GOT for this symbol, then load
3274     // the address from the GOT. This generates the pattern (PseudoLA sym),
3275     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3276     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3277   }
3278 
3279   switch (getTargetMachine().getCodeModel()) {
3280   default:
3281     report_fatal_error("Unsupported code model for lowering");
3282   case CodeModel::Small: {
3283     // Generate a sequence for accessing addresses within the first 2 GiB of
3284     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3285     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3286     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3287     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3288     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3289   }
3290   case CodeModel::Medium: {
3291     // Generate a sequence for accessing addresses within any 2GiB range within
3292     // the address space. This generates the pattern (PseudoLLA sym), which
3293     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3294     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3295     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3296   }
3297   }
3298 }
3299 
3300 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3301                                                 SelectionDAG &DAG) const {
3302   SDLoc DL(Op);
3303   EVT Ty = Op.getValueType();
3304   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3305   int64_t Offset = N->getOffset();
3306   MVT XLenVT = Subtarget.getXLenVT();
3307 
3308   const GlobalValue *GV = N->getGlobal();
3309   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3310   SDValue Addr = getAddr(N, DAG, IsLocal);
3311 
3312   // In order to maximise the opportunity for common subexpression elimination,
3313   // emit a separate ADD node for the global address offset instead of folding
3314   // it in the global address node. Later peephole optimisations may choose to
3315   // fold it back in when profitable.
3316   if (Offset != 0)
3317     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3318                        DAG.getConstant(Offset, DL, XLenVT));
3319   return Addr;
3320 }
3321 
3322 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3323                                                SelectionDAG &DAG) const {
3324   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3325 
3326   return getAddr(N, DAG);
3327 }
3328 
3329 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3330                                                SelectionDAG &DAG) const {
3331   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3332 
3333   return getAddr(N, DAG);
3334 }
3335 
3336 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3337                                             SelectionDAG &DAG) const {
3338   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3339 
3340   return getAddr(N, DAG);
3341 }
3342 
3343 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3344                                               SelectionDAG &DAG,
3345                                               bool UseGOT) const {
3346   SDLoc DL(N);
3347   EVT Ty = getPointerTy(DAG.getDataLayout());
3348   const GlobalValue *GV = N->getGlobal();
3349   MVT XLenVT = Subtarget.getXLenVT();
3350 
3351   if (UseGOT) {
3352     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3353     // load the address from the GOT and add the thread pointer. This generates
3354     // the pattern (PseudoLA_TLS_IE sym), which expands to
3355     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3356     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3357     SDValue Load =
3358         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3359 
3360     // Add the thread pointer.
3361     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3362     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3363   }
3364 
3365   // Generate a sequence for accessing the address relative to the thread
3366   // pointer, with the appropriate adjustment for the thread pointer offset.
3367   // This generates the pattern
3368   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3369   SDValue AddrHi =
3370       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3371   SDValue AddrAdd =
3372       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3373   SDValue AddrLo =
3374       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3375 
3376   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3377   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3378   SDValue MNAdd = SDValue(
3379       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3380       0);
3381   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3382 }
3383 
3384 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3385                                                SelectionDAG &DAG) const {
3386   SDLoc DL(N);
3387   EVT Ty = getPointerTy(DAG.getDataLayout());
3388   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3389   const GlobalValue *GV = N->getGlobal();
3390 
3391   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3392   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3393   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3394   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3395   SDValue Load =
3396       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3397 
3398   // Prepare argument list to generate call.
3399   ArgListTy Args;
3400   ArgListEntry Entry;
3401   Entry.Node = Load;
3402   Entry.Ty = CallTy;
3403   Args.push_back(Entry);
3404 
3405   // Setup call to __tls_get_addr.
3406   TargetLowering::CallLoweringInfo CLI(DAG);
3407   CLI.setDebugLoc(DL)
3408       .setChain(DAG.getEntryNode())
3409       .setLibCallee(CallingConv::C, CallTy,
3410                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3411                     std::move(Args));
3412 
3413   return LowerCallTo(CLI).first;
3414 }
3415 
3416 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3417                                                    SelectionDAG &DAG) const {
3418   SDLoc DL(Op);
3419   EVT Ty = Op.getValueType();
3420   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3421   int64_t Offset = N->getOffset();
3422   MVT XLenVT = Subtarget.getXLenVT();
3423 
3424   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3425 
3426   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3427       CallingConv::GHC)
3428     report_fatal_error("In GHC calling convention TLS is not supported");
3429 
3430   SDValue Addr;
3431   switch (Model) {
3432   case TLSModel::LocalExec:
3433     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3434     break;
3435   case TLSModel::InitialExec:
3436     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3437     break;
3438   case TLSModel::LocalDynamic:
3439   case TLSModel::GeneralDynamic:
3440     Addr = getDynamicTLSAddr(N, DAG);
3441     break;
3442   }
3443 
3444   // In order to maximise the opportunity for common subexpression elimination,
3445   // emit a separate ADD node for the global address offset instead of folding
3446   // it in the global address node. Later peephole optimisations may choose to
3447   // fold it back in when profitable.
3448   if (Offset != 0)
3449     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3450                        DAG.getConstant(Offset, DL, XLenVT));
3451   return Addr;
3452 }
3453 
3454 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3455   SDValue CondV = Op.getOperand(0);
3456   SDValue TrueV = Op.getOperand(1);
3457   SDValue FalseV = Op.getOperand(2);
3458   SDLoc DL(Op);
3459   MVT VT = Op.getSimpleValueType();
3460   MVT XLenVT = Subtarget.getXLenVT();
3461 
3462   // Lower vector SELECTs to VSELECTs by splatting the condition.
3463   if (VT.isVector()) {
3464     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3465     SDValue CondSplat = VT.isScalableVector()
3466                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3467                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3468     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3469   }
3470 
3471   // If the result type is XLenVT and CondV is the output of a SETCC node
3472   // which also operated on XLenVT inputs, then merge the SETCC node into the
3473   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3474   // compare+branch instructions. i.e.:
3475   // (select (setcc lhs, rhs, cc), truev, falsev)
3476   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3477   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3478       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3479     SDValue LHS = CondV.getOperand(0);
3480     SDValue RHS = CondV.getOperand(1);
3481     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3482     ISD::CondCode CCVal = CC->get();
3483 
3484     // Special case for a select of 2 constants that have a diffence of 1.
3485     // Normally this is done by DAGCombine, but if the select is introduced by
3486     // type legalization or op legalization, we miss it. Restricting to SETLT
3487     // case for now because that is what signed saturating add/sub need.
3488     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3489     // but we would probably want to swap the true/false values if the condition
3490     // is SETGE/SETLE to avoid an XORI.
3491     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3492         CCVal == ISD::SETLT) {
3493       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3494       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3495       if (TrueVal - 1 == FalseVal)
3496         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3497       if (TrueVal + 1 == FalseVal)
3498         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3499     }
3500 
3501     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3502 
3503     SDValue TargetCC = DAG.getCondCode(CCVal);
3504     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3505     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3506   }
3507 
3508   // Otherwise:
3509   // (select condv, truev, falsev)
3510   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3511   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3512   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3513 
3514   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3515 
3516   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3517 }
3518 
3519 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3520   SDValue CondV = Op.getOperand(1);
3521   SDLoc DL(Op);
3522   MVT XLenVT = Subtarget.getXLenVT();
3523 
3524   if (CondV.getOpcode() == ISD::SETCC &&
3525       CondV.getOperand(0).getValueType() == XLenVT) {
3526     SDValue LHS = CondV.getOperand(0);
3527     SDValue RHS = CondV.getOperand(1);
3528     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3529 
3530     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3531 
3532     SDValue TargetCC = DAG.getCondCode(CCVal);
3533     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3534                        LHS, RHS, TargetCC, Op.getOperand(2));
3535   }
3536 
3537   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3538                      CondV, DAG.getConstant(0, DL, XLenVT),
3539                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3540 }
3541 
3542 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3543   MachineFunction &MF = DAG.getMachineFunction();
3544   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3545 
3546   SDLoc DL(Op);
3547   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3548                                  getPointerTy(MF.getDataLayout()));
3549 
3550   // vastart just stores the address of the VarArgsFrameIndex slot into the
3551   // memory location argument.
3552   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3553   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3554                       MachinePointerInfo(SV));
3555 }
3556 
3557 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3558                                             SelectionDAG &DAG) const {
3559   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3560   MachineFunction &MF = DAG.getMachineFunction();
3561   MachineFrameInfo &MFI = MF.getFrameInfo();
3562   MFI.setFrameAddressIsTaken(true);
3563   Register FrameReg = RI.getFrameRegister(MF);
3564   int XLenInBytes = Subtarget.getXLen() / 8;
3565 
3566   EVT VT = Op.getValueType();
3567   SDLoc DL(Op);
3568   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3569   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3570   while (Depth--) {
3571     int Offset = -(XLenInBytes * 2);
3572     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3573                               DAG.getIntPtrConstant(Offset, DL));
3574     FrameAddr =
3575         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3576   }
3577   return FrameAddr;
3578 }
3579 
3580 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3581                                              SelectionDAG &DAG) const {
3582   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3583   MachineFunction &MF = DAG.getMachineFunction();
3584   MachineFrameInfo &MFI = MF.getFrameInfo();
3585   MFI.setReturnAddressIsTaken(true);
3586   MVT XLenVT = Subtarget.getXLenVT();
3587   int XLenInBytes = Subtarget.getXLen() / 8;
3588 
3589   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3590     return SDValue();
3591 
3592   EVT VT = Op.getValueType();
3593   SDLoc DL(Op);
3594   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3595   if (Depth) {
3596     int Off = -XLenInBytes;
3597     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3598     SDValue Offset = DAG.getConstant(Off, DL, VT);
3599     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3600                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3601                        MachinePointerInfo());
3602   }
3603 
3604   // Return the value of the return address register, marking it an implicit
3605   // live-in.
3606   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3607   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3608 }
3609 
3610 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3611                                                  SelectionDAG &DAG) const {
3612   SDLoc DL(Op);
3613   SDValue Lo = Op.getOperand(0);
3614   SDValue Hi = Op.getOperand(1);
3615   SDValue Shamt = Op.getOperand(2);
3616   EVT VT = Lo.getValueType();
3617 
3618   // if Shamt-XLEN < 0: // Shamt < XLEN
3619   //   Lo = Lo << Shamt
3620   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3621   // else:
3622   //   Lo = 0
3623   //   Hi = Lo << (Shamt-XLEN)
3624 
3625   SDValue Zero = DAG.getConstant(0, DL, VT);
3626   SDValue One = DAG.getConstant(1, DL, VT);
3627   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3628   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3629   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3630   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3631 
3632   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3633   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3634   SDValue ShiftRightLo =
3635       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3636   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3637   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3638   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3639 
3640   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3641 
3642   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3643   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3644 
3645   SDValue Parts[2] = {Lo, Hi};
3646   return DAG.getMergeValues(Parts, DL);
3647 }
3648 
3649 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3650                                                   bool IsSRA) const {
3651   SDLoc DL(Op);
3652   SDValue Lo = Op.getOperand(0);
3653   SDValue Hi = Op.getOperand(1);
3654   SDValue Shamt = Op.getOperand(2);
3655   EVT VT = Lo.getValueType();
3656 
3657   // SRA expansion:
3658   //   if Shamt-XLEN < 0: // Shamt < XLEN
3659   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3660   //     Hi = Hi >>s Shamt
3661   //   else:
3662   //     Lo = Hi >>s (Shamt-XLEN);
3663   //     Hi = Hi >>s (XLEN-1)
3664   //
3665   // SRL expansion:
3666   //   if Shamt-XLEN < 0: // Shamt < XLEN
3667   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3668   //     Hi = Hi >>u Shamt
3669   //   else:
3670   //     Lo = Hi >>u (Shamt-XLEN);
3671   //     Hi = 0;
3672 
3673   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3674 
3675   SDValue Zero = DAG.getConstant(0, DL, VT);
3676   SDValue One = DAG.getConstant(1, DL, VT);
3677   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3678   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3679   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3680   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3681 
3682   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3683   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3684   SDValue ShiftLeftHi =
3685       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3686   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3687   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3688   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3689   SDValue HiFalse =
3690       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3691 
3692   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3693 
3694   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3695   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3696 
3697   SDValue Parts[2] = {Lo, Hi};
3698   return DAG.getMergeValues(Parts, DL);
3699 }
3700 
3701 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3702 // legal equivalently-sized i8 type, so we can use that as a go-between.
3703 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3704                                                   SelectionDAG &DAG) const {
3705   SDLoc DL(Op);
3706   MVT VT = Op.getSimpleValueType();
3707   SDValue SplatVal = Op.getOperand(0);
3708   // All-zeros or all-ones splats are handled specially.
3709   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3710     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3711     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3712   }
3713   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3714     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3715     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3716   }
3717   MVT XLenVT = Subtarget.getXLenVT();
3718   assert(SplatVal.getValueType() == XLenVT &&
3719          "Unexpected type for i1 splat value");
3720   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3721   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3722                          DAG.getConstant(1, DL, XLenVT));
3723   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3724   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3725   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3726 }
3727 
3728 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3729 // illegal (currently only vXi64 RV32).
3730 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3731 // them to SPLAT_VECTOR_I64
3732 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3733                                                      SelectionDAG &DAG) const {
3734   SDLoc DL(Op);
3735   MVT VecVT = Op.getSimpleValueType();
3736   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3737          "Unexpected SPLAT_VECTOR_PARTS lowering");
3738 
3739   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3740   SDValue Lo = Op.getOperand(0);
3741   SDValue Hi = Op.getOperand(1);
3742 
3743   if (VecVT.isFixedLengthVector()) {
3744     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3745     SDLoc DL(Op);
3746     SDValue Mask, VL;
3747     std::tie(Mask, VL) =
3748         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3749 
3750     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3751     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3752   }
3753 
3754   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3755     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3756     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3757     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3758     // node in order to try and match RVV vector/scalar instructions.
3759     if ((LoC >> 31) == HiC)
3760       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3761   }
3762 
3763   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3764   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3765       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3766       Hi.getConstantOperandVal(1) == 31)
3767     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3768 
3769   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3770   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3771                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3772 }
3773 
3774 // Custom-lower extensions from mask vectors by using a vselect either with 1
3775 // for zero/any-extension or -1 for sign-extension:
3776 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3777 // Note that any-extension is lowered identically to zero-extension.
3778 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3779                                                 int64_t ExtTrueVal) const {
3780   SDLoc DL(Op);
3781   MVT VecVT = Op.getSimpleValueType();
3782   SDValue Src = Op.getOperand(0);
3783   // Only custom-lower extensions from mask types
3784   assert(Src.getValueType().isVector() &&
3785          Src.getValueType().getVectorElementType() == MVT::i1);
3786 
3787   MVT XLenVT = Subtarget.getXLenVT();
3788   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3789   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3790 
3791   if (VecVT.isScalableVector()) {
3792     // Be careful not to introduce illegal scalar types at this stage, and be
3793     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3794     // illegal and must be expanded. Since we know that the constants are
3795     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3796     bool IsRV32E64 =
3797         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3798 
3799     if (!IsRV32E64) {
3800       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3801       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3802     } else {
3803       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3804       SplatTrueVal =
3805           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3806     }
3807 
3808     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3809   }
3810 
3811   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3812   MVT I1ContainerVT =
3813       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3814 
3815   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3816 
3817   SDValue Mask, VL;
3818   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3819 
3820   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3821   SplatTrueVal =
3822       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3823   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3824                                SplatTrueVal, SplatZero, VL);
3825 
3826   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3827 }
3828 
3829 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3830     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3831   MVT ExtVT = Op.getSimpleValueType();
3832   // Only custom-lower extensions from fixed-length vector types.
3833   if (!ExtVT.isFixedLengthVector())
3834     return Op;
3835   MVT VT = Op.getOperand(0).getSimpleValueType();
3836   // Grab the canonical container type for the extended type. Infer the smaller
3837   // type from that to ensure the same number of vector elements, as we know
3838   // the LMUL will be sufficient to hold the smaller type.
3839   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3840   // Get the extended container type manually to ensure the same number of
3841   // vector elements between source and dest.
3842   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3843                                      ContainerExtVT.getVectorElementCount());
3844 
3845   SDValue Op1 =
3846       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3847 
3848   SDLoc DL(Op);
3849   SDValue Mask, VL;
3850   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3851 
3852   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3853 
3854   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3855 }
3856 
3857 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3858 // setcc operation:
3859 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3860 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3861                                                   SelectionDAG &DAG) const {
3862   SDLoc DL(Op);
3863   EVT MaskVT = Op.getValueType();
3864   // Only expect to custom-lower truncations to mask types
3865   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3866          "Unexpected type for vector mask lowering");
3867   SDValue Src = Op.getOperand(0);
3868   MVT VecVT = Src.getSimpleValueType();
3869 
3870   // If this is a fixed vector, we need to convert it to a scalable vector.
3871   MVT ContainerVT = VecVT;
3872   if (VecVT.isFixedLengthVector()) {
3873     ContainerVT = getContainerForFixedLengthVector(VecVT);
3874     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3875   }
3876 
3877   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3878   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3879 
3880   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3881   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3882 
3883   if (VecVT.isScalableVector()) {
3884     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3885     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3886   }
3887 
3888   SDValue Mask, VL;
3889   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3890 
3891   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3892   SDValue Trunc =
3893       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3894   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3895                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3896   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3897 }
3898 
3899 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3900 // first position of a vector, and that vector is slid up to the insert index.
3901 // By limiting the active vector length to index+1 and merging with the
3902 // original vector (with an undisturbed tail policy for elements >= VL), we
3903 // achieve the desired result of leaving all elements untouched except the one
3904 // at VL-1, which is replaced with the desired value.
3905 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3906                                                     SelectionDAG &DAG) const {
3907   SDLoc DL(Op);
3908   MVT VecVT = Op.getSimpleValueType();
3909   SDValue Vec = Op.getOperand(0);
3910   SDValue Val = Op.getOperand(1);
3911   SDValue Idx = Op.getOperand(2);
3912 
3913   if (VecVT.getVectorElementType() == MVT::i1) {
3914     // FIXME: For now we just promote to an i8 vector and insert into that,
3915     // but this is probably not optimal.
3916     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3917     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3918     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3919     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3920   }
3921 
3922   MVT ContainerVT = VecVT;
3923   // If the operand is a fixed-length vector, convert to a scalable one.
3924   if (VecVT.isFixedLengthVector()) {
3925     ContainerVT = getContainerForFixedLengthVector(VecVT);
3926     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3927   }
3928 
3929   MVT XLenVT = Subtarget.getXLenVT();
3930 
3931   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3932   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3933   // Even i64-element vectors on RV32 can be lowered without scalar
3934   // legalization if the most-significant 32 bits of the value are not affected
3935   // by the sign-extension of the lower 32 bits.
3936   // TODO: We could also catch sign extensions of a 32-bit value.
3937   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3938     const auto *CVal = cast<ConstantSDNode>(Val);
3939     if (isInt<32>(CVal->getSExtValue())) {
3940       IsLegalInsert = true;
3941       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3942     }
3943   }
3944 
3945   SDValue Mask, VL;
3946   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3947 
3948   SDValue ValInVec;
3949 
3950   if (IsLegalInsert) {
3951     unsigned Opc =
3952         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3953     if (isNullConstant(Idx)) {
3954       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3955       if (!VecVT.isFixedLengthVector())
3956         return Vec;
3957       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3958     }
3959     ValInVec =
3960         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3961   } else {
3962     // On RV32, i64-element vectors must be specially handled to place the
3963     // value at element 0, by using two vslide1up instructions in sequence on
3964     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3965     // this.
3966     SDValue One = DAG.getConstant(1, DL, XLenVT);
3967     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3968     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3969     MVT I32ContainerVT =
3970         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3971     SDValue I32Mask =
3972         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3973     // Limit the active VL to two.
3974     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3975     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3976     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3977     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3978                            InsertI64VL);
3979     // First slide in the hi value, then the lo in underneath it.
3980     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3981                            ValHi, I32Mask, InsertI64VL);
3982     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3983                            ValLo, I32Mask, InsertI64VL);
3984     // Bitcast back to the right container type.
3985     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3986   }
3987 
3988   // Now that the value is in a vector, slide it into position.
3989   SDValue InsertVL =
3990       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3991   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3992                                 ValInVec, Idx, Mask, InsertVL);
3993   if (!VecVT.isFixedLengthVector())
3994     return Slideup;
3995   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3996 }
3997 
3998 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3999 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4000 // types this is done using VMV_X_S to allow us to glean information about the
4001 // sign bits of the result.
4002 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4003                                                      SelectionDAG &DAG) const {
4004   SDLoc DL(Op);
4005   SDValue Idx = Op.getOperand(1);
4006   SDValue Vec = Op.getOperand(0);
4007   EVT EltVT = Op.getValueType();
4008   MVT VecVT = Vec.getSimpleValueType();
4009   MVT XLenVT = Subtarget.getXLenVT();
4010 
4011   if (VecVT.getVectorElementType() == MVT::i1) {
4012     // FIXME: For now we just promote to an i8 vector and extract from that,
4013     // but this is probably not optimal.
4014     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4015     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4016     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4017   }
4018 
4019   // If this is a fixed vector, we need to convert it to a scalable vector.
4020   MVT ContainerVT = VecVT;
4021   if (VecVT.isFixedLengthVector()) {
4022     ContainerVT = getContainerForFixedLengthVector(VecVT);
4023     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4024   }
4025 
4026   // If the index is 0, the vector is already in the right position.
4027   if (!isNullConstant(Idx)) {
4028     // Use a VL of 1 to avoid processing more elements than we need.
4029     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4030     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4031     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4032     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4033                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4034   }
4035 
4036   if (!EltVT.isInteger()) {
4037     // Floating-point extracts are handled in TableGen.
4038     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4039                        DAG.getConstant(0, DL, XLenVT));
4040   }
4041 
4042   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4043   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4044 }
4045 
4046 // Some RVV intrinsics may claim that they want an integer operand to be
4047 // promoted or expanded.
4048 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4049                                           const RISCVSubtarget &Subtarget) {
4050   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4051           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4052          "Unexpected opcode");
4053 
4054   if (!Subtarget.hasVInstructions())
4055     return SDValue();
4056 
4057   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4058   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4059   SDLoc DL(Op);
4060 
4061   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4062       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4063   if (!II || !II->SplatOperand)
4064     return SDValue();
4065 
4066   unsigned SplatOp = II->SplatOperand + HasChain;
4067   assert(SplatOp < Op.getNumOperands());
4068 
4069   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4070   SDValue &ScalarOp = Operands[SplatOp];
4071   MVT OpVT = ScalarOp.getSimpleValueType();
4072   MVT XLenVT = Subtarget.getXLenVT();
4073 
4074   // If this isn't a scalar, or its type is XLenVT we're done.
4075   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4076     return SDValue();
4077 
4078   // Simplest case is that the operand needs to be promoted to XLenVT.
4079   if (OpVT.bitsLT(XLenVT)) {
4080     // If the operand is a constant, sign extend to increase our chances
4081     // of being able to use a .vi instruction. ANY_EXTEND would become a
4082     // a zero extend and the simm5 check in isel would fail.
4083     // FIXME: Should we ignore the upper bits in isel instead?
4084     unsigned ExtOpc =
4085         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4086     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4087     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4088   }
4089 
4090   // Use the previous operand to get the vXi64 VT. The result might be a mask
4091   // VT for compares. Using the previous operand assumes that the previous
4092   // operand will never have a smaller element size than a scalar operand and
4093   // that a widening operation never uses SEW=64.
4094   // NOTE: If this fails the below assert, we can probably just find the
4095   // element count from any operand or result and use it to construct the VT.
4096   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4097   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4098 
4099   // The more complex case is when the scalar is larger than XLenVT.
4100   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4101          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4102 
4103   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4104   // on the instruction to sign-extend since SEW>XLEN.
4105   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4106     if (isInt<32>(CVal->getSExtValue())) {
4107       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4108       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4109     }
4110   }
4111 
4112   // We need to convert the scalar to a splat vector.
4113   // FIXME: Can we implicitly truncate the scalar if it is known to
4114   // be sign extended?
4115   // VL should be the last operand.
4116   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4117   assert(VL.getValueType() == XLenVT);
4118   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4119   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4120 }
4121 
4122 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4123                                                      SelectionDAG &DAG) const {
4124   unsigned IntNo = Op.getConstantOperandVal(0);
4125   SDLoc DL(Op);
4126   MVT XLenVT = Subtarget.getXLenVT();
4127 
4128   switch (IntNo) {
4129   default:
4130     break; // Don't custom lower most intrinsics.
4131   case Intrinsic::thread_pointer: {
4132     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4133     return DAG.getRegister(RISCV::X4, PtrVT);
4134   }
4135   case Intrinsic::riscv_orc_b:
4136     // Lower to the GORCI encoding for orc.b.
4137     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4138                        DAG.getConstant(7, DL, XLenVT));
4139   case Intrinsic::riscv_grev:
4140   case Intrinsic::riscv_gorc: {
4141     unsigned Opc =
4142         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4143     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4144   }
4145   case Intrinsic::riscv_shfl:
4146   case Intrinsic::riscv_unshfl: {
4147     unsigned Opc =
4148         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4149     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4150   }
4151   case Intrinsic::riscv_bcompress:
4152   case Intrinsic::riscv_bdecompress: {
4153     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4154                                                        : RISCVISD::BDECOMPRESS;
4155     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4156   }
4157   case Intrinsic::riscv_vmv_x_s:
4158     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4159     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4160                        Op.getOperand(1));
4161   case Intrinsic::riscv_vmv_v_x:
4162     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4163                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4164   case Intrinsic::riscv_vfmv_v_f:
4165     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4166                        Op.getOperand(1), Op.getOperand(2));
4167   case Intrinsic::riscv_vmv_s_x: {
4168     SDValue Scalar = Op.getOperand(2);
4169 
4170     if (Scalar.getValueType().bitsLE(XLenVT)) {
4171       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4172       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4173                          Op.getOperand(1), Scalar, Op.getOperand(3));
4174     }
4175 
4176     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4177 
4178     // This is an i64 value that lives in two scalar registers. We have to
4179     // insert this in a convoluted way. First we build vXi64 splat containing
4180     // the/ two values that we assemble using some bit math. Next we'll use
4181     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4182     // to merge element 0 from our splat into the source vector.
4183     // FIXME: This is probably not the best way to do this, but it is
4184     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4185     // point.
4186     //   sw lo, (a0)
4187     //   sw hi, 4(a0)
4188     //   vlse vX, (a0)
4189     //
4190     //   vid.v      vVid
4191     //   vmseq.vx   mMask, vVid, 0
4192     //   vmerge.vvm vDest, vSrc, vVal, mMask
4193     MVT VT = Op.getSimpleValueType();
4194     SDValue Vec = Op.getOperand(1);
4195     SDValue VL = Op.getOperand(3);
4196 
4197     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4198     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4199                                       DAG.getConstant(0, DL, MVT::i32), VL);
4200 
4201     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4202     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4203     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4204     SDValue SelectCond =
4205         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4206                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4207     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4208                        Vec, VL);
4209   }
4210   case Intrinsic::riscv_vslide1up:
4211   case Intrinsic::riscv_vslide1down:
4212   case Intrinsic::riscv_vslide1up_mask:
4213   case Intrinsic::riscv_vslide1down_mask: {
4214     // We need to special case these when the scalar is larger than XLen.
4215     unsigned NumOps = Op.getNumOperands();
4216     bool IsMasked = NumOps == 7;
4217     unsigned OpOffset = IsMasked ? 1 : 0;
4218     SDValue Scalar = Op.getOperand(2 + OpOffset);
4219     if (Scalar.getValueType().bitsLE(XLenVT))
4220       break;
4221 
4222     // Splatting a sign extended constant is fine.
4223     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4224       if (isInt<32>(CVal->getSExtValue()))
4225         break;
4226 
4227     MVT VT = Op.getSimpleValueType();
4228     assert(VT.getVectorElementType() == MVT::i64 &&
4229            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4230 
4231     // Convert the vector source to the equivalent nxvXi32 vector.
4232     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4233     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4234 
4235     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4236                                    DAG.getConstant(0, DL, XLenVT));
4237     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4238                                    DAG.getConstant(1, DL, XLenVT));
4239 
4240     // Double the VL since we halved SEW.
4241     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4242     SDValue I32VL =
4243         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4244 
4245     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4246     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4247 
4248     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4249     // instructions.
4250     if (IntNo == Intrinsic::riscv_vslide1up ||
4251         IntNo == Intrinsic::riscv_vslide1up_mask) {
4252       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4253                         I32Mask, I32VL);
4254       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4255                         I32Mask, I32VL);
4256     } else {
4257       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4258                         I32Mask, I32VL);
4259       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4260                         I32Mask, I32VL);
4261     }
4262 
4263     // Convert back to nxvXi64.
4264     Vec = DAG.getBitcast(VT, Vec);
4265 
4266     if (!IsMasked)
4267       return Vec;
4268 
4269     // Apply mask after the operation.
4270     SDValue Mask = Op.getOperand(NumOps - 3);
4271     SDValue MaskedOff = Op.getOperand(1);
4272     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4273   }
4274   }
4275 
4276   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4277 }
4278 
4279 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4280                                                     SelectionDAG &DAG) const {
4281   unsigned IntNo = Op.getConstantOperandVal(1);
4282   switch (IntNo) {
4283   default:
4284     break;
4285   case Intrinsic::riscv_masked_strided_load: {
4286     SDLoc DL(Op);
4287     MVT XLenVT = Subtarget.getXLenVT();
4288 
4289     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4290     // the selection of the masked intrinsics doesn't do this for us.
4291     SDValue Mask = Op.getOperand(5);
4292     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4293 
4294     MVT VT = Op->getSimpleValueType(0);
4295     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4296 
4297     SDValue PassThru = Op.getOperand(2);
4298     if (!IsUnmasked) {
4299       MVT MaskVT =
4300           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4301       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4302       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4303     }
4304 
4305     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4306 
4307     SDValue IntID = DAG.getTargetConstant(
4308         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4309         XLenVT);
4310 
4311     auto *Load = cast<MemIntrinsicSDNode>(Op);
4312     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4313     if (!IsUnmasked)
4314       Ops.push_back(PassThru);
4315     Ops.push_back(Op.getOperand(3)); // Ptr
4316     Ops.push_back(Op.getOperand(4)); // Stride
4317     if (!IsUnmasked)
4318       Ops.push_back(Mask);
4319     Ops.push_back(VL);
4320     if (!IsUnmasked) {
4321       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4322       Ops.push_back(Policy);
4323     }
4324 
4325     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4326     SDValue Result =
4327         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4328                                 Load->getMemoryVT(), Load->getMemOperand());
4329     SDValue Chain = Result.getValue(1);
4330     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4331     return DAG.getMergeValues({Result, Chain}, DL);
4332   }
4333   }
4334 
4335   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4336 }
4337 
4338 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4339                                                  SelectionDAG &DAG) const {
4340   unsigned IntNo = Op.getConstantOperandVal(1);
4341   switch (IntNo) {
4342   default:
4343     break;
4344   case Intrinsic::riscv_masked_strided_store: {
4345     SDLoc DL(Op);
4346     MVT XLenVT = Subtarget.getXLenVT();
4347 
4348     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4349     // the selection of the masked intrinsics doesn't do this for us.
4350     SDValue Mask = Op.getOperand(5);
4351     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4352 
4353     SDValue Val = Op.getOperand(2);
4354     MVT VT = Val.getSimpleValueType();
4355     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4356 
4357     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4358     if (!IsUnmasked) {
4359       MVT MaskVT =
4360           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4361       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4362     }
4363 
4364     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4365 
4366     SDValue IntID = DAG.getTargetConstant(
4367         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4368         XLenVT);
4369 
4370     auto *Store = cast<MemIntrinsicSDNode>(Op);
4371     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4372     Ops.push_back(Val);
4373     Ops.push_back(Op.getOperand(3)); // Ptr
4374     Ops.push_back(Op.getOperand(4)); // Stride
4375     if (!IsUnmasked)
4376       Ops.push_back(Mask);
4377     Ops.push_back(VL);
4378 
4379     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4380                                    Ops, Store->getMemoryVT(),
4381                                    Store->getMemOperand());
4382   }
4383   }
4384 
4385   return SDValue();
4386 }
4387 
4388 static MVT getLMUL1VT(MVT VT) {
4389   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4390          "Unexpected vector MVT");
4391   return MVT::getScalableVectorVT(
4392       VT.getVectorElementType(),
4393       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4394 }
4395 
4396 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4397   switch (ISDOpcode) {
4398   default:
4399     llvm_unreachable("Unhandled reduction");
4400   case ISD::VECREDUCE_ADD:
4401     return RISCVISD::VECREDUCE_ADD_VL;
4402   case ISD::VECREDUCE_UMAX:
4403     return RISCVISD::VECREDUCE_UMAX_VL;
4404   case ISD::VECREDUCE_SMAX:
4405     return RISCVISD::VECREDUCE_SMAX_VL;
4406   case ISD::VECREDUCE_UMIN:
4407     return RISCVISD::VECREDUCE_UMIN_VL;
4408   case ISD::VECREDUCE_SMIN:
4409     return RISCVISD::VECREDUCE_SMIN_VL;
4410   case ISD::VECREDUCE_AND:
4411     return RISCVISD::VECREDUCE_AND_VL;
4412   case ISD::VECREDUCE_OR:
4413     return RISCVISD::VECREDUCE_OR_VL;
4414   case ISD::VECREDUCE_XOR:
4415     return RISCVISD::VECREDUCE_XOR_VL;
4416   }
4417 }
4418 
4419 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4420                                                          SelectionDAG &DAG,
4421                                                          bool IsVP) const {
4422   SDLoc DL(Op);
4423   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4424   MVT VecVT = Vec.getSimpleValueType();
4425   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4426           Op.getOpcode() == ISD::VECREDUCE_OR ||
4427           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4428           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4429           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4430           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4431          "Unexpected reduction lowering");
4432 
4433   MVT XLenVT = Subtarget.getXLenVT();
4434   assert(Op.getValueType() == XLenVT &&
4435          "Expected reduction output to be legalized to XLenVT");
4436 
4437   MVT ContainerVT = VecVT;
4438   if (VecVT.isFixedLengthVector()) {
4439     ContainerVT = getContainerForFixedLengthVector(VecVT);
4440     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4441   }
4442 
4443   SDValue Mask, VL;
4444   if (IsVP) {
4445     Mask = Op.getOperand(2);
4446     VL = Op.getOperand(3);
4447   } else {
4448     std::tie(Mask, VL) =
4449         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4450   }
4451 
4452   unsigned BaseOpc;
4453   ISD::CondCode CC;
4454   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4455 
4456   switch (Op.getOpcode()) {
4457   default:
4458     llvm_unreachable("Unhandled reduction");
4459   case ISD::VECREDUCE_AND:
4460   case ISD::VP_REDUCE_AND: {
4461     // vcpop ~x == 0
4462     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4463     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4464     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4465     CC = ISD::SETEQ;
4466     BaseOpc = ISD::AND;
4467     break;
4468   }
4469   case ISD::VECREDUCE_OR:
4470   case ISD::VP_REDUCE_OR:
4471     // vcpop x != 0
4472     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4473     CC = ISD::SETNE;
4474     BaseOpc = ISD::OR;
4475     break;
4476   case ISD::VECREDUCE_XOR:
4477   case ISD::VP_REDUCE_XOR: {
4478     // ((vcpop x) & 1) != 0
4479     SDValue One = DAG.getConstant(1, DL, XLenVT);
4480     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4481     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4482     CC = ISD::SETNE;
4483     BaseOpc = ISD::XOR;
4484     break;
4485   }
4486   }
4487 
4488   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4489 
4490   if (!IsVP)
4491     return SetCC;
4492 
4493   // Now include the start value in the operation.
4494   // Note that we must return the start value when no elements are operated
4495   // upon. The vcpop instructions we've emitted in each case above will return
4496   // 0 for an inactive vector, and so we've already received the neutral value:
4497   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4498   // can simply include the start value.
4499   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4500 }
4501 
4502 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4503                                             SelectionDAG &DAG) const {
4504   SDLoc DL(Op);
4505   SDValue Vec = Op.getOperand(0);
4506   EVT VecEVT = Vec.getValueType();
4507 
4508   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4509 
4510   // Due to ordering in legalize types we may have a vector type that needs to
4511   // be split. Do that manually so we can get down to a legal type.
4512   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4513          TargetLowering::TypeSplitVector) {
4514     SDValue Lo, Hi;
4515     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4516     VecEVT = Lo.getValueType();
4517     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4518   }
4519 
4520   // TODO: The type may need to be widened rather than split. Or widened before
4521   // it can be split.
4522   if (!isTypeLegal(VecEVT))
4523     return SDValue();
4524 
4525   MVT VecVT = VecEVT.getSimpleVT();
4526   MVT VecEltVT = VecVT.getVectorElementType();
4527   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4528 
4529   MVT ContainerVT = VecVT;
4530   if (VecVT.isFixedLengthVector()) {
4531     ContainerVT = getContainerForFixedLengthVector(VecVT);
4532     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4533   }
4534 
4535   MVT M1VT = getLMUL1VT(ContainerVT);
4536   MVT XLenVT = Subtarget.getXLenVT();
4537 
4538   SDValue Mask, VL;
4539   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4540 
4541   SDValue NeutralElem =
4542       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4543   SDValue IdentitySplat = lowerScalarSplat(
4544       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4545   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4546                                   IdentitySplat, Mask, VL);
4547   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4548                              DAG.getConstant(0, DL, XLenVT));
4549   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4550 }
4551 
4552 // Given a reduction op, this function returns the matching reduction opcode,
4553 // the vector SDValue and the scalar SDValue required to lower this to a
4554 // RISCVISD node.
4555 static std::tuple<unsigned, SDValue, SDValue>
4556 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4557   SDLoc DL(Op);
4558   auto Flags = Op->getFlags();
4559   unsigned Opcode = Op.getOpcode();
4560   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4561   switch (Opcode) {
4562   default:
4563     llvm_unreachable("Unhandled reduction");
4564   case ISD::VECREDUCE_FADD: {
4565     // Use positive zero if we can. It is cheaper to materialize.
4566     SDValue Zero =
4567         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4568     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4569   }
4570   case ISD::VECREDUCE_SEQ_FADD:
4571     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4572                            Op.getOperand(0));
4573   case ISD::VECREDUCE_FMIN:
4574     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4575                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4576   case ISD::VECREDUCE_FMAX:
4577     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4578                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4579   }
4580 }
4581 
4582 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4583                                               SelectionDAG &DAG) const {
4584   SDLoc DL(Op);
4585   MVT VecEltVT = Op.getSimpleValueType();
4586 
4587   unsigned RVVOpcode;
4588   SDValue VectorVal, ScalarVal;
4589   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4590       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4591   MVT VecVT = VectorVal.getSimpleValueType();
4592 
4593   MVT ContainerVT = VecVT;
4594   if (VecVT.isFixedLengthVector()) {
4595     ContainerVT = getContainerForFixedLengthVector(VecVT);
4596     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4597   }
4598 
4599   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4600   MVT XLenVT = Subtarget.getXLenVT();
4601 
4602   SDValue Mask, VL;
4603   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4604 
4605   SDValue ScalarSplat = lowerScalarSplat(
4606       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4607   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4608                                   VectorVal, ScalarSplat, Mask, VL);
4609   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4610                      DAG.getConstant(0, DL, XLenVT));
4611 }
4612 
4613 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4614   switch (ISDOpcode) {
4615   default:
4616     llvm_unreachable("Unhandled reduction");
4617   case ISD::VP_REDUCE_ADD:
4618     return RISCVISD::VECREDUCE_ADD_VL;
4619   case ISD::VP_REDUCE_UMAX:
4620     return RISCVISD::VECREDUCE_UMAX_VL;
4621   case ISD::VP_REDUCE_SMAX:
4622     return RISCVISD::VECREDUCE_SMAX_VL;
4623   case ISD::VP_REDUCE_UMIN:
4624     return RISCVISD::VECREDUCE_UMIN_VL;
4625   case ISD::VP_REDUCE_SMIN:
4626     return RISCVISD::VECREDUCE_SMIN_VL;
4627   case ISD::VP_REDUCE_AND:
4628     return RISCVISD::VECREDUCE_AND_VL;
4629   case ISD::VP_REDUCE_OR:
4630     return RISCVISD::VECREDUCE_OR_VL;
4631   case ISD::VP_REDUCE_XOR:
4632     return RISCVISD::VECREDUCE_XOR_VL;
4633   case ISD::VP_REDUCE_FADD:
4634     return RISCVISD::VECREDUCE_FADD_VL;
4635   case ISD::VP_REDUCE_SEQ_FADD:
4636     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4637   case ISD::VP_REDUCE_FMAX:
4638     return RISCVISD::VECREDUCE_FMAX_VL;
4639   case ISD::VP_REDUCE_FMIN:
4640     return RISCVISD::VECREDUCE_FMIN_VL;
4641   }
4642 }
4643 
4644 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4645                                            SelectionDAG &DAG) const {
4646   SDLoc DL(Op);
4647   SDValue Vec = Op.getOperand(1);
4648   EVT VecEVT = Vec.getValueType();
4649 
4650   // TODO: The type may need to be widened rather than split. Or widened before
4651   // it can be split.
4652   if (!isTypeLegal(VecEVT))
4653     return SDValue();
4654 
4655   MVT VecVT = VecEVT.getSimpleVT();
4656   MVT VecEltVT = VecVT.getVectorElementType();
4657   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4658 
4659   MVT ContainerVT = VecVT;
4660   if (VecVT.isFixedLengthVector()) {
4661     ContainerVT = getContainerForFixedLengthVector(VecVT);
4662     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4663   }
4664 
4665   SDValue VL = Op.getOperand(3);
4666   SDValue Mask = Op.getOperand(2);
4667 
4668   MVT M1VT = getLMUL1VT(ContainerVT);
4669   MVT XLenVT = Subtarget.getXLenVT();
4670   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4671 
4672   SDValue StartSplat =
4673       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4674                        DL, DAG, Subtarget);
4675   SDValue Reduction =
4676       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4677   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4678                              DAG.getConstant(0, DL, XLenVT));
4679   if (!VecVT.isInteger())
4680     return Elt0;
4681   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4682 }
4683 
4684 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4685                                                    SelectionDAG &DAG) const {
4686   SDValue Vec = Op.getOperand(0);
4687   SDValue SubVec = Op.getOperand(1);
4688   MVT VecVT = Vec.getSimpleValueType();
4689   MVT SubVecVT = SubVec.getSimpleValueType();
4690 
4691   SDLoc DL(Op);
4692   MVT XLenVT = Subtarget.getXLenVT();
4693   unsigned OrigIdx = Op.getConstantOperandVal(2);
4694   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4695 
4696   // We don't have the ability to slide mask vectors up indexed by their i1
4697   // elements; the smallest we can do is i8. Often we are able to bitcast to
4698   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4699   // into a scalable one, we might not necessarily have enough scalable
4700   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4701   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4702       (OrigIdx != 0 || !Vec.isUndef())) {
4703     if (VecVT.getVectorMinNumElements() >= 8 &&
4704         SubVecVT.getVectorMinNumElements() >= 8) {
4705       assert(OrigIdx % 8 == 0 && "Invalid index");
4706       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4707              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4708              "Unexpected mask vector lowering");
4709       OrigIdx /= 8;
4710       SubVecVT =
4711           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4712                            SubVecVT.isScalableVector());
4713       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4714                                VecVT.isScalableVector());
4715       Vec = DAG.getBitcast(VecVT, Vec);
4716       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4717     } else {
4718       // We can't slide this mask vector up indexed by its i1 elements.
4719       // This poses a problem when we wish to insert a scalable vector which
4720       // can't be re-expressed as a larger type. Just choose the slow path and
4721       // extend to a larger type, then truncate back down.
4722       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4723       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4724       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4725       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4726       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4727                         Op.getOperand(2));
4728       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4729       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4730     }
4731   }
4732 
4733   // If the subvector vector is a fixed-length type, we cannot use subregister
4734   // manipulation to simplify the codegen; we don't know which register of a
4735   // LMUL group contains the specific subvector as we only know the minimum
4736   // register size. Therefore we must slide the vector group up the full
4737   // amount.
4738   if (SubVecVT.isFixedLengthVector()) {
4739     if (OrigIdx == 0 && Vec.isUndef())
4740       return Op;
4741     MVT ContainerVT = VecVT;
4742     if (VecVT.isFixedLengthVector()) {
4743       ContainerVT = getContainerForFixedLengthVector(VecVT);
4744       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4745     }
4746     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4747                          DAG.getUNDEF(ContainerVT), SubVec,
4748                          DAG.getConstant(0, DL, XLenVT));
4749     SDValue Mask =
4750         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4751     // Set the vector length to only the number of elements we care about. Note
4752     // that for slideup this includes the offset.
4753     SDValue VL =
4754         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4755     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4756     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4757                                   SubVec, SlideupAmt, Mask, VL);
4758     if (VecVT.isFixedLengthVector())
4759       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4760     return DAG.getBitcast(Op.getValueType(), Slideup);
4761   }
4762 
4763   unsigned SubRegIdx, RemIdx;
4764   std::tie(SubRegIdx, RemIdx) =
4765       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4766           VecVT, SubVecVT, OrigIdx, TRI);
4767 
4768   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4769   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4770                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4771                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4772 
4773   // 1. If the Idx has been completely eliminated and this subvector's size is
4774   // a vector register or a multiple thereof, or the surrounding elements are
4775   // undef, then this is a subvector insert which naturally aligns to a vector
4776   // register. These can easily be handled using subregister manipulation.
4777   // 2. If the subvector is smaller than a vector register, then the insertion
4778   // must preserve the undisturbed elements of the register. We do this by
4779   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4780   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4781   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4782   // LMUL=1 type back into the larger vector (resolving to another subregister
4783   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4784   // to avoid allocating a large register group to hold our subvector.
4785   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4786     return Op;
4787 
4788   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4789   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4790   // (in our case undisturbed). This means we can set up a subvector insertion
4791   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4792   // size of the subvector.
4793   MVT InterSubVT = VecVT;
4794   SDValue AlignedExtract = Vec;
4795   unsigned AlignedIdx = OrigIdx - RemIdx;
4796   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4797     InterSubVT = getLMUL1VT(VecVT);
4798     // Extract a subvector equal to the nearest full vector register type. This
4799     // should resolve to a EXTRACT_SUBREG instruction.
4800     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4801                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4802   }
4803 
4804   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4805   // For scalable vectors this must be further multiplied by vscale.
4806   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4807 
4808   SDValue Mask, VL;
4809   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4810 
4811   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4812   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4813   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4814   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4815 
4816   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4817                        DAG.getUNDEF(InterSubVT), SubVec,
4818                        DAG.getConstant(0, DL, XLenVT));
4819 
4820   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4821                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4822 
4823   // If required, insert this subvector back into the correct vector register.
4824   // This should resolve to an INSERT_SUBREG instruction.
4825   if (VecVT.bitsGT(InterSubVT))
4826     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4827                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4828 
4829   // We might have bitcast from a mask type: cast back to the original type if
4830   // required.
4831   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4832 }
4833 
4834 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4835                                                     SelectionDAG &DAG) const {
4836   SDValue Vec = Op.getOperand(0);
4837   MVT SubVecVT = Op.getSimpleValueType();
4838   MVT VecVT = Vec.getSimpleValueType();
4839 
4840   SDLoc DL(Op);
4841   MVT XLenVT = Subtarget.getXLenVT();
4842   unsigned OrigIdx = Op.getConstantOperandVal(1);
4843   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4844 
4845   // We don't have the ability to slide mask vectors down indexed by their i1
4846   // elements; the smallest we can do is i8. Often we are able to bitcast to
4847   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4848   // from a scalable one, we might not necessarily have enough scalable
4849   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4850   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4851     if (VecVT.getVectorMinNumElements() >= 8 &&
4852         SubVecVT.getVectorMinNumElements() >= 8) {
4853       assert(OrigIdx % 8 == 0 && "Invalid index");
4854       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4855              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4856              "Unexpected mask vector lowering");
4857       OrigIdx /= 8;
4858       SubVecVT =
4859           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4860                            SubVecVT.isScalableVector());
4861       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4862                                VecVT.isScalableVector());
4863       Vec = DAG.getBitcast(VecVT, Vec);
4864     } else {
4865       // We can't slide this mask vector down, indexed by its i1 elements.
4866       // This poses a problem when we wish to extract a scalable vector which
4867       // can't be re-expressed as a larger type. Just choose the slow path and
4868       // extend to a larger type, then truncate back down.
4869       // TODO: We could probably improve this when extracting certain fixed
4870       // from fixed, where we can extract as i8 and shift the correct element
4871       // right to reach the desired subvector?
4872       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4873       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4874       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4875       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4876                         Op.getOperand(1));
4877       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4878       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4879     }
4880   }
4881 
4882   // If the subvector vector is a fixed-length type, we cannot use subregister
4883   // manipulation to simplify the codegen; we don't know which register of a
4884   // LMUL group contains the specific subvector as we only know the minimum
4885   // register size. Therefore we must slide the vector group down the full
4886   // amount.
4887   if (SubVecVT.isFixedLengthVector()) {
4888     // With an index of 0 this is a cast-like subvector, which can be performed
4889     // with subregister operations.
4890     if (OrigIdx == 0)
4891       return Op;
4892     MVT ContainerVT = VecVT;
4893     if (VecVT.isFixedLengthVector()) {
4894       ContainerVT = getContainerForFixedLengthVector(VecVT);
4895       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4896     }
4897     SDValue Mask =
4898         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4899     // Set the vector length to only the number of elements we care about. This
4900     // avoids sliding down elements we're going to discard straight away.
4901     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4902     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4903     SDValue Slidedown =
4904         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4905                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4906     // Now we can use a cast-like subvector extract to get the result.
4907     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4908                             DAG.getConstant(0, DL, XLenVT));
4909     return DAG.getBitcast(Op.getValueType(), Slidedown);
4910   }
4911 
4912   unsigned SubRegIdx, RemIdx;
4913   std::tie(SubRegIdx, RemIdx) =
4914       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4915           VecVT, SubVecVT, OrigIdx, TRI);
4916 
4917   // If the Idx has been completely eliminated then this is a subvector extract
4918   // which naturally aligns to a vector register. These can easily be handled
4919   // using subregister manipulation.
4920   if (RemIdx == 0)
4921     return Op;
4922 
4923   // Else we must shift our vector register directly to extract the subvector.
4924   // Do this using VSLIDEDOWN.
4925 
4926   // If the vector type is an LMUL-group type, extract a subvector equal to the
4927   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4928   // instruction.
4929   MVT InterSubVT = VecVT;
4930   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4931     InterSubVT = getLMUL1VT(VecVT);
4932     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4933                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4934   }
4935 
4936   // Slide this vector register down by the desired number of elements in order
4937   // to place the desired subvector starting at element 0.
4938   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4939   // For scalable vectors this must be further multiplied by vscale.
4940   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4941 
4942   SDValue Mask, VL;
4943   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4944   SDValue Slidedown =
4945       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4946                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4947 
4948   // Now the vector is in the right position, extract our final subvector. This
4949   // should resolve to a COPY.
4950   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4951                           DAG.getConstant(0, DL, XLenVT));
4952 
4953   // We might have bitcast from a mask type: cast back to the original type if
4954   // required.
4955   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4956 }
4957 
4958 // Lower step_vector to the vid instruction. Any non-identity step value must
4959 // be accounted for my manual expansion.
4960 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4961                                               SelectionDAG &DAG) const {
4962   SDLoc DL(Op);
4963   MVT VT = Op.getSimpleValueType();
4964   MVT XLenVT = Subtarget.getXLenVT();
4965   SDValue Mask, VL;
4966   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4967   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4968   uint64_t StepValImm = Op.getConstantOperandVal(0);
4969   if (StepValImm != 1) {
4970     if (isPowerOf2_64(StepValImm)) {
4971       SDValue StepVal =
4972           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4973                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4974       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4975     } else {
4976       SDValue StepVal = lowerScalarSplat(
4977           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4978           DL, DAG, Subtarget);
4979       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4980     }
4981   }
4982   return StepVec;
4983 }
4984 
4985 // Implement vector_reverse using vrgather.vv with indices determined by
4986 // subtracting the id of each element from (VLMAX-1). This will convert
4987 // the indices like so:
4988 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4989 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4990 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4991                                                  SelectionDAG &DAG) const {
4992   SDLoc DL(Op);
4993   MVT VecVT = Op.getSimpleValueType();
4994   unsigned EltSize = VecVT.getScalarSizeInBits();
4995   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4996 
4997   unsigned MaxVLMAX = 0;
4998   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4999   if (VectorBitsMax != 0)
5000     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5001 
5002   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5003   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5004 
5005   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5006   // to use vrgatherei16.vv.
5007   // TODO: It's also possible to use vrgatherei16.vv for other types to
5008   // decrease register width for the index calculation.
5009   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5010     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5011     // Reverse each half, then reassemble them in reverse order.
5012     // NOTE: It's also possible that after splitting that VLMAX no longer
5013     // requires vrgatherei16.vv.
5014     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5015       SDValue Lo, Hi;
5016       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5017       EVT LoVT, HiVT;
5018       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5019       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5020       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5021       // Reassemble the low and high pieces reversed.
5022       // FIXME: This is a CONCAT_VECTORS.
5023       SDValue Res =
5024           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5025                       DAG.getIntPtrConstant(0, DL));
5026       return DAG.getNode(
5027           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5028           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5029     }
5030 
5031     // Just promote the int type to i16 which will double the LMUL.
5032     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5033     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5034   }
5035 
5036   MVT XLenVT = Subtarget.getXLenVT();
5037   SDValue Mask, VL;
5038   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5039 
5040   // Calculate VLMAX-1 for the desired SEW.
5041   unsigned MinElts = VecVT.getVectorMinNumElements();
5042   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5043                               DAG.getConstant(MinElts, DL, XLenVT));
5044   SDValue VLMinus1 =
5045       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5046 
5047   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5048   bool IsRV32E64 =
5049       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5050   SDValue SplatVL;
5051   if (!IsRV32E64)
5052     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5053   else
5054     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5055 
5056   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5057   SDValue Indices =
5058       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5059 
5060   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5061 }
5062 
5063 SDValue
5064 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5065                                                      SelectionDAG &DAG) const {
5066   SDLoc DL(Op);
5067   auto *Load = cast<LoadSDNode>(Op);
5068 
5069   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5070                                         Load->getMemoryVT(),
5071                                         *Load->getMemOperand()) &&
5072          "Expecting a correctly-aligned load");
5073 
5074   MVT VT = Op.getSimpleValueType();
5075   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5076 
5077   SDValue VL =
5078       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5079 
5080   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5081   SDValue NewLoad = DAG.getMemIntrinsicNode(
5082       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5083       Load->getMemoryVT(), Load->getMemOperand());
5084 
5085   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5086   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5087 }
5088 
5089 SDValue
5090 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5091                                                       SelectionDAG &DAG) const {
5092   SDLoc DL(Op);
5093   auto *Store = cast<StoreSDNode>(Op);
5094 
5095   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5096                                         Store->getMemoryVT(),
5097                                         *Store->getMemOperand()) &&
5098          "Expecting a correctly-aligned store");
5099 
5100   SDValue StoreVal = Store->getValue();
5101   MVT VT = StoreVal.getSimpleValueType();
5102 
5103   // If the size less than a byte, we need to pad with zeros to make a byte.
5104   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5105     VT = MVT::v8i1;
5106     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5107                            DAG.getConstant(0, DL, VT), StoreVal,
5108                            DAG.getIntPtrConstant(0, DL));
5109   }
5110 
5111   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5112 
5113   SDValue VL =
5114       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5115 
5116   SDValue NewValue =
5117       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5118   return DAG.getMemIntrinsicNode(
5119       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5120       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5121       Store->getMemoryVT(), Store->getMemOperand());
5122 }
5123 
5124 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5125                                              SelectionDAG &DAG) const {
5126   SDLoc DL(Op);
5127   MVT VT = Op.getSimpleValueType();
5128 
5129   const auto *MemSD = cast<MemSDNode>(Op);
5130   EVT MemVT = MemSD->getMemoryVT();
5131   MachineMemOperand *MMO = MemSD->getMemOperand();
5132   SDValue Chain = MemSD->getChain();
5133   SDValue BasePtr = MemSD->getBasePtr();
5134 
5135   SDValue Mask, PassThru, VL;
5136   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5137     Mask = VPLoad->getMask();
5138     PassThru = DAG.getUNDEF(VT);
5139     VL = VPLoad->getVectorLength();
5140   } else {
5141     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5142     Mask = MLoad->getMask();
5143     PassThru = MLoad->getPassThru();
5144   }
5145 
5146   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5147 
5148   MVT XLenVT = Subtarget.getXLenVT();
5149 
5150   MVT ContainerVT = VT;
5151   if (VT.isFixedLengthVector()) {
5152     ContainerVT = getContainerForFixedLengthVector(VT);
5153     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5154     if (!IsUnmasked) {
5155       MVT MaskVT =
5156           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5157       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5158     }
5159   }
5160 
5161   if (!VL)
5162     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5163 
5164   unsigned IntID =
5165       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5166   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5167   if (!IsUnmasked)
5168     Ops.push_back(PassThru);
5169   Ops.push_back(BasePtr);
5170   if (!IsUnmasked)
5171     Ops.push_back(Mask);
5172   Ops.push_back(VL);
5173   if (!IsUnmasked)
5174     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5175 
5176   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5177 
5178   SDValue Result =
5179       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5180   Chain = Result.getValue(1);
5181 
5182   if (VT.isFixedLengthVector())
5183     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5184 
5185   return DAG.getMergeValues({Result, Chain}, DL);
5186 }
5187 
5188 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5189                                               SelectionDAG &DAG) const {
5190   SDLoc DL(Op);
5191 
5192   const auto *MemSD = cast<MemSDNode>(Op);
5193   EVT MemVT = MemSD->getMemoryVT();
5194   MachineMemOperand *MMO = MemSD->getMemOperand();
5195   SDValue Chain = MemSD->getChain();
5196   SDValue BasePtr = MemSD->getBasePtr();
5197   SDValue Val, Mask, VL;
5198 
5199   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5200     Val = VPStore->getValue();
5201     Mask = VPStore->getMask();
5202     VL = VPStore->getVectorLength();
5203   } else {
5204     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5205     Val = MStore->getValue();
5206     Mask = MStore->getMask();
5207   }
5208 
5209   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5210 
5211   MVT VT = Val.getSimpleValueType();
5212   MVT XLenVT = Subtarget.getXLenVT();
5213 
5214   MVT ContainerVT = VT;
5215   if (VT.isFixedLengthVector()) {
5216     ContainerVT = getContainerForFixedLengthVector(VT);
5217 
5218     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5219     if (!IsUnmasked) {
5220       MVT MaskVT =
5221           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5222       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5223     }
5224   }
5225 
5226   if (!VL)
5227     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5228 
5229   unsigned IntID =
5230       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5231   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5232   Ops.push_back(Val);
5233   Ops.push_back(BasePtr);
5234   if (!IsUnmasked)
5235     Ops.push_back(Mask);
5236   Ops.push_back(VL);
5237 
5238   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5239                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5240 }
5241 
5242 SDValue
5243 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5244                                                       SelectionDAG &DAG) const {
5245   MVT InVT = Op.getOperand(0).getSimpleValueType();
5246   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5247 
5248   MVT VT = Op.getSimpleValueType();
5249 
5250   SDValue Op1 =
5251       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5252   SDValue Op2 =
5253       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5254 
5255   SDLoc DL(Op);
5256   SDValue VL =
5257       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5258 
5259   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5260   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5261 
5262   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5263                             Op.getOperand(2), Mask, VL);
5264 
5265   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5266 }
5267 
5268 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5269     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5270   MVT VT = Op.getSimpleValueType();
5271 
5272   if (VT.getVectorElementType() == MVT::i1)
5273     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5274 
5275   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5276 }
5277 
5278 SDValue
5279 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5280                                                       SelectionDAG &DAG) const {
5281   unsigned Opc;
5282   switch (Op.getOpcode()) {
5283   default: llvm_unreachable("Unexpected opcode!");
5284   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5285   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5286   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5287   }
5288 
5289   return lowerToScalableOp(Op, DAG, Opc);
5290 }
5291 
5292 // Lower vector ABS to smax(X, sub(0, X)).
5293 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5294   SDLoc DL(Op);
5295   MVT VT = Op.getSimpleValueType();
5296   SDValue X = Op.getOperand(0);
5297 
5298   assert(VT.isFixedLengthVector() && "Unexpected type");
5299 
5300   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5301   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5302 
5303   SDValue Mask, VL;
5304   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5305 
5306   SDValue SplatZero =
5307       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5308                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5309   SDValue NegX =
5310       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5311   SDValue Max =
5312       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5313 
5314   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5315 }
5316 
5317 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5318     SDValue Op, SelectionDAG &DAG) const {
5319   SDLoc DL(Op);
5320   MVT VT = Op.getSimpleValueType();
5321   SDValue Mag = Op.getOperand(0);
5322   SDValue Sign = Op.getOperand(1);
5323   assert(Mag.getValueType() == Sign.getValueType() &&
5324          "Can only handle COPYSIGN with matching types.");
5325 
5326   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5327   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5328   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5329 
5330   SDValue Mask, VL;
5331   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5332 
5333   SDValue CopySign =
5334       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5335 
5336   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5337 }
5338 
5339 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5340     SDValue Op, SelectionDAG &DAG) const {
5341   MVT VT = Op.getSimpleValueType();
5342   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5343 
5344   MVT I1ContainerVT =
5345       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5346 
5347   SDValue CC =
5348       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5349   SDValue Op1 =
5350       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5351   SDValue Op2 =
5352       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5353 
5354   SDLoc DL(Op);
5355   SDValue Mask, VL;
5356   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5357 
5358   SDValue Select =
5359       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5360 
5361   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5362 }
5363 
5364 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5365                                                unsigned NewOpc,
5366                                                bool HasMask) const {
5367   MVT VT = Op.getSimpleValueType();
5368   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5369 
5370   // Create list of operands by converting existing ones to scalable types.
5371   SmallVector<SDValue, 6> Ops;
5372   for (const SDValue &V : Op->op_values()) {
5373     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5374 
5375     // Pass through non-vector operands.
5376     if (!V.getValueType().isVector()) {
5377       Ops.push_back(V);
5378       continue;
5379     }
5380 
5381     // "cast" fixed length vector to a scalable vector.
5382     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5383            "Only fixed length vectors are supported!");
5384     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5385   }
5386 
5387   SDLoc DL(Op);
5388   SDValue Mask, VL;
5389   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5390   if (HasMask)
5391     Ops.push_back(Mask);
5392   Ops.push_back(VL);
5393 
5394   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5395   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5396 }
5397 
5398 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5399 // * Operands of each node are assumed to be in the same order.
5400 // * The EVL operand is promoted from i32 to i64 on RV64.
5401 // * Fixed-length vectors are converted to their scalable-vector container
5402 //   types.
5403 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5404                                        unsigned RISCVISDOpc) const {
5405   SDLoc DL(Op);
5406   MVT VT = Op.getSimpleValueType();
5407   SmallVector<SDValue, 4> Ops;
5408 
5409   for (const auto &OpIdx : enumerate(Op->ops())) {
5410     SDValue V = OpIdx.value();
5411     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5412     // Pass through operands which aren't fixed-length vectors.
5413     if (!V.getValueType().isFixedLengthVector()) {
5414       Ops.push_back(V);
5415       continue;
5416     }
5417     // "cast" fixed length vector to a scalable vector.
5418     MVT OpVT = V.getSimpleValueType();
5419     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5420     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5421            "Only fixed length vectors are supported!");
5422     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5423   }
5424 
5425   if (!VT.isFixedLengthVector())
5426     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5427 
5428   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5429 
5430   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5431 
5432   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5433 }
5434 
5435 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5436                                             unsigned MaskOpc,
5437                                             unsigned VecOpc) const {
5438   MVT VT = Op.getSimpleValueType();
5439   if (VT.getVectorElementType() != MVT::i1)
5440     return lowerVPOp(Op, DAG, VecOpc);
5441 
5442   // It is safe to drop mask parameter as masked-off elements are undef.
5443   SDValue Op1 = Op->getOperand(0);
5444   SDValue Op2 = Op->getOperand(1);
5445   SDValue VL = Op->getOperand(3);
5446 
5447   MVT ContainerVT = VT;
5448   const bool IsFixed = VT.isFixedLengthVector();
5449   if (IsFixed) {
5450     ContainerVT = getContainerForFixedLengthVector(VT);
5451     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5452     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5453   }
5454 
5455   SDLoc DL(Op);
5456   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5457   if (!IsFixed)
5458     return Val;
5459   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5460 }
5461 
5462 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5463 // matched to a RVV indexed load. The RVV indexed load instructions only
5464 // support the "unsigned unscaled" addressing mode; indices are implicitly
5465 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5466 // signed or scaled indexing is extended to the XLEN value type and scaled
5467 // accordingly.
5468 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5469                                                SelectionDAG &DAG) const {
5470   SDLoc DL(Op);
5471   MVT VT = Op.getSimpleValueType();
5472 
5473   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5474   EVT MemVT = MemSD->getMemoryVT();
5475   MachineMemOperand *MMO = MemSD->getMemOperand();
5476   SDValue Chain = MemSD->getChain();
5477   SDValue BasePtr = MemSD->getBasePtr();
5478 
5479   ISD::LoadExtType LoadExtType;
5480   SDValue Index, Mask, PassThru, VL;
5481 
5482   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5483     Index = VPGN->getIndex();
5484     Mask = VPGN->getMask();
5485     PassThru = DAG.getUNDEF(VT);
5486     VL = VPGN->getVectorLength();
5487     // VP doesn't support extending loads.
5488     LoadExtType = ISD::NON_EXTLOAD;
5489   } else {
5490     // Else it must be a MGATHER.
5491     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5492     Index = MGN->getIndex();
5493     Mask = MGN->getMask();
5494     PassThru = MGN->getPassThru();
5495     LoadExtType = MGN->getExtensionType();
5496   }
5497 
5498   MVT IndexVT = Index.getSimpleValueType();
5499   MVT XLenVT = Subtarget.getXLenVT();
5500 
5501   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5502          "Unexpected VTs!");
5503   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5504   // Targets have to explicitly opt-in for extending vector loads.
5505   assert(LoadExtType == ISD::NON_EXTLOAD &&
5506          "Unexpected extending MGATHER/VP_GATHER");
5507   (void)LoadExtType;
5508 
5509   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5510   // the selection of the masked intrinsics doesn't do this for us.
5511   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5512 
5513   MVT ContainerVT = VT;
5514   if (VT.isFixedLengthVector()) {
5515     // We need to use the larger of the result and index type to determine the
5516     // scalable type to use so we don't increase LMUL for any operand/result.
5517     if (VT.bitsGE(IndexVT)) {
5518       ContainerVT = getContainerForFixedLengthVector(VT);
5519       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5520                                  ContainerVT.getVectorElementCount());
5521     } else {
5522       IndexVT = getContainerForFixedLengthVector(IndexVT);
5523       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5524                                      IndexVT.getVectorElementCount());
5525     }
5526 
5527     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5528 
5529     if (!IsUnmasked) {
5530       MVT MaskVT =
5531           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5532       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5533       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5534     }
5535   }
5536 
5537   if (!VL)
5538     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5539 
5540   unsigned IntID =
5541       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5542   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5543   if (!IsUnmasked)
5544     Ops.push_back(PassThru);
5545   Ops.push_back(BasePtr);
5546   Ops.push_back(Index);
5547   if (!IsUnmasked)
5548     Ops.push_back(Mask);
5549   Ops.push_back(VL);
5550   if (!IsUnmasked)
5551     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5552 
5553   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5554   SDValue Result =
5555       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5556   Chain = Result.getValue(1);
5557 
5558   if (VT.isFixedLengthVector())
5559     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5560 
5561   return DAG.getMergeValues({Result, Chain}, DL);
5562 }
5563 
5564 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5565 // matched to a RVV indexed store. The RVV indexed store instructions only
5566 // support the "unsigned unscaled" addressing mode; indices are implicitly
5567 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5568 // signed or scaled indexing is extended to the XLEN value type and scaled
5569 // accordingly.
5570 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5571                                                 SelectionDAG &DAG) const {
5572   SDLoc DL(Op);
5573   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5574   EVT MemVT = MemSD->getMemoryVT();
5575   MachineMemOperand *MMO = MemSD->getMemOperand();
5576   SDValue Chain = MemSD->getChain();
5577   SDValue BasePtr = MemSD->getBasePtr();
5578 
5579   bool IsTruncatingStore = false;
5580   SDValue Index, Mask, Val, VL;
5581 
5582   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5583     Index = VPSN->getIndex();
5584     Mask = VPSN->getMask();
5585     Val = VPSN->getValue();
5586     VL = VPSN->getVectorLength();
5587     // VP doesn't support truncating stores.
5588     IsTruncatingStore = false;
5589   } else {
5590     // Else it must be a MSCATTER.
5591     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5592     Index = MSN->getIndex();
5593     Mask = MSN->getMask();
5594     Val = MSN->getValue();
5595     IsTruncatingStore = MSN->isTruncatingStore();
5596   }
5597 
5598   MVT VT = Val.getSimpleValueType();
5599   MVT IndexVT = Index.getSimpleValueType();
5600   MVT XLenVT = Subtarget.getXLenVT();
5601 
5602   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5603          "Unexpected VTs!");
5604   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5605   // Targets have to explicitly opt-in for extending vector loads and
5606   // truncating vector stores.
5607   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5608   (void)IsTruncatingStore;
5609 
5610   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5611   // the selection of the masked intrinsics doesn't do this for us.
5612   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5613 
5614   MVT ContainerVT = VT;
5615   if (VT.isFixedLengthVector()) {
5616     // We need to use the larger of the value and index type to determine the
5617     // scalable type to use so we don't increase LMUL for any operand/result.
5618     if (VT.bitsGE(IndexVT)) {
5619       ContainerVT = getContainerForFixedLengthVector(VT);
5620       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5621                                  ContainerVT.getVectorElementCount());
5622     } else {
5623       IndexVT = getContainerForFixedLengthVector(IndexVT);
5624       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5625                                      IndexVT.getVectorElementCount());
5626     }
5627 
5628     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5629     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5630 
5631     if (!IsUnmasked) {
5632       MVT MaskVT =
5633           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5634       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5635     }
5636   }
5637 
5638   if (!VL)
5639     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5640 
5641   unsigned IntID =
5642       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5643   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5644   Ops.push_back(Val);
5645   Ops.push_back(BasePtr);
5646   Ops.push_back(Index);
5647   if (!IsUnmasked)
5648     Ops.push_back(Mask);
5649   Ops.push_back(VL);
5650 
5651   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5652                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5653 }
5654 
5655 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5656                                                SelectionDAG &DAG) const {
5657   const MVT XLenVT = Subtarget.getXLenVT();
5658   SDLoc DL(Op);
5659   SDValue Chain = Op->getOperand(0);
5660   SDValue SysRegNo = DAG.getTargetConstant(
5661       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5662   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5663   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5664 
5665   // Encoding used for rounding mode in RISCV differs from that used in
5666   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5667   // table, which consists of a sequence of 4-bit fields, each representing
5668   // corresponding FLT_ROUNDS mode.
5669   static const int Table =
5670       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5671       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5672       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5673       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5674       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5675 
5676   SDValue Shift =
5677       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5678   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5679                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5680   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5681                                DAG.getConstant(7, DL, XLenVT));
5682 
5683   return DAG.getMergeValues({Masked, Chain}, DL);
5684 }
5685 
5686 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5687                                                SelectionDAG &DAG) const {
5688   const MVT XLenVT = Subtarget.getXLenVT();
5689   SDLoc DL(Op);
5690   SDValue Chain = Op->getOperand(0);
5691   SDValue RMValue = Op->getOperand(1);
5692   SDValue SysRegNo = DAG.getTargetConstant(
5693       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5694 
5695   // Encoding used for rounding mode in RISCV differs from that used in
5696   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5697   // a table, which consists of a sequence of 4-bit fields, each representing
5698   // corresponding RISCV mode.
5699   static const unsigned Table =
5700       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5701       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5702       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5703       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5704       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5705 
5706   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5707                               DAG.getConstant(2, DL, XLenVT));
5708   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5709                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5710   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5711                         DAG.getConstant(0x7, DL, XLenVT));
5712   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5713                      RMValue);
5714 }
5715 
5716 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5717 // form of the given Opcode.
5718 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5719   switch (Opcode) {
5720   default:
5721     llvm_unreachable("Unexpected opcode");
5722   case ISD::SHL:
5723     return RISCVISD::SLLW;
5724   case ISD::SRA:
5725     return RISCVISD::SRAW;
5726   case ISD::SRL:
5727     return RISCVISD::SRLW;
5728   case ISD::SDIV:
5729     return RISCVISD::DIVW;
5730   case ISD::UDIV:
5731     return RISCVISD::DIVUW;
5732   case ISD::UREM:
5733     return RISCVISD::REMUW;
5734   case ISD::ROTL:
5735     return RISCVISD::ROLW;
5736   case ISD::ROTR:
5737     return RISCVISD::RORW;
5738   case RISCVISD::GREV:
5739     return RISCVISD::GREVW;
5740   case RISCVISD::GORC:
5741     return RISCVISD::GORCW;
5742   }
5743 }
5744 
5745 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5746 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5747 // otherwise be promoted to i64, making it difficult to select the
5748 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5749 // type i8/i16/i32 is lost.
5750 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5751                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5752   SDLoc DL(N);
5753   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5754   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5755   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5756   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5757   // ReplaceNodeResults requires we maintain the same type for the return value.
5758   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5759 }
5760 
5761 // Converts the given 32-bit operation to a i64 operation with signed extension
5762 // semantic to reduce the signed extension instructions.
5763 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5764   SDLoc DL(N);
5765   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5766   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5767   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5768   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5769                                DAG.getValueType(MVT::i32));
5770   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5771 }
5772 
5773 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5774                                              SmallVectorImpl<SDValue> &Results,
5775                                              SelectionDAG &DAG) const {
5776   SDLoc DL(N);
5777   switch (N->getOpcode()) {
5778   default:
5779     llvm_unreachable("Don't know how to custom type legalize this operation!");
5780   case ISD::STRICT_FP_TO_SINT:
5781   case ISD::STRICT_FP_TO_UINT:
5782   case ISD::FP_TO_SINT:
5783   case ISD::FP_TO_UINT: {
5784     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5785            "Unexpected custom legalisation");
5786     bool IsStrict = N->isStrictFPOpcode();
5787     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5788                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5789     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5790     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5791         TargetLowering::TypeSoftenFloat) {
5792       if (!isTypeLegal(Op0.getValueType()))
5793         return;
5794       if (IsStrict) {
5795         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RTZ_RV64
5796                                 : RISCVISD::STRICT_FCVT_WU_RTZ_RV64;
5797         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
5798         SDValue Res = DAG.getNode(Opc, DL, VTs, N->getOperand(0), Op0);
5799         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5800         Results.push_back(Res.getValue(1));
5801         return;
5802       }
5803       unsigned Opc =
5804           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5805       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5806       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5807       return;
5808     }
5809     // If the FP type needs to be softened, emit a library call using the 'si'
5810     // version. If we left it to default legalization we'd end up with 'di'. If
5811     // the FP type doesn't need to be softened just let generic type
5812     // legalization promote the result type.
5813     RTLIB::Libcall LC;
5814     if (IsSigned)
5815       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5816     else
5817       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5818     MakeLibCallOptions CallOptions;
5819     EVT OpVT = Op0.getValueType();
5820     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5821     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5822     SDValue Result;
5823     std::tie(Result, Chain) =
5824         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5825     Results.push_back(Result);
5826     if (IsStrict)
5827       Results.push_back(Chain);
5828     break;
5829   }
5830   case ISD::READCYCLECOUNTER: {
5831     assert(!Subtarget.is64Bit() &&
5832            "READCYCLECOUNTER only has custom type legalization on riscv32");
5833 
5834     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5835     SDValue RCW =
5836         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5837 
5838     Results.push_back(
5839         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5840     Results.push_back(RCW.getValue(2));
5841     break;
5842   }
5843   case ISD::MUL: {
5844     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5845     unsigned XLen = Subtarget.getXLen();
5846     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5847     if (Size > XLen) {
5848       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5849       SDValue LHS = N->getOperand(0);
5850       SDValue RHS = N->getOperand(1);
5851       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5852 
5853       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5854       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5855       // We need exactly one side to be unsigned.
5856       if (LHSIsU == RHSIsU)
5857         return;
5858 
5859       auto MakeMULPair = [&](SDValue S, SDValue U) {
5860         MVT XLenVT = Subtarget.getXLenVT();
5861         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5862         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5863         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5864         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5865         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5866       };
5867 
5868       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5869       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5870 
5871       // The other operand should be signed, but still prefer MULH when
5872       // possible.
5873       if (RHSIsU && LHSIsS && !RHSIsS)
5874         Results.push_back(MakeMULPair(LHS, RHS));
5875       else if (LHSIsU && RHSIsS && !LHSIsS)
5876         Results.push_back(MakeMULPair(RHS, LHS));
5877 
5878       return;
5879     }
5880     LLVM_FALLTHROUGH;
5881   }
5882   case ISD::ADD:
5883   case ISD::SUB:
5884     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5885            "Unexpected custom legalisation");
5886     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5887     break;
5888   case ISD::SHL:
5889   case ISD::SRA:
5890   case ISD::SRL:
5891     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5892            "Unexpected custom legalisation");
5893     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5894       Results.push_back(customLegalizeToWOp(N, DAG));
5895       break;
5896     }
5897 
5898     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5899     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5900     // shift amount.
5901     if (N->getOpcode() == ISD::SHL) {
5902       SDLoc DL(N);
5903       SDValue NewOp0 =
5904           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5905       SDValue NewOp1 =
5906           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5907       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5908       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5909                                    DAG.getValueType(MVT::i32));
5910       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5911     }
5912 
5913     break;
5914   case ISD::ROTL:
5915   case ISD::ROTR:
5916     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5917            "Unexpected custom legalisation");
5918     Results.push_back(customLegalizeToWOp(N, DAG));
5919     break;
5920   case ISD::CTTZ:
5921   case ISD::CTTZ_ZERO_UNDEF:
5922   case ISD::CTLZ:
5923   case ISD::CTLZ_ZERO_UNDEF: {
5924     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5925            "Unexpected custom legalisation");
5926 
5927     SDValue NewOp0 =
5928         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5929     bool IsCTZ =
5930         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5931     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5932     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5933     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5934     return;
5935   }
5936   case ISD::SDIV:
5937   case ISD::UDIV:
5938   case ISD::UREM: {
5939     MVT VT = N->getSimpleValueType(0);
5940     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5941            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5942            "Unexpected custom legalisation");
5943     // Don't promote division/remainder by constant since we should expand those
5944     // to multiply by magic constant.
5945     // FIXME: What if the expansion is disabled for minsize.
5946     if (N->getOperand(1).getOpcode() == ISD::Constant)
5947       return;
5948 
5949     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5950     // the upper 32 bits. For other types we need to sign or zero extend
5951     // based on the opcode.
5952     unsigned ExtOpc = ISD::ANY_EXTEND;
5953     if (VT != MVT::i32)
5954       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5955                                            : ISD::ZERO_EXTEND;
5956 
5957     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5958     break;
5959   }
5960   case ISD::UADDO:
5961   case ISD::USUBO: {
5962     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5963            "Unexpected custom legalisation");
5964     bool IsAdd = N->getOpcode() == ISD::UADDO;
5965     // Create an ADDW or SUBW.
5966     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5967     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5968     SDValue Res =
5969         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5970     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5971                       DAG.getValueType(MVT::i32));
5972 
5973     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5974     // Since the inputs are sign extended from i32, this is equivalent to
5975     // comparing the lower 32 bits.
5976     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5977     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5978                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5979 
5980     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5981     Results.push_back(Overflow);
5982     return;
5983   }
5984   case ISD::UADDSAT:
5985   case ISD::USUBSAT: {
5986     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5987            "Unexpected custom legalisation");
5988     if (Subtarget.hasStdExtZbb()) {
5989       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5990       // sign extend allows overflow of the lower 32 bits to be detected on
5991       // the promoted size.
5992       SDValue LHS =
5993           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5994       SDValue RHS =
5995           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5996       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5997       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5998       return;
5999     }
6000 
6001     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6002     // promotion for UADDO/USUBO.
6003     Results.push_back(expandAddSubSat(N, DAG));
6004     return;
6005   }
6006   case ISD::BITCAST: {
6007     EVT VT = N->getValueType(0);
6008     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6009     SDValue Op0 = N->getOperand(0);
6010     EVT Op0VT = Op0.getValueType();
6011     MVT XLenVT = Subtarget.getXLenVT();
6012     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6013       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6014       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6015     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6016                Subtarget.hasStdExtF()) {
6017       SDValue FPConv =
6018           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6019       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6020     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6021                isTypeLegal(Op0VT)) {
6022       // Custom-legalize bitcasts from fixed-length vector types to illegal
6023       // scalar types in order to improve codegen. Bitcast the vector to a
6024       // one-element vector type whose element type is the same as the result
6025       // type, and extract the first element.
6026       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6027       if (isTypeLegal(BVT)) {
6028         SDValue BVec = DAG.getBitcast(BVT, Op0);
6029         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6030                                       DAG.getConstant(0, DL, XLenVT)));
6031       }
6032     }
6033     break;
6034   }
6035   case RISCVISD::GREV:
6036   case RISCVISD::GORC: {
6037     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6038            "Unexpected custom legalisation");
6039     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6040     // This is similar to customLegalizeToWOp, except that we pass the second
6041     // operand (a TargetConstant) straight through: it is already of type
6042     // XLenVT.
6043     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6044     SDValue NewOp0 =
6045         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6046     SDValue NewOp1 =
6047         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6048     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6049     // ReplaceNodeResults requires we maintain the same type for the return
6050     // value.
6051     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6052     break;
6053   }
6054   case RISCVISD::SHFL: {
6055     // There is no SHFLIW instruction, but we can just promote the operation.
6056     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6057            "Unexpected custom legalisation");
6058     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6059     SDValue NewOp0 =
6060         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6061     SDValue NewOp1 =
6062         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6063     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6064     // ReplaceNodeResults requires we maintain the same type for the return
6065     // value.
6066     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6067     break;
6068   }
6069   case ISD::BSWAP:
6070   case ISD::BITREVERSE: {
6071     MVT VT = N->getSimpleValueType(0);
6072     MVT XLenVT = Subtarget.getXLenVT();
6073     assert((VT == MVT::i8 || VT == MVT::i16 ||
6074             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6075            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6076     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6077     unsigned Imm = VT.getSizeInBits() - 1;
6078     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6079     if (N->getOpcode() == ISD::BSWAP)
6080       Imm &= ~0x7U;
6081     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6082     SDValue GREVI =
6083         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6084     // ReplaceNodeResults requires we maintain the same type for the return
6085     // value.
6086     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6087     break;
6088   }
6089   case ISD::FSHL:
6090   case ISD::FSHR: {
6091     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6092            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6093     SDValue NewOp0 =
6094         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6095     SDValue NewOp1 =
6096         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6097     SDValue NewOp2 =
6098         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6099     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6100     // Mask the shift amount to 5 bits.
6101     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6102                          DAG.getConstant(0x1f, DL, MVT::i64));
6103     unsigned Opc =
6104         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6105     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6106     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6107     break;
6108   }
6109   case ISD::EXTRACT_VECTOR_ELT: {
6110     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6111     // type is illegal (currently only vXi64 RV32).
6112     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6113     // transferred to the destination register. We issue two of these from the
6114     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6115     // first element.
6116     SDValue Vec = N->getOperand(0);
6117     SDValue Idx = N->getOperand(1);
6118 
6119     // The vector type hasn't been legalized yet so we can't issue target
6120     // specific nodes if it needs legalization.
6121     // FIXME: We would manually legalize if it's important.
6122     if (!isTypeLegal(Vec.getValueType()))
6123       return;
6124 
6125     MVT VecVT = Vec.getSimpleValueType();
6126 
6127     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6128            VecVT.getVectorElementType() == MVT::i64 &&
6129            "Unexpected EXTRACT_VECTOR_ELT legalization");
6130 
6131     // If this is a fixed vector, we need to convert it to a scalable vector.
6132     MVT ContainerVT = VecVT;
6133     if (VecVT.isFixedLengthVector()) {
6134       ContainerVT = getContainerForFixedLengthVector(VecVT);
6135       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6136     }
6137 
6138     MVT XLenVT = Subtarget.getXLenVT();
6139 
6140     // Use a VL of 1 to avoid processing more elements than we need.
6141     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6142     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6143     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6144 
6145     // Unless the index is known to be 0, we must slide the vector down to get
6146     // the desired element into index 0.
6147     if (!isNullConstant(Idx)) {
6148       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6149                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6150     }
6151 
6152     // Extract the lower XLEN bits of the correct vector element.
6153     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6154 
6155     // To extract the upper XLEN bits of the vector element, shift the first
6156     // element right by 32 bits and re-extract the lower XLEN bits.
6157     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6158                                      DAG.getConstant(32, DL, XLenVT), VL);
6159     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6160                                  ThirtyTwoV, Mask, VL);
6161 
6162     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6163 
6164     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6165     break;
6166   }
6167   case ISD::INTRINSIC_WO_CHAIN: {
6168     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6169     switch (IntNo) {
6170     default:
6171       llvm_unreachable(
6172           "Don't know how to custom type legalize this intrinsic!");
6173     case Intrinsic::riscv_orc_b: {
6174       // Lower to the GORCI encoding for orc.b with the operand extended.
6175       SDValue NewOp =
6176           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6177       // If Zbp is enabled, use GORCIW which will sign extend the result.
6178       unsigned Opc =
6179           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6180       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6181                                 DAG.getConstant(7, DL, MVT::i64));
6182       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6183       return;
6184     }
6185     case Intrinsic::riscv_grev:
6186     case Intrinsic::riscv_gorc: {
6187       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6188              "Unexpected custom legalisation");
6189       SDValue NewOp1 =
6190           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6191       SDValue NewOp2 =
6192           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6193       unsigned Opc =
6194           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6195       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6196       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6197       break;
6198     }
6199     case Intrinsic::riscv_shfl:
6200     case Intrinsic::riscv_unshfl: {
6201       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6202              "Unexpected custom legalisation");
6203       SDValue NewOp1 =
6204           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6205       SDValue NewOp2 =
6206           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6207       unsigned Opc =
6208           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6209       if (isa<ConstantSDNode>(N->getOperand(2))) {
6210         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6211                              DAG.getConstant(0xf, DL, MVT::i64));
6212         Opc =
6213             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6214       }
6215       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6216       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6217       break;
6218     }
6219     case Intrinsic::riscv_bcompress:
6220     case Intrinsic::riscv_bdecompress: {
6221       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6222              "Unexpected custom legalisation");
6223       SDValue NewOp1 =
6224           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6225       SDValue NewOp2 =
6226           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6227       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6228                          ? RISCVISD::BCOMPRESSW
6229                          : RISCVISD::BDECOMPRESSW;
6230       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6231       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6232       break;
6233     }
6234     case Intrinsic::riscv_vmv_x_s: {
6235       EVT VT = N->getValueType(0);
6236       MVT XLenVT = Subtarget.getXLenVT();
6237       if (VT.bitsLT(XLenVT)) {
6238         // Simple case just extract using vmv.x.s and truncate.
6239         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6240                                       Subtarget.getXLenVT(), N->getOperand(1));
6241         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6242         return;
6243       }
6244 
6245       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6246              "Unexpected custom legalization");
6247 
6248       // We need to do the move in two steps.
6249       SDValue Vec = N->getOperand(1);
6250       MVT VecVT = Vec.getSimpleValueType();
6251 
6252       // First extract the lower XLEN bits of the element.
6253       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6254 
6255       // To extract the upper XLEN bits of the vector element, shift the first
6256       // element right by 32 bits and re-extract the lower XLEN bits.
6257       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6258       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6259       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6260       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6261                                        DAG.getConstant(32, DL, XLenVT), VL);
6262       SDValue LShr32 =
6263           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6264       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6265 
6266       Results.push_back(
6267           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6268       break;
6269     }
6270     }
6271     break;
6272   }
6273   case ISD::VECREDUCE_ADD:
6274   case ISD::VECREDUCE_AND:
6275   case ISD::VECREDUCE_OR:
6276   case ISD::VECREDUCE_XOR:
6277   case ISD::VECREDUCE_SMAX:
6278   case ISD::VECREDUCE_UMAX:
6279   case ISD::VECREDUCE_SMIN:
6280   case ISD::VECREDUCE_UMIN:
6281     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6282       Results.push_back(V);
6283     break;
6284   case ISD::VP_REDUCE_ADD:
6285   case ISD::VP_REDUCE_AND:
6286   case ISD::VP_REDUCE_OR:
6287   case ISD::VP_REDUCE_XOR:
6288   case ISD::VP_REDUCE_SMAX:
6289   case ISD::VP_REDUCE_UMAX:
6290   case ISD::VP_REDUCE_SMIN:
6291   case ISD::VP_REDUCE_UMIN:
6292     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6293       Results.push_back(V);
6294     break;
6295   case ISD::FLT_ROUNDS_: {
6296     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6297     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6298     Results.push_back(Res.getValue(0));
6299     Results.push_back(Res.getValue(1));
6300     break;
6301   }
6302   }
6303 }
6304 
6305 // A structure to hold one of the bit-manipulation patterns below. Together, a
6306 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6307 //   (or (and (shl x, 1), 0xAAAAAAAA),
6308 //       (and (srl x, 1), 0x55555555))
6309 struct RISCVBitmanipPat {
6310   SDValue Op;
6311   unsigned ShAmt;
6312   bool IsSHL;
6313 
6314   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6315     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6316   }
6317 };
6318 
6319 // Matches patterns of the form
6320 //   (and (shl x, C2), (C1 << C2))
6321 //   (and (srl x, C2), C1)
6322 //   (shl (and x, C1), C2)
6323 //   (srl (and x, (C1 << C2)), C2)
6324 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6325 // The expected masks for each shift amount are specified in BitmanipMasks where
6326 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6327 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6328 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6329 // XLen is 64.
6330 static Optional<RISCVBitmanipPat>
6331 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6332   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6333          "Unexpected number of masks");
6334   Optional<uint64_t> Mask;
6335   // Optionally consume a mask around the shift operation.
6336   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6337     Mask = Op.getConstantOperandVal(1);
6338     Op = Op.getOperand(0);
6339   }
6340   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6341     return None;
6342   bool IsSHL = Op.getOpcode() == ISD::SHL;
6343 
6344   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6345     return None;
6346   uint64_t ShAmt = Op.getConstantOperandVal(1);
6347 
6348   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6349   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6350     return None;
6351   // If we don't have enough masks for 64 bit, then we must be trying to
6352   // match SHFL so we're only allowed to shift 1/4 of the width.
6353   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6354     return None;
6355 
6356   SDValue Src = Op.getOperand(0);
6357 
6358   // The expected mask is shifted left when the AND is found around SHL
6359   // patterns.
6360   //   ((x >> 1) & 0x55555555)
6361   //   ((x << 1) & 0xAAAAAAAA)
6362   bool SHLExpMask = IsSHL;
6363 
6364   if (!Mask) {
6365     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6366     // the mask is all ones: consume that now.
6367     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6368       Mask = Src.getConstantOperandVal(1);
6369       Src = Src.getOperand(0);
6370       // The expected mask is now in fact shifted left for SRL, so reverse the
6371       // decision.
6372       //   ((x & 0xAAAAAAAA) >> 1)
6373       //   ((x & 0x55555555) << 1)
6374       SHLExpMask = !SHLExpMask;
6375     } else {
6376       // Use a default shifted mask of all-ones if there's no AND, truncated
6377       // down to the expected width. This simplifies the logic later on.
6378       Mask = maskTrailingOnes<uint64_t>(Width);
6379       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6380     }
6381   }
6382 
6383   unsigned MaskIdx = Log2_32(ShAmt);
6384   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6385 
6386   if (SHLExpMask)
6387     ExpMask <<= ShAmt;
6388 
6389   if (Mask != ExpMask)
6390     return None;
6391 
6392   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6393 }
6394 
6395 // Matches any of the following bit-manipulation patterns:
6396 //   (and (shl x, 1), (0x55555555 << 1))
6397 //   (and (srl x, 1), 0x55555555)
6398 //   (shl (and x, 0x55555555), 1)
6399 //   (srl (and x, (0x55555555 << 1)), 1)
6400 // where the shift amount and mask may vary thus:
6401 //   [1]  = 0x55555555 / 0xAAAAAAAA
6402 //   [2]  = 0x33333333 / 0xCCCCCCCC
6403 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6404 //   [8]  = 0x00FF00FF / 0xFF00FF00
6405 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6406 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6407 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6408   // These are the unshifted masks which we use to match bit-manipulation
6409   // patterns. They may be shifted left in certain circumstances.
6410   static const uint64_t BitmanipMasks[] = {
6411       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6412       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6413 
6414   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6415 }
6416 
6417 // Match the following pattern as a GREVI(W) operation
6418 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6419 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6420                                const RISCVSubtarget &Subtarget) {
6421   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6422   EVT VT = Op.getValueType();
6423 
6424   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6425     auto LHS = matchGREVIPat(Op.getOperand(0));
6426     auto RHS = matchGREVIPat(Op.getOperand(1));
6427     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6428       SDLoc DL(Op);
6429       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6430                          DAG.getConstant(LHS->ShAmt, DL, VT));
6431     }
6432   }
6433   return SDValue();
6434 }
6435 
6436 // Matches any the following pattern as a GORCI(W) operation
6437 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6438 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6439 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6440 // Note that with the variant of 3.,
6441 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6442 // the inner pattern will first be matched as GREVI and then the outer
6443 // pattern will be matched to GORC via the first rule above.
6444 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6445 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6446                                const RISCVSubtarget &Subtarget) {
6447   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6448   EVT VT = Op.getValueType();
6449 
6450   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6451     SDLoc DL(Op);
6452     SDValue Op0 = Op.getOperand(0);
6453     SDValue Op1 = Op.getOperand(1);
6454 
6455     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6456       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6457           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6458           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6459         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6460       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6461       if ((Reverse.getOpcode() == ISD::ROTL ||
6462            Reverse.getOpcode() == ISD::ROTR) &&
6463           Reverse.getOperand(0) == X &&
6464           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6465         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6466         if (RotAmt == (VT.getSizeInBits() / 2))
6467           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6468                              DAG.getConstant(RotAmt, DL, VT));
6469       }
6470       return SDValue();
6471     };
6472 
6473     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6474     if (SDValue V = MatchOROfReverse(Op0, Op1))
6475       return V;
6476     if (SDValue V = MatchOROfReverse(Op1, Op0))
6477       return V;
6478 
6479     // OR is commutable so canonicalize its OR operand to the left
6480     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6481       std::swap(Op0, Op1);
6482     if (Op0.getOpcode() != ISD::OR)
6483       return SDValue();
6484     SDValue OrOp0 = Op0.getOperand(0);
6485     SDValue OrOp1 = Op0.getOperand(1);
6486     auto LHS = matchGREVIPat(OrOp0);
6487     // OR is commutable so swap the operands and try again: x might have been
6488     // on the left
6489     if (!LHS) {
6490       std::swap(OrOp0, OrOp1);
6491       LHS = matchGREVIPat(OrOp0);
6492     }
6493     auto RHS = matchGREVIPat(Op1);
6494     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6495       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6496                          DAG.getConstant(LHS->ShAmt, DL, VT));
6497     }
6498   }
6499   return SDValue();
6500 }
6501 
6502 // Matches any of the following bit-manipulation patterns:
6503 //   (and (shl x, 1), (0x22222222 << 1))
6504 //   (and (srl x, 1), 0x22222222)
6505 //   (shl (and x, 0x22222222), 1)
6506 //   (srl (and x, (0x22222222 << 1)), 1)
6507 // where the shift amount and mask may vary thus:
6508 //   [1]  = 0x22222222 / 0x44444444
6509 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6510 //   [4]  = 0x00F000F0 / 0x0F000F00
6511 //   [8]  = 0x0000FF00 / 0x00FF0000
6512 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6513 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6514   // These are the unshifted masks which we use to match bit-manipulation
6515   // patterns. They may be shifted left in certain circumstances.
6516   static const uint64_t BitmanipMasks[] = {
6517       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6518       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6519 
6520   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6521 }
6522 
6523 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6524 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6525                                const RISCVSubtarget &Subtarget) {
6526   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6527   EVT VT = Op.getValueType();
6528 
6529   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6530     return SDValue();
6531 
6532   SDValue Op0 = Op.getOperand(0);
6533   SDValue Op1 = Op.getOperand(1);
6534 
6535   // Or is commutable so canonicalize the second OR to the LHS.
6536   if (Op0.getOpcode() != ISD::OR)
6537     std::swap(Op0, Op1);
6538   if (Op0.getOpcode() != ISD::OR)
6539     return SDValue();
6540 
6541   // We found an inner OR, so our operands are the operands of the inner OR
6542   // and the other operand of the outer OR.
6543   SDValue A = Op0.getOperand(0);
6544   SDValue B = Op0.getOperand(1);
6545   SDValue C = Op1;
6546 
6547   auto Match1 = matchSHFLPat(A);
6548   auto Match2 = matchSHFLPat(B);
6549 
6550   // If neither matched, we failed.
6551   if (!Match1 && !Match2)
6552     return SDValue();
6553 
6554   // We had at least one match. if one failed, try the remaining C operand.
6555   if (!Match1) {
6556     std::swap(A, C);
6557     Match1 = matchSHFLPat(A);
6558     if (!Match1)
6559       return SDValue();
6560   } else if (!Match2) {
6561     std::swap(B, C);
6562     Match2 = matchSHFLPat(B);
6563     if (!Match2)
6564       return SDValue();
6565   }
6566   assert(Match1 && Match2);
6567 
6568   // Make sure our matches pair up.
6569   if (!Match1->formsPairWith(*Match2))
6570     return SDValue();
6571 
6572   // All the remains is to make sure C is an AND with the same input, that masks
6573   // out the bits that are being shuffled.
6574   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6575       C.getOperand(0) != Match1->Op)
6576     return SDValue();
6577 
6578   uint64_t Mask = C.getConstantOperandVal(1);
6579 
6580   static const uint64_t BitmanipMasks[] = {
6581       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6582       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6583   };
6584 
6585   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6586   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6587   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6588 
6589   if (Mask != ExpMask)
6590     return SDValue();
6591 
6592   SDLoc DL(Op);
6593   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6594                      DAG.getConstant(Match1->ShAmt, DL, VT));
6595 }
6596 
6597 // Optimize (add (shl x, c0), (shl y, c1)) ->
6598 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6599 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6600                                   const RISCVSubtarget &Subtarget) {
6601   // Perform this optimization only in the zba extension.
6602   if (!Subtarget.hasStdExtZba())
6603     return SDValue();
6604 
6605   // Skip for vector types and larger types.
6606   EVT VT = N->getValueType(0);
6607   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6608     return SDValue();
6609 
6610   // The two operand nodes must be SHL and have no other use.
6611   SDValue N0 = N->getOperand(0);
6612   SDValue N1 = N->getOperand(1);
6613   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6614       !N0->hasOneUse() || !N1->hasOneUse())
6615     return SDValue();
6616 
6617   // Check c0 and c1.
6618   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6619   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6620   if (!N0C || !N1C)
6621     return SDValue();
6622   int64_t C0 = N0C->getSExtValue();
6623   int64_t C1 = N1C->getSExtValue();
6624   if (C0 <= 0 || C1 <= 0)
6625     return SDValue();
6626 
6627   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6628   int64_t Bits = std::min(C0, C1);
6629   int64_t Diff = std::abs(C0 - C1);
6630   if (Diff != 1 && Diff != 2 && Diff != 3)
6631     return SDValue();
6632 
6633   // Build nodes.
6634   SDLoc DL(N);
6635   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6636   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6637   SDValue NA0 =
6638       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6639   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6640   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6641 }
6642 
6643 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6644 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6645 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6646 // not undo itself, but they are redundant.
6647 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6648   SDValue Src = N->getOperand(0);
6649 
6650   if (Src.getOpcode() != N->getOpcode())
6651     return SDValue();
6652 
6653   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6654       !isa<ConstantSDNode>(Src.getOperand(1)))
6655     return SDValue();
6656 
6657   unsigned ShAmt1 = N->getConstantOperandVal(1);
6658   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6659   Src = Src.getOperand(0);
6660 
6661   unsigned CombinedShAmt;
6662   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6663     CombinedShAmt = ShAmt1 | ShAmt2;
6664   else
6665     CombinedShAmt = ShAmt1 ^ ShAmt2;
6666 
6667   if (CombinedShAmt == 0)
6668     return Src;
6669 
6670   SDLoc DL(N);
6671   return DAG.getNode(
6672       N->getOpcode(), DL, N->getValueType(0), Src,
6673       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6674 }
6675 
6676 // Combine a constant select operand into its use:
6677 //
6678 // (and (select cond, -1, c), x)
6679 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6680 // (or  (select cond, 0, c), x)
6681 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6682 // (xor (select cond, 0, c), x)
6683 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6684 // (add (select cond, 0, c), x)
6685 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6686 // (sub x, (select cond, 0, c))
6687 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6688 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6689                                    SelectionDAG &DAG, bool AllOnes) {
6690   EVT VT = N->getValueType(0);
6691 
6692   // Skip vectors.
6693   if (VT.isVector())
6694     return SDValue();
6695 
6696   if ((Slct.getOpcode() != ISD::SELECT &&
6697        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6698       !Slct.hasOneUse())
6699     return SDValue();
6700 
6701   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6702     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6703   };
6704 
6705   bool SwapSelectOps;
6706   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6707   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6708   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6709   SDValue NonConstantVal;
6710   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6711     SwapSelectOps = false;
6712     NonConstantVal = FalseVal;
6713   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6714     SwapSelectOps = true;
6715     NonConstantVal = TrueVal;
6716   } else
6717     return SDValue();
6718 
6719   // Slct is now know to be the desired identity constant when CC is true.
6720   TrueVal = OtherOp;
6721   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6722   // Unless SwapSelectOps says the condition should be false.
6723   if (SwapSelectOps)
6724     std::swap(TrueVal, FalseVal);
6725 
6726   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6727     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6728                        {Slct.getOperand(0), Slct.getOperand(1),
6729                         Slct.getOperand(2), TrueVal, FalseVal});
6730 
6731   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6732                      {Slct.getOperand(0), TrueVal, FalseVal});
6733 }
6734 
6735 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6736 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6737                                               bool AllOnes) {
6738   SDValue N0 = N->getOperand(0);
6739   SDValue N1 = N->getOperand(1);
6740   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6741     return Result;
6742   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6743     return Result;
6744   return SDValue();
6745 }
6746 
6747 // Transform (add (mul x, c0), c1) ->
6748 //           (add (mul (add x, c1/c0), c0), c1%c0).
6749 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6750 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6751 // to an infinite loop in DAGCombine if transformed.
6752 // Or transform (add (mul x, c0), c1) ->
6753 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6754 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6755 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6756 // lead to an infinite loop in DAGCombine if transformed.
6757 // Or transform (add (mul x, c0), c1) ->
6758 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6759 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6760 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6761 // lead to an infinite loop in DAGCombine if transformed.
6762 // Or transform (add (mul x, c0), c1) ->
6763 //              (mul (add x, c1/c0), c0).
6764 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6765 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6766                                      const RISCVSubtarget &Subtarget) {
6767   // Skip for vector types and larger types.
6768   EVT VT = N->getValueType(0);
6769   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6770     return SDValue();
6771   // The first operand node must be a MUL and has no other use.
6772   SDValue N0 = N->getOperand(0);
6773   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6774     return SDValue();
6775   // Check if c0 and c1 match above conditions.
6776   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6777   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6778   if (!N0C || !N1C)
6779     return SDValue();
6780   int64_t C0 = N0C->getSExtValue();
6781   int64_t C1 = N1C->getSExtValue();
6782   int64_t CA, CB;
6783   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6784     return SDValue();
6785   // Search for proper CA (non-zero) and CB that both are simm12.
6786   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6787       !isInt<12>(C0 * (C1 / C0))) {
6788     CA = C1 / C0;
6789     CB = C1 % C0;
6790   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6791              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6792     CA = C1 / C0 + 1;
6793     CB = C1 % C0 - C0;
6794   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6795              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6796     CA = C1 / C0 - 1;
6797     CB = C1 % C0 + C0;
6798   } else
6799     return SDValue();
6800   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6801   SDLoc DL(N);
6802   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6803                              DAG.getConstant(CA, DL, VT));
6804   SDValue New1 =
6805       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6806   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6807 }
6808 
6809 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6810                                  const RISCVSubtarget &Subtarget) {
6811   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6812     return V;
6813   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6814     return V;
6815   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6816   //      (select lhs, rhs, cc, x, (add x, y))
6817   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6818 }
6819 
6820 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6821   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6822   //      (select lhs, rhs, cc, x, (sub x, y))
6823   SDValue N0 = N->getOperand(0);
6824   SDValue N1 = N->getOperand(1);
6825   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6826 }
6827 
6828 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6829   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6830   //      (select lhs, rhs, cc, x, (and x, y))
6831   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6832 }
6833 
6834 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6835                                 const RISCVSubtarget &Subtarget) {
6836   if (Subtarget.hasStdExtZbp()) {
6837     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6838       return GREV;
6839     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6840       return GORC;
6841     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6842       return SHFL;
6843   }
6844 
6845   // fold (or (select cond, 0, y), x) ->
6846   //      (select cond, x, (or x, y))
6847   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6848 }
6849 
6850 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6851   // fold (xor (select cond, 0, y), x) ->
6852   //      (select cond, x, (xor x, y))
6853   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6854 }
6855 
6856 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6857 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6858 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6859 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6860 // ADDW/SUBW/MULW.
6861 static SDValue performANY_EXTENDCombine(SDNode *N,
6862                                         TargetLowering::DAGCombinerInfo &DCI,
6863                                         const RISCVSubtarget &Subtarget) {
6864   if (!Subtarget.is64Bit())
6865     return SDValue();
6866 
6867   SelectionDAG &DAG = DCI.DAG;
6868 
6869   SDValue Src = N->getOperand(0);
6870   EVT VT = N->getValueType(0);
6871   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6872     return SDValue();
6873 
6874   // The opcode must be one that can implicitly sign_extend.
6875   // FIXME: Additional opcodes.
6876   switch (Src.getOpcode()) {
6877   default:
6878     return SDValue();
6879   case ISD::MUL:
6880     if (!Subtarget.hasStdExtM())
6881       return SDValue();
6882     LLVM_FALLTHROUGH;
6883   case ISD::ADD:
6884   case ISD::SUB:
6885     break;
6886   }
6887 
6888   // Only handle cases where the result is used by a CopyToReg. That likely
6889   // means the value is a liveout of the basic block. This helps prevent
6890   // infinite combine loops like PR51206.
6891   if (none_of(N->uses(),
6892               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6893     return SDValue();
6894 
6895   SmallVector<SDNode *, 4> SetCCs;
6896   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6897                             UE = Src.getNode()->use_end();
6898        UI != UE; ++UI) {
6899     SDNode *User = *UI;
6900     if (User == N)
6901       continue;
6902     if (UI.getUse().getResNo() != Src.getResNo())
6903       continue;
6904     // All i32 setccs are legalized by sign extending operands.
6905     if (User->getOpcode() == ISD::SETCC) {
6906       SetCCs.push_back(User);
6907       continue;
6908     }
6909     // We don't know if we can extend this user.
6910     break;
6911   }
6912 
6913   // If we don't have any SetCCs, this isn't worthwhile.
6914   if (SetCCs.empty())
6915     return SDValue();
6916 
6917   SDLoc DL(N);
6918   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6919   DCI.CombineTo(N, SExt);
6920 
6921   // Promote all the setccs.
6922   for (SDNode *SetCC : SetCCs) {
6923     SmallVector<SDValue, 4> Ops;
6924 
6925     for (unsigned j = 0; j != 2; ++j) {
6926       SDValue SOp = SetCC->getOperand(j);
6927       if (SOp == Src)
6928         Ops.push_back(SExt);
6929       else
6930         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6931     }
6932 
6933     Ops.push_back(SetCC->getOperand(2));
6934     DCI.CombineTo(SetCC,
6935                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6936   }
6937   return SDValue(N, 0);
6938 }
6939 
6940 // Try to form VWMUL or VWMULU.
6941 // FIXME: Support VWMULSU.
6942 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6943                                     SelectionDAG &DAG) {
6944   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6945   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6946   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6947   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6948     return SDValue();
6949 
6950   SDValue Mask = N->getOperand(2);
6951   SDValue VL = N->getOperand(3);
6952 
6953   // Make sure the mask and VL match.
6954   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6955     return SDValue();
6956 
6957   MVT VT = N->getSimpleValueType(0);
6958 
6959   // Determine the narrow size for a widening multiply.
6960   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6961   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6962                                   VT.getVectorElementCount());
6963 
6964   SDLoc DL(N);
6965 
6966   // See if the other operand is the same opcode.
6967   if (Op0.getOpcode() == Op1.getOpcode()) {
6968     if (!Op1.hasOneUse())
6969       return SDValue();
6970 
6971     // Make sure the mask and VL match.
6972     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6973       return SDValue();
6974 
6975     Op1 = Op1.getOperand(0);
6976   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6977     // The operand is a splat of a scalar.
6978 
6979     // The VL must be the same.
6980     if (Op1.getOperand(1) != VL)
6981       return SDValue();
6982 
6983     // Get the scalar value.
6984     Op1 = Op1.getOperand(0);
6985 
6986     // See if have enough sign bits or zero bits in the scalar to use a
6987     // widening multiply by splatting to smaller element size.
6988     unsigned EltBits = VT.getScalarSizeInBits();
6989     unsigned ScalarBits = Op1.getValueSizeInBits();
6990     // Make sure we're getting all element bits from the scalar register.
6991     // FIXME: Support implicit sign extension of vmv.v.x?
6992     if (ScalarBits < EltBits)
6993       return SDValue();
6994 
6995     if (IsSignExt) {
6996       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6997         return SDValue();
6998     } else {
6999       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7000       if (!DAG.MaskedValueIsZero(Op1, Mask))
7001         return SDValue();
7002     }
7003 
7004     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7005   } else
7006     return SDValue();
7007 
7008   Op0 = Op0.getOperand(0);
7009 
7010   // Re-introduce narrower extends if needed.
7011   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7012   if (Op0.getValueType() != NarrowVT)
7013     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7014   if (Op1.getValueType() != NarrowVT)
7015     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7016 
7017   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7018   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7019 }
7020 
7021 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7022                                                DAGCombinerInfo &DCI) const {
7023   SelectionDAG &DAG = DCI.DAG;
7024 
7025   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7026   // bits are demanded. N will be added to the Worklist if it was not deleted.
7027   // Caller should return SDValue(N, 0) if this returns true.
7028   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7029     SDValue Op = N->getOperand(OpNo);
7030     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7031     if (!SimplifyDemandedBits(Op, Mask, DCI))
7032       return false;
7033 
7034     if (N->getOpcode() != ISD::DELETED_NODE)
7035       DCI.AddToWorklist(N);
7036     return true;
7037   };
7038 
7039   switch (N->getOpcode()) {
7040   default:
7041     break;
7042   case RISCVISD::SplitF64: {
7043     SDValue Op0 = N->getOperand(0);
7044     // If the input to SplitF64 is just BuildPairF64 then the operation is
7045     // redundant. Instead, use BuildPairF64's operands directly.
7046     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7047       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7048 
7049     SDLoc DL(N);
7050 
7051     // It's cheaper to materialise two 32-bit integers than to load a double
7052     // from the constant pool and transfer it to integer registers through the
7053     // stack.
7054     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7055       APInt V = C->getValueAPF().bitcastToAPInt();
7056       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7057       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7058       return DCI.CombineTo(N, Lo, Hi);
7059     }
7060 
7061     // This is a target-specific version of a DAGCombine performed in
7062     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7063     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7064     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7065     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7066         !Op0.getNode()->hasOneUse())
7067       break;
7068     SDValue NewSplitF64 =
7069         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7070                     Op0.getOperand(0));
7071     SDValue Lo = NewSplitF64.getValue(0);
7072     SDValue Hi = NewSplitF64.getValue(1);
7073     APInt SignBit = APInt::getSignMask(32);
7074     if (Op0.getOpcode() == ISD::FNEG) {
7075       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7076                                   DAG.getConstant(SignBit, DL, MVT::i32));
7077       return DCI.CombineTo(N, Lo, NewHi);
7078     }
7079     assert(Op0.getOpcode() == ISD::FABS);
7080     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7081                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7082     return DCI.CombineTo(N, Lo, NewHi);
7083   }
7084   case RISCVISD::SLLW:
7085   case RISCVISD::SRAW:
7086   case RISCVISD::SRLW:
7087   case RISCVISD::ROLW:
7088   case RISCVISD::RORW: {
7089     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7090     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7091         SimplifyDemandedLowBitsHelper(1, 5))
7092       return SDValue(N, 0);
7093     break;
7094   }
7095   case RISCVISD::CLZW:
7096   case RISCVISD::CTZW: {
7097     // Only the lower 32 bits of the first operand are read
7098     if (SimplifyDemandedLowBitsHelper(0, 32))
7099       return SDValue(N, 0);
7100     break;
7101   }
7102   case RISCVISD::FSL:
7103   case RISCVISD::FSR: {
7104     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7105     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7106     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7107     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7108       return SDValue(N, 0);
7109     break;
7110   }
7111   case RISCVISD::FSLW:
7112   case RISCVISD::FSRW: {
7113     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7114     // read.
7115     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7116         SimplifyDemandedLowBitsHelper(1, 32) ||
7117         SimplifyDemandedLowBitsHelper(2, 6))
7118       return SDValue(N, 0);
7119     break;
7120   }
7121   case RISCVISD::GREV:
7122   case RISCVISD::GORC: {
7123     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7124     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7125     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7126     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7127       return SDValue(N, 0);
7128 
7129     return combineGREVI_GORCI(N, DAG);
7130   }
7131   case RISCVISD::GREVW:
7132   case RISCVISD::GORCW: {
7133     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7134     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7135         SimplifyDemandedLowBitsHelper(1, 5))
7136       return SDValue(N, 0);
7137 
7138     return combineGREVI_GORCI(N, DAG);
7139   }
7140   case RISCVISD::SHFL:
7141   case RISCVISD::UNSHFL: {
7142     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7143     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7144     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7145     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7146       return SDValue(N, 0);
7147 
7148     break;
7149   }
7150   case RISCVISD::SHFLW:
7151   case RISCVISD::UNSHFLW: {
7152     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7153     SDValue LHS = N->getOperand(0);
7154     SDValue RHS = N->getOperand(1);
7155     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7156     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7157     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7158         SimplifyDemandedLowBitsHelper(1, 4))
7159       return SDValue(N, 0);
7160 
7161     break;
7162   }
7163   case RISCVISD::BCOMPRESSW:
7164   case RISCVISD::BDECOMPRESSW: {
7165     // Only the lower 32 bits of LHS and RHS are read.
7166     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7167         SimplifyDemandedLowBitsHelper(1, 32))
7168       return SDValue(N, 0);
7169 
7170     break;
7171   }
7172   case RISCVISD::FMV_X_ANYEXTH:
7173   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7174     SDLoc DL(N);
7175     SDValue Op0 = N->getOperand(0);
7176     MVT VT = N->getSimpleValueType(0);
7177     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7178     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7179     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7180     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7181          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7182         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7183          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7184       assert(Op0.getOperand(0).getValueType() == VT &&
7185              "Unexpected value type!");
7186       return Op0.getOperand(0);
7187     }
7188 
7189     // This is a target-specific version of a DAGCombine performed in
7190     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7191     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7192     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7193     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7194         !Op0.getNode()->hasOneUse())
7195       break;
7196     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7197     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7198     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7199     if (Op0.getOpcode() == ISD::FNEG)
7200       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7201                          DAG.getConstant(SignBit, DL, VT));
7202 
7203     assert(Op0.getOpcode() == ISD::FABS);
7204     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7205                        DAG.getConstant(~SignBit, DL, VT));
7206   }
7207   case ISD::ADD:
7208     return performADDCombine(N, DAG, Subtarget);
7209   case ISD::SUB:
7210     return performSUBCombine(N, DAG);
7211   case ISD::AND:
7212     return performANDCombine(N, DAG);
7213   case ISD::OR:
7214     return performORCombine(N, DAG, Subtarget);
7215   case ISD::XOR:
7216     return performXORCombine(N, DAG);
7217   case ISD::ANY_EXTEND:
7218     return performANY_EXTENDCombine(N, DCI, Subtarget);
7219   case ISD::ZERO_EXTEND:
7220     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7221     // type legalization. This is safe because fp_to_uint produces poison if
7222     // it overflows.
7223     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7224       SDValue Src = N->getOperand(0);
7225       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7226           isTypeLegal(Src.getOperand(0).getValueType()))
7227         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7228                            Src.getOperand(0));
7229       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7230           isTypeLegal(Src.getOperand(1).getValueType())) {
7231         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7232         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7233                                   Src.getOperand(0), Src.getOperand(1));
7234         DCI.CombineTo(N, Res);
7235         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7236         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7237         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7238       }
7239     }
7240     return SDValue();
7241   case RISCVISD::SELECT_CC: {
7242     // Transform
7243     SDValue LHS = N->getOperand(0);
7244     SDValue RHS = N->getOperand(1);
7245     SDValue TrueV = N->getOperand(3);
7246     SDValue FalseV = N->getOperand(4);
7247 
7248     // If the True and False values are the same, we don't need a select_cc.
7249     if (TrueV == FalseV)
7250       return TrueV;
7251 
7252     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7253     if (!ISD::isIntEqualitySetCC(CCVal))
7254       break;
7255 
7256     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7257     //      (select_cc X, Y, lt, trueV, falseV)
7258     // Sometimes the setcc is introduced after select_cc has been formed.
7259     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7260         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7261       // If we're looking for eq 0 instead of ne 0, we need to invert the
7262       // condition.
7263       bool Invert = CCVal == ISD::SETEQ;
7264       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7265       if (Invert)
7266         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7267 
7268       SDLoc DL(N);
7269       RHS = LHS.getOperand(1);
7270       LHS = LHS.getOperand(0);
7271       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7272 
7273       SDValue TargetCC = DAG.getCondCode(CCVal);
7274       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7275                          {LHS, RHS, TargetCC, TrueV, FalseV});
7276     }
7277 
7278     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7279     //      (select_cc X, Y, eq/ne, trueV, falseV)
7280     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7281       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7282                          {LHS.getOperand(0), LHS.getOperand(1),
7283                           N->getOperand(2), TrueV, FalseV});
7284     // (select_cc X, 1, setne, trueV, falseV) ->
7285     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7286     // This can occur when legalizing some floating point comparisons.
7287     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7288     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7289       SDLoc DL(N);
7290       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7291       SDValue TargetCC = DAG.getCondCode(CCVal);
7292       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7293       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7294                          {LHS, RHS, TargetCC, TrueV, FalseV});
7295     }
7296 
7297     break;
7298   }
7299   case RISCVISD::BR_CC: {
7300     SDValue LHS = N->getOperand(1);
7301     SDValue RHS = N->getOperand(2);
7302     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7303     if (!ISD::isIntEqualitySetCC(CCVal))
7304       break;
7305 
7306     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7307     //      (br_cc X, Y, lt, dest)
7308     // Sometimes the setcc is introduced after br_cc has been formed.
7309     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7310         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7311       // If we're looking for eq 0 instead of ne 0, we need to invert the
7312       // condition.
7313       bool Invert = CCVal == ISD::SETEQ;
7314       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7315       if (Invert)
7316         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7317 
7318       SDLoc DL(N);
7319       RHS = LHS.getOperand(1);
7320       LHS = LHS.getOperand(0);
7321       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7322 
7323       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7324                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7325                          N->getOperand(4));
7326     }
7327 
7328     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7329     //      (br_cc X, Y, eq/ne, trueV, falseV)
7330     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7331       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7332                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7333                          N->getOperand(3), N->getOperand(4));
7334 
7335     // (br_cc X, 1, setne, br_cc) ->
7336     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7337     // This can occur when legalizing some floating point comparisons.
7338     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7339     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7340       SDLoc DL(N);
7341       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7342       SDValue TargetCC = DAG.getCondCode(CCVal);
7343       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7344       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7345                          N->getOperand(0), LHS, RHS, TargetCC,
7346                          N->getOperand(4));
7347     }
7348     break;
7349   }
7350   case ISD::FCOPYSIGN: {
7351     EVT VT = N->getValueType(0);
7352     if (!VT.isVector())
7353       break;
7354     // There is a form of VFSGNJ which injects the negated sign of its second
7355     // operand. Try and bubble any FNEG up after the extend/round to produce
7356     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7357     // TRUNC=1.
7358     SDValue In2 = N->getOperand(1);
7359     // Avoid cases where the extend/round has multiple uses, as duplicating
7360     // those is typically more expensive than removing a fneg.
7361     if (!In2.hasOneUse())
7362       break;
7363     if (In2.getOpcode() != ISD::FP_EXTEND &&
7364         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7365       break;
7366     In2 = In2.getOperand(0);
7367     if (In2.getOpcode() != ISD::FNEG)
7368       break;
7369     SDLoc DL(N);
7370     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7371     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7372                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7373   }
7374   case ISD::MGATHER:
7375   case ISD::MSCATTER:
7376   case ISD::VP_GATHER:
7377   case ISD::VP_SCATTER: {
7378     if (!DCI.isBeforeLegalize())
7379       break;
7380     SDValue Index, ScaleOp;
7381     bool IsIndexScaled = false;
7382     bool IsIndexSigned = false;
7383     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7384       Index = VPGSN->getIndex();
7385       ScaleOp = VPGSN->getScale();
7386       IsIndexScaled = VPGSN->isIndexScaled();
7387       IsIndexSigned = VPGSN->isIndexSigned();
7388     } else {
7389       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7390       Index = MGSN->getIndex();
7391       ScaleOp = MGSN->getScale();
7392       IsIndexScaled = MGSN->isIndexScaled();
7393       IsIndexSigned = MGSN->isIndexSigned();
7394     }
7395     EVT IndexVT = Index.getValueType();
7396     MVT XLenVT = Subtarget.getXLenVT();
7397     // RISCV indexed loads only support the "unsigned unscaled" addressing
7398     // mode, so anything else must be manually legalized.
7399     bool NeedsIdxLegalization =
7400         IsIndexScaled ||
7401         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7402     if (!NeedsIdxLegalization)
7403       break;
7404 
7405     SDLoc DL(N);
7406 
7407     // Any index legalization should first promote to XLenVT, so we don't lose
7408     // bits when scaling. This may create an illegal index type so we let
7409     // LLVM's legalization take care of the splitting.
7410     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7411     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7412       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7413       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7414                           DL, IndexVT, Index);
7415     }
7416 
7417     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7418     if (IsIndexScaled && Scale != 1) {
7419       // Manually scale the indices by the element size.
7420       // TODO: Sanitize the scale operand here?
7421       // TODO: For VP nodes, should we use VP_SHL here?
7422       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7423       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7424       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7425     }
7426 
7427     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7428     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7429       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7430                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7431                               VPGN->getScale(), VPGN->getMask(),
7432                               VPGN->getVectorLength()},
7433                              VPGN->getMemOperand(), NewIndexTy);
7434     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7435       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7436                               {VPSN->getChain(), VPSN->getValue(),
7437                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7438                                VPSN->getMask(), VPSN->getVectorLength()},
7439                               VPSN->getMemOperand(), NewIndexTy);
7440     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7441       return DAG.getMaskedGather(
7442           N->getVTList(), MGN->getMemoryVT(), DL,
7443           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7444            MGN->getBasePtr(), Index, MGN->getScale()},
7445           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7446     const auto *MSN = cast<MaskedScatterSDNode>(N);
7447     return DAG.getMaskedScatter(
7448         N->getVTList(), MSN->getMemoryVT(), DL,
7449         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7450          Index, MSN->getScale()},
7451         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7452   }
7453   case RISCVISD::SRA_VL:
7454   case RISCVISD::SRL_VL:
7455   case RISCVISD::SHL_VL: {
7456     SDValue ShAmt = N->getOperand(1);
7457     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7458       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7459       SDLoc DL(N);
7460       SDValue VL = N->getOperand(3);
7461       EVT VT = N->getValueType(0);
7462       ShAmt =
7463           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7464       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7465                          N->getOperand(2), N->getOperand(3));
7466     }
7467     break;
7468   }
7469   case ISD::SRA:
7470   case ISD::SRL:
7471   case ISD::SHL: {
7472     SDValue ShAmt = N->getOperand(1);
7473     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7474       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7475       SDLoc DL(N);
7476       EVT VT = N->getValueType(0);
7477       ShAmt =
7478           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7479       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7480     }
7481     break;
7482   }
7483   case RISCVISD::MUL_VL: {
7484     SDValue Op0 = N->getOperand(0);
7485     SDValue Op1 = N->getOperand(1);
7486     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7487       return V;
7488     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7489       return V;
7490     return SDValue();
7491   }
7492   case ISD::STORE: {
7493     auto *Store = cast<StoreSDNode>(N);
7494     SDValue Val = Store->getValue();
7495     // Combine store of vmv.x.s to vse with VL of 1.
7496     // FIXME: Support FP.
7497     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7498       SDValue Src = Val.getOperand(0);
7499       EVT VecVT = Src.getValueType();
7500       EVT MemVT = Store->getMemoryVT();
7501       // The memory VT and the element type must match.
7502       if (VecVT.getVectorElementType() == MemVT) {
7503         SDLoc DL(N);
7504         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7505         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7506                               DAG.getConstant(1, DL, MaskVT),
7507                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7508                               Store->getPointerInfo(),
7509                               Store->getOriginalAlign(),
7510                               Store->getMemOperand()->getFlags());
7511       }
7512     }
7513 
7514     break;
7515   }
7516   }
7517 
7518   return SDValue();
7519 }
7520 
7521 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7522     const SDNode *N, CombineLevel Level) const {
7523   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7524   // materialised in fewer instructions than `(OP _, c1)`:
7525   //
7526   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7527   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7528   SDValue N0 = N->getOperand(0);
7529   EVT Ty = N0.getValueType();
7530   if (Ty.isScalarInteger() &&
7531       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7532     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7533     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7534     if (C1 && C2) {
7535       const APInt &C1Int = C1->getAPIntValue();
7536       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7537 
7538       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7539       // and the combine should happen, to potentially allow further combines
7540       // later.
7541       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7542           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7543         return true;
7544 
7545       // We can materialise `c1` in an add immediate, so it's "free", and the
7546       // combine should be prevented.
7547       if (C1Int.getMinSignedBits() <= 64 &&
7548           isLegalAddImmediate(C1Int.getSExtValue()))
7549         return false;
7550 
7551       // Neither constant will fit into an immediate, so find materialisation
7552       // costs.
7553       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7554                                               Subtarget.getFeatureBits(),
7555                                               /*CompressionCost*/true);
7556       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7557           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7558           /*CompressionCost*/true);
7559 
7560       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7561       // combine should be prevented.
7562       if (C1Cost < ShiftedC1Cost)
7563         return false;
7564     }
7565   }
7566   return true;
7567 }
7568 
7569 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7570     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7571     TargetLoweringOpt &TLO) const {
7572   // Delay this optimization as late as possible.
7573   if (!TLO.LegalOps)
7574     return false;
7575 
7576   EVT VT = Op.getValueType();
7577   if (VT.isVector())
7578     return false;
7579 
7580   // Only handle AND for now.
7581   if (Op.getOpcode() != ISD::AND)
7582     return false;
7583 
7584   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7585   if (!C)
7586     return false;
7587 
7588   const APInt &Mask = C->getAPIntValue();
7589 
7590   // Clear all non-demanded bits initially.
7591   APInt ShrunkMask = Mask & DemandedBits;
7592 
7593   // Try to make a smaller immediate by setting undemanded bits.
7594 
7595   APInt ExpandedMask = Mask | ~DemandedBits;
7596 
7597   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7598     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7599   };
7600   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7601     if (NewMask == Mask)
7602       return true;
7603     SDLoc DL(Op);
7604     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7605     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7606     return TLO.CombineTo(Op, NewOp);
7607   };
7608 
7609   // If the shrunk mask fits in sign extended 12 bits, let the target
7610   // independent code apply it.
7611   if (ShrunkMask.isSignedIntN(12))
7612     return false;
7613 
7614   // Preserve (and X, 0xffff) when zext.h is supported.
7615   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7616     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7617     if (IsLegalMask(NewMask))
7618       return UseMask(NewMask);
7619   }
7620 
7621   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7622   if (VT == MVT::i64) {
7623     APInt NewMask = APInt(64, 0xffffffff);
7624     if (IsLegalMask(NewMask))
7625       return UseMask(NewMask);
7626   }
7627 
7628   // For the remaining optimizations, we need to be able to make a negative
7629   // number through a combination of mask and undemanded bits.
7630   if (!ExpandedMask.isNegative())
7631     return false;
7632 
7633   // What is the fewest number of bits we need to represent the negative number.
7634   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7635 
7636   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7637   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7638   APInt NewMask = ShrunkMask;
7639   if (MinSignedBits <= 12)
7640     NewMask.setBitsFrom(11);
7641   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7642     NewMask.setBitsFrom(31);
7643   else
7644     return false;
7645 
7646   // Check that our new mask is a subset of the demanded mask.
7647   assert(IsLegalMask(NewMask));
7648   return UseMask(NewMask);
7649 }
7650 
7651 static void computeGREV(APInt &Src, unsigned ShAmt) {
7652   ShAmt &= Src.getBitWidth() - 1;
7653   uint64_t x = Src.getZExtValue();
7654   if (ShAmt & 1)
7655     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7656   if (ShAmt & 2)
7657     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7658   if (ShAmt & 4)
7659     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7660   if (ShAmt & 8)
7661     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7662   if (ShAmt & 16)
7663     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7664   if (ShAmt & 32)
7665     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7666   Src = x;
7667 }
7668 
7669 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7670                                                         KnownBits &Known,
7671                                                         const APInt &DemandedElts,
7672                                                         const SelectionDAG &DAG,
7673                                                         unsigned Depth) const {
7674   unsigned BitWidth = Known.getBitWidth();
7675   unsigned Opc = Op.getOpcode();
7676   assert((Opc >= ISD::BUILTIN_OP_END ||
7677           Opc == ISD::INTRINSIC_WO_CHAIN ||
7678           Opc == ISD::INTRINSIC_W_CHAIN ||
7679           Opc == ISD::INTRINSIC_VOID) &&
7680          "Should use MaskedValueIsZero if you don't know whether Op"
7681          " is a target node!");
7682 
7683   Known.resetAll();
7684   switch (Opc) {
7685   default: break;
7686   case RISCVISD::SELECT_CC: {
7687     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7688     // If we don't know any bits, early out.
7689     if (Known.isUnknown())
7690       break;
7691     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7692 
7693     // Only known if known in both the LHS and RHS.
7694     Known = KnownBits::commonBits(Known, Known2);
7695     break;
7696   }
7697   case RISCVISD::REMUW: {
7698     KnownBits Known2;
7699     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7700     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7701     // We only care about the lower 32 bits.
7702     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7703     // Restore the original width by sign extending.
7704     Known = Known.sext(BitWidth);
7705     break;
7706   }
7707   case RISCVISD::DIVUW: {
7708     KnownBits Known2;
7709     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7710     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7711     // We only care about the lower 32 bits.
7712     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7713     // Restore the original width by sign extending.
7714     Known = Known.sext(BitWidth);
7715     break;
7716   }
7717   case RISCVISD::CTZW: {
7718     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7719     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7720     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7721     Known.Zero.setBitsFrom(LowBits);
7722     break;
7723   }
7724   case RISCVISD::CLZW: {
7725     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7726     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7727     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7728     Known.Zero.setBitsFrom(LowBits);
7729     break;
7730   }
7731   case RISCVISD::GREV:
7732   case RISCVISD::GREVW: {
7733     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7734       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7735       if (Opc == RISCVISD::GREVW)
7736         Known = Known.trunc(32);
7737       unsigned ShAmt = C->getZExtValue();
7738       computeGREV(Known.Zero, ShAmt);
7739       computeGREV(Known.One, ShAmt);
7740       if (Opc == RISCVISD::GREVW)
7741         Known = Known.sext(BitWidth);
7742     }
7743     break;
7744   }
7745   case RISCVISD::READ_VLENB:
7746     // We assume VLENB is at least 16 bytes.
7747     Known.Zero.setLowBits(4);
7748     // We assume VLENB is no more than 65536 / 8 bytes.
7749     Known.Zero.setBitsFrom(14);
7750     break;
7751   case ISD::INTRINSIC_W_CHAIN: {
7752     unsigned IntNo = Op.getConstantOperandVal(1);
7753     switch (IntNo) {
7754     default:
7755       // We can't do anything for most intrinsics.
7756       break;
7757     case Intrinsic::riscv_vsetvli:
7758     case Intrinsic::riscv_vsetvlimax:
7759       // Assume that VL output is positive and would fit in an int32_t.
7760       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7761       if (BitWidth >= 32)
7762         Known.Zero.setBitsFrom(31);
7763       break;
7764     }
7765     break;
7766   }
7767   }
7768 }
7769 
7770 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7771     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7772     unsigned Depth) const {
7773   switch (Op.getOpcode()) {
7774   default:
7775     break;
7776   case RISCVISD::SELECT_CC: {
7777     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7778     if (Tmp == 1) return 1;  // Early out.
7779     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7780     return std::min(Tmp, Tmp2);
7781   }
7782   case RISCVISD::SLLW:
7783   case RISCVISD::SRAW:
7784   case RISCVISD::SRLW:
7785   case RISCVISD::DIVW:
7786   case RISCVISD::DIVUW:
7787   case RISCVISD::REMUW:
7788   case RISCVISD::ROLW:
7789   case RISCVISD::RORW:
7790   case RISCVISD::GREVW:
7791   case RISCVISD::GORCW:
7792   case RISCVISD::FSLW:
7793   case RISCVISD::FSRW:
7794   case RISCVISD::SHFLW:
7795   case RISCVISD::UNSHFLW:
7796   case RISCVISD::BCOMPRESSW:
7797   case RISCVISD::BDECOMPRESSW:
7798   case RISCVISD::FCVT_W_RTZ_RV64:
7799   case RISCVISD::FCVT_WU_RTZ_RV64:
7800   case RISCVISD::STRICT_FCVT_W_RTZ_RV64:
7801   case RISCVISD::STRICT_FCVT_WU_RTZ_RV64:
7802     // TODO: As the result is sign-extended, this is conservatively correct. A
7803     // more precise answer could be calculated for SRAW depending on known
7804     // bits in the shift amount.
7805     return 33;
7806   case RISCVISD::SHFL:
7807   case RISCVISD::UNSHFL: {
7808     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7809     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7810     // will stay within the upper 32 bits. If there were more than 32 sign bits
7811     // before there will be at least 33 sign bits after.
7812     if (Op.getValueType() == MVT::i64 &&
7813         isa<ConstantSDNode>(Op.getOperand(1)) &&
7814         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7815       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7816       if (Tmp > 32)
7817         return 33;
7818     }
7819     break;
7820   }
7821   case RISCVISD::VMV_X_S:
7822     // The number of sign bits of the scalar result is computed by obtaining the
7823     // element type of the input vector operand, subtracting its width from the
7824     // XLEN, and then adding one (sign bit within the element type). If the
7825     // element type is wider than XLen, the least-significant XLEN bits are
7826     // taken.
7827     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7828       return 1;
7829     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7830   }
7831 
7832   return 1;
7833 }
7834 
7835 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7836                                                   MachineBasicBlock *BB) {
7837   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7838 
7839   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7840   // Should the count have wrapped while it was being read, we need to try
7841   // again.
7842   // ...
7843   // read:
7844   // rdcycleh x3 # load high word of cycle
7845   // rdcycle  x2 # load low word of cycle
7846   // rdcycleh x4 # load high word of cycle
7847   // bne x3, x4, read # check if high word reads match, otherwise try again
7848   // ...
7849 
7850   MachineFunction &MF = *BB->getParent();
7851   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7852   MachineFunction::iterator It = ++BB->getIterator();
7853 
7854   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7855   MF.insert(It, LoopMBB);
7856 
7857   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7858   MF.insert(It, DoneMBB);
7859 
7860   // Transfer the remainder of BB and its successor edges to DoneMBB.
7861   DoneMBB->splice(DoneMBB->begin(), BB,
7862                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7863   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7864 
7865   BB->addSuccessor(LoopMBB);
7866 
7867   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7868   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7869   Register LoReg = MI.getOperand(0).getReg();
7870   Register HiReg = MI.getOperand(1).getReg();
7871   DebugLoc DL = MI.getDebugLoc();
7872 
7873   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7874   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7875       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7876       .addReg(RISCV::X0);
7877   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7878       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7879       .addReg(RISCV::X0);
7880   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7881       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7882       .addReg(RISCV::X0);
7883 
7884   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7885       .addReg(HiReg)
7886       .addReg(ReadAgainReg)
7887       .addMBB(LoopMBB);
7888 
7889   LoopMBB->addSuccessor(LoopMBB);
7890   LoopMBB->addSuccessor(DoneMBB);
7891 
7892   MI.eraseFromParent();
7893 
7894   return DoneMBB;
7895 }
7896 
7897 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7898                                              MachineBasicBlock *BB) {
7899   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7900 
7901   MachineFunction &MF = *BB->getParent();
7902   DebugLoc DL = MI.getDebugLoc();
7903   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7904   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7905   Register LoReg = MI.getOperand(0).getReg();
7906   Register HiReg = MI.getOperand(1).getReg();
7907   Register SrcReg = MI.getOperand(2).getReg();
7908   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7909   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7910 
7911   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7912                           RI);
7913   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7914   MachineMemOperand *MMOLo =
7915       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7916   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7917       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7918   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7919       .addFrameIndex(FI)
7920       .addImm(0)
7921       .addMemOperand(MMOLo);
7922   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7923       .addFrameIndex(FI)
7924       .addImm(4)
7925       .addMemOperand(MMOHi);
7926   MI.eraseFromParent(); // The pseudo instruction is gone now.
7927   return BB;
7928 }
7929 
7930 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7931                                                  MachineBasicBlock *BB) {
7932   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7933          "Unexpected instruction");
7934 
7935   MachineFunction &MF = *BB->getParent();
7936   DebugLoc DL = MI.getDebugLoc();
7937   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7938   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7939   Register DstReg = MI.getOperand(0).getReg();
7940   Register LoReg = MI.getOperand(1).getReg();
7941   Register HiReg = MI.getOperand(2).getReg();
7942   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7943   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7944 
7945   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7946   MachineMemOperand *MMOLo =
7947       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7948   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7949       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7950   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7951       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7952       .addFrameIndex(FI)
7953       .addImm(0)
7954       .addMemOperand(MMOLo);
7955   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7956       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7957       .addFrameIndex(FI)
7958       .addImm(4)
7959       .addMemOperand(MMOHi);
7960   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7961   MI.eraseFromParent(); // The pseudo instruction is gone now.
7962   return BB;
7963 }
7964 
7965 static bool isSelectPseudo(MachineInstr &MI) {
7966   switch (MI.getOpcode()) {
7967   default:
7968     return false;
7969   case RISCV::Select_GPR_Using_CC_GPR:
7970   case RISCV::Select_FPR16_Using_CC_GPR:
7971   case RISCV::Select_FPR32_Using_CC_GPR:
7972   case RISCV::Select_FPR64_Using_CC_GPR:
7973     return true;
7974   }
7975 }
7976 
7977 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7978                                            MachineBasicBlock *BB,
7979                                            const RISCVSubtarget &Subtarget) {
7980   // To "insert" Select_* instructions, we actually have to insert the triangle
7981   // control-flow pattern.  The incoming instructions know the destination vreg
7982   // to set, the condition code register to branch on, the true/false values to
7983   // select between, and the condcode to use to select the appropriate branch.
7984   //
7985   // We produce the following control flow:
7986   //     HeadMBB
7987   //     |  \
7988   //     |  IfFalseMBB
7989   //     | /
7990   //    TailMBB
7991   //
7992   // When we find a sequence of selects we attempt to optimize their emission
7993   // by sharing the control flow. Currently we only handle cases where we have
7994   // multiple selects with the exact same condition (same LHS, RHS and CC).
7995   // The selects may be interleaved with other instructions if the other
7996   // instructions meet some requirements we deem safe:
7997   // - They are debug instructions. Otherwise,
7998   // - They do not have side-effects, do not access memory and their inputs do
7999   //   not depend on the results of the select pseudo-instructions.
8000   // The TrueV/FalseV operands of the selects cannot depend on the result of
8001   // previous selects in the sequence.
8002   // These conditions could be further relaxed. See the X86 target for a
8003   // related approach and more information.
8004   Register LHS = MI.getOperand(1).getReg();
8005   Register RHS = MI.getOperand(2).getReg();
8006   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8007 
8008   SmallVector<MachineInstr *, 4> SelectDebugValues;
8009   SmallSet<Register, 4> SelectDests;
8010   SelectDests.insert(MI.getOperand(0).getReg());
8011 
8012   MachineInstr *LastSelectPseudo = &MI;
8013 
8014   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8015        SequenceMBBI != E; ++SequenceMBBI) {
8016     if (SequenceMBBI->isDebugInstr())
8017       continue;
8018     else if (isSelectPseudo(*SequenceMBBI)) {
8019       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8020           SequenceMBBI->getOperand(2).getReg() != RHS ||
8021           SequenceMBBI->getOperand(3).getImm() != CC ||
8022           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8023           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8024         break;
8025       LastSelectPseudo = &*SequenceMBBI;
8026       SequenceMBBI->collectDebugValues(SelectDebugValues);
8027       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8028     } else {
8029       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8030           SequenceMBBI->mayLoadOrStore())
8031         break;
8032       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8033             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8034           }))
8035         break;
8036     }
8037   }
8038 
8039   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8040   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8041   DebugLoc DL = MI.getDebugLoc();
8042   MachineFunction::iterator I = ++BB->getIterator();
8043 
8044   MachineBasicBlock *HeadMBB = BB;
8045   MachineFunction *F = BB->getParent();
8046   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8047   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8048 
8049   F->insert(I, IfFalseMBB);
8050   F->insert(I, TailMBB);
8051 
8052   // Transfer debug instructions associated with the selects to TailMBB.
8053   for (MachineInstr *DebugInstr : SelectDebugValues) {
8054     TailMBB->push_back(DebugInstr->removeFromParent());
8055   }
8056 
8057   // Move all instructions after the sequence to TailMBB.
8058   TailMBB->splice(TailMBB->end(), HeadMBB,
8059                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8060   // Update machine-CFG edges by transferring all successors of the current
8061   // block to the new block which will contain the Phi nodes for the selects.
8062   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8063   // Set the successors for HeadMBB.
8064   HeadMBB->addSuccessor(IfFalseMBB);
8065   HeadMBB->addSuccessor(TailMBB);
8066 
8067   // Insert appropriate branch.
8068   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8069     .addReg(LHS)
8070     .addReg(RHS)
8071     .addMBB(TailMBB);
8072 
8073   // IfFalseMBB just falls through to TailMBB.
8074   IfFalseMBB->addSuccessor(TailMBB);
8075 
8076   // Create PHIs for all of the select pseudo-instructions.
8077   auto SelectMBBI = MI.getIterator();
8078   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8079   auto InsertionPoint = TailMBB->begin();
8080   while (SelectMBBI != SelectEnd) {
8081     auto Next = std::next(SelectMBBI);
8082     if (isSelectPseudo(*SelectMBBI)) {
8083       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8084       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8085               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8086           .addReg(SelectMBBI->getOperand(4).getReg())
8087           .addMBB(HeadMBB)
8088           .addReg(SelectMBBI->getOperand(5).getReg())
8089           .addMBB(IfFalseMBB);
8090       SelectMBBI->eraseFromParent();
8091     }
8092     SelectMBBI = Next;
8093   }
8094 
8095   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8096   return TailMBB;
8097 }
8098 
8099 MachineBasicBlock *
8100 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8101                                                  MachineBasicBlock *BB) const {
8102   switch (MI.getOpcode()) {
8103   default:
8104     llvm_unreachable("Unexpected instr type to insert");
8105   case RISCV::ReadCycleWide:
8106     assert(!Subtarget.is64Bit() &&
8107            "ReadCycleWrite is only to be used on riscv32");
8108     return emitReadCycleWidePseudo(MI, BB);
8109   case RISCV::Select_GPR_Using_CC_GPR:
8110   case RISCV::Select_FPR16_Using_CC_GPR:
8111   case RISCV::Select_FPR32_Using_CC_GPR:
8112   case RISCV::Select_FPR64_Using_CC_GPR:
8113     return emitSelectPseudo(MI, BB, Subtarget);
8114   case RISCV::BuildPairF64Pseudo:
8115     return emitBuildPairF64Pseudo(MI, BB);
8116   case RISCV::SplitF64Pseudo:
8117     return emitSplitF64Pseudo(MI, BB);
8118   }
8119 }
8120 
8121 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8122                                                         SDNode *Node) const {
8123   // Add FRM dependency to any instructions with dynamic rounding mode.
8124   unsigned Opc = MI.getOpcode();
8125   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8126   if (Idx < 0)
8127     return;
8128   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8129     return;
8130   // If the instruction already reads FRM, don't add another read.
8131   if (MI.readsRegister(RISCV::FRM))
8132     return;
8133   MI.addOperand(
8134       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8135 }
8136 
8137 // Calling Convention Implementation.
8138 // The expectations for frontend ABI lowering vary from target to target.
8139 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8140 // details, but this is a longer term goal. For now, we simply try to keep the
8141 // role of the frontend as simple and well-defined as possible. The rules can
8142 // be summarised as:
8143 // * Never split up large scalar arguments. We handle them here.
8144 // * If a hardfloat calling convention is being used, and the struct may be
8145 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8146 // available, then pass as two separate arguments. If either the GPRs or FPRs
8147 // are exhausted, then pass according to the rule below.
8148 // * If a struct could never be passed in registers or directly in a stack
8149 // slot (as it is larger than 2*XLEN and the floating point rules don't
8150 // apply), then pass it using a pointer with the byval attribute.
8151 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8152 // word-sized array or a 2*XLEN scalar (depending on alignment).
8153 // * The frontend can determine whether a struct is returned by reference or
8154 // not based on its size and fields. If it will be returned by reference, the
8155 // frontend must modify the prototype so a pointer with the sret annotation is
8156 // passed as the first argument. This is not necessary for large scalar
8157 // returns.
8158 // * Struct return values and varargs should be coerced to structs containing
8159 // register-size fields in the same situations they would be for fixed
8160 // arguments.
8161 
8162 static const MCPhysReg ArgGPRs[] = {
8163   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8164   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8165 };
8166 static const MCPhysReg ArgFPR16s[] = {
8167   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8168   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8169 };
8170 static const MCPhysReg ArgFPR32s[] = {
8171   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8172   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8173 };
8174 static const MCPhysReg ArgFPR64s[] = {
8175   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8176   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8177 };
8178 // This is an interim calling convention and it may be changed in the future.
8179 static const MCPhysReg ArgVRs[] = {
8180     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8181     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8182     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8183 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8184                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8185                                      RISCV::V20M2, RISCV::V22M2};
8186 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8187                                      RISCV::V20M4};
8188 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8189 
8190 // Pass a 2*XLEN argument that has been split into two XLEN values through
8191 // registers or the stack as necessary.
8192 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8193                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8194                                 MVT ValVT2, MVT LocVT2,
8195                                 ISD::ArgFlagsTy ArgFlags2) {
8196   unsigned XLenInBytes = XLen / 8;
8197   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8198     // At least one half can be passed via register.
8199     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8200                                      VA1.getLocVT(), CCValAssign::Full));
8201   } else {
8202     // Both halves must be passed on the stack, with proper alignment.
8203     Align StackAlign =
8204         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8205     State.addLoc(
8206         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8207                             State.AllocateStack(XLenInBytes, StackAlign),
8208                             VA1.getLocVT(), CCValAssign::Full));
8209     State.addLoc(CCValAssign::getMem(
8210         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8211         LocVT2, CCValAssign::Full));
8212     return false;
8213   }
8214 
8215   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8216     // The second half can also be passed via register.
8217     State.addLoc(
8218         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8219   } else {
8220     // The second half is passed via the stack, without additional alignment.
8221     State.addLoc(CCValAssign::getMem(
8222         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8223         LocVT2, CCValAssign::Full));
8224   }
8225 
8226   return false;
8227 }
8228 
8229 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8230                                Optional<unsigned> FirstMaskArgument,
8231                                CCState &State, const RISCVTargetLowering &TLI) {
8232   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8233   if (RC == &RISCV::VRRegClass) {
8234     // Assign the first mask argument to V0.
8235     // This is an interim calling convention and it may be changed in the
8236     // future.
8237     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8238       return State.AllocateReg(RISCV::V0);
8239     return State.AllocateReg(ArgVRs);
8240   }
8241   if (RC == &RISCV::VRM2RegClass)
8242     return State.AllocateReg(ArgVRM2s);
8243   if (RC == &RISCV::VRM4RegClass)
8244     return State.AllocateReg(ArgVRM4s);
8245   if (RC == &RISCV::VRM8RegClass)
8246     return State.AllocateReg(ArgVRM8s);
8247   llvm_unreachable("Unhandled register class for ValueType");
8248 }
8249 
8250 // Implements the RISC-V calling convention. Returns true upon failure.
8251 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8252                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8253                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8254                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8255                      Optional<unsigned> FirstMaskArgument) {
8256   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8257   assert(XLen == 32 || XLen == 64);
8258   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8259 
8260   // Any return value split in to more than two values can't be returned
8261   // directly. Vectors are returned via the available vector registers.
8262   if (!LocVT.isVector() && IsRet && ValNo > 1)
8263     return true;
8264 
8265   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8266   // variadic argument, or if no F16/F32 argument registers are available.
8267   bool UseGPRForF16_F32 = true;
8268   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8269   // variadic argument, or if no F64 argument registers are available.
8270   bool UseGPRForF64 = true;
8271 
8272   switch (ABI) {
8273   default:
8274     llvm_unreachable("Unexpected ABI");
8275   case RISCVABI::ABI_ILP32:
8276   case RISCVABI::ABI_LP64:
8277     break;
8278   case RISCVABI::ABI_ILP32F:
8279   case RISCVABI::ABI_LP64F:
8280     UseGPRForF16_F32 = !IsFixed;
8281     break;
8282   case RISCVABI::ABI_ILP32D:
8283   case RISCVABI::ABI_LP64D:
8284     UseGPRForF16_F32 = !IsFixed;
8285     UseGPRForF64 = !IsFixed;
8286     break;
8287   }
8288 
8289   // FPR16, FPR32, and FPR64 alias each other.
8290   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8291     UseGPRForF16_F32 = true;
8292     UseGPRForF64 = true;
8293   }
8294 
8295   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8296   // similar local variables rather than directly checking against the target
8297   // ABI.
8298 
8299   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8300     LocVT = XLenVT;
8301     LocInfo = CCValAssign::BCvt;
8302   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8303     LocVT = MVT::i64;
8304     LocInfo = CCValAssign::BCvt;
8305   }
8306 
8307   // If this is a variadic argument, the RISC-V calling convention requires
8308   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8309   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8310   // be used regardless of whether the original argument was split during
8311   // legalisation or not. The argument will not be passed by registers if the
8312   // original type is larger than 2*XLEN, so the register alignment rule does
8313   // not apply.
8314   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8315   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8316       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8317     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8318     // Skip 'odd' register if necessary.
8319     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8320       State.AllocateReg(ArgGPRs);
8321   }
8322 
8323   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8324   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8325       State.getPendingArgFlags();
8326 
8327   assert(PendingLocs.size() == PendingArgFlags.size() &&
8328          "PendingLocs and PendingArgFlags out of sync");
8329 
8330   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8331   // registers are exhausted.
8332   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8333     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8334            "Can't lower f64 if it is split");
8335     // Depending on available argument GPRS, f64 may be passed in a pair of
8336     // GPRs, split between a GPR and the stack, or passed completely on the
8337     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8338     // cases.
8339     Register Reg = State.AllocateReg(ArgGPRs);
8340     LocVT = MVT::i32;
8341     if (!Reg) {
8342       unsigned StackOffset = State.AllocateStack(8, Align(8));
8343       State.addLoc(
8344           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8345       return false;
8346     }
8347     if (!State.AllocateReg(ArgGPRs))
8348       State.AllocateStack(4, Align(4));
8349     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8350     return false;
8351   }
8352 
8353   // Fixed-length vectors are located in the corresponding scalable-vector
8354   // container types.
8355   if (ValVT.isFixedLengthVector())
8356     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8357 
8358   // Split arguments might be passed indirectly, so keep track of the pending
8359   // values. Split vectors are passed via a mix of registers and indirectly, so
8360   // treat them as we would any other argument.
8361   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8362     LocVT = XLenVT;
8363     LocInfo = CCValAssign::Indirect;
8364     PendingLocs.push_back(
8365         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8366     PendingArgFlags.push_back(ArgFlags);
8367     if (!ArgFlags.isSplitEnd()) {
8368       return false;
8369     }
8370   }
8371 
8372   // If the split argument only had two elements, it should be passed directly
8373   // in registers or on the stack.
8374   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8375       PendingLocs.size() <= 2) {
8376     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8377     // Apply the normal calling convention rules to the first half of the
8378     // split argument.
8379     CCValAssign VA = PendingLocs[0];
8380     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8381     PendingLocs.clear();
8382     PendingArgFlags.clear();
8383     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8384                                ArgFlags);
8385   }
8386 
8387   // Allocate to a register if possible, or else a stack slot.
8388   Register Reg;
8389   unsigned StoreSizeBytes = XLen / 8;
8390   Align StackAlign = Align(XLen / 8);
8391 
8392   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8393     Reg = State.AllocateReg(ArgFPR16s);
8394   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8395     Reg = State.AllocateReg(ArgFPR32s);
8396   else if (ValVT == MVT::f64 && !UseGPRForF64)
8397     Reg = State.AllocateReg(ArgFPR64s);
8398   else if (ValVT.isVector()) {
8399     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8400     if (!Reg) {
8401       // For return values, the vector must be passed fully via registers or
8402       // via the stack.
8403       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8404       // but we're using all of them.
8405       if (IsRet)
8406         return true;
8407       // Try using a GPR to pass the address
8408       if ((Reg = State.AllocateReg(ArgGPRs))) {
8409         LocVT = XLenVT;
8410         LocInfo = CCValAssign::Indirect;
8411       } else if (ValVT.isScalableVector()) {
8412         LocVT = XLenVT;
8413         LocInfo = CCValAssign::Indirect;
8414       } else {
8415         // Pass fixed-length vectors on the stack.
8416         LocVT = ValVT;
8417         StoreSizeBytes = ValVT.getStoreSize();
8418         // Align vectors to their element sizes, being careful for vXi1
8419         // vectors.
8420         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8421       }
8422     }
8423   } else {
8424     Reg = State.AllocateReg(ArgGPRs);
8425   }
8426 
8427   unsigned StackOffset =
8428       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8429 
8430   // If we reach this point and PendingLocs is non-empty, we must be at the
8431   // end of a split argument that must be passed indirectly.
8432   if (!PendingLocs.empty()) {
8433     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8434     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8435 
8436     for (auto &It : PendingLocs) {
8437       if (Reg)
8438         It.convertToReg(Reg);
8439       else
8440         It.convertToMem(StackOffset);
8441       State.addLoc(It);
8442     }
8443     PendingLocs.clear();
8444     PendingArgFlags.clear();
8445     return false;
8446   }
8447 
8448   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8449           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8450          "Expected an XLenVT or vector types at this stage");
8451 
8452   if (Reg) {
8453     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8454     return false;
8455   }
8456 
8457   // When a floating-point value is passed on the stack, no bit-conversion is
8458   // needed.
8459   if (ValVT.isFloatingPoint()) {
8460     LocVT = ValVT;
8461     LocInfo = CCValAssign::Full;
8462   }
8463   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8464   return false;
8465 }
8466 
8467 template <typename ArgTy>
8468 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8469   for (const auto &ArgIdx : enumerate(Args)) {
8470     MVT ArgVT = ArgIdx.value().VT;
8471     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8472       return ArgIdx.index();
8473   }
8474   return None;
8475 }
8476 
8477 void RISCVTargetLowering::analyzeInputArgs(
8478     MachineFunction &MF, CCState &CCInfo,
8479     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8480     RISCVCCAssignFn Fn) const {
8481   unsigned NumArgs = Ins.size();
8482   FunctionType *FType = MF.getFunction().getFunctionType();
8483 
8484   Optional<unsigned> FirstMaskArgument;
8485   if (Subtarget.hasVInstructions())
8486     FirstMaskArgument = preAssignMask(Ins);
8487 
8488   for (unsigned i = 0; i != NumArgs; ++i) {
8489     MVT ArgVT = Ins[i].VT;
8490     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8491 
8492     Type *ArgTy = nullptr;
8493     if (IsRet)
8494       ArgTy = FType->getReturnType();
8495     else if (Ins[i].isOrigArg())
8496       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8497 
8498     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8499     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8500            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8501            FirstMaskArgument)) {
8502       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8503                         << EVT(ArgVT).getEVTString() << '\n');
8504       llvm_unreachable(nullptr);
8505     }
8506   }
8507 }
8508 
8509 void RISCVTargetLowering::analyzeOutputArgs(
8510     MachineFunction &MF, CCState &CCInfo,
8511     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8512     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8513   unsigned NumArgs = Outs.size();
8514 
8515   Optional<unsigned> FirstMaskArgument;
8516   if (Subtarget.hasVInstructions())
8517     FirstMaskArgument = preAssignMask(Outs);
8518 
8519   for (unsigned i = 0; i != NumArgs; i++) {
8520     MVT ArgVT = Outs[i].VT;
8521     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8522     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8523 
8524     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8525     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8526            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8527            FirstMaskArgument)) {
8528       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8529                         << EVT(ArgVT).getEVTString() << "\n");
8530       llvm_unreachable(nullptr);
8531     }
8532   }
8533 }
8534 
8535 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8536 // values.
8537 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8538                                    const CCValAssign &VA, const SDLoc &DL,
8539                                    const RISCVSubtarget &Subtarget) {
8540   switch (VA.getLocInfo()) {
8541   default:
8542     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8543   case CCValAssign::Full:
8544     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8545       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8546     break;
8547   case CCValAssign::BCvt:
8548     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8549       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8550     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8551       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8552     else
8553       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8554     break;
8555   }
8556   return Val;
8557 }
8558 
8559 // The caller is responsible for loading the full value if the argument is
8560 // passed with CCValAssign::Indirect.
8561 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8562                                 const CCValAssign &VA, const SDLoc &DL,
8563                                 const RISCVTargetLowering &TLI) {
8564   MachineFunction &MF = DAG.getMachineFunction();
8565   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8566   EVT LocVT = VA.getLocVT();
8567   SDValue Val;
8568   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8569   Register VReg = RegInfo.createVirtualRegister(RC);
8570   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8571   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8572 
8573   if (VA.getLocInfo() == CCValAssign::Indirect)
8574     return Val;
8575 
8576   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8577 }
8578 
8579 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8580                                    const CCValAssign &VA, const SDLoc &DL,
8581                                    const RISCVSubtarget &Subtarget) {
8582   EVT LocVT = VA.getLocVT();
8583 
8584   switch (VA.getLocInfo()) {
8585   default:
8586     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8587   case CCValAssign::Full:
8588     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8589       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8590     break;
8591   case CCValAssign::BCvt:
8592     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8593       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8594     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8595       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8596     else
8597       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8598     break;
8599   }
8600   return Val;
8601 }
8602 
8603 // The caller is responsible for loading the full value if the argument is
8604 // passed with CCValAssign::Indirect.
8605 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8606                                 const CCValAssign &VA, const SDLoc &DL) {
8607   MachineFunction &MF = DAG.getMachineFunction();
8608   MachineFrameInfo &MFI = MF.getFrameInfo();
8609   EVT LocVT = VA.getLocVT();
8610   EVT ValVT = VA.getValVT();
8611   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8612   if (ValVT.isScalableVector()) {
8613     // When the value is a scalable vector, we save the pointer which points to
8614     // the scalable vector value in the stack. The ValVT will be the pointer
8615     // type, instead of the scalable vector type.
8616     ValVT = LocVT;
8617   }
8618   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8619                                  /*Immutable=*/true);
8620   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8621   SDValue Val;
8622 
8623   ISD::LoadExtType ExtType;
8624   switch (VA.getLocInfo()) {
8625   default:
8626     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8627   case CCValAssign::Full:
8628   case CCValAssign::Indirect:
8629   case CCValAssign::BCvt:
8630     ExtType = ISD::NON_EXTLOAD;
8631     break;
8632   }
8633   Val = DAG.getExtLoad(
8634       ExtType, DL, LocVT, Chain, FIN,
8635       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8636   return Val;
8637 }
8638 
8639 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8640                                        const CCValAssign &VA, const SDLoc &DL) {
8641   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8642          "Unexpected VA");
8643   MachineFunction &MF = DAG.getMachineFunction();
8644   MachineFrameInfo &MFI = MF.getFrameInfo();
8645   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8646 
8647   if (VA.isMemLoc()) {
8648     // f64 is passed on the stack.
8649     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8650     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8651     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8652                        MachinePointerInfo::getFixedStack(MF, FI));
8653   }
8654 
8655   assert(VA.isRegLoc() && "Expected register VA assignment");
8656 
8657   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8658   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8659   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8660   SDValue Hi;
8661   if (VA.getLocReg() == RISCV::X17) {
8662     // Second half of f64 is passed on the stack.
8663     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8664     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8665     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8666                      MachinePointerInfo::getFixedStack(MF, FI));
8667   } else {
8668     // Second half of f64 is passed in another GPR.
8669     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8670     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8671     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8672   }
8673   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8674 }
8675 
8676 // FastCC has less than 1% performance improvement for some particular
8677 // benchmark. But theoretically, it may has benenfit for some cases.
8678 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8679                             unsigned ValNo, MVT ValVT, MVT LocVT,
8680                             CCValAssign::LocInfo LocInfo,
8681                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8682                             bool IsFixed, bool IsRet, Type *OrigTy,
8683                             const RISCVTargetLowering &TLI,
8684                             Optional<unsigned> FirstMaskArgument) {
8685 
8686   // X5 and X6 might be used for save-restore libcall.
8687   static const MCPhysReg GPRList[] = {
8688       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8689       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8690       RISCV::X29, RISCV::X30, RISCV::X31};
8691 
8692   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8693     if (unsigned Reg = State.AllocateReg(GPRList)) {
8694       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8695       return false;
8696     }
8697   }
8698 
8699   if (LocVT == MVT::f16) {
8700     static const MCPhysReg FPR16List[] = {
8701         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8702         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8703         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8704         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8705     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8706       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8707       return false;
8708     }
8709   }
8710 
8711   if (LocVT == MVT::f32) {
8712     static const MCPhysReg FPR32List[] = {
8713         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8714         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8715         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8716         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8717     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8718       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8719       return false;
8720     }
8721   }
8722 
8723   if (LocVT == MVT::f64) {
8724     static const MCPhysReg FPR64List[] = {
8725         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8726         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8727         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8728         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8729     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8730       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8731       return false;
8732     }
8733   }
8734 
8735   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8736     unsigned Offset4 = State.AllocateStack(4, Align(4));
8737     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8738     return false;
8739   }
8740 
8741   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8742     unsigned Offset5 = State.AllocateStack(8, Align(8));
8743     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8744     return false;
8745   }
8746 
8747   if (LocVT.isVector()) {
8748     if (unsigned Reg =
8749             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8750       // Fixed-length vectors are located in the corresponding scalable-vector
8751       // container types.
8752       if (ValVT.isFixedLengthVector())
8753         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8754       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8755     } else {
8756       // Try and pass the address via a "fast" GPR.
8757       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8758         LocInfo = CCValAssign::Indirect;
8759         LocVT = TLI.getSubtarget().getXLenVT();
8760         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8761       } else if (ValVT.isFixedLengthVector()) {
8762         auto StackAlign =
8763             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8764         unsigned StackOffset =
8765             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8766         State.addLoc(
8767             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8768       } else {
8769         // Can't pass scalable vectors on the stack.
8770         return true;
8771       }
8772     }
8773 
8774     return false;
8775   }
8776 
8777   return true; // CC didn't match.
8778 }
8779 
8780 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8781                          CCValAssign::LocInfo LocInfo,
8782                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8783 
8784   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8785     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8786     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8787     static const MCPhysReg GPRList[] = {
8788         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8789         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8790     if (unsigned Reg = State.AllocateReg(GPRList)) {
8791       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8792       return false;
8793     }
8794   }
8795 
8796   if (LocVT == MVT::f32) {
8797     // Pass in STG registers: F1, ..., F6
8798     //                        fs0 ... fs5
8799     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8800                                           RISCV::F18_F, RISCV::F19_F,
8801                                           RISCV::F20_F, RISCV::F21_F};
8802     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8803       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8804       return false;
8805     }
8806   }
8807 
8808   if (LocVT == MVT::f64) {
8809     // Pass in STG registers: D1, ..., D6
8810     //                        fs6 ... fs11
8811     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8812                                           RISCV::F24_D, RISCV::F25_D,
8813                                           RISCV::F26_D, RISCV::F27_D};
8814     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8815       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8816       return false;
8817     }
8818   }
8819 
8820   report_fatal_error("No registers left in GHC calling convention");
8821   return true;
8822 }
8823 
8824 // Transform physical registers into virtual registers.
8825 SDValue RISCVTargetLowering::LowerFormalArguments(
8826     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8827     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8828     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8829 
8830   MachineFunction &MF = DAG.getMachineFunction();
8831 
8832   switch (CallConv) {
8833   default:
8834     report_fatal_error("Unsupported calling convention");
8835   case CallingConv::C:
8836   case CallingConv::Fast:
8837     break;
8838   case CallingConv::GHC:
8839     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8840         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8841       report_fatal_error(
8842         "GHC calling convention requires the F and D instruction set extensions");
8843   }
8844 
8845   const Function &Func = MF.getFunction();
8846   if (Func.hasFnAttribute("interrupt")) {
8847     if (!Func.arg_empty())
8848       report_fatal_error(
8849         "Functions with the interrupt attribute cannot have arguments!");
8850 
8851     StringRef Kind =
8852       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8853 
8854     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8855       report_fatal_error(
8856         "Function interrupt attribute argument not supported!");
8857   }
8858 
8859   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8860   MVT XLenVT = Subtarget.getXLenVT();
8861   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8862   // Used with vargs to acumulate store chains.
8863   std::vector<SDValue> OutChains;
8864 
8865   // Assign locations to all of the incoming arguments.
8866   SmallVector<CCValAssign, 16> ArgLocs;
8867   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8868 
8869   if (CallConv == CallingConv::GHC)
8870     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8871   else
8872     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8873                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8874                                                    : CC_RISCV);
8875 
8876   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8877     CCValAssign &VA = ArgLocs[i];
8878     SDValue ArgValue;
8879     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8880     // case.
8881     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8882       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8883     else if (VA.isRegLoc())
8884       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8885     else
8886       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8887 
8888     if (VA.getLocInfo() == CCValAssign::Indirect) {
8889       // If the original argument was split and passed by reference (e.g. i128
8890       // on RV32), we need to load all parts of it here (using the same
8891       // address). Vectors may be partly split to registers and partly to the
8892       // stack, in which case the base address is partly offset and subsequent
8893       // stores are relative to that.
8894       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8895                                    MachinePointerInfo()));
8896       unsigned ArgIndex = Ins[i].OrigArgIndex;
8897       unsigned ArgPartOffset = Ins[i].PartOffset;
8898       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8899       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8900         CCValAssign &PartVA = ArgLocs[i + 1];
8901         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8902         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8903         if (PartVA.getValVT().isScalableVector())
8904           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8905         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8906         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8907                                      MachinePointerInfo()));
8908         ++i;
8909       }
8910       continue;
8911     }
8912     InVals.push_back(ArgValue);
8913   }
8914 
8915   if (IsVarArg) {
8916     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8917     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8918     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8919     MachineFrameInfo &MFI = MF.getFrameInfo();
8920     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8921     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8922 
8923     // Offset of the first variable argument from stack pointer, and size of
8924     // the vararg save area. For now, the varargs save area is either zero or
8925     // large enough to hold a0-a7.
8926     int VaArgOffset, VarArgsSaveSize;
8927 
8928     // If all registers are allocated, then all varargs must be passed on the
8929     // stack and we don't need to save any argregs.
8930     if (ArgRegs.size() == Idx) {
8931       VaArgOffset = CCInfo.getNextStackOffset();
8932       VarArgsSaveSize = 0;
8933     } else {
8934       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8935       VaArgOffset = -VarArgsSaveSize;
8936     }
8937 
8938     // Record the frame index of the first variable argument
8939     // which is a value necessary to VASTART.
8940     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8941     RVFI->setVarArgsFrameIndex(FI);
8942 
8943     // If saving an odd number of registers then create an extra stack slot to
8944     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8945     // offsets to even-numbered registered remain 2*XLEN-aligned.
8946     if (Idx % 2) {
8947       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8948       VarArgsSaveSize += XLenInBytes;
8949     }
8950 
8951     // Copy the integer registers that may have been used for passing varargs
8952     // to the vararg save area.
8953     for (unsigned I = Idx; I < ArgRegs.size();
8954          ++I, VaArgOffset += XLenInBytes) {
8955       const Register Reg = RegInfo.createVirtualRegister(RC);
8956       RegInfo.addLiveIn(ArgRegs[I], Reg);
8957       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8958       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8959       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8960       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8961                                    MachinePointerInfo::getFixedStack(MF, FI));
8962       cast<StoreSDNode>(Store.getNode())
8963           ->getMemOperand()
8964           ->setValue((Value *)nullptr);
8965       OutChains.push_back(Store);
8966     }
8967     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8968   }
8969 
8970   // All stores are grouped in one node to allow the matching between
8971   // the size of Ins and InVals. This only happens for vararg functions.
8972   if (!OutChains.empty()) {
8973     OutChains.push_back(Chain);
8974     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8975   }
8976 
8977   return Chain;
8978 }
8979 
8980 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8981 /// for tail call optimization.
8982 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8983 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8984     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8985     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8986 
8987   auto &Callee = CLI.Callee;
8988   auto CalleeCC = CLI.CallConv;
8989   auto &Outs = CLI.Outs;
8990   auto &Caller = MF.getFunction();
8991   auto CallerCC = Caller.getCallingConv();
8992 
8993   // Exception-handling functions need a special set of instructions to
8994   // indicate a return to the hardware. Tail-calling another function would
8995   // probably break this.
8996   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8997   // should be expanded as new function attributes are introduced.
8998   if (Caller.hasFnAttribute("interrupt"))
8999     return false;
9000 
9001   // Do not tail call opt if the stack is used to pass parameters.
9002   if (CCInfo.getNextStackOffset() != 0)
9003     return false;
9004 
9005   // Do not tail call opt if any parameters need to be passed indirectly.
9006   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9007   // passed indirectly. So the address of the value will be passed in a
9008   // register, or if not available, then the address is put on the stack. In
9009   // order to pass indirectly, space on the stack often needs to be allocated
9010   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9011   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9012   // are passed CCValAssign::Indirect.
9013   for (auto &VA : ArgLocs)
9014     if (VA.getLocInfo() == CCValAssign::Indirect)
9015       return false;
9016 
9017   // Do not tail call opt if either caller or callee uses struct return
9018   // semantics.
9019   auto IsCallerStructRet = Caller.hasStructRetAttr();
9020   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9021   if (IsCallerStructRet || IsCalleeStructRet)
9022     return false;
9023 
9024   // Externally-defined functions with weak linkage should not be
9025   // tail-called. The behaviour of branch instructions in this situation (as
9026   // used for tail calls) is implementation-defined, so we cannot rely on the
9027   // linker replacing the tail call with a return.
9028   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9029     const GlobalValue *GV = G->getGlobal();
9030     if (GV->hasExternalWeakLinkage())
9031       return false;
9032   }
9033 
9034   // The callee has to preserve all registers the caller needs to preserve.
9035   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9036   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9037   if (CalleeCC != CallerCC) {
9038     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9039     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9040       return false;
9041   }
9042 
9043   // Byval parameters hand the function a pointer directly into the stack area
9044   // we want to reuse during a tail call. Working around this *is* possible
9045   // but less efficient and uglier in LowerCall.
9046   for (auto &Arg : Outs)
9047     if (Arg.Flags.isByVal())
9048       return false;
9049 
9050   return true;
9051 }
9052 
9053 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9054   return DAG.getDataLayout().getPrefTypeAlign(
9055       VT.getTypeForEVT(*DAG.getContext()));
9056 }
9057 
9058 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9059 // and output parameter nodes.
9060 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9061                                        SmallVectorImpl<SDValue> &InVals) const {
9062   SelectionDAG &DAG = CLI.DAG;
9063   SDLoc &DL = CLI.DL;
9064   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9065   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9066   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9067   SDValue Chain = CLI.Chain;
9068   SDValue Callee = CLI.Callee;
9069   bool &IsTailCall = CLI.IsTailCall;
9070   CallingConv::ID CallConv = CLI.CallConv;
9071   bool IsVarArg = CLI.IsVarArg;
9072   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9073   MVT XLenVT = Subtarget.getXLenVT();
9074 
9075   MachineFunction &MF = DAG.getMachineFunction();
9076 
9077   // Analyze the operands of the call, assigning locations to each operand.
9078   SmallVector<CCValAssign, 16> ArgLocs;
9079   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9080 
9081   if (CallConv == CallingConv::GHC)
9082     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9083   else
9084     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9085                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9086                                                     : CC_RISCV);
9087 
9088   // Check if it's really possible to do a tail call.
9089   if (IsTailCall)
9090     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9091 
9092   if (IsTailCall)
9093     ++NumTailCalls;
9094   else if (CLI.CB && CLI.CB->isMustTailCall())
9095     report_fatal_error("failed to perform tail call elimination on a call "
9096                        "site marked musttail");
9097 
9098   // Get a count of how many bytes are to be pushed on the stack.
9099   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9100 
9101   // Create local copies for byval args
9102   SmallVector<SDValue, 8> ByValArgs;
9103   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9104     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9105     if (!Flags.isByVal())
9106       continue;
9107 
9108     SDValue Arg = OutVals[i];
9109     unsigned Size = Flags.getByValSize();
9110     Align Alignment = Flags.getNonZeroByValAlign();
9111 
9112     int FI =
9113         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9114     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9115     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9116 
9117     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9118                           /*IsVolatile=*/false,
9119                           /*AlwaysInline=*/false, IsTailCall,
9120                           MachinePointerInfo(), MachinePointerInfo());
9121     ByValArgs.push_back(FIPtr);
9122   }
9123 
9124   if (!IsTailCall)
9125     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9126 
9127   // Copy argument values to their designated locations.
9128   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9129   SmallVector<SDValue, 8> MemOpChains;
9130   SDValue StackPtr;
9131   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9132     CCValAssign &VA = ArgLocs[i];
9133     SDValue ArgValue = OutVals[i];
9134     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9135 
9136     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9137     bool IsF64OnRV32DSoftABI =
9138         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9139     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9140       SDValue SplitF64 = DAG.getNode(
9141           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9142       SDValue Lo = SplitF64.getValue(0);
9143       SDValue Hi = SplitF64.getValue(1);
9144 
9145       Register RegLo = VA.getLocReg();
9146       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9147 
9148       if (RegLo == RISCV::X17) {
9149         // Second half of f64 is passed on the stack.
9150         // Work out the address of the stack slot.
9151         if (!StackPtr.getNode())
9152           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9153         // Emit the store.
9154         MemOpChains.push_back(
9155             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9156       } else {
9157         // Second half of f64 is passed in another GPR.
9158         assert(RegLo < RISCV::X31 && "Invalid register pair");
9159         Register RegHigh = RegLo + 1;
9160         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9161       }
9162       continue;
9163     }
9164 
9165     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9166     // as any other MemLoc.
9167 
9168     // Promote the value if needed.
9169     // For now, only handle fully promoted and indirect arguments.
9170     if (VA.getLocInfo() == CCValAssign::Indirect) {
9171       // Store the argument in a stack slot and pass its address.
9172       Align StackAlign =
9173           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9174                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9175       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9176       // If the original argument was split (e.g. i128), we need
9177       // to store the required parts of it here (and pass just one address).
9178       // Vectors may be partly split to registers and partly to the stack, in
9179       // which case the base address is partly offset and subsequent stores are
9180       // relative to that.
9181       unsigned ArgIndex = Outs[i].OrigArgIndex;
9182       unsigned ArgPartOffset = Outs[i].PartOffset;
9183       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9184       // Calculate the total size to store. We don't have access to what we're
9185       // actually storing other than performing the loop and collecting the
9186       // info.
9187       SmallVector<std::pair<SDValue, SDValue>> Parts;
9188       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9189         SDValue PartValue = OutVals[i + 1];
9190         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9191         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9192         EVT PartVT = PartValue.getValueType();
9193         if (PartVT.isScalableVector())
9194           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9195         StoredSize += PartVT.getStoreSize();
9196         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9197         Parts.push_back(std::make_pair(PartValue, Offset));
9198         ++i;
9199       }
9200       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9201       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9202       MemOpChains.push_back(
9203           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9204                        MachinePointerInfo::getFixedStack(MF, FI)));
9205       for (const auto &Part : Parts) {
9206         SDValue PartValue = Part.first;
9207         SDValue PartOffset = Part.second;
9208         SDValue Address =
9209             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9210         MemOpChains.push_back(
9211             DAG.getStore(Chain, DL, PartValue, Address,
9212                          MachinePointerInfo::getFixedStack(MF, FI)));
9213       }
9214       ArgValue = SpillSlot;
9215     } else {
9216       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9217     }
9218 
9219     // Use local copy if it is a byval arg.
9220     if (Flags.isByVal())
9221       ArgValue = ByValArgs[j++];
9222 
9223     if (VA.isRegLoc()) {
9224       // Queue up the argument copies and emit them at the end.
9225       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9226     } else {
9227       assert(VA.isMemLoc() && "Argument not register or memory");
9228       assert(!IsTailCall && "Tail call not allowed if stack is used "
9229                             "for passing parameters");
9230 
9231       // Work out the address of the stack slot.
9232       if (!StackPtr.getNode())
9233         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9234       SDValue Address =
9235           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9236                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9237 
9238       // Emit the store.
9239       MemOpChains.push_back(
9240           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9241     }
9242   }
9243 
9244   // Join the stores, which are independent of one another.
9245   if (!MemOpChains.empty())
9246     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9247 
9248   SDValue Glue;
9249 
9250   // Build a sequence of copy-to-reg nodes, chained and glued together.
9251   for (auto &Reg : RegsToPass) {
9252     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9253     Glue = Chain.getValue(1);
9254   }
9255 
9256   // Validate that none of the argument registers have been marked as
9257   // reserved, if so report an error. Do the same for the return address if this
9258   // is not a tailcall.
9259   validateCCReservedRegs(RegsToPass, MF);
9260   if (!IsTailCall &&
9261       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9262     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9263         MF.getFunction(),
9264         "Return address register required, but has been reserved."});
9265 
9266   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9267   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9268   // split it and then direct call can be matched by PseudoCALL.
9269   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9270     const GlobalValue *GV = S->getGlobal();
9271 
9272     unsigned OpFlags = RISCVII::MO_CALL;
9273     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9274       OpFlags = RISCVII::MO_PLT;
9275 
9276     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9277   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9278     unsigned OpFlags = RISCVII::MO_CALL;
9279 
9280     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9281                                                  nullptr))
9282       OpFlags = RISCVII::MO_PLT;
9283 
9284     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9285   }
9286 
9287   // The first call operand is the chain and the second is the target address.
9288   SmallVector<SDValue, 8> Ops;
9289   Ops.push_back(Chain);
9290   Ops.push_back(Callee);
9291 
9292   // Add argument registers to the end of the list so that they are
9293   // known live into the call.
9294   for (auto &Reg : RegsToPass)
9295     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9296 
9297   if (!IsTailCall) {
9298     // Add a register mask operand representing the call-preserved registers.
9299     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9300     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9301     assert(Mask && "Missing call preserved mask for calling convention");
9302     Ops.push_back(DAG.getRegisterMask(Mask));
9303   }
9304 
9305   // Glue the call to the argument copies, if any.
9306   if (Glue.getNode())
9307     Ops.push_back(Glue);
9308 
9309   // Emit the call.
9310   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9311 
9312   if (IsTailCall) {
9313     MF.getFrameInfo().setHasTailCall();
9314     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9315   }
9316 
9317   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9318   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9319   Glue = Chain.getValue(1);
9320 
9321   // Mark the end of the call, which is glued to the call itself.
9322   Chain = DAG.getCALLSEQ_END(Chain,
9323                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9324                              DAG.getConstant(0, DL, PtrVT, true),
9325                              Glue, DL);
9326   Glue = Chain.getValue(1);
9327 
9328   // Assign locations to each value returned by this call.
9329   SmallVector<CCValAssign, 16> RVLocs;
9330   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9331   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9332 
9333   // Copy all of the result registers out of their specified physreg.
9334   for (auto &VA : RVLocs) {
9335     // Copy the value out
9336     SDValue RetValue =
9337         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9338     // Glue the RetValue to the end of the call sequence
9339     Chain = RetValue.getValue(1);
9340     Glue = RetValue.getValue(2);
9341 
9342     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9343       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9344       SDValue RetValue2 =
9345           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9346       Chain = RetValue2.getValue(1);
9347       Glue = RetValue2.getValue(2);
9348       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9349                              RetValue2);
9350     }
9351 
9352     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9353 
9354     InVals.push_back(RetValue);
9355   }
9356 
9357   return Chain;
9358 }
9359 
9360 bool RISCVTargetLowering::CanLowerReturn(
9361     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9362     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9363   SmallVector<CCValAssign, 16> RVLocs;
9364   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9365 
9366   Optional<unsigned> FirstMaskArgument;
9367   if (Subtarget.hasVInstructions())
9368     FirstMaskArgument = preAssignMask(Outs);
9369 
9370   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9371     MVT VT = Outs[i].VT;
9372     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9373     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9374     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9375                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9376                  *this, FirstMaskArgument))
9377       return false;
9378   }
9379   return true;
9380 }
9381 
9382 SDValue
9383 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9384                                  bool IsVarArg,
9385                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9386                                  const SmallVectorImpl<SDValue> &OutVals,
9387                                  const SDLoc &DL, SelectionDAG &DAG) const {
9388   const MachineFunction &MF = DAG.getMachineFunction();
9389   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9390 
9391   // Stores the assignment of the return value to a location.
9392   SmallVector<CCValAssign, 16> RVLocs;
9393 
9394   // Info about the registers and stack slot.
9395   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9396                  *DAG.getContext());
9397 
9398   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9399                     nullptr, CC_RISCV);
9400 
9401   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9402     report_fatal_error("GHC functions return void only");
9403 
9404   SDValue Glue;
9405   SmallVector<SDValue, 4> RetOps(1, Chain);
9406 
9407   // Copy the result values into the output registers.
9408   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9409     SDValue Val = OutVals[i];
9410     CCValAssign &VA = RVLocs[i];
9411     assert(VA.isRegLoc() && "Can only return in registers!");
9412 
9413     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9414       // Handle returning f64 on RV32D with a soft float ABI.
9415       assert(VA.isRegLoc() && "Expected return via registers");
9416       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9417                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9418       SDValue Lo = SplitF64.getValue(0);
9419       SDValue Hi = SplitF64.getValue(1);
9420       Register RegLo = VA.getLocReg();
9421       assert(RegLo < RISCV::X31 && "Invalid register pair");
9422       Register RegHi = RegLo + 1;
9423 
9424       if (STI.isRegisterReservedByUser(RegLo) ||
9425           STI.isRegisterReservedByUser(RegHi))
9426         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9427             MF.getFunction(),
9428             "Return value register required, but has been reserved."});
9429 
9430       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9431       Glue = Chain.getValue(1);
9432       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9433       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9434       Glue = Chain.getValue(1);
9435       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9436     } else {
9437       // Handle a 'normal' return.
9438       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9439       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9440 
9441       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9442         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9443             MF.getFunction(),
9444             "Return value register required, but has been reserved."});
9445 
9446       // Guarantee that all emitted copies are stuck together.
9447       Glue = Chain.getValue(1);
9448       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9449     }
9450   }
9451 
9452   RetOps[0] = Chain; // Update chain.
9453 
9454   // Add the glue node if we have it.
9455   if (Glue.getNode()) {
9456     RetOps.push_back(Glue);
9457   }
9458 
9459   unsigned RetOpc = RISCVISD::RET_FLAG;
9460   // Interrupt service routines use different return instructions.
9461   const Function &Func = DAG.getMachineFunction().getFunction();
9462   if (Func.hasFnAttribute("interrupt")) {
9463     if (!Func.getReturnType()->isVoidTy())
9464       report_fatal_error(
9465           "Functions with the interrupt attribute must have void return type!");
9466 
9467     MachineFunction &MF = DAG.getMachineFunction();
9468     StringRef Kind =
9469       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9470 
9471     if (Kind == "user")
9472       RetOpc = RISCVISD::URET_FLAG;
9473     else if (Kind == "supervisor")
9474       RetOpc = RISCVISD::SRET_FLAG;
9475     else
9476       RetOpc = RISCVISD::MRET_FLAG;
9477   }
9478 
9479   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9480 }
9481 
9482 void RISCVTargetLowering::validateCCReservedRegs(
9483     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9484     MachineFunction &MF) const {
9485   const Function &F = MF.getFunction();
9486   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9487 
9488   if (llvm::any_of(Regs, [&STI](auto Reg) {
9489         return STI.isRegisterReservedByUser(Reg.first);
9490       }))
9491     F.getContext().diagnose(DiagnosticInfoUnsupported{
9492         F, "Argument register required, but has been reserved."});
9493 }
9494 
9495 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9496   return CI->isTailCall();
9497 }
9498 
9499 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9500 #define NODE_NAME_CASE(NODE)                                                   \
9501   case RISCVISD::NODE:                                                         \
9502     return "RISCVISD::" #NODE;
9503   // clang-format off
9504   switch ((RISCVISD::NodeType)Opcode) {
9505   case RISCVISD::FIRST_NUMBER:
9506     break;
9507   NODE_NAME_CASE(RET_FLAG)
9508   NODE_NAME_CASE(URET_FLAG)
9509   NODE_NAME_CASE(SRET_FLAG)
9510   NODE_NAME_CASE(MRET_FLAG)
9511   NODE_NAME_CASE(CALL)
9512   NODE_NAME_CASE(SELECT_CC)
9513   NODE_NAME_CASE(BR_CC)
9514   NODE_NAME_CASE(BuildPairF64)
9515   NODE_NAME_CASE(SplitF64)
9516   NODE_NAME_CASE(TAIL)
9517   NODE_NAME_CASE(MULHSU)
9518   NODE_NAME_CASE(SLLW)
9519   NODE_NAME_CASE(SRAW)
9520   NODE_NAME_CASE(SRLW)
9521   NODE_NAME_CASE(DIVW)
9522   NODE_NAME_CASE(DIVUW)
9523   NODE_NAME_CASE(REMUW)
9524   NODE_NAME_CASE(ROLW)
9525   NODE_NAME_CASE(RORW)
9526   NODE_NAME_CASE(CLZW)
9527   NODE_NAME_CASE(CTZW)
9528   NODE_NAME_CASE(FSLW)
9529   NODE_NAME_CASE(FSRW)
9530   NODE_NAME_CASE(FSL)
9531   NODE_NAME_CASE(FSR)
9532   NODE_NAME_CASE(FMV_H_X)
9533   NODE_NAME_CASE(FMV_X_ANYEXTH)
9534   NODE_NAME_CASE(FMV_W_X_RV64)
9535   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9536   NODE_NAME_CASE(FCVT_X_RTZ)
9537   NODE_NAME_CASE(FCVT_XU_RTZ)
9538   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9539   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9540   NODE_NAME_CASE(STRICT_FCVT_W_RTZ_RV64)
9541   NODE_NAME_CASE(STRICT_FCVT_WU_RTZ_RV64)
9542   NODE_NAME_CASE(READ_CYCLE_WIDE)
9543   NODE_NAME_CASE(GREV)
9544   NODE_NAME_CASE(GREVW)
9545   NODE_NAME_CASE(GORC)
9546   NODE_NAME_CASE(GORCW)
9547   NODE_NAME_CASE(SHFL)
9548   NODE_NAME_CASE(SHFLW)
9549   NODE_NAME_CASE(UNSHFL)
9550   NODE_NAME_CASE(UNSHFLW)
9551   NODE_NAME_CASE(BCOMPRESS)
9552   NODE_NAME_CASE(BCOMPRESSW)
9553   NODE_NAME_CASE(BDECOMPRESS)
9554   NODE_NAME_CASE(BDECOMPRESSW)
9555   NODE_NAME_CASE(VMV_V_X_VL)
9556   NODE_NAME_CASE(VFMV_V_F_VL)
9557   NODE_NAME_CASE(VMV_X_S)
9558   NODE_NAME_CASE(VMV_S_X_VL)
9559   NODE_NAME_CASE(VFMV_S_F_VL)
9560   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9561   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9562   NODE_NAME_CASE(READ_VLENB)
9563   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9564   NODE_NAME_CASE(VSLIDEUP_VL)
9565   NODE_NAME_CASE(VSLIDE1UP_VL)
9566   NODE_NAME_CASE(VSLIDEDOWN_VL)
9567   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9568   NODE_NAME_CASE(VID_VL)
9569   NODE_NAME_CASE(VFNCVT_ROD_VL)
9570   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9571   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9572   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9573   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9574   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9575   NODE_NAME_CASE(VECREDUCE_AND_VL)
9576   NODE_NAME_CASE(VECREDUCE_OR_VL)
9577   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9578   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9579   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9580   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9581   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9582   NODE_NAME_CASE(ADD_VL)
9583   NODE_NAME_CASE(AND_VL)
9584   NODE_NAME_CASE(MUL_VL)
9585   NODE_NAME_CASE(OR_VL)
9586   NODE_NAME_CASE(SDIV_VL)
9587   NODE_NAME_CASE(SHL_VL)
9588   NODE_NAME_CASE(SREM_VL)
9589   NODE_NAME_CASE(SRA_VL)
9590   NODE_NAME_CASE(SRL_VL)
9591   NODE_NAME_CASE(SUB_VL)
9592   NODE_NAME_CASE(UDIV_VL)
9593   NODE_NAME_CASE(UREM_VL)
9594   NODE_NAME_CASE(XOR_VL)
9595   NODE_NAME_CASE(SADDSAT_VL)
9596   NODE_NAME_CASE(UADDSAT_VL)
9597   NODE_NAME_CASE(SSUBSAT_VL)
9598   NODE_NAME_CASE(USUBSAT_VL)
9599   NODE_NAME_CASE(FADD_VL)
9600   NODE_NAME_CASE(FSUB_VL)
9601   NODE_NAME_CASE(FMUL_VL)
9602   NODE_NAME_CASE(FDIV_VL)
9603   NODE_NAME_CASE(FNEG_VL)
9604   NODE_NAME_CASE(FABS_VL)
9605   NODE_NAME_CASE(FSQRT_VL)
9606   NODE_NAME_CASE(FMA_VL)
9607   NODE_NAME_CASE(FCOPYSIGN_VL)
9608   NODE_NAME_CASE(SMIN_VL)
9609   NODE_NAME_CASE(SMAX_VL)
9610   NODE_NAME_CASE(UMIN_VL)
9611   NODE_NAME_CASE(UMAX_VL)
9612   NODE_NAME_CASE(FMINNUM_VL)
9613   NODE_NAME_CASE(FMAXNUM_VL)
9614   NODE_NAME_CASE(MULHS_VL)
9615   NODE_NAME_CASE(MULHU_VL)
9616   NODE_NAME_CASE(FP_TO_SINT_VL)
9617   NODE_NAME_CASE(FP_TO_UINT_VL)
9618   NODE_NAME_CASE(SINT_TO_FP_VL)
9619   NODE_NAME_CASE(UINT_TO_FP_VL)
9620   NODE_NAME_CASE(FP_EXTEND_VL)
9621   NODE_NAME_CASE(FP_ROUND_VL)
9622   NODE_NAME_CASE(VWMUL_VL)
9623   NODE_NAME_CASE(VWMULU_VL)
9624   NODE_NAME_CASE(SETCC_VL)
9625   NODE_NAME_CASE(VSELECT_VL)
9626   NODE_NAME_CASE(VMAND_VL)
9627   NODE_NAME_CASE(VMOR_VL)
9628   NODE_NAME_CASE(VMXOR_VL)
9629   NODE_NAME_CASE(VMCLR_VL)
9630   NODE_NAME_CASE(VMSET_VL)
9631   NODE_NAME_CASE(VRGATHER_VX_VL)
9632   NODE_NAME_CASE(VRGATHER_VV_VL)
9633   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9634   NODE_NAME_CASE(VSEXT_VL)
9635   NODE_NAME_CASE(VZEXT_VL)
9636   NODE_NAME_CASE(VCPOP_VL)
9637   NODE_NAME_CASE(VLE_VL)
9638   NODE_NAME_CASE(VSE_VL)
9639   NODE_NAME_CASE(READ_CSR)
9640   NODE_NAME_CASE(WRITE_CSR)
9641   NODE_NAME_CASE(SWAP_CSR)
9642   }
9643   // clang-format on
9644   return nullptr;
9645 #undef NODE_NAME_CASE
9646 }
9647 
9648 /// getConstraintType - Given a constraint letter, return the type of
9649 /// constraint it is for this target.
9650 RISCVTargetLowering::ConstraintType
9651 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9652   if (Constraint.size() == 1) {
9653     switch (Constraint[0]) {
9654     default:
9655       break;
9656     case 'f':
9657       return C_RegisterClass;
9658     case 'I':
9659     case 'J':
9660     case 'K':
9661       return C_Immediate;
9662     case 'A':
9663       return C_Memory;
9664     case 'S': // A symbolic address
9665       return C_Other;
9666     }
9667   } else {
9668     if (Constraint == "vr" || Constraint == "vm")
9669       return C_RegisterClass;
9670   }
9671   return TargetLowering::getConstraintType(Constraint);
9672 }
9673 
9674 std::pair<unsigned, const TargetRegisterClass *>
9675 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9676                                                   StringRef Constraint,
9677                                                   MVT VT) const {
9678   // First, see if this is a constraint that directly corresponds to a
9679   // RISCV register class.
9680   if (Constraint.size() == 1) {
9681     switch (Constraint[0]) {
9682     case 'r':
9683       // TODO: Support fixed vectors up to XLen for P extension?
9684       if (VT.isVector())
9685         break;
9686       return std::make_pair(0U, &RISCV::GPRRegClass);
9687     case 'f':
9688       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9689         return std::make_pair(0U, &RISCV::FPR16RegClass);
9690       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9691         return std::make_pair(0U, &RISCV::FPR32RegClass);
9692       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9693         return std::make_pair(0U, &RISCV::FPR64RegClass);
9694       break;
9695     default:
9696       break;
9697     }
9698   } else if (Constraint == "vr") {
9699     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9700                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9701       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9702         return std::make_pair(0U, RC);
9703     }
9704   } else if (Constraint == "vm") {
9705     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
9706       return std::make_pair(0U, &RISCV::VMV0RegClass);
9707   }
9708 
9709   // Clang will correctly decode the usage of register name aliases into their
9710   // official names. However, other frontends like `rustc` do not. This allows
9711   // users of these frontends to use the ABI names for registers in LLVM-style
9712   // register constraints.
9713   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9714                                .Case("{zero}", RISCV::X0)
9715                                .Case("{ra}", RISCV::X1)
9716                                .Case("{sp}", RISCV::X2)
9717                                .Case("{gp}", RISCV::X3)
9718                                .Case("{tp}", RISCV::X4)
9719                                .Case("{t0}", RISCV::X5)
9720                                .Case("{t1}", RISCV::X6)
9721                                .Case("{t2}", RISCV::X7)
9722                                .Cases("{s0}", "{fp}", RISCV::X8)
9723                                .Case("{s1}", RISCV::X9)
9724                                .Case("{a0}", RISCV::X10)
9725                                .Case("{a1}", RISCV::X11)
9726                                .Case("{a2}", RISCV::X12)
9727                                .Case("{a3}", RISCV::X13)
9728                                .Case("{a4}", RISCV::X14)
9729                                .Case("{a5}", RISCV::X15)
9730                                .Case("{a6}", RISCV::X16)
9731                                .Case("{a7}", RISCV::X17)
9732                                .Case("{s2}", RISCV::X18)
9733                                .Case("{s3}", RISCV::X19)
9734                                .Case("{s4}", RISCV::X20)
9735                                .Case("{s5}", RISCV::X21)
9736                                .Case("{s6}", RISCV::X22)
9737                                .Case("{s7}", RISCV::X23)
9738                                .Case("{s8}", RISCV::X24)
9739                                .Case("{s9}", RISCV::X25)
9740                                .Case("{s10}", RISCV::X26)
9741                                .Case("{s11}", RISCV::X27)
9742                                .Case("{t3}", RISCV::X28)
9743                                .Case("{t4}", RISCV::X29)
9744                                .Case("{t5}", RISCV::X30)
9745                                .Case("{t6}", RISCV::X31)
9746                                .Default(RISCV::NoRegister);
9747   if (XRegFromAlias != RISCV::NoRegister)
9748     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9749 
9750   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9751   // TableGen record rather than the AsmName to choose registers for InlineAsm
9752   // constraints, plus we want to match those names to the widest floating point
9753   // register type available, manually select floating point registers here.
9754   //
9755   // The second case is the ABI name of the register, so that frontends can also
9756   // use the ABI names in register constraint lists.
9757   if (Subtarget.hasStdExtF()) {
9758     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9759                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9760                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9761                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9762                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9763                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9764                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9765                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9766                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9767                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9768                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9769                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9770                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9771                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9772                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9773                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9774                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9775                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9776                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9777                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9778                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9779                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9780                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9781                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9782                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9783                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9784                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9785                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9786                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9787                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9788                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9789                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9790                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9791                         .Default(RISCV::NoRegister);
9792     if (FReg != RISCV::NoRegister) {
9793       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9794       if (Subtarget.hasStdExtD()) {
9795         unsigned RegNo = FReg - RISCV::F0_F;
9796         unsigned DReg = RISCV::F0_D + RegNo;
9797         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9798       }
9799       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9800     }
9801   }
9802 
9803   if (Subtarget.hasVInstructions()) {
9804     Register VReg = StringSwitch<Register>(Constraint.lower())
9805                         .Case("{v0}", RISCV::V0)
9806                         .Case("{v1}", RISCV::V1)
9807                         .Case("{v2}", RISCV::V2)
9808                         .Case("{v3}", RISCV::V3)
9809                         .Case("{v4}", RISCV::V4)
9810                         .Case("{v5}", RISCV::V5)
9811                         .Case("{v6}", RISCV::V6)
9812                         .Case("{v7}", RISCV::V7)
9813                         .Case("{v8}", RISCV::V8)
9814                         .Case("{v9}", RISCV::V9)
9815                         .Case("{v10}", RISCV::V10)
9816                         .Case("{v11}", RISCV::V11)
9817                         .Case("{v12}", RISCV::V12)
9818                         .Case("{v13}", RISCV::V13)
9819                         .Case("{v14}", RISCV::V14)
9820                         .Case("{v15}", RISCV::V15)
9821                         .Case("{v16}", RISCV::V16)
9822                         .Case("{v17}", RISCV::V17)
9823                         .Case("{v18}", RISCV::V18)
9824                         .Case("{v19}", RISCV::V19)
9825                         .Case("{v20}", RISCV::V20)
9826                         .Case("{v21}", RISCV::V21)
9827                         .Case("{v22}", RISCV::V22)
9828                         .Case("{v23}", RISCV::V23)
9829                         .Case("{v24}", RISCV::V24)
9830                         .Case("{v25}", RISCV::V25)
9831                         .Case("{v26}", RISCV::V26)
9832                         .Case("{v27}", RISCV::V27)
9833                         .Case("{v28}", RISCV::V28)
9834                         .Case("{v29}", RISCV::V29)
9835                         .Case("{v30}", RISCV::V30)
9836                         .Case("{v31}", RISCV::V31)
9837                         .Default(RISCV::NoRegister);
9838     if (VReg != RISCV::NoRegister) {
9839       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9840         return std::make_pair(VReg, &RISCV::VMRegClass);
9841       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9842         return std::make_pair(VReg, &RISCV::VRRegClass);
9843       for (const auto *RC :
9844            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9845         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9846           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9847           return std::make_pair(VReg, RC);
9848         }
9849       }
9850     }
9851   }
9852 
9853   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9854 }
9855 
9856 unsigned
9857 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9858   // Currently only support length 1 constraints.
9859   if (ConstraintCode.size() == 1) {
9860     switch (ConstraintCode[0]) {
9861     case 'A':
9862       return InlineAsm::Constraint_A;
9863     default:
9864       break;
9865     }
9866   }
9867 
9868   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9869 }
9870 
9871 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9872     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9873     SelectionDAG &DAG) const {
9874   // Currently only support length 1 constraints.
9875   if (Constraint.length() == 1) {
9876     switch (Constraint[0]) {
9877     case 'I':
9878       // Validate & create a 12-bit signed immediate operand.
9879       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9880         uint64_t CVal = C->getSExtValue();
9881         if (isInt<12>(CVal))
9882           Ops.push_back(
9883               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9884       }
9885       return;
9886     case 'J':
9887       // Validate & create an integer zero operand.
9888       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9889         if (C->getZExtValue() == 0)
9890           Ops.push_back(
9891               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9892       return;
9893     case 'K':
9894       // Validate & create a 5-bit unsigned immediate operand.
9895       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9896         uint64_t CVal = C->getZExtValue();
9897         if (isUInt<5>(CVal))
9898           Ops.push_back(
9899               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9900       }
9901       return;
9902     case 'S':
9903       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9904         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9905                                                  GA->getValueType(0)));
9906       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9907         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9908                                                 BA->getValueType(0)));
9909       }
9910       return;
9911     default:
9912       break;
9913     }
9914   }
9915   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9916 }
9917 
9918 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9919                                                    Instruction *Inst,
9920                                                    AtomicOrdering Ord) const {
9921   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9922     return Builder.CreateFence(Ord);
9923   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9924     return Builder.CreateFence(AtomicOrdering::Release);
9925   return nullptr;
9926 }
9927 
9928 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9929                                                     Instruction *Inst,
9930                                                     AtomicOrdering Ord) const {
9931   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9932     return Builder.CreateFence(AtomicOrdering::Acquire);
9933   return nullptr;
9934 }
9935 
9936 TargetLowering::AtomicExpansionKind
9937 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9938   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9939   // point operations can't be used in an lr/sc sequence without breaking the
9940   // forward-progress guarantee.
9941   if (AI->isFloatingPointOperation())
9942     return AtomicExpansionKind::CmpXChg;
9943 
9944   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9945   if (Size == 8 || Size == 16)
9946     return AtomicExpansionKind::MaskedIntrinsic;
9947   return AtomicExpansionKind::None;
9948 }
9949 
9950 static Intrinsic::ID
9951 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9952   if (XLen == 32) {
9953     switch (BinOp) {
9954     default:
9955       llvm_unreachable("Unexpected AtomicRMW BinOp");
9956     case AtomicRMWInst::Xchg:
9957       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9958     case AtomicRMWInst::Add:
9959       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9960     case AtomicRMWInst::Sub:
9961       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9962     case AtomicRMWInst::Nand:
9963       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9964     case AtomicRMWInst::Max:
9965       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9966     case AtomicRMWInst::Min:
9967       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9968     case AtomicRMWInst::UMax:
9969       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9970     case AtomicRMWInst::UMin:
9971       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9972     }
9973   }
9974 
9975   if (XLen == 64) {
9976     switch (BinOp) {
9977     default:
9978       llvm_unreachable("Unexpected AtomicRMW BinOp");
9979     case AtomicRMWInst::Xchg:
9980       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9981     case AtomicRMWInst::Add:
9982       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9983     case AtomicRMWInst::Sub:
9984       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9985     case AtomicRMWInst::Nand:
9986       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9987     case AtomicRMWInst::Max:
9988       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9989     case AtomicRMWInst::Min:
9990       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9991     case AtomicRMWInst::UMax:
9992       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9993     case AtomicRMWInst::UMin:
9994       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9995     }
9996   }
9997 
9998   llvm_unreachable("Unexpected XLen\n");
9999 }
10000 
10001 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10002     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10003     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10004   unsigned XLen = Subtarget.getXLen();
10005   Value *Ordering =
10006       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10007   Type *Tys[] = {AlignedAddr->getType()};
10008   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10009       AI->getModule(),
10010       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10011 
10012   if (XLen == 64) {
10013     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10014     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10015     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10016   }
10017 
10018   Value *Result;
10019 
10020   // Must pass the shift amount needed to sign extend the loaded value prior
10021   // to performing a signed comparison for min/max. ShiftAmt is the number of
10022   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10023   // is the number of bits to left+right shift the value in order to
10024   // sign-extend.
10025   if (AI->getOperation() == AtomicRMWInst::Min ||
10026       AI->getOperation() == AtomicRMWInst::Max) {
10027     const DataLayout &DL = AI->getModule()->getDataLayout();
10028     unsigned ValWidth =
10029         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10030     Value *SextShamt =
10031         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10032     Result = Builder.CreateCall(LrwOpScwLoop,
10033                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10034   } else {
10035     Result =
10036         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10037   }
10038 
10039   if (XLen == 64)
10040     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10041   return Result;
10042 }
10043 
10044 TargetLowering::AtomicExpansionKind
10045 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10046     AtomicCmpXchgInst *CI) const {
10047   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10048   if (Size == 8 || Size == 16)
10049     return AtomicExpansionKind::MaskedIntrinsic;
10050   return AtomicExpansionKind::None;
10051 }
10052 
10053 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10054     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10055     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10056   unsigned XLen = Subtarget.getXLen();
10057   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10058   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10059   if (XLen == 64) {
10060     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10061     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10062     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10063     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10064   }
10065   Type *Tys[] = {AlignedAddr->getType()};
10066   Function *MaskedCmpXchg =
10067       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10068   Value *Result = Builder.CreateCall(
10069       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10070   if (XLen == 64)
10071     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10072   return Result;
10073 }
10074 
10075 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10076   return false;
10077 }
10078 
10079 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10080                                                EVT VT) const {
10081   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10082     return false;
10083 
10084   switch (FPVT.getSimpleVT().SimpleTy) {
10085   case MVT::f16:
10086     return Subtarget.hasStdExtZfh();
10087   case MVT::f32:
10088     return Subtarget.hasStdExtF();
10089   case MVT::f64:
10090     return Subtarget.hasStdExtD();
10091   default:
10092     return false;
10093   }
10094 }
10095 
10096 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10097                                                      EVT VT) const {
10098   VT = VT.getScalarType();
10099 
10100   if (!VT.isSimple())
10101     return false;
10102 
10103   switch (VT.getSimpleVT().SimpleTy) {
10104   case MVT::f16:
10105     return Subtarget.hasStdExtZfh();
10106   case MVT::f32:
10107     return Subtarget.hasStdExtF();
10108   case MVT::f64:
10109     return Subtarget.hasStdExtD();
10110   default:
10111     break;
10112   }
10113 
10114   return false;
10115 }
10116 
10117 Register RISCVTargetLowering::getExceptionPointerRegister(
10118     const Constant *PersonalityFn) const {
10119   return RISCV::X10;
10120 }
10121 
10122 Register RISCVTargetLowering::getExceptionSelectorRegister(
10123     const Constant *PersonalityFn) const {
10124   return RISCV::X11;
10125 }
10126 
10127 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10128   // Return false to suppress the unnecessary extensions if the LibCall
10129   // arguments or return value is f32 type for LP64 ABI.
10130   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10131   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10132     return false;
10133 
10134   return true;
10135 }
10136 
10137 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10138   if (Subtarget.is64Bit() && Type == MVT::i32)
10139     return true;
10140 
10141   return IsSigned;
10142 }
10143 
10144 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10145                                                  SDValue C) const {
10146   // Check integral scalar types.
10147   if (VT.isScalarInteger()) {
10148     // Omit the optimization if the sub target has the M extension and the data
10149     // size exceeds XLen.
10150     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10151       return false;
10152     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10153       // Break the MUL to a SLLI and an ADD/SUB.
10154       const APInt &Imm = ConstNode->getAPIntValue();
10155       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10156           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10157         return true;
10158       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10159       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10160           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10161            (Imm - 8).isPowerOf2()))
10162         return true;
10163       // Omit the following optimization if the sub target has the M extension
10164       // and the data size >= XLen.
10165       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10166         return false;
10167       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10168       // a pair of LUI/ADDI.
10169       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10170         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10171         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10172             (1 - ImmS).isPowerOf2())
10173         return true;
10174       }
10175     }
10176   }
10177 
10178   return false;
10179 }
10180 
10181 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10182     const SDValue &AddNode, const SDValue &ConstNode) const {
10183   // Let the DAGCombiner decide for vectors.
10184   EVT VT = AddNode.getValueType();
10185   if (VT.isVector())
10186     return true;
10187 
10188   // Let the DAGCombiner decide for larger types.
10189   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10190     return true;
10191 
10192   // It is worse if c1 is simm12 while c1*c2 is not.
10193   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10194   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10195   const APInt &C1 = C1Node->getAPIntValue();
10196   const APInt &C2 = C2Node->getAPIntValue();
10197   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10198     return false;
10199 
10200   // Default to true and let the DAGCombiner decide.
10201   return true;
10202 }
10203 
10204 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10205     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10206     bool *Fast) const {
10207   if (!VT.isVector())
10208     return false;
10209 
10210   EVT ElemVT = VT.getVectorElementType();
10211   if (Alignment >= ElemVT.getStoreSize()) {
10212     if (Fast)
10213       *Fast = true;
10214     return true;
10215   }
10216 
10217   return false;
10218 }
10219 
10220 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10221     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10222     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10223   bool IsABIRegCopy = CC.hasValue();
10224   EVT ValueVT = Val.getValueType();
10225   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10226     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10227     // and cast to f32.
10228     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10229     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10230     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10231                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10232     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10233     Parts[0] = Val;
10234     return true;
10235   }
10236 
10237   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10238     LLVMContext &Context = *DAG.getContext();
10239     EVT ValueEltVT = ValueVT.getVectorElementType();
10240     EVT PartEltVT = PartVT.getVectorElementType();
10241     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10242     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10243     if (PartVTBitSize % ValueVTBitSize == 0) {
10244       assert(PartVTBitSize >= ValueVTBitSize);
10245       // If the element types are different, bitcast to the same element type of
10246       // PartVT first.
10247       // Give an example here, we want copy a <vscale x 1 x i8> value to
10248       // <vscale x 4 x i16>.
10249       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10250       // subvector, then we can bitcast to <vscale x 4 x i16>.
10251       if (ValueEltVT != PartEltVT) {
10252         if (PartVTBitSize > ValueVTBitSize) {
10253           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10254           assert(Count != 0 && "The number of element should not be zero.");
10255           EVT SameEltTypeVT =
10256               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10257           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10258                             DAG.getUNDEF(SameEltTypeVT), Val,
10259                             DAG.getVectorIdxConstant(0, DL));
10260         }
10261         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10262       } else {
10263         Val =
10264             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10265                         Val, DAG.getVectorIdxConstant(0, DL));
10266       }
10267       Parts[0] = Val;
10268       return true;
10269     }
10270   }
10271   return false;
10272 }
10273 
10274 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10275     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10276     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10277   bool IsABIRegCopy = CC.hasValue();
10278   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10279     SDValue Val = Parts[0];
10280 
10281     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10282     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10283     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10284     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10285     return Val;
10286   }
10287 
10288   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10289     LLVMContext &Context = *DAG.getContext();
10290     SDValue Val = Parts[0];
10291     EVT ValueEltVT = ValueVT.getVectorElementType();
10292     EVT PartEltVT = PartVT.getVectorElementType();
10293     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10294     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10295     if (PartVTBitSize % ValueVTBitSize == 0) {
10296       assert(PartVTBitSize >= ValueVTBitSize);
10297       EVT SameEltTypeVT = ValueVT;
10298       // If the element types are different, convert it to the same element type
10299       // of PartVT.
10300       // Give an example here, we want copy a <vscale x 1 x i8> value from
10301       // <vscale x 4 x i16>.
10302       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10303       // then we can extract <vscale x 1 x i8>.
10304       if (ValueEltVT != PartEltVT) {
10305         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10306         assert(Count != 0 && "The number of element should not be zero.");
10307         SameEltTypeVT =
10308             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10309         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10310       }
10311       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10312                         DAG.getVectorIdxConstant(0, DL));
10313       return Val;
10314     }
10315   }
10316   return SDValue();
10317 }
10318 
10319 #define GET_REGISTER_MATCHER
10320 #include "RISCVGenAsmMatcher.inc"
10321 
10322 Register
10323 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10324                                        const MachineFunction &MF) const {
10325   Register Reg = MatchRegisterAltName(RegName);
10326   if (Reg == RISCV::NoRegister)
10327     Reg = MatchRegisterName(RegName);
10328   if (Reg == RISCV::NoRegister)
10329     report_fatal_error(
10330         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10331   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10332   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10333     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10334                              StringRef(RegName) + "\"."));
10335   return Reg;
10336 }
10337 
10338 namespace llvm {
10339 namespace RISCVVIntrinsicsTable {
10340 
10341 #define GET_RISCVVIntrinsicsTable_IMPL
10342 #include "RISCVGenSearchableTables.inc"
10343 
10344 } // namespace RISCVVIntrinsicsTable
10345 
10346 } // namespace llvm
10347