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_FADD, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
339     for (auto CC : FPCCToExpand)
340       setCondCodeAction(CC, MVT::f16, Expand);
341     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
342     setOperationAction(ISD::SELECT, MVT::f16, Custom);
343     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
344 
345     setOperationAction(ISD::FREM,       MVT::f16, Promote);
346     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
347     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
348     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
349     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
350     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
351     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
352     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
353     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
354     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
355     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
356     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
357     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
358     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
359     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
360     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
361     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
362     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
363 
364     // We need to custom promote this.
365     if (Subtarget.is64Bit())
366       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
367   }
368 
369   if (Subtarget.hasStdExtF()) {
370     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
371     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
372     setOperationAction(ISD::LRINT, MVT::f32, Legal);
373     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
374     setOperationAction(ISD::LROUND, MVT::f32, Legal);
375     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
376     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
377     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
378     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
379     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
380     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
381     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
382     for (auto CC : FPCCToExpand)
383       setCondCodeAction(CC, MVT::f32, Expand);
384     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
385     setOperationAction(ISD::SELECT, MVT::f32, Custom);
386     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
387     for (auto Op : FPOpToExpand)
388       setOperationAction(Op, MVT::f32, Expand);
389     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
390     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391   }
392 
393   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
394     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
395 
396   if (Subtarget.hasStdExtD()) {
397     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
398     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
399     setOperationAction(ISD::LRINT, MVT::f64, Legal);
400     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
401     setOperationAction(ISD::LROUND, MVT::f64, Legal);
402     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
403     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
404     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
405     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
406     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
407     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
408     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
409     for (auto CC : FPCCToExpand)
410       setCondCodeAction(CC, MVT::f64, Expand);
411     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
412     setOperationAction(ISD::SELECT, MVT::f64, Custom);
413     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
414     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
415     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
416     for (auto Op : FPOpToExpand)
417       setOperationAction(Op, MVT::f64, Expand);
418     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
419     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
420   }
421 
422   if (Subtarget.is64Bit()) {
423     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
424     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
425     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
426     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
427   }
428 
429   if (Subtarget.hasStdExtF()) {
430     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
431     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_SELECT};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
498         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
499 
500     if (!Subtarget.is64Bit()) {
501       // We must custom-lower certain vXi64 operations on RV32 due to the vector
502       // element type being illegal.
503       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
504       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
505 
506       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
507       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
514 
515       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
516       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
523     }
524 
525     for (MVT VT : BoolVecVTs) {
526       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
527 
528       // Mask VTs are custom-expanded into a series of standard nodes
529       setOperationAction(ISD::TRUNCATE, VT, Custom);
530       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
531       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
532       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
533 
534       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
535       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
536 
537       setOperationAction(ISD::SELECT, VT, Custom);
538       setOperationAction(ISD::SELECT_CC, VT, Expand);
539       setOperationAction(ISD::VSELECT, VT, Expand);
540 
541       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
542       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
543       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
544 
545       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
546       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
547       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
548 
549       // RVV has native int->float & float->int conversions where the
550       // element type sizes are within one power-of-two of each other. Any
551       // wider distances between type sizes have to be lowered as sequences
552       // which progressively narrow the gap in stages.
553       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
554       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
555       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
556       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
557 
558       // Expand all extending loads to types larger than this, and truncating
559       // stores from types larger than this.
560       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
561         setTruncStoreAction(OtherVT, VT, Expand);
562         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
563         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
564         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
565       }
566     }
567 
568     for (MVT VT : IntVecVTs) {
569       if (VT.getVectorElementType() == MVT::i64 &&
570           !Subtarget.hasVInstructionsI64())
571         continue;
572 
573       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
574       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
575 
576       // Vectors implement MULHS/MULHU.
577       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
578       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
579 
580       setOperationAction(ISD::SMIN, VT, Legal);
581       setOperationAction(ISD::SMAX, VT, Legal);
582       setOperationAction(ISD::UMIN, VT, Legal);
583       setOperationAction(ISD::UMAX, VT, Legal);
584 
585       setOperationAction(ISD::ROTL, VT, Expand);
586       setOperationAction(ISD::ROTR, VT, Expand);
587 
588       setOperationAction(ISD::CTTZ, VT, Expand);
589       setOperationAction(ISD::CTLZ, VT, Expand);
590       setOperationAction(ISD::CTPOP, VT, Expand);
591 
592       setOperationAction(ISD::BSWAP, VT, Expand);
593 
594       // Custom-lower extensions and truncations from/to mask types.
595       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
596       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
597       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
598 
599       // RVV has native int->float & float->int conversions where the
600       // element type sizes are within one power-of-two of each other. Any
601       // wider distances between type sizes have to be lowered as sequences
602       // which progressively narrow the gap in stages.
603       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
604       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
605       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
606       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
607 
608       setOperationAction(ISD::SADDSAT, VT, Legal);
609       setOperationAction(ISD::UADDSAT, VT, Legal);
610       setOperationAction(ISD::SSUBSAT, VT, Legal);
611       setOperationAction(ISD::USUBSAT, VT, Legal);
612 
613       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
614       // nodes which truncate by one power of two at a time.
615       setOperationAction(ISD::TRUNCATE, VT, Custom);
616 
617       // Custom-lower insert/extract operations to simplify patterns.
618       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
619       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
620 
621       // Custom-lower reduction operations to set up the corresponding custom
622       // nodes' operands.
623       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
624       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
625       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
626       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
627       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
628       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
629       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
630       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
631 
632       for (unsigned VPOpc : IntegerVPOps)
633         setOperationAction(VPOpc, VT, Custom);
634 
635       setOperationAction(ISD::LOAD, VT, Custom);
636       setOperationAction(ISD::STORE, VT, Custom);
637 
638       setOperationAction(ISD::MLOAD, VT, Custom);
639       setOperationAction(ISD::MSTORE, VT, Custom);
640       setOperationAction(ISD::MGATHER, VT, Custom);
641       setOperationAction(ISD::MSCATTER, VT, Custom);
642 
643       setOperationAction(ISD::VP_LOAD, VT, Custom);
644       setOperationAction(ISD::VP_STORE, VT, Custom);
645       setOperationAction(ISD::VP_GATHER, VT, Custom);
646       setOperationAction(ISD::VP_SCATTER, VT, Custom);
647 
648       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
649       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
650       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
651 
652       setOperationAction(ISD::SELECT, VT, Custom);
653       setOperationAction(ISD::SELECT_CC, VT, Expand);
654 
655       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
656       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
657 
658       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
659         setTruncStoreAction(VT, OtherVT, Expand);
660         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
661         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
662         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
663       }
664 
665       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
666       // type that can represent the value exactly.
667       if (VT.getVectorElementType() != MVT::i64) {
668         MVT FloatEltVT =
669             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
670         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
671         if (isTypeLegal(FloatVT)) {
672           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
673           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
674         }
675       }
676     }
677 
678     // Expand various CCs to best match the RVV ISA, which natively supports UNE
679     // but no other unordered comparisons, and supports all ordered comparisons
680     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
681     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
682     // and we pattern-match those back to the "original", swapping operands once
683     // more. This way we catch both operations and both "vf" and "fv" forms with
684     // fewer patterns.
685     static const ISD::CondCode VFPCCToExpand[] = {
686         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
687         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
688         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
689     };
690 
691     // Sets common operation actions on RVV floating-point vector types.
692     const auto SetCommonVFPActions = [&](MVT VT) {
693       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
694       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
695       // sizes are within one power-of-two of each other. Therefore conversions
696       // between vXf16 and vXf64 must be lowered as sequences which convert via
697       // vXf32.
698       setOperationAction(ISD::FP_ROUND, VT, Custom);
699       setOperationAction(ISD::FP_EXTEND, VT, Custom);
700       // Custom-lower insert/extract operations to simplify patterns.
701       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
702       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
703       // Expand various condition codes (explained above).
704       for (auto CC : VFPCCToExpand)
705         setCondCodeAction(CC, VT, Expand);
706 
707       setOperationAction(ISD::FMINNUM, VT, Legal);
708       setOperationAction(ISD::FMAXNUM, VT, Legal);
709 
710       setOperationAction(ISD::FTRUNC, VT, Custom);
711       setOperationAction(ISD::FCEIL, VT, Custom);
712       setOperationAction(ISD::FFLOOR, VT, Custom);
713 
714       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
715       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
716       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
717       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
718 
719       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
720 
721       setOperationAction(ISD::LOAD, VT, Custom);
722       setOperationAction(ISD::STORE, VT, Custom);
723 
724       setOperationAction(ISD::MLOAD, VT, Custom);
725       setOperationAction(ISD::MSTORE, VT, Custom);
726       setOperationAction(ISD::MGATHER, VT, Custom);
727       setOperationAction(ISD::MSCATTER, VT, Custom);
728 
729       setOperationAction(ISD::VP_LOAD, VT, Custom);
730       setOperationAction(ISD::VP_STORE, VT, Custom);
731       setOperationAction(ISD::VP_GATHER, VT, Custom);
732       setOperationAction(ISD::VP_SCATTER, VT, Custom);
733 
734       setOperationAction(ISD::SELECT, VT, Custom);
735       setOperationAction(ISD::SELECT_CC, VT, Expand);
736 
737       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
738       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
739       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
740 
741       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
742 
743       for (unsigned VPOpc : FloatingPointVPOps)
744         setOperationAction(VPOpc, VT, Custom);
745     };
746 
747     // Sets common extload/truncstore actions on RVV floating-point vector
748     // types.
749     const auto SetCommonVFPExtLoadTruncStoreActions =
750         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
751           for (auto SmallVT : SmallerVTs) {
752             setTruncStoreAction(VT, SmallVT, Expand);
753             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
754           }
755         };
756 
757     if (Subtarget.hasVInstructionsF16())
758       for (MVT VT : F16VecVTs)
759         SetCommonVFPActions(VT);
760 
761     for (MVT VT : F32VecVTs) {
762       if (Subtarget.hasVInstructionsF32())
763         SetCommonVFPActions(VT);
764       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
765     }
766 
767     for (MVT VT : F64VecVTs) {
768       if (Subtarget.hasVInstructionsF64())
769         SetCommonVFPActions(VT);
770       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
771       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
772     }
773 
774     if (Subtarget.useRVVForFixedLengthVectors()) {
775       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
776         if (!useRVVForFixedLengthVectorVT(VT))
777           continue;
778 
779         // By default everything must be expanded.
780         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
781           setOperationAction(Op, VT, Expand);
782         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
783           setTruncStoreAction(VT, OtherVT, Expand);
784           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
785           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
786           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
787         }
788 
789         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
790         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
791         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
792 
793         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
794         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
795 
796         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
797         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
798 
799         setOperationAction(ISD::LOAD, VT, Custom);
800         setOperationAction(ISD::STORE, VT, Custom);
801 
802         setOperationAction(ISD::SETCC, VT, Custom);
803 
804         setOperationAction(ISD::SELECT, VT, Custom);
805 
806         setOperationAction(ISD::TRUNCATE, VT, Custom);
807 
808         setOperationAction(ISD::BITCAST, VT, Custom);
809 
810         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
811         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
812         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
813 
814         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
815         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
816         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
817 
818         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
819         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
820         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
821         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
822 
823         // Operations below are different for between masks and other vectors.
824         if (VT.getVectorElementType() == MVT::i1) {
825           setOperationAction(ISD::AND, VT, Custom);
826           setOperationAction(ISD::OR, VT, Custom);
827           setOperationAction(ISD::XOR, VT, Custom);
828           continue;
829         }
830 
831         // Use SPLAT_VECTOR to prevent type legalization from destroying the
832         // splats when type legalizing i64 scalar on RV32.
833         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
834         // improvements first.
835         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
836           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
837           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
838         }
839 
840         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
841         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
842 
843         setOperationAction(ISD::MLOAD, VT, Custom);
844         setOperationAction(ISD::MSTORE, VT, Custom);
845         setOperationAction(ISD::MGATHER, VT, Custom);
846         setOperationAction(ISD::MSCATTER, VT, Custom);
847 
848         setOperationAction(ISD::VP_LOAD, VT, Custom);
849         setOperationAction(ISD::VP_STORE, VT, Custom);
850         setOperationAction(ISD::VP_GATHER, VT, Custom);
851         setOperationAction(ISD::VP_SCATTER, VT, Custom);
852 
853         setOperationAction(ISD::ADD, VT, Custom);
854         setOperationAction(ISD::MUL, VT, Custom);
855         setOperationAction(ISD::SUB, VT, Custom);
856         setOperationAction(ISD::AND, VT, Custom);
857         setOperationAction(ISD::OR, VT, Custom);
858         setOperationAction(ISD::XOR, VT, Custom);
859         setOperationAction(ISD::SDIV, VT, Custom);
860         setOperationAction(ISD::SREM, VT, Custom);
861         setOperationAction(ISD::UDIV, VT, Custom);
862         setOperationAction(ISD::UREM, VT, Custom);
863         setOperationAction(ISD::SHL, VT, Custom);
864         setOperationAction(ISD::SRA, VT, Custom);
865         setOperationAction(ISD::SRL, VT, Custom);
866 
867         setOperationAction(ISD::SMIN, VT, Custom);
868         setOperationAction(ISD::SMAX, VT, Custom);
869         setOperationAction(ISD::UMIN, VT, Custom);
870         setOperationAction(ISD::UMAX, VT, Custom);
871         setOperationAction(ISD::ABS,  VT, Custom);
872 
873         setOperationAction(ISD::MULHS, VT, Custom);
874         setOperationAction(ISD::MULHU, VT, Custom);
875 
876         setOperationAction(ISD::SADDSAT, VT, Custom);
877         setOperationAction(ISD::UADDSAT, VT, Custom);
878         setOperationAction(ISD::SSUBSAT, VT, Custom);
879         setOperationAction(ISD::USUBSAT, VT, Custom);
880 
881         setOperationAction(ISD::VSELECT, VT, Custom);
882         setOperationAction(ISD::SELECT_CC, VT, Expand);
883 
884         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
885         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
886         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
887 
888         // Custom-lower reduction operations to set up the corresponding custom
889         // nodes' operands.
890         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
891         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
892         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
893         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
894         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
895 
896         for (unsigned VPOpc : IntegerVPOps)
897           setOperationAction(VPOpc, VT, Custom);
898 
899         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
900         // type that can represent the value exactly.
901         if (VT.getVectorElementType() != MVT::i64) {
902           MVT FloatEltVT =
903               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
904           EVT FloatVT =
905               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
906           if (isTypeLegal(FloatVT)) {
907             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
908             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
909           }
910         }
911       }
912 
913       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
914         if (!useRVVForFixedLengthVectorVT(VT))
915           continue;
916 
917         // By default everything must be expanded.
918         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
919           setOperationAction(Op, VT, Expand);
920         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
921           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
922           setTruncStoreAction(VT, OtherVT, Expand);
923         }
924 
925         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
926         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
927         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
928 
929         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
930         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
931         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
932         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
933         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934 
935         setOperationAction(ISD::LOAD, VT, Custom);
936         setOperationAction(ISD::STORE, VT, Custom);
937         setOperationAction(ISD::MLOAD, VT, Custom);
938         setOperationAction(ISD::MSTORE, VT, Custom);
939         setOperationAction(ISD::MGATHER, VT, Custom);
940         setOperationAction(ISD::MSCATTER, VT, Custom);
941 
942         setOperationAction(ISD::VP_LOAD, VT, Custom);
943         setOperationAction(ISD::VP_STORE, VT, Custom);
944         setOperationAction(ISD::VP_GATHER, VT, Custom);
945         setOperationAction(ISD::VP_SCATTER, VT, Custom);
946 
947         setOperationAction(ISD::FADD, VT, Custom);
948         setOperationAction(ISD::FSUB, VT, Custom);
949         setOperationAction(ISD::FMUL, VT, Custom);
950         setOperationAction(ISD::FDIV, VT, Custom);
951         setOperationAction(ISD::FNEG, VT, Custom);
952         setOperationAction(ISD::FABS, VT, Custom);
953         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
954         setOperationAction(ISD::FSQRT, VT, Custom);
955         setOperationAction(ISD::FMA, VT, Custom);
956         setOperationAction(ISD::FMINNUM, VT, Custom);
957         setOperationAction(ISD::FMAXNUM, VT, Custom);
958 
959         setOperationAction(ISD::FP_ROUND, VT, Custom);
960         setOperationAction(ISD::FP_EXTEND, VT, Custom);
961 
962         setOperationAction(ISD::FTRUNC, VT, Custom);
963         setOperationAction(ISD::FCEIL, VT, Custom);
964         setOperationAction(ISD::FFLOOR, VT, Custom);
965 
966         for (auto CC : VFPCCToExpand)
967           setCondCodeAction(CC, VT, Expand);
968 
969         setOperationAction(ISD::VSELECT, VT, Custom);
970         setOperationAction(ISD::SELECT, VT, Custom);
971         setOperationAction(ISD::SELECT_CC, VT, Expand);
972 
973         setOperationAction(ISD::BITCAST, VT, Custom);
974 
975         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
976         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
977         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
978         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
979 
980         for (unsigned VPOpc : FloatingPointVPOps)
981           setOperationAction(VPOpc, VT, Custom);
982       }
983 
984       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
985       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
986       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
987       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
988       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
989       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
990       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
991       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
992     }
993   }
994 
995   // Function alignments.
996   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
997   setMinFunctionAlignment(FunctionAlignment);
998   setPrefFunctionAlignment(FunctionAlignment);
999 
1000   setMinimumJumpTableEntries(5);
1001 
1002   // Jumps are expensive, compared to logic
1003   setJumpIsExpensive();
1004 
1005   setTargetDAGCombine(ISD::ADD);
1006   setTargetDAGCombine(ISD::SUB);
1007   setTargetDAGCombine(ISD::AND);
1008   setTargetDAGCombine(ISD::OR);
1009   setTargetDAGCombine(ISD::XOR);
1010   setTargetDAGCombine(ISD::ANY_EXTEND);
1011   setTargetDAGCombine(ISD::ZERO_EXTEND);
1012   if (Subtarget.hasVInstructions()) {
1013     setTargetDAGCombine(ISD::FCOPYSIGN);
1014     setTargetDAGCombine(ISD::MGATHER);
1015     setTargetDAGCombine(ISD::MSCATTER);
1016     setTargetDAGCombine(ISD::VP_GATHER);
1017     setTargetDAGCombine(ISD::VP_SCATTER);
1018     setTargetDAGCombine(ISD::SRA);
1019     setTargetDAGCombine(ISD::SRL);
1020     setTargetDAGCombine(ISD::SHL);
1021     setTargetDAGCombine(ISD::STORE);
1022   }
1023 }
1024 
1025 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1026                                             LLVMContext &Context,
1027                                             EVT VT) const {
1028   if (!VT.isVector())
1029     return getPointerTy(DL);
1030   if (Subtarget.hasVInstructions() &&
1031       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1032     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1033   return VT.changeVectorElementTypeToInteger();
1034 }
1035 
1036 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1037   return Subtarget.getXLenVT();
1038 }
1039 
1040 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1041                                              const CallInst &I,
1042                                              MachineFunction &MF,
1043                                              unsigned Intrinsic) const {
1044   auto &DL = I.getModule()->getDataLayout();
1045   switch (Intrinsic) {
1046   default:
1047     return false;
1048   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1049   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1050   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1051   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1052   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1053   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1054   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1055   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1056   case Intrinsic::riscv_masked_cmpxchg_i32: {
1057     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1058     Info.opc = ISD::INTRINSIC_W_CHAIN;
1059     Info.memVT = MVT::getVT(PtrTy->getElementType());
1060     Info.ptrVal = I.getArgOperand(0);
1061     Info.offset = 0;
1062     Info.align = Align(4);
1063     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1064                  MachineMemOperand::MOVolatile;
1065     return true;
1066   }
1067   case Intrinsic::riscv_masked_strided_load:
1068     Info.opc = ISD::INTRINSIC_W_CHAIN;
1069     Info.ptrVal = I.getArgOperand(1);
1070     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1071     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1072     Info.size = MemoryLocation::UnknownSize;
1073     Info.flags |= MachineMemOperand::MOLoad;
1074     return true;
1075   case Intrinsic::riscv_masked_strided_store:
1076     Info.opc = ISD::INTRINSIC_VOID;
1077     Info.ptrVal = I.getArgOperand(1);
1078     Info.memVT =
1079         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1080     Info.align = Align(
1081         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1082         8);
1083     Info.size = MemoryLocation::UnknownSize;
1084     Info.flags |= MachineMemOperand::MOStore;
1085     return true;
1086   }
1087 }
1088 
1089 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1090                                                 const AddrMode &AM, Type *Ty,
1091                                                 unsigned AS,
1092                                                 Instruction *I) const {
1093   // No global is ever allowed as a base.
1094   if (AM.BaseGV)
1095     return false;
1096 
1097   // Require a 12-bit signed offset.
1098   if (!isInt<12>(AM.BaseOffs))
1099     return false;
1100 
1101   switch (AM.Scale) {
1102   case 0: // "r+i" or just "i", depending on HasBaseReg.
1103     break;
1104   case 1:
1105     if (!AM.HasBaseReg) // allow "r+i".
1106       break;
1107     return false; // disallow "r+r" or "r+r+i".
1108   default:
1109     return false;
1110   }
1111 
1112   return true;
1113 }
1114 
1115 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1116   return isInt<12>(Imm);
1117 }
1118 
1119 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1120   return isInt<12>(Imm);
1121 }
1122 
1123 // On RV32, 64-bit integers are split into their high and low parts and held
1124 // in two different registers, so the trunc is free since the low register can
1125 // just be used.
1126 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1127   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1128     return false;
1129   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1130   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1131   return (SrcBits == 64 && DestBits == 32);
1132 }
1133 
1134 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1135   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1136       !SrcVT.isInteger() || !DstVT.isInteger())
1137     return false;
1138   unsigned SrcBits = SrcVT.getSizeInBits();
1139   unsigned DestBits = DstVT.getSizeInBits();
1140   return (SrcBits == 64 && DestBits == 32);
1141 }
1142 
1143 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1144   // Zexts are free if they can be combined with a load.
1145   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1146     EVT MemVT = LD->getMemoryVT();
1147     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1148          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1149         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1150          LD->getExtensionType() == ISD::ZEXTLOAD))
1151       return true;
1152   }
1153 
1154   return TargetLowering::isZExtFree(Val, VT2);
1155 }
1156 
1157 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1158   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1159 }
1160 
1161 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1162   return Subtarget.hasStdExtZbb();
1163 }
1164 
1165 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1166   return Subtarget.hasStdExtZbb();
1167 }
1168 
1169 bool RISCVTargetLowering::hasAndNot(SDValue Y) const {
1170   EVT VT = Y.getValueType();
1171 
1172   // FIXME: Support vectors once we have tests.
1173   if (VT.isVector())
1174     return false;
1175 
1176   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1177 }
1178 
1179 /// Check if sinking \p I's operands to I's basic block is profitable, because
1180 /// the operands can be folded into a target instruction, e.g.
1181 /// splats of scalars can fold into vector instructions.
1182 bool RISCVTargetLowering::shouldSinkOperands(
1183     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1184   using namespace llvm::PatternMatch;
1185 
1186   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1187     return false;
1188 
1189   auto IsSinker = [&](Instruction *I, int Operand) {
1190     switch (I->getOpcode()) {
1191     case Instruction::Add:
1192     case Instruction::Sub:
1193     case Instruction::Mul:
1194     case Instruction::And:
1195     case Instruction::Or:
1196     case Instruction::Xor:
1197     case Instruction::FAdd:
1198     case Instruction::FSub:
1199     case Instruction::FMul:
1200     case Instruction::FDiv:
1201     case Instruction::ICmp:
1202     case Instruction::FCmp:
1203       return true;
1204     case Instruction::Shl:
1205     case Instruction::LShr:
1206     case Instruction::AShr:
1207     case Instruction::UDiv:
1208     case Instruction::SDiv:
1209     case Instruction::URem:
1210     case Instruction::SRem:
1211       return Operand == 1;
1212     case Instruction::Call:
1213       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1214         switch (II->getIntrinsicID()) {
1215         case Intrinsic::fma:
1216           return Operand == 0 || Operand == 1;
1217         default:
1218           return false;
1219         }
1220       }
1221       return false;
1222     default:
1223       return false;
1224     }
1225   };
1226 
1227   for (auto OpIdx : enumerate(I->operands())) {
1228     if (!IsSinker(I, OpIdx.index()))
1229       continue;
1230 
1231     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1232     // Make sure we are not already sinking this operand
1233     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1234       continue;
1235 
1236     // We are looking for a splat that can be sunk.
1237     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1238                              m_Undef(), m_ZeroMask())))
1239       continue;
1240 
1241     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1242     // and vector registers
1243     for (Use &U : Op->uses()) {
1244       Instruction *Insn = cast<Instruction>(U.getUser());
1245       if (!IsSinker(Insn, U.getOperandNo()))
1246         return false;
1247     }
1248 
1249     Ops.push_back(&Op->getOperandUse(0));
1250     Ops.push_back(&OpIdx.value());
1251   }
1252   return true;
1253 }
1254 
1255 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1256                                        bool ForCodeSize) const {
1257   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1258     return false;
1259   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1260     return false;
1261   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1262     return false;
1263   if (Imm.isNegZero())
1264     return false;
1265   return Imm.isZero();
1266 }
1267 
1268 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1269   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1270          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1271          (VT == MVT::f64 && Subtarget.hasStdExtD());
1272 }
1273 
1274 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1275                                                       CallingConv::ID CC,
1276                                                       EVT VT) const {
1277   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1278   // We might still end up using a GPR but that will be decided based on ABI.
1279   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1280     return MVT::f32;
1281 
1282   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1283 }
1284 
1285 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1286                                                            CallingConv::ID CC,
1287                                                            EVT VT) const {
1288   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1289   // We might still end up using a GPR but that will be decided based on ABI.
1290   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1291     return 1;
1292 
1293   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1294 }
1295 
1296 // Changes the condition code and swaps operands if necessary, so the SetCC
1297 // operation matches one of the comparisons supported directly by branches
1298 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1299 // with 1/-1.
1300 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1301                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1302   // Convert X > -1 to X >= 0.
1303   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1304     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1305     CC = ISD::SETGE;
1306     return;
1307   }
1308   // Convert X < 1 to 0 >= X.
1309   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1310     RHS = LHS;
1311     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1312     CC = ISD::SETGE;
1313     return;
1314   }
1315 
1316   switch (CC) {
1317   default:
1318     break;
1319   case ISD::SETGT:
1320   case ISD::SETLE:
1321   case ISD::SETUGT:
1322   case ISD::SETULE:
1323     CC = ISD::getSetCCSwappedOperands(CC);
1324     std::swap(LHS, RHS);
1325     break;
1326   }
1327 }
1328 
1329 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1330   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1331   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1332   if (VT.getVectorElementType() == MVT::i1)
1333     KnownSize *= 8;
1334 
1335   switch (KnownSize) {
1336   default:
1337     llvm_unreachable("Invalid LMUL.");
1338   case 8:
1339     return RISCVII::VLMUL::LMUL_F8;
1340   case 16:
1341     return RISCVII::VLMUL::LMUL_F4;
1342   case 32:
1343     return RISCVII::VLMUL::LMUL_F2;
1344   case 64:
1345     return RISCVII::VLMUL::LMUL_1;
1346   case 128:
1347     return RISCVII::VLMUL::LMUL_2;
1348   case 256:
1349     return RISCVII::VLMUL::LMUL_4;
1350   case 512:
1351     return RISCVII::VLMUL::LMUL_8;
1352   }
1353 }
1354 
1355 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1356   switch (LMul) {
1357   default:
1358     llvm_unreachable("Invalid LMUL.");
1359   case RISCVII::VLMUL::LMUL_F8:
1360   case RISCVII::VLMUL::LMUL_F4:
1361   case RISCVII::VLMUL::LMUL_F2:
1362   case RISCVII::VLMUL::LMUL_1:
1363     return RISCV::VRRegClassID;
1364   case RISCVII::VLMUL::LMUL_2:
1365     return RISCV::VRM2RegClassID;
1366   case RISCVII::VLMUL::LMUL_4:
1367     return RISCV::VRM4RegClassID;
1368   case RISCVII::VLMUL::LMUL_8:
1369     return RISCV::VRM8RegClassID;
1370   }
1371 }
1372 
1373 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1374   RISCVII::VLMUL LMUL = getLMUL(VT);
1375   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1376       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1377       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1378       LMUL == RISCVII::VLMUL::LMUL_1) {
1379     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1380                   "Unexpected subreg numbering");
1381     return RISCV::sub_vrm1_0 + Index;
1382   }
1383   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1384     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1385                   "Unexpected subreg numbering");
1386     return RISCV::sub_vrm2_0 + Index;
1387   }
1388   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1389     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1390                   "Unexpected subreg numbering");
1391     return RISCV::sub_vrm4_0 + Index;
1392   }
1393   llvm_unreachable("Invalid vector type.");
1394 }
1395 
1396 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1397   if (VT.getVectorElementType() == MVT::i1)
1398     return RISCV::VRRegClassID;
1399   return getRegClassIDForLMUL(getLMUL(VT));
1400 }
1401 
1402 // Attempt to decompose a subvector insert/extract between VecVT and
1403 // SubVecVT via subregister indices. Returns the subregister index that
1404 // can perform the subvector insert/extract with the given element index, as
1405 // well as the index corresponding to any leftover subvectors that must be
1406 // further inserted/extracted within the register class for SubVecVT.
1407 std::pair<unsigned, unsigned>
1408 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1409     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1410     const RISCVRegisterInfo *TRI) {
1411   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1412                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1413                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1414                 "Register classes not ordered");
1415   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1416   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1417   // Try to compose a subregister index that takes us from the incoming
1418   // LMUL>1 register class down to the outgoing one. At each step we half
1419   // the LMUL:
1420   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1421   // Note that this is not guaranteed to find a subregister index, such as
1422   // when we are extracting from one VR type to another.
1423   unsigned SubRegIdx = RISCV::NoSubRegister;
1424   for (const unsigned RCID :
1425        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1426     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1427       VecVT = VecVT.getHalfNumVectorElementsVT();
1428       bool IsHi =
1429           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1430       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1431                                             getSubregIndexByMVT(VecVT, IsHi));
1432       if (IsHi)
1433         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1434     }
1435   return {SubRegIdx, InsertExtractIdx};
1436 }
1437 
1438 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1439 // stores for those types.
1440 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1441   return !Subtarget.useRVVForFixedLengthVectors() ||
1442          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1443 }
1444 
1445 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1446   if (ScalarTy->isPointerTy())
1447     return true;
1448 
1449   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1450       ScalarTy->isIntegerTy(32))
1451     return true;
1452 
1453   if (ScalarTy->isIntegerTy(64))
1454     return Subtarget.hasVInstructionsI64();
1455 
1456   if (ScalarTy->isHalfTy())
1457     return Subtarget.hasVInstructionsF16();
1458   if (ScalarTy->isFloatTy())
1459     return Subtarget.hasVInstructionsF32();
1460   if (ScalarTy->isDoubleTy())
1461     return Subtarget.hasVInstructionsF64();
1462 
1463   return false;
1464 }
1465 
1466 static bool useRVVForFixedLengthVectorVT(MVT VT,
1467                                          const RISCVSubtarget &Subtarget) {
1468   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1469   if (!Subtarget.useRVVForFixedLengthVectors())
1470     return false;
1471 
1472   // We only support a set of vector types with a consistent maximum fixed size
1473   // across all supported vector element types to avoid legalization issues.
1474   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1475   // fixed-length vector type we support is 1024 bytes.
1476   if (VT.getFixedSizeInBits() > 1024 * 8)
1477     return false;
1478 
1479   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1480 
1481   MVT EltVT = VT.getVectorElementType();
1482 
1483   // Don't use RVV for vectors we cannot scalarize if required.
1484   switch (EltVT.SimpleTy) {
1485   // i1 is supported but has different rules.
1486   default:
1487     return false;
1488   case MVT::i1:
1489     // Masks can only use a single register.
1490     if (VT.getVectorNumElements() > MinVLen)
1491       return false;
1492     MinVLen /= 8;
1493     break;
1494   case MVT::i8:
1495   case MVT::i16:
1496   case MVT::i32:
1497     break;
1498   case MVT::i64:
1499     if (!Subtarget.hasVInstructionsI64())
1500       return false;
1501     break;
1502   case MVT::f16:
1503     if (!Subtarget.hasVInstructionsF16())
1504       return false;
1505     break;
1506   case MVT::f32:
1507     if (!Subtarget.hasVInstructionsF32())
1508       return false;
1509     break;
1510   case MVT::f64:
1511     if (!Subtarget.hasVInstructionsF64())
1512       return false;
1513     break;
1514   }
1515 
1516   // Reject elements larger than ELEN.
1517   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1518     return false;
1519 
1520   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1521   // Don't use RVV for types that don't fit.
1522   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1523     return false;
1524 
1525   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1526   // the base fixed length RVV support in place.
1527   if (!VT.isPow2VectorType())
1528     return false;
1529 
1530   return true;
1531 }
1532 
1533 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1534   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1535 }
1536 
1537 // Return the largest legal scalable vector type that matches VT's element type.
1538 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1539                                             const RISCVSubtarget &Subtarget) {
1540   // This may be called before legal types are setup.
1541   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1542           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1543          "Expected legal fixed length vector!");
1544 
1545   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1546   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1547 
1548   MVT EltVT = VT.getVectorElementType();
1549   switch (EltVT.SimpleTy) {
1550   default:
1551     llvm_unreachable("unexpected element type for RVV container");
1552   case MVT::i1:
1553   case MVT::i8:
1554   case MVT::i16:
1555   case MVT::i32:
1556   case MVT::i64:
1557   case MVT::f16:
1558   case MVT::f32:
1559   case MVT::f64: {
1560     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1561     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1562     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1563     unsigned NumElts =
1564         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1565     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1566     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1567     return MVT::getScalableVectorVT(EltVT, NumElts);
1568   }
1569   }
1570 }
1571 
1572 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1573                                             const RISCVSubtarget &Subtarget) {
1574   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1575                                           Subtarget);
1576 }
1577 
1578 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1579   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1580 }
1581 
1582 // Grow V to consume an entire RVV register.
1583 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1584                                        const RISCVSubtarget &Subtarget) {
1585   assert(VT.isScalableVector() &&
1586          "Expected to convert into a scalable vector!");
1587   assert(V.getValueType().isFixedLengthVector() &&
1588          "Expected a fixed length vector operand!");
1589   SDLoc DL(V);
1590   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1591   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1592 }
1593 
1594 // Shrink V so it's just big enough to maintain a VT's worth of data.
1595 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1596                                          const RISCVSubtarget &Subtarget) {
1597   assert(VT.isFixedLengthVector() &&
1598          "Expected to convert into a fixed length vector!");
1599   assert(V.getValueType().isScalableVector() &&
1600          "Expected a scalable vector operand!");
1601   SDLoc DL(V);
1602   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1603   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1604 }
1605 
1606 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1607 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1608 // the vector type that it is contained in.
1609 static std::pair<SDValue, SDValue>
1610 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1611                 const RISCVSubtarget &Subtarget) {
1612   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1613   MVT XLenVT = Subtarget.getXLenVT();
1614   SDValue VL = VecVT.isFixedLengthVector()
1615                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1616                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1617   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1618   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1619   return {Mask, VL};
1620 }
1621 
1622 // As above but assuming the given type is a scalable vector type.
1623 static std::pair<SDValue, SDValue>
1624 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1625                         const RISCVSubtarget &Subtarget) {
1626   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1627   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1628 }
1629 
1630 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1631 // of either is (currently) supported. This can get us into an infinite loop
1632 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1633 // as a ..., etc.
1634 // Until either (or both) of these can reliably lower any node, reporting that
1635 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1636 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1637 // which is not desirable.
1638 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1639     EVT VT, unsigned DefinedValues) const {
1640   return false;
1641 }
1642 
1643 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1644   // Only splats are currently supported.
1645   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1646     return true;
1647 
1648   return false;
1649 }
1650 
1651 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1652   // RISCV FP-to-int conversions saturate to the destination register size, but
1653   // don't produce 0 for nan. We can use a conversion instruction and fix the
1654   // nan case with a compare and a select.
1655   SDValue Src = Op.getOperand(0);
1656 
1657   EVT DstVT = Op.getValueType();
1658   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1659 
1660   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1661   unsigned Opc;
1662   if (SatVT == DstVT)
1663     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1664   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1665     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1666   else
1667     return SDValue();
1668   // FIXME: Support other SatVTs by clamping before or after the conversion.
1669 
1670   SDLoc DL(Op);
1671   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1672 
1673   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1674   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1675 }
1676 
1677 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1678 // and back. Taking care to avoid converting values that are nan or already
1679 // correct.
1680 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1681 // have FRM dependencies modeled yet.
1682 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1683   MVT VT = Op.getSimpleValueType();
1684   assert(VT.isVector() && "Unexpected type");
1685 
1686   SDLoc DL(Op);
1687 
1688   // Freeze the source since we are increasing the number of uses.
1689   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1690 
1691   // Truncate to integer and convert back to FP.
1692   MVT IntVT = VT.changeVectorElementTypeToInteger();
1693   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1694   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1695 
1696   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1697 
1698   if (Op.getOpcode() == ISD::FCEIL) {
1699     // If the truncated value is the greater than or equal to the original
1700     // value, we've computed the ceil. Otherwise, we went the wrong way and
1701     // need to increase by 1.
1702     // FIXME: This should use a masked operation. Handle here or in isel?
1703     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1704                                  DAG.getConstantFP(1.0, DL, VT));
1705     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1706     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1707   } else if (Op.getOpcode() == ISD::FFLOOR) {
1708     // If the truncated value is the less than or equal to the original value,
1709     // we've computed the floor. Otherwise, we went the wrong way and need to
1710     // decrease by 1.
1711     // FIXME: This should use a masked operation. Handle here or in isel?
1712     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1713                                  DAG.getConstantFP(1.0, DL, VT));
1714     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1715     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1716   }
1717 
1718   // Restore the original sign so that -0.0 is preserved.
1719   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1720 
1721   // Determine the largest integer that can be represented exactly. This and
1722   // values larger than it don't have any fractional bits so don't need to
1723   // be converted.
1724   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1725   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1726   APFloat MaxVal = APFloat(FltSem);
1727   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1728                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1729   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1730 
1731   // If abs(Src) was larger than MaxVal or nan, keep it.
1732   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1733   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1734   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1735 }
1736 
1737 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1738                                  const RISCVSubtarget &Subtarget) {
1739   MVT VT = Op.getSimpleValueType();
1740   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1741 
1742   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1743 
1744   SDLoc DL(Op);
1745   SDValue Mask, VL;
1746   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1747 
1748   unsigned Opc =
1749       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1750   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1751   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1752 }
1753 
1754 struct VIDSequence {
1755   int64_t StepNumerator;
1756   unsigned StepDenominator;
1757   int64_t Addend;
1758 };
1759 
1760 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1761 // to the (non-zero) step S and start value X. This can be then lowered as the
1762 // RVV sequence (VID * S) + X, for example.
1763 // The step S is represented as an integer numerator divided by a positive
1764 // denominator. Note that the implementation currently only identifies
1765 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1766 // cannot detect 2/3, for example.
1767 // Note that this method will also match potentially unappealing index
1768 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1769 // determine whether this is worth generating code for.
1770 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1771   unsigned NumElts = Op.getNumOperands();
1772   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1773   if (!Op.getValueType().isInteger())
1774     return None;
1775 
1776   Optional<unsigned> SeqStepDenom;
1777   Optional<int64_t> SeqStepNum, SeqAddend;
1778   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1779   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1780   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1781     // Assume undef elements match the sequence; we just have to be careful
1782     // when interpolating across them.
1783     if (Op.getOperand(Idx).isUndef())
1784       continue;
1785     // The BUILD_VECTOR must be all constants.
1786     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1787       return None;
1788 
1789     uint64_t Val = Op.getConstantOperandVal(Idx) &
1790                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1791 
1792     if (PrevElt) {
1793       // Calculate the step since the last non-undef element, and ensure
1794       // it's consistent across the entire sequence.
1795       unsigned IdxDiff = Idx - PrevElt->second;
1796       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1797 
1798       // A zero-value value difference means that we're somewhere in the middle
1799       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1800       // step change before evaluating the sequence.
1801       if (ValDiff != 0) {
1802         int64_t Remainder = ValDiff % IdxDiff;
1803         // Normalize the step if it's greater than 1.
1804         if (Remainder != ValDiff) {
1805           // The difference must cleanly divide the element span.
1806           if (Remainder != 0)
1807             return None;
1808           ValDiff /= IdxDiff;
1809           IdxDiff = 1;
1810         }
1811 
1812         if (!SeqStepNum)
1813           SeqStepNum = ValDiff;
1814         else if (ValDiff != SeqStepNum)
1815           return None;
1816 
1817         if (!SeqStepDenom)
1818           SeqStepDenom = IdxDiff;
1819         else if (IdxDiff != *SeqStepDenom)
1820           return None;
1821       }
1822     }
1823 
1824     // Record and/or check any addend.
1825     if (SeqStepNum && SeqStepDenom) {
1826       uint64_t ExpectedVal =
1827           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1828       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1829       if (!SeqAddend)
1830         SeqAddend = Addend;
1831       else if (SeqAddend != Addend)
1832         return None;
1833     }
1834 
1835     // Record this non-undef element for later.
1836     if (!PrevElt || PrevElt->first != Val)
1837       PrevElt = std::make_pair(Val, Idx);
1838   }
1839   // We need to have logged both a step and an addend for this to count as
1840   // a legal index sequence.
1841   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1842     return None;
1843 
1844   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1845 }
1846 
1847 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1848                                  const RISCVSubtarget &Subtarget) {
1849   MVT VT = Op.getSimpleValueType();
1850   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1851 
1852   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1853 
1854   SDLoc DL(Op);
1855   SDValue Mask, VL;
1856   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1857 
1858   MVT XLenVT = Subtarget.getXLenVT();
1859   unsigned NumElts = Op.getNumOperands();
1860 
1861   if (VT.getVectorElementType() == MVT::i1) {
1862     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1863       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1864       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1865     }
1866 
1867     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1868       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1869       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1870     }
1871 
1872     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1873     // scalar integer chunks whose bit-width depends on the number of mask
1874     // bits and XLEN.
1875     // First, determine the most appropriate scalar integer type to use. This
1876     // is at most XLenVT, but may be shrunk to a smaller vector element type
1877     // according to the size of the final vector - use i8 chunks rather than
1878     // XLenVT if we're producing a v8i1. This results in more consistent
1879     // codegen across RV32 and RV64.
1880     unsigned NumViaIntegerBits =
1881         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1882     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1883       // If we have to use more than one INSERT_VECTOR_ELT then this
1884       // optimization is likely to increase code size; avoid peforming it in
1885       // such a case. We can use a load from a constant pool in this case.
1886       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1887         return SDValue();
1888       // Now we can create our integer vector type. Note that it may be larger
1889       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1890       MVT IntegerViaVecVT =
1891           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1892                            divideCeil(NumElts, NumViaIntegerBits));
1893 
1894       uint64_t Bits = 0;
1895       unsigned BitPos = 0, IntegerEltIdx = 0;
1896       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1897 
1898       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1899         // Once we accumulate enough bits to fill our scalar type, insert into
1900         // our vector and clear our accumulated data.
1901         if (I != 0 && I % NumViaIntegerBits == 0) {
1902           if (NumViaIntegerBits <= 32)
1903             Bits = SignExtend64(Bits, 32);
1904           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1905           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1906                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1907           Bits = 0;
1908           BitPos = 0;
1909           IntegerEltIdx++;
1910         }
1911         SDValue V = Op.getOperand(I);
1912         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1913         Bits |= ((uint64_t)BitValue << BitPos);
1914       }
1915 
1916       // Insert the (remaining) scalar value into position in our integer
1917       // vector type.
1918       if (NumViaIntegerBits <= 32)
1919         Bits = SignExtend64(Bits, 32);
1920       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1921       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1922                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1923 
1924       if (NumElts < NumViaIntegerBits) {
1925         // If we're producing a smaller vector than our minimum legal integer
1926         // type, bitcast to the equivalent (known-legal) mask type, and extract
1927         // our final mask.
1928         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1929         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1930         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1931                           DAG.getConstant(0, DL, XLenVT));
1932       } else {
1933         // Else we must have produced an integer type with the same size as the
1934         // mask type; bitcast for the final result.
1935         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1936         Vec = DAG.getBitcast(VT, Vec);
1937       }
1938 
1939       return Vec;
1940     }
1941 
1942     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1943     // vector type, we have a legal equivalently-sized i8 type, so we can use
1944     // that.
1945     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1946     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1947 
1948     SDValue WideVec;
1949     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1950       // For a splat, perform a scalar truncate before creating the wider
1951       // vector.
1952       assert(Splat.getValueType() == XLenVT &&
1953              "Unexpected type for i1 splat value");
1954       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1955                           DAG.getConstant(1, DL, XLenVT));
1956       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1957     } else {
1958       SmallVector<SDValue, 8> Ops(Op->op_values());
1959       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1960       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1961       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1962     }
1963 
1964     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1965   }
1966 
1967   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1968     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1969                                         : RISCVISD::VMV_V_X_VL;
1970     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1971     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1972   }
1973 
1974   // Try and match index sequences, which we can lower to the vid instruction
1975   // with optional modifications. An all-undef vector is matched by
1976   // getSplatValue, above.
1977   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1978     int64_t StepNumerator = SimpleVID->StepNumerator;
1979     unsigned StepDenominator = SimpleVID->StepDenominator;
1980     int64_t Addend = SimpleVID->Addend;
1981 
1982     assert(StepNumerator != 0 && "Invalid step");
1983     bool Negate = false;
1984     int64_t SplatStepVal = StepNumerator;
1985     unsigned StepOpcode = ISD::MUL;
1986     if (StepNumerator != 1) {
1987       if (isPowerOf2_64(std::abs(StepNumerator))) {
1988         Negate = StepNumerator < 0;
1989         StepOpcode = ISD::SHL;
1990         SplatStepVal = Log2_64(std::abs(StepNumerator));
1991       }
1992     }
1993 
1994     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1995     // threshold since it's the immediate value many RVV instructions accept.
1996     // There is no vmul.vi instruction so ensure multiply constant can fit in
1997     // a single addi instruction.
1998     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
1999          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2000         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2001       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2002       // Convert right out of the scalable type so we can use standard ISD
2003       // nodes for the rest of the computation. If we used scalable types with
2004       // these, we'd lose the fixed-length vector info and generate worse
2005       // vsetvli code.
2006       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2007       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2008           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2009         SDValue SplatStep = DAG.getSplatVector(
2010             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2011         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2012       }
2013       if (StepDenominator != 1) {
2014         SDValue SplatStep = DAG.getSplatVector(
2015             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2016         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2017       }
2018       if (Addend != 0 || Negate) {
2019         SDValue SplatAddend =
2020             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2021         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2022       }
2023       return VID;
2024     }
2025   }
2026 
2027   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2028   // when re-interpreted as a vector with a larger element type. For example,
2029   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2030   // could be instead splat as
2031   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2032   // TODO: This optimization could also work on non-constant splats, but it
2033   // would require bit-manipulation instructions to construct the splat value.
2034   SmallVector<SDValue> Sequence;
2035   unsigned EltBitSize = VT.getScalarSizeInBits();
2036   const auto *BV = cast<BuildVectorSDNode>(Op);
2037   if (VT.isInteger() && EltBitSize < 64 &&
2038       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2039       BV->getRepeatedSequence(Sequence) &&
2040       (Sequence.size() * EltBitSize) <= 64) {
2041     unsigned SeqLen = Sequence.size();
2042     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2043     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2044     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2045             ViaIntVT == MVT::i64) &&
2046            "Unexpected sequence type");
2047 
2048     unsigned EltIdx = 0;
2049     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2050     uint64_t SplatValue = 0;
2051     // Construct the amalgamated value which can be splatted as this larger
2052     // vector type.
2053     for (const auto &SeqV : Sequence) {
2054       if (!SeqV.isUndef())
2055         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2056                        << (EltIdx * EltBitSize));
2057       EltIdx++;
2058     }
2059 
2060     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2061     // achieve better constant materializion.
2062     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2063       SplatValue = SignExtend64(SplatValue, 32);
2064 
2065     // Since we can't introduce illegal i64 types at this stage, we can only
2066     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2067     // way we can use RVV instructions to splat.
2068     assert((ViaIntVT.bitsLE(XLenVT) ||
2069             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2070            "Unexpected bitcast sequence");
2071     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2072       SDValue ViaVL =
2073           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2074       MVT ViaContainerVT =
2075           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2076       SDValue Splat =
2077           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2078                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2079       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2080       return DAG.getBitcast(VT, Splat);
2081     }
2082   }
2083 
2084   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2085   // which constitute a large proportion of the elements. In such cases we can
2086   // splat a vector with the dominant element and make up the shortfall with
2087   // INSERT_VECTOR_ELTs.
2088   // Note that this includes vectors of 2 elements by association. The
2089   // upper-most element is the "dominant" one, allowing us to use a splat to
2090   // "insert" the upper element, and an insert of the lower element at position
2091   // 0, which improves codegen.
2092   SDValue DominantValue;
2093   unsigned MostCommonCount = 0;
2094   DenseMap<SDValue, unsigned> ValueCounts;
2095   unsigned NumUndefElts =
2096       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2097 
2098   // Track the number of scalar loads we know we'd be inserting, estimated as
2099   // any non-zero floating-point constant. Other kinds of element are either
2100   // already in registers or are materialized on demand. The threshold at which
2101   // a vector load is more desirable than several scalar materializion and
2102   // vector-insertion instructions is not known.
2103   unsigned NumScalarLoads = 0;
2104 
2105   for (SDValue V : Op->op_values()) {
2106     if (V.isUndef())
2107       continue;
2108 
2109     ValueCounts.insert(std::make_pair(V, 0));
2110     unsigned &Count = ValueCounts[V];
2111 
2112     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2113       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2114 
2115     // Is this value dominant? In case of a tie, prefer the highest element as
2116     // it's cheaper to insert near the beginning of a vector than it is at the
2117     // end.
2118     if (++Count >= MostCommonCount) {
2119       DominantValue = V;
2120       MostCommonCount = Count;
2121     }
2122   }
2123 
2124   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2125   unsigned NumDefElts = NumElts - NumUndefElts;
2126   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2127 
2128   // Don't perform this optimization when optimizing for size, since
2129   // materializing elements and inserting them tends to cause code bloat.
2130   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2131       ((MostCommonCount > DominantValueCountThreshold) ||
2132        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2133     // Start by splatting the most common element.
2134     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2135 
2136     DenseSet<SDValue> Processed{DominantValue};
2137     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2138     for (const auto &OpIdx : enumerate(Op->ops())) {
2139       const SDValue &V = OpIdx.value();
2140       if (V.isUndef() || !Processed.insert(V).second)
2141         continue;
2142       if (ValueCounts[V] == 1) {
2143         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2144                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2145       } else {
2146         // Blend in all instances of this value using a VSELECT, using a
2147         // mask where each bit signals whether that element is the one
2148         // we're after.
2149         SmallVector<SDValue> Ops;
2150         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2151           return DAG.getConstant(V == V1, DL, XLenVT);
2152         });
2153         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2154                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2155                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2156       }
2157     }
2158 
2159     return Vec;
2160   }
2161 
2162   return SDValue();
2163 }
2164 
2165 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2166                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2167   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2168     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2169     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2170     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2171     // node in order to try and match RVV vector/scalar instructions.
2172     if ((LoC >> 31) == HiC)
2173       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2174   }
2175 
2176   // Fall back to a stack store and stride x0 vector load.
2177   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2178 }
2179 
2180 // Called by type legalization to handle splat of i64 on RV32.
2181 // FIXME: We can optimize this when the type has sign or zero bits in one
2182 // of the halves.
2183 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2184                                    SDValue VL, SelectionDAG &DAG) {
2185   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2186   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2187                            DAG.getConstant(0, DL, MVT::i32));
2188   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2189                            DAG.getConstant(1, DL, MVT::i32));
2190   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2191 }
2192 
2193 // This function lowers a splat of a scalar operand Splat with the vector
2194 // length VL. It ensures the final sequence is type legal, which is useful when
2195 // lowering a splat after type legalization.
2196 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2197                                 SelectionDAG &DAG,
2198                                 const RISCVSubtarget &Subtarget) {
2199   if (VT.isFloatingPoint())
2200     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2201 
2202   MVT XLenVT = Subtarget.getXLenVT();
2203 
2204   // Simplest case is that the operand needs to be promoted to XLenVT.
2205   if (Scalar.getValueType().bitsLE(XLenVT)) {
2206     // If the operand is a constant, sign extend to increase our chances
2207     // of being able to use a .vi instruction. ANY_EXTEND would become a
2208     // a zero extend and the simm5 check in isel would fail.
2209     // FIXME: Should we ignore the upper bits in isel instead?
2210     unsigned ExtOpc =
2211         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2212     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2213     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2214   }
2215 
2216   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2217          "Unexpected scalar for splat lowering!");
2218 
2219   // Otherwise use the more complicated splatting algorithm.
2220   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2221 }
2222 
2223 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2224                                    const RISCVSubtarget &Subtarget) {
2225   SDValue V1 = Op.getOperand(0);
2226   SDValue V2 = Op.getOperand(1);
2227   SDLoc DL(Op);
2228   MVT XLenVT = Subtarget.getXLenVT();
2229   MVT VT = Op.getSimpleValueType();
2230   unsigned NumElts = VT.getVectorNumElements();
2231   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2232 
2233   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2234 
2235   SDValue TrueMask, VL;
2236   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2237 
2238   if (SVN->isSplat()) {
2239     const int Lane = SVN->getSplatIndex();
2240     if (Lane >= 0) {
2241       MVT SVT = VT.getVectorElementType();
2242 
2243       // Turn splatted vector load into a strided load with an X0 stride.
2244       SDValue V = V1;
2245       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2246       // with undef.
2247       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2248       int Offset = Lane;
2249       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2250         int OpElements =
2251             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2252         V = V.getOperand(Offset / OpElements);
2253         Offset %= OpElements;
2254       }
2255 
2256       // We need to ensure the load isn't atomic or volatile.
2257       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2258         auto *Ld = cast<LoadSDNode>(V);
2259         Offset *= SVT.getStoreSize();
2260         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2261                                                    TypeSize::Fixed(Offset), DL);
2262 
2263         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2264         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2265           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2266           SDValue IntID =
2267               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2268           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2269                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2270           SDValue NewLoad = DAG.getMemIntrinsicNode(
2271               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2272               DAG.getMachineFunction().getMachineMemOperand(
2273                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2274           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2275           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2276         }
2277 
2278         // Otherwise use a scalar load and splat. This will give the best
2279         // opportunity to fold a splat into the operation. ISel can turn it into
2280         // the x0 strided load if we aren't able to fold away the select.
2281         if (SVT.isFloatingPoint())
2282           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2283                           Ld->getPointerInfo().getWithOffset(Offset),
2284                           Ld->getOriginalAlign(),
2285                           Ld->getMemOperand()->getFlags());
2286         else
2287           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2288                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2289                              Ld->getOriginalAlign(),
2290                              Ld->getMemOperand()->getFlags());
2291         DAG.makeEquivalentMemoryOrdering(Ld, V);
2292 
2293         unsigned Opc =
2294             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2295         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2296         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2297       }
2298 
2299       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2300       assert(Lane < (int)NumElts && "Unexpected lane!");
2301       SDValue Gather =
2302           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2303                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2304       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2305     }
2306   }
2307 
2308   // Detect shuffles which can be re-expressed as vector selects; these are
2309   // shuffles in which each element in the destination is taken from an element
2310   // at the corresponding index in either source vectors.
2311   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2312     int MaskIndex = MaskIdx.value();
2313     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2314   });
2315 
2316   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2317 
2318   SmallVector<SDValue> MaskVals;
2319   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2320   // merged with a second vrgather.
2321   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2322 
2323   // By default we preserve the original operand order, and use a mask to
2324   // select LHS as true and RHS as false. However, since RVV vector selects may
2325   // feature splats but only on the LHS, we may choose to invert our mask and
2326   // instead select between RHS and LHS.
2327   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2328   bool InvertMask = IsSelect == SwapOps;
2329 
2330   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2331   // half.
2332   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2333 
2334   // Now construct the mask that will be used by the vselect or blended
2335   // vrgather operation. For vrgathers, construct the appropriate indices into
2336   // each vector.
2337   for (int MaskIndex : SVN->getMask()) {
2338     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2339     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2340     if (!IsSelect) {
2341       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2342       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2343                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2344                                      : DAG.getUNDEF(XLenVT));
2345       GatherIndicesRHS.push_back(
2346           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2347                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2348       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2349         ++LHSIndexCounts[MaskIndex];
2350       if (!IsLHSOrUndefIndex)
2351         ++RHSIndexCounts[MaskIndex - NumElts];
2352     }
2353   }
2354 
2355   if (SwapOps) {
2356     std::swap(V1, V2);
2357     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2358   }
2359 
2360   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2361   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2362   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2363 
2364   if (IsSelect)
2365     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2366 
2367   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2368     // On such a large vector we're unable to use i8 as the index type.
2369     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2370     // may involve vector splitting if we're already at LMUL=8, or our
2371     // user-supplied maximum fixed-length LMUL.
2372     return SDValue();
2373   }
2374 
2375   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2376   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2377   MVT IndexVT = VT.changeTypeToInteger();
2378   // Since we can't introduce illegal index types at this stage, use i16 and
2379   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2380   // than XLenVT.
2381   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2382     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2383     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2384   }
2385 
2386   MVT IndexContainerVT =
2387       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2388 
2389   SDValue Gather;
2390   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2391   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2392   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2393     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2394   } else {
2395     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2396     // If only one index is used, we can use a "splat" vrgather.
2397     // TODO: We can splat the most-common index and fix-up any stragglers, if
2398     // that's beneficial.
2399     if (LHSIndexCounts.size() == 1) {
2400       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2401       Gather =
2402           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2403                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2404     } else {
2405       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2406       LHSIndices =
2407           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2408 
2409       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2410                            TrueMask, VL);
2411     }
2412   }
2413 
2414   // If a second vector operand is used by this shuffle, blend it in with an
2415   // additional vrgather.
2416   if (!V2.isUndef()) {
2417     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2418     // If only one index is used, we can use a "splat" vrgather.
2419     // TODO: We can splat the most-common index and fix-up any stragglers, if
2420     // that's beneficial.
2421     if (RHSIndexCounts.size() == 1) {
2422       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2423       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2424                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2425     } else {
2426       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2427       RHSIndices =
2428           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2429       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2430                        VL);
2431     }
2432 
2433     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2434     SelectMask =
2435         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2436 
2437     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2438                          Gather, VL);
2439   }
2440 
2441   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2442 }
2443 
2444 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2445                                      SDLoc DL, SelectionDAG &DAG,
2446                                      const RISCVSubtarget &Subtarget) {
2447   if (VT.isScalableVector())
2448     return DAG.getFPExtendOrRound(Op, DL, VT);
2449   assert(VT.isFixedLengthVector() &&
2450          "Unexpected value type for RVV FP extend/round lowering");
2451   SDValue Mask, VL;
2452   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2453   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2454                         ? RISCVISD::FP_EXTEND_VL
2455                         : RISCVISD::FP_ROUND_VL;
2456   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2457 }
2458 
2459 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2460 // the exponent.
2461 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2462   MVT VT = Op.getSimpleValueType();
2463   unsigned EltSize = VT.getScalarSizeInBits();
2464   SDValue Src = Op.getOperand(0);
2465   SDLoc DL(Op);
2466 
2467   // We need a FP type that can represent the value.
2468   // TODO: Use f16 for i8 when possible?
2469   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2470   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2471 
2472   // Legal types should have been checked in the RISCVTargetLowering
2473   // constructor.
2474   // TODO: Splitting may make sense in some cases.
2475   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2476          "Expected legal float type!");
2477 
2478   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2479   // The trailing zero count is equal to log2 of this single bit value.
2480   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2481     SDValue Neg =
2482         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2483     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2484   }
2485 
2486   // We have a legal FP type, convert to it.
2487   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2488   // Bitcast to integer and shift the exponent to the LSB.
2489   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2490   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2491   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2492   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2493                               DAG.getConstant(ShiftAmt, DL, IntVT));
2494   // Truncate back to original type to allow vnsrl.
2495   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2496   // The exponent contains log2 of the value in biased form.
2497   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2498 
2499   // For trailing zeros, we just need to subtract the bias.
2500   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2501     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2502                        DAG.getConstant(ExponentBias, DL, VT));
2503 
2504   // For leading zeros, we need to remove the bias and convert from log2 to
2505   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2506   unsigned Adjust = ExponentBias + (EltSize - 1);
2507   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2508 }
2509 
2510 // While RVV has alignment restrictions, we should always be able to load as a
2511 // legal equivalently-sized byte-typed vector instead. This method is
2512 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2513 // the load is already correctly-aligned, it returns SDValue().
2514 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2515                                                     SelectionDAG &DAG) const {
2516   auto *Load = cast<LoadSDNode>(Op);
2517   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2518 
2519   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2520                                      Load->getMemoryVT(),
2521                                      *Load->getMemOperand()))
2522     return SDValue();
2523 
2524   SDLoc DL(Op);
2525   MVT VT = Op.getSimpleValueType();
2526   unsigned EltSizeBits = VT.getScalarSizeInBits();
2527   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2528          "Unexpected unaligned RVV load type");
2529   MVT NewVT =
2530       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2531   assert(NewVT.isValid() &&
2532          "Expecting equally-sized RVV vector types to be legal");
2533   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2534                           Load->getPointerInfo(), Load->getOriginalAlign(),
2535                           Load->getMemOperand()->getFlags());
2536   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2537 }
2538 
2539 // While RVV has alignment restrictions, we should always be able to store as a
2540 // legal equivalently-sized byte-typed vector instead. This method is
2541 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2542 // returns SDValue() if the store is already correctly aligned.
2543 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2544                                                      SelectionDAG &DAG) const {
2545   auto *Store = cast<StoreSDNode>(Op);
2546   assert(Store && Store->getValue().getValueType().isVector() &&
2547          "Expected vector store");
2548 
2549   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2550                                      Store->getMemoryVT(),
2551                                      *Store->getMemOperand()))
2552     return SDValue();
2553 
2554   SDLoc DL(Op);
2555   SDValue StoredVal = Store->getValue();
2556   MVT VT = StoredVal.getSimpleValueType();
2557   unsigned EltSizeBits = VT.getScalarSizeInBits();
2558   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2559          "Unexpected unaligned RVV store type");
2560   MVT NewVT =
2561       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2562   assert(NewVT.isValid() &&
2563          "Expecting equally-sized RVV vector types to be legal");
2564   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2565   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2566                       Store->getPointerInfo(), Store->getOriginalAlign(),
2567                       Store->getMemOperand()->getFlags());
2568 }
2569 
2570 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2571                                             SelectionDAG &DAG) const {
2572   switch (Op.getOpcode()) {
2573   default:
2574     report_fatal_error("unimplemented operand");
2575   case ISD::GlobalAddress:
2576     return lowerGlobalAddress(Op, DAG);
2577   case ISD::BlockAddress:
2578     return lowerBlockAddress(Op, DAG);
2579   case ISD::ConstantPool:
2580     return lowerConstantPool(Op, DAG);
2581   case ISD::JumpTable:
2582     return lowerJumpTable(Op, DAG);
2583   case ISD::GlobalTLSAddress:
2584     return lowerGlobalTLSAddress(Op, DAG);
2585   case ISD::SELECT:
2586     return lowerSELECT(Op, DAG);
2587   case ISD::BRCOND:
2588     return lowerBRCOND(Op, DAG);
2589   case ISD::VASTART:
2590     return lowerVASTART(Op, DAG);
2591   case ISD::FRAMEADDR:
2592     return lowerFRAMEADDR(Op, DAG);
2593   case ISD::RETURNADDR:
2594     return lowerRETURNADDR(Op, DAG);
2595   case ISD::SHL_PARTS:
2596     return lowerShiftLeftParts(Op, DAG);
2597   case ISD::SRA_PARTS:
2598     return lowerShiftRightParts(Op, DAG, true);
2599   case ISD::SRL_PARTS:
2600     return lowerShiftRightParts(Op, DAG, false);
2601   case ISD::BITCAST: {
2602     SDLoc DL(Op);
2603     EVT VT = Op.getValueType();
2604     SDValue Op0 = Op.getOperand(0);
2605     EVT Op0VT = Op0.getValueType();
2606     MVT XLenVT = Subtarget.getXLenVT();
2607     if (VT.isFixedLengthVector()) {
2608       // We can handle fixed length vector bitcasts with a simple replacement
2609       // in isel.
2610       if (Op0VT.isFixedLengthVector())
2611         return Op;
2612       // When bitcasting from scalar to fixed-length vector, insert the scalar
2613       // into a one-element vector of the result type, and perform a vector
2614       // bitcast.
2615       if (!Op0VT.isVector()) {
2616         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2617         if (!isTypeLegal(BVT))
2618           return SDValue();
2619         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2620                                               DAG.getUNDEF(BVT), Op0,
2621                                               DAG.getConstant(0, DL, XLenVT)));
2622       }
2623       return SDValue();
2624     }
2625     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2626     // thus: bitcast the vector to a one-element vector type whose element type
2627     // is the same as the result type, and extract the first element.
2628     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2629       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2630       if (!isTypeLegal(BVT))
2631         return SDValue();
2632       SDValue BVec = DAG.getBitcast(BVT, Op0);
2633       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2634                          DAG.getConstant(0, DL, XLenVT));
2635     }
2636     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2637       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2638       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2639       return FPConv;
2640     }
2641     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2642         Subtarget.hasStdExtF()) {
2643       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2644       SDValue FPConv =
2645           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2646       return FPConv;
2647     }
2648     return SDValue();
2649   }
2650   case ISD::INTRINSIC_WO_CHAIN:
2651     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2652   case ISD::INTRINSIC_W_CHAIN:
2653     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2654   case ISD::INTRINSIC_VOID:
2655     return LowerINTRINSIC_VOID(Op, DAG);
2656   case ISD::BSWAP:
2657   case ISD::BITREVERSE: {
2658     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2659     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2660     MVT VT = Op.getSimpleValueType();
2661     SDLoc DL(Op);
2662     // Start with the maximum immediate value which is the bitwidth - 1.
2663     unsigned Imm = VT.getSizeInBits() - 1;
2664     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2665     if (Op.getOpcode() == ISD::BSWAP)
2666       Imm &= ~0x7U;
2667     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2668                        DAG.getConstant(Imm, DL, VT));
2669   }
2670   case ISD::FSHL:
2671   case ISD::FSHR: {
2672     MVT VT = Op.getSimpleValueType();
2673     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2674     SDLoc DL(Op);
2675     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2676       return Op;
2677     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2678     // use log(XLen) bits. Mask the shift amount accordingly.
2679     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2680     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2681                                 DAG.getConstant(ShAmtWidth, DL, VT));
2682     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2683     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2684   }
2685   case ISD::TRUNCATE: {
2686     SDLoc DL(Op);
2687     MVT VT = Op.getSimpleValueType();
2688     // Only custom-lower vector truncates
2689     if (!VT.isVector())
2690       return Op;
2691 
2692     // Truncates to mask types are handled differently
2693     if (VT.getVectorElementType() == MVT::i1)
2694       return lowerVectorMaskTrunc(Op, DAG);
2695 
2696     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2697     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2698     // truncate by one power of two at a time.
2699     MVT DstEltVT = VT.getVectorElementType();
2700 
2701     SDValue Src = Op.getOperand(0);
2702     MVT SrcVT = Src.getSimpleValueType();
2703     MVT SrcEltVT = SrcVT.getVectorElementType();
2704 
2705     assert(DstEltVT.bitsLT(SrcEltVT) &&
2706            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2707            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2708            "Unexpected vector truncate lowering");
2709 
2710     MVT ContainerVT = SrcVT;
2711     if (SrcVT.isFixedLengthVector()) {
2712       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2713       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2714     }
2715 
2716     SDValue Result = Src;
2717     SDValue Mask, VL;
2718     std::tie(Mask, VL) =
2719         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2720     LLVMContext &Context = *DAG.getContext();
2721     const ElementCount Count = ContainerVT.getVectorElementCount();
2722     do {
2723       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2724       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2725       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2726                            Mask, VL);
2727     } while (SrcEltVT != DstEltVT);
2728 
2729     if (SrcVT.isFixedLengthVector())
2730       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2731 
2732     return Result;
2733   }
2734   case ISD::ANY_EXTEND:
2735   case ISD::ZERO_EXTEND:
2736     if (Op.getOperand(0).getValueType().isVector() &&
2737         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2738       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2739     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2740   case ISD::SIGN_EXTEND:
2741     if (Op.getOperand(0).getValueType().isVector() &&
2742         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2743       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2744     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2745   case ISD::SPLAT_VECTOR_PARTS:
2746     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2747   case ISD::INSERT_VECTOR_ELT:
2748     return lowerINSERT_VECTOR_ELT(Op, DAG);
2749   case ISD::EXTRACT_VECTOR_ELT:
2750     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2751   case ISD::VSCALE: {
2752     MVT VT = Op.getSimpleValueType();
2753     SDLoc DL(Op);
2754     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2755     // We define our scalable vector types for lmul=1 to use a 64 bit known
2756     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2757     // vscale as VLENB / 8.
2758     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2759     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2760       // We assume VLENB is a multiple of 8. We manually choose the best shift
2761       // here because SimplifyDemandedBits isn't always able to simplify it.
2762       uint64_t Val = Op.getConstantOperandVal(0);
2763       if (isPowerOf2_64(Val)) {
2764         uint64_t Log2 = Log2_64(Val);
2765         if (Log2 < 3)
2766           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2767                              DAG.getConstant(3 - Log2, DL, VT));
2768         if (Log2 > 3)
2769           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2770                              DAG.getConstant(Log2 - 3, DL, VT));
2771         return VLENB;
2772       }
2773       // If the multiplier is a multiple of 8, scale it down to avoid needing
2774       // to shift the VLENB value.
2775       if ((Val % 8) == 0)
2776         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2777                            DAG.getConstant(Val / 8, DL, VT));
2778     }
2779 
2780     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2781                                  DAG.getConstant(3, DL, VT));
2782     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2783   }
2784   case ISD::FPOWI: {
2785     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2786     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2787     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2788         Op.getOperand(1).getValueType() == MVT::i32) {
2789       SDLoc DL(Op);
2790       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2791       SDValue Powi =
2792           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2793       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2794                          DAG.getIntPtrConstant(0, DL));
2795     }
2796     return SDValue();
2797   }
2798   case ISD::FP_EXTEND: {
2799     // RVV can only do fp_extend to types double the size as the source. We
2800     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2801     // via f32.
2802     SDLoc DL(Op);
2803     MVT VT = Op.getSimpleValueType();
2804     SDValue Src = Op.getOperand(0);
2805     MVT SrcVT = Src.getSimpleValueType();
2806 
2807     // Prepare any fixed-length vector operands.
2808     MVT ContainerVT = VT;
2809     if (SrcVT.isFixedLengthVector()) {
2810       ContainerVT = getContainerForFixedLengthVector(VT);
2811       MVT SrcContainerVT =
2812           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2813       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2814     }
2815 
2816     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2817         SrcVT.getVectorElementType() != MVT::f16) {
2818       // For scalable vectors, we only need to close the gap between
2819       // vXf16->vXf64.
2820       if (!VT.isFixedLengthVector())
2821         return Op;
2822       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2823       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2824       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2825     }
2826 
2827     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2828     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2829     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2830         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2831 
2832     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2833                                            DL, DAG, Subtarget);
2834     if (VT.isFixedLengthVector())
2835       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2836     return Extend;
2837   }
2838   case ISD::FP_ROUND: {
2839     // RVV can only do fp_round to types half the size as the source. We
2840     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2841     // conversion instruction.
2842     SDLoc DL(Op);
2843     MVT VT = Op.getSimpleValueType();
2844     SDValue Src = Op.getOperand(0);
2845     MVT SrcVT = Src.getSimpleValueType();
2846 
2847     // Prepare any fixed-length vector operands.
2848     MVT ContainerVT = VT;
2849     if (VT.isFixedLengthVector()) {
2850       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2851       ContainerVT =
2852           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2853       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2854     }
2855 
2856     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2857         SrcVT.getVectorElementType() != MVT::f64) {
2858       // For scalable vectors, we only need to close the gap between
2859       // vXf64<->vXf16.
2860       if (!VT.isFixedLengthVector())
2861         return Op;
2862       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2863       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2864       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2865     }
2866 
2867     SDValue Mask, VL;
2868     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2869 
2870     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2871     SDValue IntermediateRound =
2872         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2873     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2874                                           DL, DAG, Subtarget);
2875 
2876     if (VT.isFixedLengthVector())
2877       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2878     return Round;
2879   }
2880   case ISD::FP_TO_SINT:
2881   case ISD::FP_TO_UINT:
2882   case ISD::SINT_TO_FP:
2883   case ISD::UINT_TO_FP: {
2884     // RVV can only do fp<->int conversions to types half/double the size as
2885     // the source. We custom-lower any conversions that do two hops into
2886     // sequences.
2887     MVT VT = Op.getSimpleValueType();
2888     if (!VT.isVector())
2889       return Op;
2890     SDLoc DL(Op);
2891     SDValue Src = Op.getOperand(0);
2892     MVT EltVT = VT.getVectorElementType();
2893     MVT SrcVT = Src.getSimpleValueType();
2894     MVT SrcEltVT = SrcVT.getVectorElementType();
2895     unsigned EltSize = EltVT.getSizeInBits();
2896     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2897     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2898            "Unexpected vector element types");
2899 
2900     bool IsInt2FP = SrcEltVT.isInteger();
2901     // Widening conversions
2902     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2903       if (IsInt2FP) {
2904         // Do a regular integer sign/zero extension then convert to float.
2905         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2906                                       VT.getVectorElementCount());
2907         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2908                                  ? ISD::ZERO_EXTEND
2909                                  : ISD::SIGN_EXTEND;
2910         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2911         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2912       }
2913       // FP2Int
2914       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2915       // Do one doubling fp_extend then complete the operation by converting
2916       // to int.
2917       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2918       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2919       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2920     }
2921 
2922     // Narrowing conversions
2923     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2924       if (IsInt2FP) {
2925         // One narrowing int_to_fp, then an fp_round.
2926         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2927         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2928         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2929         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2930       }
2931       // FP2Int
2932       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2933       // representable by the integer, the result is poison.
2934       MVT IVecVT =
2935           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2936                            VT.getVectorElementCount());
2937       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2938       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2939     }
2940 
2941     // Scalable vectors can exit here. Patterns will handle equally-sized
2942     // conversions halving/doubling ones.
2943     if (!VT.isFixedLengthVector())
2944       return Op;
2945 
2946     // For fixed-length vectors we lower to a custom "VL" node.
2947     unsigned RVVOpc = 0;
2948     switch (Op.getOpcode()) {
2949     default:
2950       llvm_unreachable("Impossible opcode");
2951     case ISD::FP_TO_SINT:
2952       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2953       break;
2954     case ISD::FP_TO_UINT:
2955       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2956       break;
2957     case ISD::SINT_TO_FP:
2958       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2959       break;
2960     case ISD::UINT_TO_FP:
2961       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2962       break;
2963     }
2964 
2965     MVT ContainerVT, SrcContainerVT;
2966     // Derive the reference container type from the larger vector type.
2967     if (SrcEltSize > EltSize) {
2968       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2969       ContainerVT =
2970           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2971     } else {
2972       ContainerVT = getContainerForFixedLengthVector(VT);
2973       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2974     }
2975 
2976     SDValue Mask, VL;
2977     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2978 
2979     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2980     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2981     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2982   }
2983   case ISD::FP_TO_SINT_SAT:
2984   case ISD::FP_TO_UINT_SAT:
2985     return lowerFP_TO_INT_SAT(Op, DAG);
2986   case ISD::FTRUNC:
2987   case ISD::FCEIL:
2988   case ISD::FFLOOR:
2989     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
2990   case ISD::VECREDUCE_ADD:
2991   case ISD::VECREDUCE_UMAX:
2992   case ISD::VECREDUCE_SMAX:
2993   case ISD::VECREDUCE_UMIN:
2994   case ISD::VECREDUCE_SMIN:
2995     return lowerVECREDUCE(Op, DAG);
2996   case ISD::VECREDUCE_AND:
2997   case ISD::VECREDUCE_OR:
2998   case ISD::VECREDUCE_XOR:
2999     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3000       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3001     return lowerVECREDUCE(Op, DAG);
3002   case ISD::VECREDUCE_FADD:
3003   case ISD::VECREDUCE_SEQ_FADD:
3004   case ISD::VECREDUCE_FMIN:
3005   case ISD::VECREDUCE_FMAX:
3006     return lowerFPVECREDUCE(Op, DAG);
3007   case ISD::VP_REDUCE_ADD:
3008   case ISD::VP_REDUCE_UMAX:
3009   case ISD::VP_REDUCE_SMAX:
3010   case ISD::VP_REDUCE_UMIN:
3011   case ISD::VP_REDUCE_SMIN:
3012   case ISD::VP_REDUCE_FADD:
3013   case ISD::VP_REDUCE_SEQ_FADD:
3014   case ISD::VP_REDUCE_FMIN:
3015   case ISD::VP_REDUCE_FMAX:
3016     return lowerVPREDUCE(Op, DAG);
3017   case ISD::VP_REDUCE_AND:
3018   case ISD::VP_REDUCE_OR:
3019   case ISD::VP_REDUCE_XOR:
3020     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3021       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3022     return lowerVPREDUCE(Op, DAG);
3023   case ISD::INSERT_SUBVECTOR:
3024     return lowerINSERT_SUBVECTOR(Op, DAG);
3025   case ISD::EXTRACT_SUBVECTOR:
3026     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3027   case ISD::STEP_VECTOR:
3028     return lowerSTEP_VECTOR(Op, DAG);
3029   case ISD::VECTOR_REVERSE:
3030     return lowerVECTOR_REVERSE(Op, DAG);
3031   case ISD::BUILD_VECTOR:
3032     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3033   case ISD::SPLAT_VECTOR:
3034     if (Op.getValueType().getVectorElementType() == MVT::i1)
3035       return lowerVectorMaskSplat(Op, DAG);
3036     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3037   case ISD::VECTOR_SHUFFLE:
3038     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3039   case ISD::CONCAT_VECTORS: {
3040     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3041     // better than going through the stack, as the default expansion does.
3042     SDLoc DL(Op);
3043     MVT VT = Op.getSimpleValueType();
3044     unsigned NumOpElts =
3045         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3046     SDValue Vec = DAG.getUNDEF(VT);
3047     for (const auto &OpIdx : enumerate(Op->ops()))
3048       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3049                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3050     return Vec;
3051   }
3052   case ISD::LOAD:
3053     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3054       return V;
3055     if (Op.getValueType().isFixedLengthVector())
3056       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3057     return Op;
3058   case ISD::STORE:
3059     if (auto V = expandUnalignedRVVStore(Op, DAG))
3060       return V;
3061     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3062       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3063     return Op;
3064   case ISD::MLOAD:
3065   case ISD::VP_LOAD:
3066     return lowerMaskedLoad(Op, DAG);
3067   case ISD::MSTORE:
3068   case ISD::VP_STORE:
3069     return lowerMaskedStore(Op, DAG);
3070   case ISD::SETCC:
3071     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3072   case ISD::ADD:
3073     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3074   case ISD::SUB:
3075     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3076   case ISD::MUL:
3077     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3078   case ISD::MULHS:
3079     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3080   case ISD::MULHU:
3081     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3082   case ISD::AND:
3083     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3084                                               RISCVISD::AND_VL);
3085   case ISD::OR:
3086     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3087                                               RISCVISD::OR_VL);
3088   case ISD::XOR:
3089     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3090                                               RISCVISD::XOR_VL);
3091   case ISD::SDIV:
3092     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3093   case ISD::SREM:
3094     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3095   case ISD::UDIV:
3096     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3097   case ISD::UREM:
3098     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3099   case ISD::SHL:
3100   case ISD::SRA:
3101   case ISD::SRL:
3102     if (Op.getSimpleValueType().isFixedLengthVector())
3103       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3104     // This can be called for an i32 shift amount that needs to be promoted.
3105     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3106            "Unexpected custom legalisation");
3107     return SDValue();
3108   case ISD::SADDSAT:
3109     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3110   case ISD::UADDSAT:
3111     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3112   case ISD::SSUBSAT:
3113     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3114   case ISD::USUBSAT:
3115     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3116   case ISD::FADD:
3117     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3118   case ISD::FSUB:
3119     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3120   case ISD::FMUL:
3121     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3122   case ISD::FDIV:
3123     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3124   case ISD::FNEG:
3125     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3126   case ISD::FABS:
3127     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3128   case ISD::FSQRT:
3129     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3130   case ISD::FMA:
3131     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3132   case ISD::SMIN:
3133     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3134   case ISD::SMAX:
3135     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3136   case ISD::UMIN:
3137     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3138   case ISD::UMAX:
3139     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3140   case ISD::FMINNUM:
3141     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3142   case ISD::FMAXNUM:
3143     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3144   case ISD::ABS:
3145     return lowerABS(Op, DAG);
3146   case ISD::CTLZ_ZERO_UNDEF:
3147   case ISD::CTTZ_ZERO_UNDEF:
3148     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3149   case ISD::VSELECT:
3150     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3151   case ISD::FCOPYSIGN:
3152     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3153   case ISD::MGATHER:
3154   case ISD::VP_GATHER:
3155     return lowerMaskedGather(Op, DAG);
3156   case ISD::MSCATTER:
3157   case ISD::VP_SCATTER:
3158     return lowerMaskedScatter(Op, DAG);
3159   case ISD::FLT_ROUNDS_:
3160     return lowerGET_ROUNDING(Op, DAG);
3161   case ISD::SET_ROUNDING:
3162     return lowerSET_ROUNDING(Op, DAG);
3163   case ISD::VP_SELECT:
3164     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3165   case ISD::VP_ADD:
3166     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3167   case ISD::VP_SUB:
3168     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3169   case ISD::VP_MUL:
3170     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3171   case ISD::VP_SDIV:
3172     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3173   case ISD::VP_UDIV:
3174     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3175   case ISD::VP_SREM:
3176     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3177   case ISD::VP_UREM:
3178     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3179   case ISD::VP_AND:
3180     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
3181   case ISD::VP_OR:
3182     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
3183   case ISD::VP_XOR:
3184     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
3185   case ISD::VP_ASHR:
3186     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3187   case ISD::VP_LSHR:
3188     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3189   case ISD::VP_SHL:
3190     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3191   case ISD::VP_FADD:
3192     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3193   case ISD::VP_FSUB:
3194     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3195   case ISD::VP_FMUL:
3196     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3197   case ISD::VP_FDIV:
3198     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3199   }
3200 }
3201 
3202 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3203                              SelectionDAG &DAG, unsigned Flags) {
3204   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3205 }
3206 
3207 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3208                              SelectionDAG &DAG, unsigned Flags) {
3209   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3210                                    Flags);
3211 }
3212 
3213 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3214                              SelectionDAG &DAG, unsigned Flags) {
3215   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3216                                    N->getOffset(), Flags);
3217 }
3218 
3219 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3220                              SelectionDAG &DAG, unsigned Flags) {
3221   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3222 }
3223 
3224 template <class NodeTy>
3225 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3226                                      bool IsLocal) const {
3227   SDLoc DL(N);
3228   EVT Ty = getPointerTy(DAG.getDataLayout());
3229 
3230   if (isPositionIndependent()) {
3231     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3232     if (IsLocal)
3233       // Use PC-relative addressing to access the symbol. This generates the
3234       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3235       // %pcrel_lo(auipc)).
3236       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3237 
3238     // Use PC-relative addressing to access the GOT for this symbol, then load
3239     // the address from the GOT. This generates the pattern (PseudoLA sym),
3240     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3241     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3242   }
3243 
3244   switch (getTargetMachine().getCodeModel()) {
3245   default:
3246     report_fatal_error("Unsupported code model for lowering");
3247   case CodeModel::Small: {
3248     // Generate a sequence for accessing addresses within the first 2 GiB of
3249     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3250     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3251     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3252     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3253     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3254   }
3255   case CodeModel::Medium: {
3256     // Generate a sequence for accessing addresses within any 2GiB range within
3257     // the address space. This generates the pattern (PseudoLLA sym), which
3258     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3259     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3260     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3261   }
3262   }
3263 }
3264 
3265 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3266                                                 SelectionDAG &DAG) const {
3267   SDLoc DL(Op);
3268   EVT Ty = Op.getValueType();
3269   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3270   int64_t Offset = N->getOffset();
3271   MVT XLenVT = Subtarget.getXLenVT();
3272 
3273   const GlobalValue *GV = N->getGlobal();
3274   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3275   SDValue Addr = getAddr(N, DAG, IsLocal);
3276 
3277   // In order to maximise the opportunity for common subexpression elimination,
3278   // emit a separate ADD node for the global address offset instead of folding
3279   // it in the global address node. Later peephole optimisations may choose to
3280   // fold it back in when profitable.
3281   if (Offset != 0)
3282     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3283                        DAG.getConstant(Offset, DL, XLenVT));
3284   return Addr;
3285 }
3286 
3287 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3288                                                SelectionDAG &DAG) const {
3289   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3290 
3291   return getAddr(N, DAG);
3292 }
3293 
3294 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3295                                                SelectionDAG &DAG) const {
3296   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3297 
3298   return getAddr(N, DAG);
3299 }
3300 
3301 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3302                                             SelectionDAG &DAG) const {
3303   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3304 
3305   return getAddr(N, DAG);
3306 }
3307 
3308 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3309                                               SelectionDAG &DAG,
3310                                               bool UseGOT) const {
3311   SDLoc DL(N);
3312   EVT Ty = getPointerTy(DAG.getDataLayout());
3313   const GlobalValue *GV = N->getGlobal();
3314   MVT XLenVT = Subtarget.getXLenVT();
3315 
3316   if (UseGOT) {
3317     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3318     // load the address from the GOT and add the thread pointer. This generates
3319     // the pattern (PseudoLA_TLS_IE sym), which expands to
3320     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3321     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3322     SDValue Load =
3323         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3324 
3325     // Add the thread pointer.
3326     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3327     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3328   }
3329 
3330   // Generate a sequence for accessing the address relative to the thread
3331   // pointer, with the appropriate adjustment for the thread pointer offset.
3332   // This generates the pattern
3333   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3334   SDValue AddrHi =
3335       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3336   SDValue AddrAdd =
3337       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3338   SDValue AddrLo =
3339       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3340 
3341   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3342   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3343   SDValue MNAdd = SDValue(
3344       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3345       0);
3346   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3347 }
3348 
3349 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3350                                                SelectionDAG &DAG) const {
3351   SDLoc DL(N);
3352   EVT Ty = getPointerTy(DAG.getDataLayout());
3353   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3354   const GlobalValue *GV = N->getGlobal();
3355 
3356   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3357   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3358   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3359   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3360   SDValue Load =
3361       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3362 
3363   // Prepare argument list to generate call.
3364   ArgListTy Args;
3365   ArgListEntry Entry;
3366   Entry.Node = Load;
3367   Entry.Ty = CallTy;
3368   Args.push_back(Entry);
3369 
3370   // Setup call to __tls_get_addr.
3371   TargetLowering::CallLoweringInfo CLI(DAG);
3372   CLI.setDebugLoc(DL)
3373       .setChain(DAG.getEntryNode())
3374       .setLibCallee(CallingConv::C, CallTy,
3375                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3376                     std::move(Args));
3377 
3378   return LowerCallTo(CLI).first;
3379 }
3380 
3381 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3382                                                    SelectionDAG &DAG) const {
3383   SDLoc DL(Op);
3384   EVT Ty = Op.getValueType();
3385   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3386   int64_t Offset = N->getOffset();
3387   MVT XLenVT = Subtarget.getXLenVT();
3388 
3389   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3390 
3391   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3392       CallingConv::GHC)
3393     report_fatal_error("In GHC calling convention TLS is not supported");
3394 
3395   SDValue Addr;
3396   switch (Model) {
3397   case TLSModel::LocalExec:
3398     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3399     break;
3400   case TLSModel::InitialExec:
3401     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3402     break;
3403   case TLSModel::LocalDynamic:
3404   case TLSModel::GeneralDynamic:
3405     Addr = getDynamicTLSAddr(N, DAG);
3406     break;
3407   }
3408 
3409   // In order to maximise the opportunity for common subexpression elimination,
3410   // emit a separate ADD node for the global address offset instead of folding
3411   // it in the global address node. Later peephole optimisations may choose to
3412   // fold it back in when profitable.
3413   if (Offset != 0)
3414     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3415                        DAG.getConstant(Offset, DL, XLenVT));
3416   return Addr;
3417 }
3418 
3419 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3420   SDValue CondV = Op.getOperand(0);
3421   SDValue TrueV = Op.getOperand(1);
3422   SDValue FalseV = Op.getOperand(2);
3423   SDLoc DL(Op);
3424   MVT VT = Op.getSimpleValueType();
3425   MVT XLenVT = Subtarget.getXLenVT();
3426 
3427   // Lower vector SELECTs to VSELECTs by splatting the condition.
3428   if (VT.isVector()) {
3429     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3430     SDValue CondSplat = VT.isScalableVector()
3431                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3432                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3433     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3434   }
3435 
3436   // If the result type is XLenVT and CondV is the output of a SETCC node
3437   // which also operated on XLenVT inputs, then merge the SETCC node into the
3438   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3439   // compare+branch instructions. i.e.:
3440   // (select (setcc lhs, rhs, cc), truev, falsev)
3441   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3442   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3443       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3444     SDValue LHS = CondV.getOperand(0);
3445     SDValue RHS = CondV.getOperand(1);
3446     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3447     ISD::CondCode CCVal = CC->get();
3448 
3449     // Special case for a select of 2 constants that have a diffence of 1.
3450     // Normally this is done by DAGCombine, but if the select is introduced by
3451     // type legalization or op legalization, we miss it. Restricting to SETLT
3452     // case for now because that is what signed saturating add/sub need.
3453     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3454     // but we would probably want to swap the true/false values if the condition
3455     // is SETGE/SETLE to avoid an XORI.
3456     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3457         CCVal == ISD::SETLT) {
3458       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3459       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3460       if (TrueVal - 1 == FalseVal)
3461         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3462       if (TrueVal + 1 == FalseVal)
3463         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3464     }
3465 
3466     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3467 
3468     SDValue TargetCC = DAG.getCondCode(CCVal);
3469     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3470     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3471   }
3472 
3473   // Otherwise:
3474   // (select condv, truev, falsev)
3475   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3476   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3477   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3478 
3479   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3480 
3481   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3482 }
3483 
3484 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3485   SDValue CondV = Op.getOperand(1);
3486   SDLoc DL(Op);
3487   MVT XLenVT = Subtarget.getXLenVT();
3488 
3489   if (CondV.getOpcode() == ISD::SETCC &&
3490       CondV.getOperand(0).getValueType() == XLenVT) {
3491     SDValue LHS = CondV.getOperand(0);
3492     SDValue RHS = CondV.getOperand(1);
3493     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3494 
3495     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3496 
3497     SDValue TargetCC = DAG.getCondCode(CCVal);
3498     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3499                        LHS, RHS, TargetCC, Op.getOperand(2));
3500   }
3501 
3502   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3503                      CondV, DAG.getConstant(0, DL, XLenVT),
3504                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3505 }
3506 
3507 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3508   MachineFunction &MF = DAG.getMachineFunction();
3509   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3510 
3511   SDLoc DL(Op);
3512   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3513                                  getPointerTy(MF.getDataLayout()));
3514 
3515   // vastart just stores the address of the VarArgsFrameIndex slot into the
3516   // memory location argument.
3517   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3518   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3519                       MachinePointerInfo(SV));
3520 }
3521 
3522 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3523                                             SelectionDAG &DAG) const {
3524   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3525   MachineFunction &MF = DAG.getMachineFunction();
3526   MachineFrameInfo &MFI = MF.getFrameInfo();
3527   MFI.setFrameAddressIsTaken(true);
3528   Register FrameReg = RI.getFrameRegister(MF);
3529   int XLenInBytes = Subtarget.getXLen() / 8;
3530 
3531   EVT VT = Op.getValueType();
3532   SDLoc DL(Op);
3533   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3534   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3535   while (Depth--) {
3536     int Offset = -(XLenInBytes * 2);
3537     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3538                               DAG.getIntPtrConstant(Offset, DL));
3539     FrameAddr =
3540         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3541   }
3542   return FrameAddr;
3543 }
3544 
3545 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3546                                              SelectionDAG &DAG) const {
3547   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3548   MachineFunction &MF = DAG.getMachineFunction();
3549   MachineFrameInfo &MFI = MF.getFrameInfo();
3550   MFI.setReturnAddressIsTaken(true);
3551   MVT XLenVT = Subtarget.getXLenVT();
3552   int XLenInBytes = Subtarget.getXLen() / 8;
3553 
3554   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3555     return SDValue();
3556 
3557   EVT VT = Op.getValueType();
3558   SDLoc DL(Op);
3559   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3560   if (Depth) {
3561     int Off = -XLenInBytes;
3562     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3563     SDValue Offset = DAG.getConstant(Off, DL, VT);
3564     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3565                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3566                        MachinePointerInfo());
3567   }
3568 
3569   // Return the value of the return address register, marking it an implicit
3570   // live-in.
3571   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3572   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3573 }
3574 
3575 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3576                                                  SelectionDAG &DAG) const {
3577   SDLoc DL(Op);
3578   SDValue Lo = Op.getOperand(0);
3579   SDValue Hi = Op.getOperand(1);
3580   SDValue Shamt = Op.getOperand(2);
3581   EVT VT = Lo.getValueType();
3582 
3583   // if Shamt-XLEN < 0: // Shamt < XLEN
3584   //   Lo = Lo << Shamt
3585   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3586   // else:
3587   //   Lo = 0
3588   //   Hi = Lo << (Shamt-XLEN)
3589 
3590   SDValue Zero = DAG.getConstant(0, DL, VT);
3591   SDValue One = DAG.getConstant(1, DL, VT);
3592   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3593   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3594   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3595   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3596 
3597   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3598   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3599   SDValue ShiftRightLo =
3600       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3601   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3602   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3603   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3604 
3605   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3606 
3607   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3608   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3609 
3610   SDValue Parts[2] = {Lo, Hi};
3611   return DAG.getMergeValues(Parts, DL);
3612 }
3613 
3614 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3615                                                   bool IsSRA) const {
3616   SDLoc DL(Op);
3617   SDValue Lo = Op.getOperand(0);
3618   SDValue Hi = Op.getOperand(1);
3619   SDValue Shamt = Op.getOperand(2);
3620   EVT VT = Lo.getValueType();
3621 
3622   // SRA expansion:
3623   //   if Shamt-XLEN < 0: // Shamt < XLEN
3624   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3625   //     Hi = Hi >>s Shamt
3626   //   else:
3627   //     Lo = Hi >>s (Shamt-XLEN);
3628   //     Hi = Hi >>s (XLEN-1)
3629   //
3630   // SRL expansion:
3631   //   if Shamt-XLEN < 0: // Shamt < XLEN
3632   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3633   //     Hi = Hi >>u Shamt
3634   //   else:
3635   //     Lo = Hi >>u (Shamt-XLEN);
3636   //     Hi = 0;
3637 
3638   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3639 
3640   SDValue Zero = DAG.getConstant(0, DL, VT);
3641   SDValue One = DAG.getConstant(1, DL, VT);
3642   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3643   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3644   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3645   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3646 
3647   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3648   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3649   SDValue ShiftLeftHi =
3650       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3651   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3652   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3653   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3654   SDValue HiFalse =
3655       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3656 
3657   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3658 
3659   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3660   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3661 
3662   SDValue Parts[2] = {Lo, Hi};
3663   return DAG.getMergeValues(Parts, DL);
3664 }
3665 
3666 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3667 // legal equivalently-sized i8 type, so we can use that as a go-between.
3668 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3669                                                   SelectionDAG &DAG) const {
3670   SDLoc DL(Op);
3671   MVT VT = Op.getSimpleValueType();
3672   SDValue SplatVal = Op.getOperand(0);
3673   // All-zeros or all-ones splats are handled specially.
3674   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3675     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3676     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3677   }
3678   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3679     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3680     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3681   }
3682   MVT XLenVT = Subtarget.getXLenVT();
3683   assert(SplatVal.getValueType() == XLenVT &&
3684          "Unexpected type for i1 splat value");
3685   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3686   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3687                          DAG.getConstant(1, DL, XLenVT));
3688   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3689   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3690   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3691 }
3692 
3693 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3694 // illegal (currently only vXi64 RV32).
3695 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3696 // them to SPLAT_VECTOR_I64
3697 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3698                                                      SelectionDAG &DAG) const {
3699   SDLoc DL(Op);
3700   MVT VecVT = Op.getSimpleValueType();
3701   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3702          "Unexpected SPLAT_VECTOR_PARTS lowering");
3703 
3704   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3705   SDValue Lo = Op.getOperand(0);
3706   SDValue Hi = Op.getOperand(1);
3707 
3708   if (VecVT.isFixedLengthVector()) {
3709     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3710     SDLoc DL(Op);
3711     SDValue Mask, VL;
3712     std::tie(Mask, VL) =
3713         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3714 
3715     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3716     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3717   }
3718 
3719   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3720     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3721     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3722     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3723     // node in order to try and match RVV vector/scalar instructions.
3724     if ((LoC >> 31) == HiC)
3725       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3726   }
3727 
3728   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3729   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3730       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3731       Hi.getConstantOperandVal(1) == 31)
3732     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3733 
3734   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3735   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3736                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3737 }
3738 
3739 // Custom-lower extensions from mask vectors by using a vselect either with 1
3740 // for zero/any-extension or -1 for sign-extension:
3741 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3742 // Note that any-extension is lowered identically to zero-extension.
3743 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3744                                                 int64_t ExtTrueVal) const {
3745   SDLoc DL(Op);
3746   MVT VecVT = Op.getSimpleValueType();
3747   SDValue Src = Op.getOperand(0);
3748   // Only custom-lower extensions from mask types
3749   assert(Src.getValueType().isVector() &&
3750          Src.getValueType().getVectorElementType() == MVT::i1);
3751 
3752   MVT XLenVT = Subtarget.getXLenVT();
3753   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3754   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3755 
3756   if (VecVT.isScalableVector()) {
3757     // Be careful not to introduce illegal scalar types at this stage, and be
3758     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3759     // illegal and must be expanded. Since we know that the constants are
3760     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3761     bool IsRV32E64 =
3762         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3763 
3764     if (!IsRV32E64) {
3765       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3766       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3767     } else {
3768       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3769       SplatTrueVal =
3770           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3771     }
3772 
3773     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3774   }
3775 
3776   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3777   MVT I1ContainerVT =
3778       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3779 
3780   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3781 
3782   SDValue Mask, VL;
3783   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3784 
3785   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3786   SplatTrueVal =
3787       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3788   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3789                                SplatTrueVal, SplatZero, VL);
3790 
3791   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3792 }
3793 
3794 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3795     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3796   MVT ExtVT = Op.getSimpleValueType();
3797   // Only custom-lower extensions from fixed-length vector types.
3798   if (!ExtVT.isFixedLengthVector())
3799     return Op;
3800   MVT VT = Op.getOperand(0).getSimpleValueType();
3801   // Grab the canonical container type for the extended type. Infer the smaller
3802   // type from that to ensure the same number of vector elements, as we know
3803   // the LMUL will be sufficient to hold the smaller type.
3804   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3805   // Get the extended container type manually to ensure the same number of
3806   // vector elements between source and dest.
3807   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3808                                      ContainerExtVT.getVectorElementCount());
3809 
3810   SDValue Op1 =
3811       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3812 
3813   SDLoc DL(Op);
3814   SDValue Mask, VL;
3815   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3816 
3817   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3818 
3819   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3820 }
3821 
3822 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3823 // setcc operation:
3824 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3825 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3826                                                   SelectionDAG &DAG) const {
3827   SDLoc DL(Op);
3828   EVT MaskVT = Op.getValueType();
3829   // Only expect to custom-lower truncations to mask types
3830   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3831          "Unexpected type for vector mask lowering");
3832   SDValue Src = Op.getOperand(0);
3833   MVT VecVT = Src.getSimpleValueType();
3834 
3835   // If this is a fixed vector, we need to convert it to a scalable vector.
3836   MVT ContainerVT = VecVT;
3837   if (VecVT.isFixedLengthVector()) {
3838     ContainerVT = getContainerForFixedLengthVector(VecVT);
3839     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3840   }
3841 
3842   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3843   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3844 
3845   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3846   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3847 
3848   if (VecVT.isScalableVector()) {
3849     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3850     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3851   }
3852 
3853   SDValue Mask, VL;
3854   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3855 
3856   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3857   SDValue Trunc =
3858       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3859   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3860                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3861   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3862 }
3863 
3864 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3865 // first position of a vector, and that vector is slid up to the insert index.
3866 // By limiting the active vector length to index+1 and merging with the
3867 // original vector (with an undisturbed tail policy for elements >= VL), we
3868 // achieve the desired result of leaving all elements untouched except the one
3869 // at VL-1, which is replaced with the desired value.
3870 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3871                                                     SelectionDAG &DAG) const {
3872   SDLoc DL(Op);
3873   MVT VecVT = Op.getSimpleValueType();
3874   SDValue Vec = Op.getOperand(0);
3875   SDValue Val = Op.getOperand(1);
3876   SDValue Idx = Op.getOperand(2);
3877 
3878   if (VecVT.getVectorElementType() == MVT::i1) {
3879     // FIXME: For now we just promote to an i8 vector and insert into that,
3880     // but this is probably not optimal.
3881     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3882     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3883     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3884     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3885   }
3886 
3887   MVT ContainerVT = VecVT;
3888   // If the operand is a fixed-length vector, convert to a scalable one.
3889   if (VecVT.isFixedLengthVector()) {
3890     ContainerVT = getContainerForFixedLengthVector(VecVT);
3891     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3892   }
3893 
3894   MVT XLenVT = Subtarget.getXLenVT();
3895 
3896   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3897   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3898   // Even i64-element vectors on RV32 can be lowered without scalar
3899   // legalization if the most-significant 32 bits of the value are not affected
3900   // by the sign-extension of the lower 32 bits.
3901   // TODO: We could also catch sign extensions of a 32-bit value.
3902   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3903     const auto *CVal = cast<ConstantSDNode>(Val);
3904     if (isInt<32>(CVal->getSExtValue())) {
3905       IsLegalInsert = true;
3906       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3907     }
3908   }
3909 
3910   SDValue Mask, VL;
3911   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3912 
3913   SDValue ValInVec;
3914 
3915   if (IsLegalInsert) {
3916     unsigned Opc =
3917         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3918     if (isNullConstant(Idx)) {
3919       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3920       if (!VecVT.isFixedLengthVector())
3921         return Vec;
3922       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3923     }
3924     ValInVec =
3925         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3926   } else {
3927     // On RV32, i64-element vectors must be specially handled to place the
3928     // value at element 0, by using two vslide1up instructions in sequence on
3929     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3930     // this.
3931     SDValue One = DAG.getConstant(1, DL, XLenVT);
3932     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3933     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3934     MVT I32ContainerVT =
3935         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3936     SDValue I32Mask =
3937         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3938     // Limit the active VL to two.
3939     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3940     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3941     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3942     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3943                            InsertI64VL);
3944     // First slide in the hi value, then the lo in underneath it.
3945     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3946                            ValHi, I32Mask, InsertI64VL);
3947     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3948                            ValLo, I32Mask, InsertI64VL);
3949     // Bitcast back to the right container type.
3950     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3951   }
3952 
3953   // Now that the value is in a vector, slide it into position.
3954   SDValue InsertVL =
3955       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3956   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3957                                 ValInVec, Idx, Mask, InsertVL);
3958   if (!VecVT.isFixedLengthVector())
3959     return Slideup;
3960   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3961 }
3962 
3963 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3964 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3965 // types this is done using VMV_X_S to allow us to glean information about the
3966 // sign bits of the result.
3967 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3968                                                      SelectionDAG &DAG) const {
3969   SDLoc DL(Op);
3970   SDValue Idx = Op.getOperand(1);
3971   SDValue Vec = Op.getOperand(0);
3972   EVT EltVT = Op.getValueType();
3973   MVT VecVT = Vec.getSimpleValueType();
3974   MVT XLenVT = Subtarget.getXLenVT();
3975 
3976   if (VecVT.getVectorElementType() == MVT::i1) {
3977     // FIXME: For now we just promote to an i8 vector and extract from that,
3978     // but this is probably not optimal.
3979     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3980     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3981     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3982   }
3983 
3984   // If this is a fixed vector, we need to convert it to a scalable vector.
3985   MVT ContainerVT = VecVT;
3986   if (VecVT.isFixedLengthVector()) {
3987     ContainerVT = getContainerForFixedLengthVector(VecVT);
3988     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3989   }
3990 
3991   // If the index is 0, the vector is already in the right position.
3992   if (!isNullConstant(Idx)) {
3993     // Use a VL of 1 to avoid processing more elements than we need.
3994     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3995     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3996     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3997     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3998                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3999   }
4000 
4001   if (!EltVT.isInteger()) {
4002     // Floating-point extracts are handled in TableGen.
4003     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4004                        DAG.getConstant(0, DL, XLenVT));
4005   }
4006 
4007   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4008   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4009 }
4010 
4011 // Some RVV intrinsics may claim that they want an integer operand to be
4012 // promoted or expanded.
4013 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4014                                           const RISCVSubtarget &Subtarget) {
4015   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4016           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4017          "Unexpected opcode");
4018 
4019   if (!Subtarget.hasVInstructions())
4020     return SDValue();
4021 
4022   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4023   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4024   SDLoc DL(Op);
4025 
4026   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4027       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4028   if (!II || !II->SplatOperand)
4029     return SDValue();
4030 
4031   unsigned SplatOp = II->SplatOperand + HasChain;
4032   assert(SplatOp < Op.getNumOperands());
4033 
4034   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4035   SDValue &ScalarOp = Operands[SplatOp];
4036   MVT OpVT = ScalarOp.getSimpleValueType();
4037   MVT XLenVT = Subtarget.getXLenVT();
4038 
4039   // If this isn't a scalar, or its type is XLenVT we're done.
4040   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4041     return SDValue();
4042 
4043   // Simplest case is that the operand needs to be promoted to XLenVT.
4044   if (OpVT.bitsLT(XLenVT)) {
4045     // If the operand is a constant, sign extend to increase our chances
4046     // of being able to use a .vi instruction. ANY_EXTEND would become a
4047     // a zero extend and the simm5 check in isel would fail.
4048     // FIXME: Should we ignore the upper bits in isel instead?
4049     unsigned ExtOpc =
4050         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4051     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4052     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4053   }
4054 
4055   // Use the previous operand to get the vXi64 VT. The result might be a mask
4056   // VT for compares. Using the previous operand assumes that the previous
4057   // operand will never have a smaller element size than a scalar operand and
4058   // that a widening operation never uses SEW=64.
4059   // NOTE: If this fails the below assert, we can probably just find the
4060   // element count from any operand or result and use it to construct the VT.
4061   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4062   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4063 
4064   // The more complex case is when the scalar is larger than XLenVT.
4065   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4066          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4067 
4068   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4069   // on the instruction to sign-extend since SEW>XLEN.
4070   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4071     if (isInt<32>(CVal->getSExtValue())) {
4072       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4073       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4074     }
4075   }
4076 
4077   // We need to convert the scalar to a splat vector.
4078   // FIXME: Can we implicitly truncate the scalar if it is known to
4079   // be sign extended?
4080   // VL should be the last operand.
4081   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4082   assert(VL.getValueType() == XLenVT);
4083   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4084   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4085 }
4086 
4087 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4088                                                      SelectionDAG &DAG) const {
4089   unsigned IntNo = Op.getConstantOperandVal(0);
4090   SDLoc DL(Op);
4091   MVT XLenVT = Subtarget.getXLenVT();
4092 
4093   switch (IntNo) {
4094   default:
4095     break; // Don't custom lower most intrinsics.
4096   case Intrinsic::thread_pointer: {
4097     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4098     return DAG.getRegister(RISCV::X4, PtrVT);
4099   }
4100   case Intrinsic::riscv_orc_b:
4101     // Lower to the GORCI encoding for orc.b.
4102     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4103                        DAG.getConstant(7, DL, XLenVT));
4104   case Intrinsic::riscv_grev:
4105   case Intrinsic::riscv_gorc: {
4106     unsigned Opc =
4107         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4108     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4109   }
4110   case Intrinsic::riscv_shfl:
4111   case Intrinsic::riscv_unshfl: {
4112     unsigned Opc =
4113         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4114     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4115   }
4116   case Intrinsic::riscv_bcompress:
4117   case Intrinsic::riscv_bdecompress: {
4118     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4119                                                        : RISCVISD::BDECOMPRESS;
4120     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4121   }
4122   case Intrinsic::riscv_vmv_x_s:
4123     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4124     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4125                        Op.getOperand(1));
4126   case Intrinsic::riscv_vmv_v_x:
4127     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4128                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4129   case Intrinsic::riscv_vfmv_v_f:
4130     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4131                        Op.getOperand(1), Op.getOperand(2));
4132   case Intrinsic::riscv_vmv_s_x: {
4133     SDValue Scalar = Op.getOperand(2);
4134 
4135     if (Scalar.getValueType().bitsLE(XLenVT)) {
4136       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4137       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4138                          Op.getOperand(1), Scalar, Op.getOperand(3));
4139     }
4140 
4141     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4142 
4143     // This is an i64 value that lives in two scalar registers. We have to
4144     // insert this in a convoluted way. First we build vXi64 splat containing
4145     // the/ two values that we assemble using some bit math. Next we'll use
4146     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4147     // to merge element 0 from our splat into the source vector.
4148     // FIXME: This is probably not the best way to do this, but it is
4149     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4150     // point.
4151     //   sw lo, (a0)
4152     //   sw hi, 4(a0)
4153     //   vlse vX, (a0)
4154     //
4155     //   vid.v      vVid
4156     //   vmseq.vx   mMask, vVid, 0
4157     //   vmerge.vvm vDest, vSrc, vVal, mMask
4158     MVT VT = Op.getSimpleValueType();
4159     SDValue Vec = Op.getOperand(1);
4160     SDValue VL = Op.getOperand(3);
4161 
4162     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4163     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4164                                       DAG.getConstant(0, DL, MVT::i32), VL);
4165 
4166     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4167     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4168     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4169     SDValue SelectCond =
4170         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4171                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4172     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4173                        Vec, VL);
4174   }
4175   case Intrinsic::riscv_vslide1up:
4176   case Intrinsic::riscv_vslide1down:
4177   case Intrinsic::riscv_vslide1up_mask:
4178   case Intrinsic::riscv_vslide1down_mask: {
4179     // We need to special case these when the scalar is larger than XLen.
4180     unsigned NumOps = Op.getNumOperands();
4181     bool IsMasked = NumOps == 7;
4182     unsigned OpOffset = IsMasked ? 1 : 0;
4183     SDValue Scalar = Op.getOperand(2 + OpOffset);
4184     if (Scalar.getValueType().bitsLE(XLenVT))
4185       break;
4186 
4187     // Splatting a sign extended constant is fine.
4188     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4189       if (isInt<32>(CVal->getSExtValue()))
4190         break;
4191 
4192     MVT VT = Op.getSimpleValueType();
4193     assert(VT.getVectorElementType() == MVT::i64 &&
4194            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4195 
4196     // Convert the vector source to the equivalent nxvXi32 vector.
4197     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4198     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4199 
4200     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4201                                    DAG.getConstant(0, DL, XLenVT));
4202     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4203                                    DAG.getConstant(1, DL, XLenVT));
4204 
4205     // Double the VL since we halved SEW.
4206     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4207     SDValue I32VL =
4208         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4209 
4210     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4211     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4212 
4213     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4214     // instructions.
4215     if (IntNo == Intrinsic::riscv_vslide1up ||
4216         IntNo == Intrinsic::riscv_vslide1up_mask) {
4217       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4218                         I32Mask, I32VL);
4219       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4220                         I32Mask, I32VL);
4221     } else {
4222       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4223                         I32Mask, I32VL);
4224       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4225                         I32Mask, I32VL);
4226     }
4227 
4228     // Convert back to nxvXi64.
4229     Vec = DAG.getBitcast(VT, Vec);
4230 
4231     if (!IsMasked)
4232       return Vec;
4233 
4234     // Apply mask after the operation.
4235     SDValue Mask = Op.getOperand(NumOps - 3);
4236     SDValue MaskedOff = Op.getOperand(1);
4237     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4238   }
4239   }
4240 
4241   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4242 }
4243 
4244 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4245                                                     SelectionDAG &DAG) const {
4246   unsigned IntNo = Op.getConstantOperandVal(1);
4247   switch (IntNo) {
4248   default:
4249     break;
4250   case Intrinsic::riscv_masked_strided_load: {
4251     SDLoc DL(Op);
4252     MVT XLenVT = Subtarget.getXLenVT();
4253 
4254     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4255     // the selection of the masked intrinsics doesn't do this for us.
4256     SDValue Mask = Op.getOperand(5);
4257     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4258 
4259     MVT VT = Op->getSimpleValueType(0);
4260     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4261 
4262     SDValue PassThru = Op.getOperand(2);
4263     if (!IsUnmasked) {
4264       MVT MaskVT =
4265           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4266       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4267       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4268     }
4269 
4270     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4271 
4272     SDValue IntID = DAG.getTargetConstant(
4273         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4274         XLenVT);
4275 
4276     auto *Load = cast<MemIntrinsicSDNode>(Op);
4277     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4278     if (!IsUnmasked)
4279       Ops.push_back(PassThru);
4280     Ops.push_back(Op.getOperand(3)); // Ptr
4281     Ops.push_back(Op.getOperand(4)); // Stride
4282     if (!IsUnmasked)
4283       Ops.push_back(Mask);
4284     Ops.push_back(VL);
4285     if (!IsUnmasked) {
4286       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4287       Ops.push_back(Policy);
4288     }
4289 
4290     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4291     SDValue Result =
4292         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4293                                 Load->getMemoryVT(), Load->getMemOperand());
4294     SDValue Chain = Result.getValue(1);
4295     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4296     return DAG.getMergeValues({Result, Chain}, DL);
4297   }
4298   }
4299 
4300   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4301 }
4302 
4303 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4304                                                  SelectionDAG &DAG) const {
4305   unsigned IntNo = Op.getConstantOperandVal(1);
4306   switch (IntNo) {
4307   default:
4308     break;
4309   case Intrinsic::riscv_masked_strided_store: {
4310     SDLoc DL(Op);
4311     MVT XLenVT = Subtarget.getXLenVT();
4312 
4313     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4314     // the selection of the masked intrinsics doesn't do this for us.
4315     SDValue Mask = Op.getOperand(5);
4316     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4317 
4318     SDValue Val = Op.getOperand(2);
4319     MVT VT = Val.getSimpleValueType();
4320     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4321 
4322     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4323     if (!IsUnmasked) {
4324       MVT MaskVT =
4325           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4326       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4327     }
4328 
4329     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4330 
4331     SDValue IntID = DAG.getTargetConstant(
4332         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4333         XLenVT);
4334 
4335     auto *Store = cast<MemIntrinsicSDNode>(Op);
4336     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4337     Ops.push_back(Val);
4338     Ops.push_back(Op.getOperand(3)); // Ptr
4339     Ops.push_back(Op.getOperand(4)); // Stride
4340     if (!IsUnmasked)
4341       Ops.push_back(Mask);
4342     Ops.push_back(VL);
4343 
4344     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4345                                    Ops, Store->getMemoryVT(),
4346                                    Store->getMemOperand());
4347   }
4348   }
4349 
4350   return SDValue();
4351 }
4352 
4353 static MVT getLMUL1VT(MVT VT) {
4354   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4355          "Unexpected vector MVT");
4356   return MVT::getScalableVectorVT(
4357       VT.getVectorElementType(),
4358       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4359 }
4360 
4361 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4362   switch (ISDOpcode) {
4363   default:
4364     llvm_unreachable("Unhandled reduction");
4365   case ISD::VECREDUCE_ADD:
4366     return RISCVISD::VECREDUCE_ADD_VL;
4367   case ISD::VECREDUCE_UMAX:
4368     return RISCVISD::VECREDUCE_UMAX_VL;
4369   case ISD::VECREDUCE_SMAX:
4370     return RISCVISD::VECREDUCE_SMAX_VL;
4371   case ISD::VECREDUCE_UMIN:
4372     return RISCVISD::VECREDUCE_UMIN_VL;
4373   case ISD::VECREDUCE_SMIN:
4374     return RISCVISD::VECREDUCE_SMIN_VL;
4375   case ISD::VECREDUCE_AND:
4376     return RISCVISD::VECREDUCE_AND_VL;
4377   case ISD::VECREDUCE_OR:
4378     return RISCVISD::VECREDUCE_OR_VL;
4379   case ISD::VECREDUCE_XOR:
4380     return RISCVISD::VECREDUCE_XOR_VL;
4381   }
4382 }
4383 
4384 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4385                                                          SelectionDAG &DAG,
4386                                                          bool IsVP) const {
4387   SDLoc DL(Op);
4388   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4389   MVT VecVT = Vec.getSimpleValueType();
4390   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4391           Op.getOpcode() == ISD::VECREDUCE_OR ||
4392           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4393           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4394           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4395           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4396          "Unexpected reduction lowering");
4397 
4398   MVT XLenVT = Subtarget.getXLenVT();
4399   assert(Op.getValueType() == XLenVT &&
4400          "Expected reduction output to be legalized to XLenVT");
4401 
4402   MVT ContainerVT = VecVT;
4403   if (VecVT.isFixedLengthVector()) {
4404     ContainerVT = getContainerForFixedLengthVector(VecVT);
4405     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4406   }
4407 
4408   SDValue Mask, VL;
4409   if (IsVP) {
4410     Mask = Op.getOperand(2);
4411     VL = Op.getOperand(3);
4412   } else {
4413     std::tie(Mask, VL) =
4414         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4415   }
4416 
4417   unsigned BaseOpc;
4418   ISD::CondCode CC;
4419   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4420 
4421   switch (Op.getOpcode()) {
4422   default:
4423     llvm_unreachable("Unhandled reduction");
4424   case ISD::VECREDUCE_AND:
4425   case ISD::VP_REDUCE_AND: {
4426     // vcpop ~x == 0
4427     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4428     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4429     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4430     CC = ISD::SETEQ;
4431     BaseOpc = ISD::AND;
4432     break;
4433   }
4434   case ISD::VECREDUCE_OR:
4435   case ISD::VP_REDUCE_OR:
4436     // vcpop x != 0
4437     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4438     CC = ISD::SETNE;
4439     BaseOpc = ISD::OR;
4440     break;
4441   case ISD::VECREDUCE_XOR:
4442   case ISD::VP_REDUCE_XOR: {
4443     // ((vcpop x) & 1) != 0
4444     SDValue One = DAG.getConstant(1, DL, XLenVT);
4445     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4446     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4447     CC = ISD::SETNE;
4448     BaseOpc = ISD::XOR;
4449     break;
4450   }
4451   }
4452 
4453   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4454 
4455   if (!IsVP)
4456     return SetCC;
4457 
4458   // Now include the start value in the operation.
4459   // Note that we must return the start value when no elements are operated
4460   // upon. The vcpop instructions we've emitted in each case above will return
4461   // 0 for an inactive vector, and so we've already received the neutral value:
4462   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4463   // can simply include the start value.
4464   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4465 }
4466 
4467 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4468                                             SelectionDAG &DAG) const {
4469   SDLoc DL(Op);
4470   SDValue Vec = Op.getOperand(0);
4471   EVT VecEVT = Vec.getValueType();
4472 
4473   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4474 
4475   // Due to ordering in legalize types we may have a vector type that needs to
4476   // be split. Do that manually so we can get down to a legal type.
4477   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4478          TargetLowering::TypeSplitVector) {
4479     SDValue Lo, Hi;
4480     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4481     VecEVT = Lo.getValueType();
4482     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4483   }
4484 
4485   // TODO: The type may need to be widened rather than split. Or widened before
4486   // it can be split.
4487   if (!isTypeLegal(VecEVT))
4488     return SDValue();
4489 
4490   MVT VecVT = VecEVT.getSimpleVT();
4491   MVT VecEltVT = VecVT.getVectorElementType();
4492   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4493 
4494   MVT ContainerVT = VecVT;
4495   if (VecVT.isFixedLengthVector()) {
4496     ContainerVT = getContainerForFixedLengthVector(VecVT);
4497     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4498   }
4499 
4500   MVT M1VT = getLMUL1VT(ContainerVT);
4501   MVT XLenVT = Subtarget.getXLenVT();
4502 
4503   SDValue Mask, VL;
4504   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4505 
4506   SDValue NeutralElem =
4507       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4508   SDValue IdentitySplat = lowerScalarSplat(
4509       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4510   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4511                                   IdentitySplat, Mask, VL);
4512   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4513                              DAG.getConstant(0, DL, XLenVT));
4514   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4515 }
4516 
4517 // Given a reduction op, this function returns the matching reduction opcode,
4518 // the vector SDValue and the scalar SDValue required to lower this to a
4519 // RISCVISD node.
4520 static std::tuple<unsigned, SDValue, SDValue>
4521 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4522   SDLoc DL(Op);
4523   auto Flags = Op->getFlags();
4524   unsigned Opcode = Op.getOpcode();
4525   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4526   switch (Opcode) {
4527   default:
4528     llvm_unreachable("Unhandled reduction");
4529   case ISD::VECREDUCE_FADD:
4530     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4531                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4532   case ISD::VECREDUCE_SEQ_FADD:
4533     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4534                            Op.getOperand(0));
4535   case ISD::VECREDUCE_FMIN:
4536     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4537                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4538   case ISD::VECREDUCE_FMAX:
4539     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4540                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4541   }
4542 }
4543 
4544 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4545                                               SelectionDAG &DAG) const {
4546   SDLoc DL(Op);
4547   MVT VecEltVT = Op.getSimpleValueType();
4548 
4549   unsigned RVVOpcode;
4550   SDValue VectorVal, ScalarVal;
4551   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4552       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4553   MVT VecVT = VectorVal.getSimpleValueType();
4554 
4555   MVT ContainerVT = VecVT;
4556   if (VecVT.isFixedLengthVector()) {
4557     ContainerVT = getContainerForFixedLengthVector(VecVT);
4558     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4559   }
4560 
4561   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4562   MVT XLenVT = Subtarget.getXLenVT();
4563 
4564   SDValue Mask, VL;
4565   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4566 
4567   SDValue ScalarSplat = lowerScalarSplat(
4568       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4569   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4570                                   VectorVal, ScalarSplat, Mask, VL);
4571   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4572                      DAG.getConstant(0, DL, XLenVT));
4573 }
4574 
4575 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4576   switch (ISDOpcode) {
4577   default:
4578     llvm_unreachable("Unhandled reduction");
4579   case ISD::VP_REDUCE_ADD:
4580     return RISCVISD::VECREDUCE_ADD_VL;
4581   case ISD::VP_REDUCE_UMAX:
4582     return RISCVISD::VECREDUCE_UMAX_VL;
4583   case ISD::VP_REDUCE_SMAX:
4584     return RISCVISD::VECREDUCE_SMAX_VL;
4585   case ISD::VP_REDUCE_UMIN:
4586     return RISCVISD::VECREDUCE_UMIN_VL;
4587   case ISD::VP_REDUCE_SMIN:
4588     return RISCVISD::VECREDUCE_SMIN_VL;
4589   case ISD::VP_REDUCE_AND:
4590     return RISCVISD::VECREDUCE_AND_VL;
4591   case ISD::VP_REDUCE_OR:
4592     return RISCVISD::VECREDUCE_OR_VL;
4593   case ISD::VP_REDUCE_XOR:
4594     return RISCVISD::VECREDUCE_XOR_VL;
4595   case ISD::VP_REDUCE_FADD:
4596     return RISCVISD::VECREDUCE_FADD_VL;
4597   case ISD::VP_REDUCE_SEQ_FADD:
4598     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4599   case ISD::VP_REDUCE_FMAX:
4600     return RISCVISD::VECREDUCE_FMAX_VL;
4601   case ISD::VP_REDUCE_FMIN:
4602     return RISCVISD::VECREDUCE_FMIN_VL;
4603   }
4604 }
4605 
4606 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4607                                            SelectionDAG &DAG) const {
4608   SDLoc DL(Op);
4609   SDValue Vec = Op.getOperand(1);
4610   EVT VecEVT = Vec.getValueType();
4611 
4612   // TODO: The type may need to be widened rather than split. Or widened before
4613   // it can be split.
4614   if (!isTypeLegal(VecEVT))
4615     return SDValue();
4616 
4617   MVT VecVT = VecEVT.getSimpleVT();
4618   MVT VecEltVT = VecVT.getVectorElementType();
4619   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4620 
4621   MVT ContainerVT = VecVT;
4622   if (VecVT.isFixedLengthVector()) {
4623     ContainerVT = getContainerForFixedLengthVector(VecVT);
4624     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4625   }
4626 
4627   SDValue VL = Op.getOperand(3);
4628   SDValue Mask = Op.getOperand(2);
4629 
4630   MVT M1VT = getLMUL1VT(ContainerVT);
4631   MVT XLenVT = Subtarget.getXLenVT();
4632   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4633 
4634   SDValue StartSplat =
4635       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4636                        DL, DAG, Subtarget);
4637   SDValue Reduction =
4638       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4639   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4640                              DAG.getConstant(0, DL, XLenVT));
4641   if (!VecVT.isInteger())
4642     return Elt0;
4643   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4644 }
4645 
4646 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4647                                                    SelectionDAG &DAG) const {
4648   SDValue Vec = Op.getOperand(0);
4649   SDValue SubVec = Op.getOperand(1);
4650   MVT VecVT = Vec.getSimpleValueType();
4651   MVT SubVecVT = SubVec.getSimpleValueType();
4652 
4653   SDLoc DL(Op);
4654   MVT XLenVT = Subtarget.getXLenVT();
4655   unsigned OrigIdx = Op.getConstantOperandVal(2);
4656   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4657 
4658   // We don't have the ability to slide mask vectors up indexed by their i1
4659   // elements; the smallest we can do is i8. Often we are able to bitcast to
4660   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4661   // into a scalable one, we might not necessarily have enough scalable
4662   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4663   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4664       (OrigIdx != 0 || !Vec.isUndef())) {
4665     if (VecVT.getVectorMinNumElements() >= 8 &&
4666         SubVecVT.getVectorMinNumElements() >= 8) {
4667       assert(OrigIdx % 8 == 0 && "Invalid index");
4668       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4669              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4670              "Unexpected mask vector lowering");
4671       OrigIdx /= 8;
4672       SubVecVT =
4673           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4674                            SubVecVT.isScalableVector());
4675       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4676                                VecVT.isScalableVector());
4677       Vec = DAG.getBitcast(VecVT, Vec);
4678       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4679     } else {
4680       // We can't slide this mask vector up indexed by its i1 elements.
4681       // This poses a problem when we wish to insert a scalable vector which
4682       // can't be re-expressed as a larger type. Just choose the slow path and
4683       // extend to a larger type, then truncate back down.
4684       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4685       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4686       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4687       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4688       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4689                         Op.getOperand(2));
4690       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4691       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4692     }
4693   }
4694 
4695   // If the subvector vector is a fixed-length type, we cannot use subregister
4696   // manipulation to simplify the codegen; we don't know which register of a
4697   // LMUL group contains the specific subvector as we only know the minimum
4698   // register size. Therefore we must slide the vector group up the full
4699   // amount.
4700   if (SubVecVT.isFixedLengthVector()) {
4701     if (OrigIdx == 0 && Vec.isUndef())
4702       return Op;
4703     MVT ContainerVT = VecVT;
4704     if (VecVT.isFixedLengthVector()) {
4705       ContainerVT = getContainerForFixedLengthVector(VecVT);
4706       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4707     }
4708     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4709                          DAG.getUNDEF(ContainerVT), SubVec,
4710                          DAG.getConstant(0, DL, XLenVT));
4711     SDValue Mask =
4712         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4713     // Set the vector length to only the number of elements we care about. Note
4714     // that for slideup this includes the offset.
4715     SDValue VL =
4716         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4717     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4718     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4719                                   SubVec, SlideupAmt, Mask, VL);
4720     if (VecVT.isFixedLengthVector())
4721       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4722     return DAG.getBitcast(Op.getValueType(), Slideup);
4723   }
4724 
4725   unsigned SubRegIdx, RemIdx;
4726   std::tie(SubRegIdx, RemIdx) =
4727       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4728           VecVT, SubVecVT, OrigIdx, TRI);
4729 
4730   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4731   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4732                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4733                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4734 
4735   // 1. If the Idx has been completely eliminated and this subvector's size is
4736   // a vector register or a multiple thereof, or the surrounding elements are
4737   // undef, then this is a subvector insert which naturally aligns to a vector
4738   // register. These can easily be handled using subregister manipulation.
4739   // 2. If the subvector is smaller than a vector register, then the insertion
4740   // must preserve the undisturbed elements of the register. We do this by
4741   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4742   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4743   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4744   // LMUL=1 type back into the larger vector (resolving to another subregister
4745   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4746   // to avoid allocating a large register group to hold our subvector.
4747   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4748     return Op;
4749 
4750   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4751   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4752   // (in our case undisturbed). This means we can set up a subvector insertion
4753   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4754   // size of the subvector.
4755   MVT InterSubVT = VecVT;
4756   SDValue AlignedExtract = Vec;
4757   unsigned AlignedIdx = OrigIdx - RemIdx;
4758   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4759     InterSubVT = getLMUL1VT(VecVT);
4760     // Extract a subvector equal to the nearest full vector register type. This
4761     // should resolve to a EXTRACT_SUBREG instruction.
4762     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4763                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4764   }
4765 
4766   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4767   // For scalable vectors this must be further multiplied by vscale.
4768   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4769 
4770   SDValue Mask, VL;
4771   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4772 
4773   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4774   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4775   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4776   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4777 
4778   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4779                        DAG.getUNDEF(InterSubVT), SubVec,
4780                        DAG.getConstant(0, DL, XLenVT));
4781 
4782   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4783                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4784 
4785   // If required, insert this subvector back into the correct vector register.
4786   // This should resolve to an INSERT_SUBREG instruction.
4787   if (VecVT.bitsGT(InterSubVT))
4788     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4789                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4790 
4791   // We might have bitcast from a mask type: cast back to the original type if
4792   // required.
4793   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4794 }
4795 
4796 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4797                                                     SelectionDAG &DAG) const {
4798   SDValue Vec = Op.getOperand(0);
4799   MVT SubVecVT = Op.getSimpleValueType();
4800   MVT VecVT = Vec.getSimpleValueType();
4801 
4802   SDLoc DL(Op);
4803   MVT XLenVT = Subtarget.getXLenVT();
4804   unsigned OrigIdx = Op.getConstantOperandVal(1);
4805   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4806 
4807   // We don't have the ability to slide mask vectors down indexed by their i1
4808   // elements; the smallest we can do is i8. Often we are able to bitcast to
4809   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4810   // from a scalable one, we might not necessarily have enough scalable
4811   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4812   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4813     if (VecVT.getVectorMinNumElements() >= 8 &&
4814         SubVecVT.getVectorMinNumElements() >= 8) {
4815       assert(OrigIdx % 8 == 0 && "Invalid index");
4816       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4817              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4818              "Unexpected mask vector lowering");
4819       OrigIdx /= 8;
4820       SubVecVT =
4821           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4822                            SubVecVT.isScalableVector());
4823       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4824                                VecVT.isScalableVector());
4825       Vec = DAG.getBitcast(VecVT, Vec);
4826     } else {
4827       // We can't slide this mask vector down, indexed by its i1 elements.
4828       // This poses a problem when we wish to extract a scalable vector which
4829       // can't be re-expressed as a larger type. Just choose the slow path and
4830       // extend to a larger type, then truncate back down.
4831       // TODO: We could probably improve this when extracting certain fixed
4832       // from fixed, where we can extract as i8 and shift the correct element
4833       // right to reach the desired subvector?
4834       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4835       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4836       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4837       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4838                         Op.getOperand(1));
4839       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4840       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4841     }
4842   }
4843 
4844   // If the subvector vector is a fixed-length type, we cannot use subregister
4845   // manipulation to simplify the codegen; we don't know which register of a
4846   // LMUL group contains the specific subvector as we only know the minimum
4847   // register size. Therefore we must slide the vector group down the full
4848   // amount.
4849   if (SubVecVT.isFixedLengthVector()) {
4850     // With an index of 0 this is a cast-like subvector, which can be performed
4851     // with subregister operations.
4852     if (OrigIdx == 0)
4853       return Op;
4854     MVT ContainerVT = VecVT;
4855     if (VecVT.isFixedLengthVector()) {
4856       ContainerVT = getContainerForFixedLengthVector(VecVT);
4857       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4858     }
4859     SDValue Mask =
4860         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4861     // Set the vector length to only the number of elements we care about. This
4862     // avoids sliding down elements we're going to discard straight away.
4863     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4864     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4865     SDValue Slidedown =
4866         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4867                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4868     // Now we can use a cast-like subvector extract to get the result.
4869     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4870                             DAG.getConstant(0, DL, XLenVT));
4871     return DAG.getBitcast(Op.getValueType(), Slidedown);
4872   }
4873 
4874   unsigned SubRegIdx, RemIdx;
4875   std::tie(SubRegIdx, RemIdx) =
4876       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4877           VecVT, SubVecVT, OrigIdx, TRI);
4878 
4879   // If the Idx has been completely eliminated then this is a subvector extract
4880   // which naturally aligns to a vector register. These can easily be handled
4881   // using subregister manipulation.
4882   if (RemIdx == 0)
4883     return Op;
4884 
4885   // Else we must shift our vector register directly to extract the subvector.
4886   // Do this using VSLIDEDOWN.
4887 
4888   // If the vector type is an LMUL-group type, extract a subvector equal to the
4889   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4890   // instruction.
4891   MVT InterSubVT = VecVT;
4892   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4893     InterSubVT = getLMUL1VT(VecVT);
4894     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4895                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4896   }
4897 
4898   // Slide this vector register down by the desired number of elements in order
4899   // to place the desired subvector starting at element 0.
4900   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4901   // For scalable vectors this must be further multiplied by vscale.
4902   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4903 
4904   SDValue Mask, VL;
4905   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4906   SDValue Slidedown =
4907       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4908                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4909 
4910   // Now the vector is in the right position, extract our final subvector. This
4911   // should resolve to a COPY.
4912   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4913                           DAG.getConstant(0, DL, XLenVT));
4914 
4915   // We might have bitcast from a mask type: cast back to the original type if
4916   // required.
4917   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4918 }
4919 
4920 // Lower step_vector to the vid instruction. Any non-identity step value must
4921 // be accounted for my manual expansion.
4922 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4923                                               SelectionDAG &DAG) const {
4924   SDLoc DL(Op);
4925   MVT VT = Op.getSimpleValueType();
4926   MVT XLenVT = Subtarget.getXLenVT();
4927   SDValue Mask, VL;
4928   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4929   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4930   uint64_t StepValImm = Op.getConstantOperandVal(0);
4931   if (StepValImm != 1) {
4932     if (isPowerOf2_64(StepValImm)) {
4933       SDValue StepVal =
4934           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4935                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4936       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4937     } else {
4938       SDValue StepVal = lowerScalarSplat(
4939           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4940           DL, DAG, Subtarget);
4941       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4942     }
4943   }
4944   return StepVec;
4945 }
4946 
4947 // Implement vector_reverse using vrgather.vv with indices determined by
4948 // subtracting the id of each element from (VLMAX-1). This will convert
4949 // the indices like so:
4950 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4951 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4952 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4953                                                  SelectionDAG &DAG) const {
4954   SDLoc DL(Op);
4955   MVT VecVT = Op.getSimpleValueType();
4956   unsigned EltSize = VecVT.getScalarSizeInBits();
4957   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4958 
4959   unsigned MaxVLMAX = 0;
4960   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4961   if (VectorBitsMax != 0)
4962     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4963 
4964   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4965   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4966 
4967   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4968   // to use vrgatherei16.vv.
4969   // TODO: It's also possible to use vrgatherei16.vv for other types to
4970   // decrease register width for the index calculation.
4971   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4972     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4973     // Reverse each half, then reassemble them in reverse order.
4974     // NOTE: It's also possible that after splitting that VLMAX no longer
4975     // requires vrgatherei16.vv.
4976     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4977       SDValue Lo, Hi;
4978       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4979       EVT LoVT, HiVT;
4980       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4981       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4982       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4983       // Reassemble the low and high pieces reversed.
4984       // FIXME: This is a CONCAT_VECTORS.
4985       SDValue Res =
4986           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4987                       DAG.getIntPtrConstant(0, DL));
4988       return DAG.getNode(
4989           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4990           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4991     }
4992 
4993     // Just promote the int type to i16 which will double the LMUL.
4994     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4995     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4996   }
4997 
4998   MVT XLenVT = Subtarget.getXLenVT();
4999   SDValue Mask, VL;
5000   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5001 
5002   // Calculate VLMAX-1 for the desired SEW.
5003   unsigned MinElts = VecVT.getVectorMinNumElements();
5004   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5005                               DAG.getConstant(MinElts, DL, XLenVT));
5006   SDValue VLMinus1 =
5007       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5008 
5009   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5010   bool IsRV32E64 =
5011       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5012   SDValue SplatVL;
5013   if (!IsRV32E64)
5014     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5015   else
5016     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5017 
5018   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5019   SDValue Indices =
5020       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5021 
5022   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5023 }
5024 
5025 SDValue
5026 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5027                                                      SelectionDAG &DAG) const {
5028   SDLoc DL(Op);
5029   auto *Load = cast<LoadSDNode>(Op);
5030 
5031   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5032                                         Load->getMemoryVT(),
5033                                         *Load->getMemOperand()) &&
5034          "Expecting a correctly-aligned load");
5035 
5036   MVT VT = Op.getSimpleValueType();
5037   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5038 
5039   SDValue VL =
5040       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5041 
5042   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5043   SDValue NewLoad = DAG.getMemIntrinsicNode(
5044       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5045       Load->getMemoryVT(), Load->getMemOperand());
5046 
5047   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5048   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5049 }
5050 
5051 SDValue
5052 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5053                                                       SelectionDAG &DAG) const {
5054   SDLoc DL(Op);
5055   auto *Store = cast<StoreSDNode>(Op);
5056 
5057   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5058                                         Store->getMemoryVT(),
5059                                         *Store->getMemOperand()) &&
5060          "Expecting a correctly-aligned store");
5061 
5062   SDValue StoreVal = Store->getValue();
5063   MVT VT = StoreVal.getSimpleValueType();
5064 
5065   // If the size less than a byte, we need to pad with zeros to make a byte.
5066   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5067     VT = MVT::v8i1;
5068     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5069                            DAG.getConstant(0, DL, VT), StoreVal,
5070                            DAG.getIntPtrConstant(0, DL));
5071   }
5072 
5073   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5074 
5075   SDValue VL =
5076       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5077 
5078   SDValue NewValue =
5079       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5080   return DAG.getMemIntrinsicNode(
5081       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5082       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5083       Store->getMemoryVT(), Store->getMemOperand());
5084 }
5085 
5086 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5087                                              SelectionDAG &DAG) const {
5088   SDLoc DL(Op);
5089   MVT VT = Op.getSimpleValueType();
5090 
5091   const auto *MemSD = cast<MemSDNode>(Op);
5092   EVT MemVT = MemSD->getMemoryVT();
5093   MachineMemOperand *MMO = MemSD->getMemOperand();
5094   SDValue Chain = MemSD->getChain();
5095   SDValue BasePtr = MemSD->getBasePtr();
5096 
5097   SDValue Mask, PassThru, VL;
5098   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5099     Mask = VPLoad->getMask();
5100     PassThru = DAG.getUNDEF(VT);
5101     VL = VPLoad->getVectorLength();
5102   } else {
5103     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5104     Mask = MLoad->getMask();
5105     PassThru = MLoad->getPassThru();
5106   }
5107 
5108   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5109 
5110   MVT XLenVT = Subtarget.getXLenVT();
5111 
5112   MVT ContainerVT = VT;
5113   if (VT.isFixedLengthVector()) {
5114     ContainerVT = getContainerForFixedLengthVector(VT);
5115     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5116     if (!IsUnmasked) {
5117       MVT MaskVT =
5118           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5119       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5120     }
5121   }
5122 
5123   if (!VL)
5124     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5125 
5126   unsigned IntID =
5127       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5128   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5129   if (!IsUnmasked)
5130     Ops.push_back(PassThru);
5131   Ops.push_back(BasePtr);
5132   if (!IsUnmasked)
5133     Ops.push_back(Mask);
5134   Ops.push_back(VL);
5135   if (!IsUnmasked)
5136     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5137 
5138   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5139 
5140   SDValue Result =
5141       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5142   Chain = Result.getValue(1);
5143 
5144   if (VT.isFixedLengthVector())
5145     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5146 
5147   return DAG.getMergeValues({Result, Chain}, DL);
5148 }
5149 
5150 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5151                                               SelectionDAG &DAG) const {
5152   SDLoc DL(Op);
5153 
5154   const auto *MemSD = cast<MemSDNode>(Op);
5155   EVT MemVT = MemSD->getMemoryVT();
5156   MachineMemOperand *MMO = MemSD->getMemOperand();
5157   SDValue Chain = MemSD->getChain();
5158   SDValue BasePtr = MemSD->getBasePtr();
5159   SDValue Val, Mask, VL;
5160 
5161   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5162     Val = VPStore->getValue();
5163     Mask = VPStore->getMask();
5164     VL = VPStore->getVectorLength();
5165   } else {
5166     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5167     Val = MStore->getValue();
5168     Mask = MStore->getMask();
5169   }
5170 
5171   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5172 
5173   MVT VT = Val.getSimpleValueType();
5174   MVT XLenVT = Subtarget.getXLenVT();
5175 
5176   MVT ContainerVT = VT;
5177   if (VT.isFixedLengthVector()) {
5178     ContainerVT = getContainerForFixedLengthVector(VT);
5179 
5180     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5181     if (!IsUnmasked) {
5182       MVT MaskVT =
5183           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5184       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5185     }
5186   }
5187 
5188   if (!VL)
5189     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5190 
5191   unsigned IntID =
5192       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5193   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5194   Ops.push_back(Val);
5195   Ops.push_back(BasePtr);
5196   if (!IsUnmasked)
5197     Ops.push_back(Mask);
5198   Ops.push_back(VL);
5199 
5200   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5201                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5202 }
5203 
5204 SDValue
5205 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5206                                                       SelectionDAG &DAG) const {
5207   MVT InVT = Op.getOperand(0).getSimpleValueType();
5208   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5209 
5210   MVT VT = Op.getSimpleValueType();
5211 
5212   SDValue Op1 =
5213       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5214   SDValue Op2 =
5215       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5216 
5217   SDLoc DL(Op);
5218   SDValue VL =
5219       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5220 
5221   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5222   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5223 
5224   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5225                             Op.getOperand(2), Mask, VL);
5226 
5227   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5228 }
5229 
5230 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5231     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5232   MVT VT = Op.getSimpleValueType();
5233 
5234   if (VT.getVectorElementType() == MVT::i1)
5235     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5236 
5237   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5238 }
5239 
5240 SDValue
5241 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5242                                                       SelectionDAG &DAG) const {
5243   unsigned Opc;
5244   switch (Op.getOpcode()) {
5245   default: llvm_unreachable("Unexpected opcode!");
5246   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5247   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5248   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5249   }
5250 
5251   return lowerToScalableOp(Op, DAG, Opc);
5252 }
5253 
5254 // Lower vector ABS to smax(X, sub(0, X)).
5255 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5256   SDLoc DL(Op);
5257   MVT VT = Op.getSimpleValueType();
5258   SDValue X = Op.getOperand(0);
5259 
5260   assert(VT.isFixedLengthVector() && "Unexpected type");
5261 
5262   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5263   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5264 
5265   SDValue Mask, VL;
5266   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5267 
5268   SDValue SplatZero =
5269       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5270                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5271   SDValue NegX =
5272       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5273   SDValue Max =
5274       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5275 
5276   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5277 }
5278 
5279 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5280     SDValue Op, SelectionDAG &DAG) const {
5281   SDLoc DL(Op);
5282   MVT VT = Op.getSimpleValueType();
5283   SDValue Mag = Op.getOperand(0);
5284   SDValue Sign = Op.getOperand(1);
5285   assert(Mag.getValueType() == Sign.getValueType() &&
5286          "Can only handle COPYSIGN with matching types.");
5287 
5288   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5289   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5290   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5291 
5292   SDValue Mask, VL;
5293   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5294 
5295   SDValue CopySign =
5296       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5297 
5298   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5299 }
5300 
5301 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5302     SDValue Op, SelectionDAG &DAG) const {
5303   MVT VT = Op.getSimpleValueType();
5304   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5305 
5306   MVT I1ContainerVT =
5307       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5308 
5309   SDValue CC =
5310       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5311   SDValue Op1 =
5312       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5313   SDValue Op2 =
5314       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5315 
5316   SDLoc DL(Op);
5317   SDValue Mask, VL;
5318   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5319 
5320   SDValue Select =
5321       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5322 
5323   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5324 }
5325 
5326 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5327                                                unsigned NewOpc,
5328                                                bool HasMask) const {
5329   MVT VT = Op.getSimpleValueType();
5330   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5331 
5332   // Create list of operands by converting existing ones to scalable types.
5333   SmallVector<SDValue, 6> Ops;
5334   for (const SDValue &V : Op->op_values()) {
5335     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5336 
5337     // Pass through non-vector operands.
5338     if (!V.getValueType().isVector()) {
5339       Ops.push_back(V);
5340       continue;
5341     }
5342 
5343     // "cast" fixed length vector to a scalable vector.
5344     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5345            "Only fixed length vectors are supported!");
5346     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5347   }
5348 
5349   SDLoc DL(Op);
5350   SDValue Mask, VL;
5351   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5352   if (HasMask)
5353     Ops.push_back(Mask);
5354   Ops.push_back(VL);
5355 
5356   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5357   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5358 }
5359 
5360 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5361 // * Operands of each node are assumed to be in the same order.
5362 // * The EVL operand is promoted from i32 to i64 on RV64.
5363 // * Fixed-length vectors are converted to their scalable-vector container
5364 //   types.
5365 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5366                                        unsigned RISCVISDOpc) const {
5367   SDLoc DL(Op);
5368   MVT VT = Op.getSimpleValueType();
5369   SmallVector<SDValue, 4> Ops;
5370 
5371   for (const auto &OpIdx : enumerate(Op->ops())) {
5372     SDValue V = OpIdx.value();
5373     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5374     // Pass through operands which aren't fixed-length vectors.
5375     if (!V.getValueType().isFixedLengthVector()) {
5376       Ops.push_back(V);
5377       continue;
5378     }
5379     // "cast" fixed length vector to a scalable vector.
5380     MVT OpVT = V.getSimpleValueType();
5381     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5382     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5383            "Only fixed length vectors are supported!");
5384     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5385   }
5386 
5387   if (!VT.isFixedLengthVector())
5388     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5389 
5390   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5391 
5392   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5393 
5394   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5395 }
5396 
5397 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5398 // matched to a RVV indexed load. The RVV indexed load instructions only
5399 // support the "unsigned unscaled" addressing mode; indices are implicitly
5400 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5401 // signed or scaled indexing is extended to the XLEN value type and scaled
5402 // accordingly.
5403 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5404                                                SelectionDAG &DAG) const {
5405   SDLoc DL(Op);
5406   MVT VT = Op.getSimpleValueType();
5407 
5408   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5409   EVT MemVT = MemSD->getMemoryVT();
5410   MachineMemOperand *MMO = MemSD->getMemOperand();
5411   SDValue Chain = MemSD->getChain();
5412   SDValue BasePtr = MemSD->getBasePtr();
5413 
5414   ISD::LoadExtType LoadExtType;
5415   SDValue Index, Mask, PassThru, VL;
5416 
5417   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5418     Index = VPGN->getIndex();
5419     Mask = VPGN->getMask();
5420     PassThru = DAG.getUNDEF(VT);
5421     VL = VPGN->getVectorLength();
5422     // VP doesn't support extending loads.
5423     LoadExtType = ISD::NON_EXTLOAD;
5424   } else {
5425     // Else it must be a MGATHER.
5426     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5427     Index = MGN->getIndex();
5428     Mask = MGN->getMask();
5429     PassThru = MGN->getPassThru();
5430     LoadExtType = MGN->getExtensionType();
5431   }
5432 
5433   MVT IndexVT = Index.getSimpleValueType();
5434   MVT XLenVT = Subtarget.getXLenVT();
5435 
5436   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5437          "Unexpected VTs!");
5438   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5439   // Targets have to explicitly opt-in for extending vector loads.
5440   assert(LoadExtType == ISD::NON_EXTLOAD &&
5441          "Unexpected extending MGATHER/VP_GATHER");
5442   (void)LoadExtType;
5443 
5444   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5445   // the selection of the masked intrinsics doesn't do this for us.
5446   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5447 
5448   MVT ContainerVT = VT;
5449   if (VT.isFixedLengthVector()) {
5450     // We need to use the larger of the result and index type to determine the
5451     // scalable type to use so we don't increase LMUL for any operand/result.
5452     if (VT.bitsGE(IndexVT)) {
5453       ContainerVT = getContainerForFixedLengthVector(VT);
5454       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5455                                  ContainerVT.getVectorElementCount());
5456     } else {
5457       IndexVT = getContainerForFixedLengthVector(IndexVT);
5458       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5459                                      IndexVT.getVectorElementCount());
5460     }
5461 
5462     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5463 
5464     if (!IsUnmasked) {
5465       MVT MaskVT =
5466           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5467       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5468       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5469     }
5470   }
5471 
5472   if (!VL)
5473     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5474 
5475   unsigned IntID =
5476       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5477   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5478   if (!IsUnmasked)
5479     Ops.push_back(PassThru);
5480   Ops.push_back(BasePtr);
5481   Ops.push_back(Index);
5482   if (!IsUnmasked)
5483     Ops.push_back(Mask);
5484   Ops.push_back(VL);
5485   if (!IsUnmasked)
5486     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5487 
5488   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5489   SDValue Result =
5490       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5491   Chain = Result.getValue(1);
5492 
5493   if (VT.isFixedLengthVector())
5494     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5495 
5496   return DAG.getMergeValues({Result, Chain}, DL);
5497 }
5498 
5499 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5500 // matched to a RVV indexed store. The RVV indexed store instructions only
5501 // support the "unsigned unscaled" addressing mode; indices are implicitly
5502 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5503 // signed or scaled indexing is extended to the XLEN value type and scaled
5504 // accordingly.
5505 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5506                                                 SelectionDAG &DAG) const {
5507   SDLoc DL(Op);
5508   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5509   EVT MemVT = MemSD->getMemoryVT();
5510   MachineMemOperand *MMO = MemSD->getMemOperand();
5511   SDValue Chain = MemSD->getChain();
5512   SDValue BasePtr = MemSD->getBasePtr();
5513 
5514   bool IsTruncatingStore = false;
5515   SDValue Index, Mask, Val, VL;
5516 
5517   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5518     Index = VPSN->getIndex();
5519     Mask = VPSN->getMask();
5520     Val = VPSN->getValue();
5521     VL = VPSN->getVectorLength();
5522     // VP doesn't support truncating stores.
5523     IsTruncatingStore = false;
5524   } else {
5525     // Else it must be a MSCATTER.
5526     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5527     Index = MSN->getIndex();
5528     Mask = MSN->getMask();
5529     Val = MSN->getValue();
5530     IsTruncatingStore = MSN->isTruncatingStore();
5531   }
5532 
5533   MVT VT = Val.getSimpleValueType();
5534   MVT IndexVT = Index.getSimpleValueType();
5535   MVT XLenVT = Subtarget.getXLenVT();
5536 
5537   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5538          "Unexpected VTs!");
5539   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5540   // Targets have to explicitly opt-in for extending vector loads and
5541   // truncating vector stores.
5542   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5543   (void)IsTruncatingStore;
5544 
5545   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5546   // the selection of the masked intrinsics doesn't do this for us.
5547   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5548 
5549   MVT ContainerVT = VT;
5550   if (VT.isFixedLengthVector()) {
5551     // We need to use the larger of the value and index type to determine the
5552     // scalable type to use so we don't increase LMUL for any operand/result.
5553     if (VT.bitsGE(IndexVT)) {
5554       ContainerVT = getContainerForFixedLengthVector(VT);
5555       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5556                                  ContainerVT.getVectorElementCount());
5557     } else {
5558       IndexVT = getContainerForFixedLengthVector(IndexVT);
5559       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5560                                      IndexVT.getVectorElementCount());
5561     }
5562 
5563     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5564     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5565 
5566     if (!IsUnmasked) {
5567       MVT MaskVT =
5568           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5569       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5570     }
5571   }
5572 
5573   if (!VL)
5574     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5575 
5576   unsigned IntID =
5577       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5578   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5579   Ops.push_back(Val);
5580   Ops.push_back(BasePtr);
5581   Ops.push_back(Index);
5582   if (!IsUnmasked)
5583     Ops.push_back(Mask);
5584   Ops.push_back(VL);
5585 
5586   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5587                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5588 }
5589 
5590 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5591                                                SelectionDAG &DAG) const {
5592   const MVT XLenVT = Subtarget.getXLenVT();
5593   SDLoc DL(Op);
5594   SDValue Chain = Op->getOperand(0);
5595   SDValue SysRegNo = DAG.getTargetConstant(
5596       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5597   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5598   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5599 
5600   // Encoding used for rounding mode in RISCV differs from that used in
5601   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5602   // table, which consists of a sequence of 4-bit fields, each representing
5603   // corresponding FLT_ROUNDS mode.
5604   static const int Table =
5605       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5606       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5607       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5608       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5609       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5610 
5611   SDValue Shift =
5612       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5613   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5614                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5615   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5616                                DAG.getConstant(7, DL, XLenVT));
5617 
5618   return DAG.getMergeValues({Masked, Chain}, DL);
5619 }
5620 
5621 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5622                                                SelectionDAG &DAG) const {
5623   const MVT XLenVT = Subtarget.getXLenVT();
5624   SDLoc DL(Op);
5625   SDValue Chain = Op->getOperand(0);
5626   SDValue RMValue = Op->getOperand(1);
5627   SDValue SysRegNo = DAG.getTargetConstant(
5628       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5629 
5630   // Encoding used for rounding mode in RISCV differs from that used in
5631   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5632   // a table, which consists of a sequence of 4-bit fields, each representing
5633   // corresponding RISCV mode.
5634   static const unsigned Table =
5635       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5636       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5637       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5638       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5639       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5640 
5641   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5642                               DAG.getConstant(2, DL, XLenVT));
5643   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5644                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5645   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5646                         DAG.getConstant(0x7, DL, XLenVT));
5647   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5648                      RMValue);
5649 }
5650 
5651 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5652 // form of the given Opcode.
5653 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5654   switch (Opcode) {
5655   default:
5656     llvm_unreachable("Unexpected opcode");
5657   case ISD::SHL:
5658     return RISCVISD::SLLW;
5659   case ISD::SRA:
5660     return RISCVISD::SRAW;
5661   case ISD::SRL:
5662     return RISCVISD::SRLW;
5663   case ISD::SDIV:
5664     return RISCVISD::DIVW;
5665   case ISD::UDIV:
5666     return RISCVISD::DIVUW;
5667   case ISD::UREM:
5668     return RISCVISD::REMUW;
5669   case ISD::ROTL:
5670     return RISCVISD::ROLW;
5671   case ISD::ROTR:
5672     return RISCVISD::RORW;
5673   case RISCVISD::GREV:
5674     return RISCVISD::GREVW;
5675   case RISCVISD::GORC:
5676     return RISCVISD::GORCW;
5677   }
5678 }
5679 
5680 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5681 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5682 // otherwise be promoted to i64, making it difficult to select the
5683 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5684 // type i8/i16/i32 is lost.
5685 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5686                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5687   SDLoc DL(N);
5688   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5689   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5690   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5691   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5692   // ReplaceNodeResults requires we maintain the same type for the return value.
5693   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5694 }
5695 
5696 // Converts the given 32-bit operation to a i64 operation with signed extension
5697 // semantic to reduce the signed extension instructions.
5698 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5699   SDLoc DL(N);
5700   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5701   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5702   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5703   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5704                                DAG.getValueType(MVT::i32));
5705   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5706 }
5707 
5708 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5709                                              SmallVectorImpl<SDValue> &Results,
5710                                              SelectionDAG &DAG) const {
5711   SDLoc DL(N);
5712   switch (N->getOpcode()) {
5713   default:
5714     llvm_unreachable("Don't know how to custom type legalize this operation!");
5715   case ISD::STRICT_FP_TO_SINT:
5716   case ISD::STRICT_FP_TO_UINT:
5717   case ISD::FP_TO_SINT:
5718   case ISD::FP_TO_UINT: {
5719     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5720            "Unexpected custom legalisation");
5721     bool IsStrict = N->isStrictFPOpcode();
5722     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5723                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5724     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5725     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5726         TargetLowering::TypeSoftenFloat) {
5727       // FIXME: Support strict FP.
5728       if (IsStrict)
5729         return;
5730       if (!isTypeLegal(Op0.getValueType()))
5731         return;
5732       unsigned Opc =
5733           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5734       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5735       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5736       return;
5737     }
5738     // If the FP type needs to be softened, emit a library call using the 'si'
5739     // version. If we left it to default legalization we'd end up with 'di'. If
5740     // the FP type doesn't need to be softened just let generic type
5741     // legalization promote the result type.
5742     RTLIB::Libcall LC;
5743     if (IsSigned)
5744       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5745     else
5746       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5747     MakeLibCallOptions CallOptions;
5748     EVT OpVT = Op0.getValueType();
5749     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5750     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5751     SDValue Result;
5752     std::tie(Result, Chain) =
5753         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5754     Results.push_back(Result);
5755     if (IsStrict)
5756       Results.push_back(Chain);
5757     break;
5758   }
5759   case ISD::READCYCLECOUNTER: {
5760     assert(!Subtarget.is64Bit() &&
5761            "READCYCLECOUNTER only has custom type legalization on riscv32");
5762 
5763     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5764     SDValue RCW =
5765         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5766 
5767     Results.push_back(
5768         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5769     Results.push_back(RCW.getValue(2));
5770     break;
5771   }
5772   case ISD::MUL: {
5773     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5774     unsigned XLen = Subtarget.getXLen();
5775     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5776     if (Size > XLen) {
5777       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5778       SDValue LHS = N->getOperand(0);
5779       SDValue RHS = N->getOperand(1);
5780       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5781 
5782       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5783       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5784       // We need exactly one side to be unsigned.
5785       if (LHSIsU == RHSIsU)
5786         return;
5787 
5788       auto MakeMULPair = [&](SDValue S, SDValue U) {
5789         MVT XLenVT = Subtarget.getXLenVT();
5790         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5791         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5792         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5793         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5794         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5795       };
5796 
5797       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5798       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5799 
5800       // The other operand should be signed, but still prefer MULH when
5801       // possible.
5802       if (RHSIsU && LHSIsS && !RHSIsS)
5803         Results.push_back(MakeMULPair(LHS, RHS));
5804       else if (LHSIsU && RHSIsS && !LHSIsS)
5805         Results.push_back(MakeMULPair(RHS, LHS));
5806 
5807       return;
5808     }
5809     LLVM_FALLTHROUGH;
5810   }
5811   case ISD::ADD:
5812   case ISD::SUB:
5813     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5814            "Unexpected custom legalisation");
5815     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5816     break;
5817   case ISD::SHL:
5818   case ISD::SRA:
5819   case ISD::SRL:
5820     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5821            "Unexpected custom legalisation");
5822     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5823       Results.push_back(customLegalizeToWOp(N, DAG));
5824       break;
5825     }
5826 
5827     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5828     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5829     // shift amount.
5830     if (N->getOpcode() == ISD::SHL) {
5831       SDLoc DL(N);
5832       SDValue NewOp0 =
5833           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5834       SDValue NewOp1 =
5835           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5836       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5837       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5838                                    DAG.getValueType(MVT::i32));
5839       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5840     }
5841 
5842     break;
5843   case ISD::ROTL:
5844   case ISD::ROTR:
5845     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5846            "Unexpected custom legalisation");
5847     Results.push_back(customLegalizeToWOp(N, DAG));
5848     break;
5849   case ISD::CTTZ:
5850   case ISD::CTTZ_ZERO_UNDEF:
5851   case ISD::CTLZ:
5852   case ISD::CTLZ_ZERO_UNDEF: {
5853     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5854            "Unexpected custom legalisation");
5855 
5856     SDValue NewOp0 =
5857         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5858     bool IsCTZ =
5859         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5860     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5861     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5862     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5863     return;
5864   }
5865   case ISD::SDIV:
5866   case ISD::UDIV:
5867   case ISD::UREM: {
5868     MVT VT = N->getSimpleValueType(0);
5869     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5870            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5871            "Unexpected custom legalisation");
5872     // Don't promote division/remainder by constant since we should expand those
5873     // to multiply by magic constant.
5874     // FIXME: What if the expansion is disabled for minsize.
5875     if (N->getOperand(1).getOpcode() == ISD::Constant)
5876       return;
5877 
5878     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5879     // the upper 32 bits. For other types we need to sign or zero extend
5880     // based on the opcode.
5881     unsigned ExtOpc = ISD::ANY_EXTEND;
5882     if (VT != MVT::i32)
5883       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5884                                            : ISD::ZERO_EXTEND;
5885 
5886     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5887     break;
5888   }
5889   case ISD::UADDO:
5890   case ISD::USUBO: {
5891     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5892            "Unexpected custom legalisation");
5893     bool IsAdd = N->getOpcode() == ISD::UADDO;
5894     // Create an ADDW or SUBW.
5895     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5896     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5897     SDValue Res =
5898         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5899     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5900                       DAG.getValueType(MVT::i32));
5901 
5902     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5903     // Since the inputs are sign extended from i32, this is equivalent to
5904     // comparing the lower 32 bits.
5905     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5906     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5907                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5908 
5909     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5910     Results.push_back(Overflow);
5911     return;
5912   }
5913   case ISD::UADDSAT:
5914   case ISD::USUBSAT: {
5915     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5916            "Unexpected custom legalisation");
5917     if (Subtarget.hasStdExtZbb()) {
5918       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5919       // sign extend allows overflow of the lower 32 bits to be detected on
5920       // the promoted size.
5921       SDValue LHS =
5922           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5923       SDValue RHS =
5924           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5925       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5926       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5927       return;
5928     }
5929 
5930     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5931     // promotion for UADDO/USUBO.
5932     Results.push_back(expandAddSubSat(N, DAG));
5933     return;
5934   }
5935   case ISD::BITCAST: {
5936     EVT VT = N->getValueType(0);
5937     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5938     SDValue Op0 = N->getOperand(0);
5939     EVT Op0VT = Op0.getValueType();
5940     MVT XLenVT = Subtarget.getXLenVT();
5941     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5942       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5943       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5944     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5945                Subtarget.hasStdExtF()) {
5946       SDValue FPConv =
5947           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5948       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5949     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5950                isTypeLegal(Op0VT)) {
5951       // Custom-legalize bitcasts from fixed-length vector types to illegal
5952       // scalar types in order to improve codegen. Bitcast the vector to a
5953       // one-element vector type whose element type is the same as the result
5954       // type, and extract the first element.
5955       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
5956       if (isTypeLegal(BVT)) {
5957         SDValue BVec = DAG.getBitcast(BVT, Op0);
5958         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5959                                       DAG.getConstant(0, DL, XLenVT)));
5960       }
5961     }
5962     break;
5963   }
5964   case RISCVISD::GREV:
5965   case RISCVISD::GORC: {
5966     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5967            "Unexpected custom legalisation");
5968     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5969     // This is similar to customLegalizeToWOp, except that we pass the second
5970     // operand (a TargetConstant) straight through: it is already of type
5971     // XLenVT.
5972     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5973     SDValue NewOp0 =
5974         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5975     SDValue NewOp1 =
5976         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5977     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5978     // ReplaceNodeResults requires we maintain the same type for the return
5979     // value.
5980     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5981     break;
5982   }
5983   case RISCVISD::SHFL: {
5984     // There is no SHFLIW instruction, but we can just promote the operation.
5985     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5986            "Unexpected custom legalisation");
5987     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5988     SDValue NewOp0 =
5989         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5990     SDValue NewOp1 =
5991         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5992     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5993     // ReplaceNodeResults requires we maintain the same type for the return
5994     // value.
5995     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5996     break;
5997   }
5998   case ISD::BSWAP:
5999   case ISD::BITREVERSE: {
6000     MVT VT = N->getSimpleValueType(0);
6001     MVT XLenVT = Subtarget.getXLenVT();
6002     assert((VT == MVT::i8 || VT == MVT::i16 ||
6003             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6004            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6005     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6006     unsigned Imm = VT.getSizeInBits() - 1;
6007     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6008     if (N->getOpcode() == ISD::BSWAP)
6009       Imm &= ~0x7U;
6010     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6011     SDValue GREVI =
6012         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6013     // ReplaceNodeResults requires we maintain the same type for the return
6014     // value.
6015     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6016     break;
6017   }
6018   case ISD::FSHL:
6019   case ISD::FSHR: {
6020     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6021            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6022     SDValue NewOp0 =
6023         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6024     SDValue NewOp1 =
6025         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6026     SDValue NewOp2 =
6027         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6028     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6029     // Mask the shift amount to 5 bits.
6030     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6031                          DAG.getConstant(0x1f, DL, MVT::i64));
6032     unsigned Opc =
6033         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6034     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6035     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6036     break;
6037   }
6038   case ISD::EXTRACT_VECTOR_ELT: {
6039     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6040     // type is illegal (currently only vXi64 RV32).
6041     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6042     // transferred to the destination register. We issue two of these from the
6043     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6044     // first element.
6045     SDValue Vec = N->getOperand(0);
6046     SDValue Idx = N->getOperand(1);
6047 
6048     // The vector type hasn't been legalized yet so we can't issue target
6049     // specific nodes if it needs legalization.
6050     // FIXME: We would manually legalize if it's important.
6051     if (!isTypeLegal(Vec.getValueType()))
6052       return;
6053 
6054     MVT VecVT = Vec.getSimpleValueType();
6055 
6056     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6057            VecVT.getVectorElementType() == MVT::i64 &&
6058            "Unexpected EXTRACT_VECTOR_ELT legalization");
6059 
6060     // If this is a fixed vector, we need to convert it to a scalable vector.
6061     MVT ContainerVT = VecVT;
6062     if (VecVT.isFixedLengthVector()) {
6063       ContainerVT = getContainerForFixedLengthVector(VecVT);
6064       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6065     }
6066 
6067     MVT XLenVT = Subtarget.getXLenVT();
6068 
6069     // Use a VL of 1 to avoid processing more elements than we need.
6070     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6071     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6072     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6073 
6074     // Unless the index is known to be 0, we must slide the vector down to get
6075     // the desired element into index 0.
6076     if (!isNullConstant(Idx)) {
6077       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6078                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6079     }
6080 
6081     // Extract the lower XLEN bits of the correct vector element.
6082     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6083 
6084     // To extract the upper XLEN bits of the vector element, shift the first
6085     // element right by 32 bits and re-extract the lower XLEN bits.
6086     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6087                                      DAG.getConstant(32, DL, XLenVT), VL);
6088     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6089                                  ThirtyTwoV, Mask, VL);
6090 
6091     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6092 
6093     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6094     break;
6095   }
6096   case ISD::INTRINSIC_WO_CHAIN: {
6097     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6098     switch (IntNo) {
6099     default:
6100       llvm_unreachable(
6101           "Don't know how to custom type legalize this intrinsic!");
6102     case Intrinsic::riscv_orc_b: {
6103       // Lower to the GORCI encoding for orc.b with the operand extended.
6104       SDValue NewOp =
6105           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6106       // If Zbp is enabled, use GORCIW which will sign extend the result.
6107       unsigned Opc =
6108           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6109       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6110                                 DAG.getConstant(7, DL, MVT::i64));
6111       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6112       return;
6113     }
6114     case Intrinsic::riscv_grev:
6115     case Intrinsic::riscv_gorc: {
6116       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6117              "Unexpected custom legalisation");
6118       SDValue NewOp1 =
6119           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6120       SDValue NewOp2 =
6121           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6122       unsigned Opc =
6123           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6124       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6125       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6126       break;
6127     }
6128     case Intrinsic::riscv_shfl:
6129     case Intrinsic::riscv_unshfl: {
6130       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6131              "Unexpected custom legalisation");
6132       SDValue NewOp1 =
6133           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6134       SDValue NewOp2 =
6135           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6136       unsigned Opc =
6137           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6138       if (isa<ConstantSDNode>(N->getOperand(2))) {
6139         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6140                              DAG.getConstant(0xf, DL, MVT::i64));
6141         Opc =
6142             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6143       }
6144       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6145       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6146       break;
6147     }
6148     case Intrinsic::riscv_bcompress:
6149     case Intrinsic::riscv_bdecompress: {
6150       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6151              "Unexpected custom legalisation");
6152       SDValue NewOp1 =
6153           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6154       SDValue NewOp2 =
6155           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6156       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6157                          ? RISCVISD::BCOMPRESSW
6158                          : RISCVISD::BDECOMPRESSW;
6159       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6160       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6161       break;
6162     }
6163     case Intrinsic::riscv_vmv_x_s: {
6164       EVT VT = N->getValueType(0);
6165       MVT XLenVT = Subtarget.getXLenVT();
6166       if (VT.bitsLT(XLenVT)) {
6167         // Simple case just extract using vmv.x.s and truncate.
6168         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6169                                       Subtarget.getXLenVT(), N->getOperand(1));
6170         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6171         return;
6172       }
6173 
6174       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6175              "Unexpected custom legalization");
6176 
6177       // We need to do the move in two steps.
6178       SDValue Vec = N->getOperand(1);
6179       MVT VecVT = Vec.getSimpleValueType();
6180 
6181       // First extract the lower XLEN bits of the element.
6182       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6183 
6184       // To extract the upper XLEN bits of the vector element, shift the first
6185       // element right by 32 bits and re-extract the lower XLEN bits.
6186       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6187       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6188       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6189       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6190                                        DAG.getConstant(32, DL, XLenVT), VL);
6191       SDValue LShr32 =
6192           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6193       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6194 
6195       Results.push_back(
6196           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6197       break;
6198     }
6199     }
6200     break;
6201   }
6202   case ISD::VECREDUCE_ADD:
6203   case ISD::VECREDUCE_AND:
6204   case ISD::VECREDUCE_OR:
6205   case ISD::VECREDUCE_XOR:
6206   case ISD::VECREDUCE_SMAX:
6207   case ISD::VECREDUCE_UMAX:
6208   case ISD::VECREDUCE_SMIN:
6209   case ISD::VECREDUCE_UMIN:
6210     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6211       Results.push_back(V);
6212     break;
6213   case ISD::VP_REDUCE_ADD:
6214   case ISD::VP_REDUCE_AND:
6215   case ISD::VP_REDUCE_OR:
6216   case ISD::VP_REDUCE_XOR:
6217   case ISD::VP_REDUCE_SMAX:
6218   case ISD::VP_REDUCE_UMAX:
6219   case ISD::VP_REDUCE_SMIN:
6220   case ISD::VP_REDUCE_UMIN:
6221     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6222       Results.push_back(V);
6223     break;
6224   case ISD::FLT_ROUNDS_: {
6225     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6226     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6227     Results.push_back(Res.getValue(0));
6228     Results.push_back(Res.getValue(1));
6229     break;
6230   }
6231   }
6232 }
6233 
6234 // A structure to hold one of the bit-manipulation patterns below. Together, a
6235 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6236 //   (or (and (shl x, 1), 0xAAAAAAAA),
6237 //       (and (srl x, 1), 0x55555555))
6238 struct RISCVBitmanipPat {
6239   SDValue Op;
6240   unsigned ShAmt;
6241   bool IsSHL;
6242 
6243   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6244     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6245   }
6246 };
6247 
6248 // Matches patterns of the form
6249 //   (and (shl x, C2), (C1 << C2))
6250 //   (and (srl x, C2), C1)
6251 //   (shl (and x, C1), C2)
6252 //   (srl (and x, (C1 << C2)), C2)
6253 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6254 // The expected masks for each shift amount are specified in BitmanipMasks where
6255 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6256 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6257 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6258 // XLen is 64.
6259 static Optional<RISCVBitmanipPat>
6260 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6261   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6262          "Unexpected number of masks");
6263   Optional<uint64_t> Mask;
6264   // Optionally consume a mask around the shift operation.
6265   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6266     Mask = Op.getConstantOperandVal(1);
6267     Op = Op.getOperand(0);
6268   }
6269   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6270     return None;
6271   bool IsSHL = Op.getOpcode() == ISD::SHL;
6272 
6273   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6274     return None;
6275   uint64_t ShAmt = Op.getConstantOperandVal(1);
6276 
6277   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6278   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6279     return None;
6280   // If we don't have enough masks for 64 bit, then we must be trying to
6281   // match SHFL so we're only allowed to shift 1/4 of the width.
6282   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6283     return None;
6284 
6285   SDValue Src = Op.getOperand(0);
6286 
6287   // The expected mask is shifted left when the AND is found around SHL
6288   // patterns.
6289   //   ((x >> 1) & 0x55555555)
6290   //   ((x << 1) & 0xAAAAAAAA)
6291   bool SHLExpMask = IsSHL;
6292 
6293   if (!Mask) {
6294     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6295     // the mask is all ones: consume that now.
6296     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6297       Mask = Src.getConstantOperandVal(1);
6298       Src = Src.getOperand(0);
6299       // The expected mask is now in fact shifted left for SRL, so reverse the
6300       // decision.
6301       //   ((x & 0xAAAAAAAA) >> 1)
6302       //   ((x & 0x55555555) << 1)
6303       SHLExpMask = !SHLExpMask;
6304     } else {
6305       // Use a default shifted mask of all-ones if there's no AND, truncated
6306       // down to the expected width. This simplifies the logic later on.
6307       Mask = maskTrailingOnes<uint64_t>(Width);
6308       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6309     }
6310   }
6311 
6312   unsigned MaskIdx = Log2_32(ShAmt);
6313   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6314 
6315   if (SHLExpMask)
6316     ExpMask <<= ShAmt;
6317 
6318   if (Mask != ExpMask)
6319     return None;
6320 
6321   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6322 }
6323 
6324 // Matches any of the following bit-manipulation patterns:
6325 //   (and (shl x, 1), (0x55555555 << 1))
6326 //   (and (srl x, 1), 0x55555555)
6327 //   (shl (and x, 0x55555555), 1)
6328 //   (srl (and x, (0x55555555 << 1)), 1)
6329 // where the shift amount and mask may vary thus:
6330 //   [1]  = 0x55555555 / 0xAAAAAAAA
6331 //   [2]  = 0x33333333 / 0xCCCCCCCC
6332 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6333 //   [8]  = 0x00FF00FF / 0xFF00FF00
6334 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6335 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6336 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6337   // These are the unshifted masks which we use to match bit-manipulation
6338   // patterns. They may be shifted left in certain circumstances.
6339   static const uint64_t BitmanipMasks[] = {
6340       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6341       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6342 
6343   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6344 }
6345 
6346 // Match the following pattern as a GREVI(W) operation
6347 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6348 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6349                                const RISCVSubtarget &Subtarget) {
6350   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6351   EVT VT = Op.getValueType();
6352 
6353   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6354     auto LHS = matchGREVIPat(Op.getOperand(0));
6355     auto RHS = matchGREVIPat(Op.getOperand(1));
6356     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6357       SDLoc DL(Op);
6358       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6359                          DAG.getConstant(LHS->ShAmt, DL, VT));
6360     }
6361   }
6362   return SDValue();
6363 }
6364 
6365 // Matches any the following pattern as a GORCI(W) operation
6366 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6367 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6368 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6369 // Note that with the variant of 3.,
6370 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6371 // the inner pattern will first be matched as GREVI and then the outer
6372 // pattern will be matched to GORC via the first rule above.
6373 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6374 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6375                                const RISCVSubtarget &Subtarget) {
6376   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6377   EVT VT = Op.getValueType();
6378 
6379   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6380     SDLoc DL(Op);
6381     SDValue Op0 = Op.getOperand(0);
6382     SDValue Op1 = Op.getOperand(1);
6383 
6384     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6385       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6386           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6387           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6388         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6389       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6390       if ((Reverse.getOpcode() == ISD::ROTL ||
6391            Reverse.getOpcode() == ISD::ROTR) &&
6392           Reverse.getOperand(0) == X &&
6393           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6394         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6395         if (RotAmt == (VT.getSizeInBits() / 2))
6396           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6397                              DAG.getConstant(RotAmt, DL, VT));
6398       }
6399       return SDValue();
6400     };
6401 
6402     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6403     if (SDValue V = MatchOROfReverse(Op0, Op1))
6404       return V;
6405     if (SDValue V = MatchOROfReverse(Op1, Op0))
6406       return V;
6407 
6408     // OR is commutable so canonicalize its OR operand to the left
6409     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6410       std::swap(Op0, Op1);
6411     if (Op0.getOpcode() != ISD::OR)
6412       return SDValue();
6413     SDValue OrOp0 = Op0.getOperand(0);
6414     SDValue OrOp1 = Op0.getOperand(1);
6415     auto LHS = matchGREVIPat(OrOp0);
6416     // OR is commutable so swap the operands and try again: x might have been
6417     // on the left
6418     if (!LHS) {
6419       std::swap(OrOp0, OrOp1);
6420       LHS = matchGREVIPat(OrOp0);
6421     }
6422     auto RHS = matchGREVIPat(Op1);
6423     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6424       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6425                          DAG.getConstant(LHS->ShAmt, DL, VT));
6426     }
6427   }
6428   return SDValue();
6429 }
6430 
6431 // Matches any of the following bit-manipulation patterns:
6432 //   (and (shl x, 1), (0x22222222 << 1))
6433 //   (and (srl x, 1), 0x22222222)
6434 //   (shl (and x, 0x22222222), 1)
6435 //   (srl (and x, (0x22222222 << 1)), 1)
6436 // where the shift amount and mask may vary thus:
6437 //   [1]  = 0x22222222 / 0x44444444
6438 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6439 //   [4]  = 0x00F000F0 / 0x0F000F00
6440 //   [8]  = 0x0000FF00 / 0x00FF0000
6441 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6442 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6443   // These are the unshifted masks which we use to match bit-manipulation
6444   // patterns. They may be shifted left in certain circumstances.
6445   static const uint64_t BitmanipMasks[] = {
6446       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6447       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6448 
6449   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6450 }
6451 
6452 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6453 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6454                                const RISCVSubtarget &Subtarget) {
6455   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6456   EVT VT = Op.getValueType();
6457 
6458   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6459     return SDValue();
6460 
6461   SDValue Op0 = Op.getOperand(0);
6462   SDValue Op1 = Op.getOperand(1);
6463 
6464   // Or is commutable so canonicalize the second OR to the LHS.
6465   if (Op0.getOpcode() != ISD::OR)
6466     std::swap(Op0, Op1);
6467   if (Op0.getOpcode() != ISD::OR)
6468     return SDValue();
6469 
6470   // We found an inner OR, so our operands are the operands of the inner OR
6471   // and the other operand of the outer OR.
6472   SDValue A = Op0.getOperand(0);
6473   SDValue B = Op0.getOperand(1);
6474   SDValue C = Op1;
6475 
6476   auto Match1 = matchSHFLPat(A);
6477   auto Match2 = matchSHFLPat(B);
6478 
6479   // If neither matched, we failed.
6480   if (!Match1 && !Match2)
6481     return SDValue();
6482 
6483   // We had at least one match. if one failed, try the remaining C operand.
6484   if (!Match1) {
6485     std::swap(A, C);
6486     Match1 = matchSHFLPat(A);
6487     if (!Match1)
6488       return SDValue();
6489   } else if (!Match2) {
6490     std::swap(B, C);
6491     Match2 = matchSHFLPat(B);
6492     if (!Match2)
6493       return SDValue();
6494   }
6495   assert(Match1 && Match2);
6496 
6497   // Make sure our matches pair up.
6498   if (!Match1->formsPairWith(*Match2))
6499     return SDValue();
6500 
6501   // All the remains is to make sure C is an AND with the same input, that masks
6502   // out the bits that are being shuffled.
6503   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6504       C.getOperand(0) != Match1->Op)
6505     return SDValue();
6506 
6507   uint64_t Mask = C.getConstantOperandVal(1);
6508 
6509   static const uint64_t BitmanipMasks[] = {
6510       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6511       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6512   };
6513 
6514   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6515   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6516   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6517 
6518   if (Mask != ExpMask)
6519     return SDValue();
6520 
6521   SDLoc DL(Op);
6522   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6523                      DAG.getConstant(Match1->ShAmt, DL, VT));
6524 }
6525 
6526 // Optimize (add (shl x, c0), (shl y, c1)) ->
6527 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6528 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6529                                   const RISCVSubtarget &Subtarget) {
6530   // Perform this optimization only in the zba extension.
6531   if (!Subtarget.hasStdExtZba())
6532     return SDValue();
6533 
6534   // Skip for vector types and larger types.
6535   EVT VT = N->getValueType(0);
6536   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6537     return SDValue();
6538 
6539   // The two operand nodes must be SHL and have no other use.
6540   SDValue N0 = N->getOperand(0);
6541   SDValue N1 = N->getOperand(1);
6542   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6543       !N0->hasOneUse() || !N1->hasOneUse())
6544     return SDValue();
6545 
6546   // Check c0 and c1.
6547   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6548   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6549   if (!N0C || !N1C)
6550     return SDValue();
6551   int64_t C0 = N0C->getSExtValue();
6552   int64_t C1 = N1C->getSExtValue();
6553   if (C0 <= 0 || C1 <= 0)
6554     return SDValue();
6555 
6556   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6557   int64_t Bits = std::min(C0, C1);
6558   int64_t Diff = std::abs(C0 - C1);
6559   if (Diff != 1 && Diff != 2 && Diff != 3)
6560     return SDValue();
6561 
6562   // Build nodes.
6563   SDLoc DL(N);
6564   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6565   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6566   SDValue NA0 =
6567       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6568   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6569   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6570 }
6571 
6572 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6573 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6574 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6575 // not undo itself, but they are redundant.
6576 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6577   SDValue Src = N->getOperand(0);
6578 
6579   if (Src.getOpcode() != N->getOpcode())
6580     return SDValue();
6581 
6582   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6583       !isa<ConstantSDNode>(Src.getOperand(1)))
6584     return SDValue();
6585 
6586   unsigned ShAmt1 = N->getConstantOperandVal(1);
6587   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6588   Src = Src.getOperand(0);
6589 
6590   unsigned CombinedShAmt;
6591   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6592     CombinedShAmt = ShAmt1 | ShAmt2;
6593   else
6594     CombinedShAmt = ShAmt1 ^ ShAmt2;
6595 
6596   if (CombinedShAmt == 0)
6597     return Src;
6598 
6599   SDLoc DL(N);
6600   return DAG.getNode(
6601       N->getOpcode(), DL, N->getValueType(0), Src,
6602       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6603 }
6604 
6605 // Combine a constant select operand into its use:
6606 //
6607 // (and (select cond, -1, c), x)
6608 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6609 // (or  (select cond, 0, c), x)
6610 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6611 // (xor (select cond, 0, c), x)
6612 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6613 // (add (select cond, 0, c), x)
6614 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6615 // (sub x, (select cond, 0, c))
6616 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6617 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6618                                    SelectionDAG &DAG, bool AllOnes) {
6619   EVT VT = N->getValueType(0);
6620 
6621   // Skip vectors.
6622   if (VT.isVector())
6623     return SDValue();
6624 
6625   if ((Slct.getOpcode() != ISD::SELECT &&
6626        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6627       !Slct.hasOneUse())
6628     return SDValue();
6629 
6630   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6631     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6632   };
6633 
6634   bool SwapSelectOps;
6635   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6636   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6637   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6638   SDValue NonConstantVal;
6639   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6640     SwapSelectOps = false;
6641     NonConstantVal = FalseVal;
6642   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6643     SwapSelectOps = true;
6644     NonConstantVal = TrueVal;
6645   } else
6646     return SDValue();
6647 
6648   // Slct is now know to be the desired identity constant when CC is true.
6649   TrueVal = OtherOp;
6650   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6651   // Unless SwapSelectOps says the condition should be false.
6652   if (SwapSelectOps)
6653     std::swap(TrueVal, FalseVal);
6654 
6655   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6656     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6657                        {Slct.getOperand(0), Slct.getOperand(1),
6658                         Slct.getOperand(2), TrueVal, FalseVal});
6659 
6660   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6661                      {Slct.getOperand(0), TrueVal, FalseVal});
6662 }
6663 
6664 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6665 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6666                                               bool AllOnes) {
6667   SDValue N0 = N->getOperand(0);
6668   SDValue N1 = N->getOperand(1);
6669   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6670     return Result;
6671   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6672     return Result;
6673   return SDValue();
6674 }
6675 
6676 // Transform (add (mul x, c0), c1) ->
6677 //           (add (mul (add x, c1/c0), c0), c1%c0).
6678 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6679 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6680 // to an infinite loop in DAGCombine if transformed.
6681 // Or transform (add (mul x, c0), c1) ->
6682 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6683 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6684 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6685 // lead to an infinite loop in DAGCombine if transformed.
6686 // Or transform (add (mul x, c0), c1) ->
6687 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6688 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6689 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6690 // lead to an infinite loop in DAGCombine if transformed.
6691 // Or transform (add (mul x, c0), c1) ->
6692 //              (mul (add x, c1/c0), c0).
6693 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6694 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6695                                      const RISCVSubtarget &Subtarget) {
6696   // Skip for vector types and larger types.
6697   EVT VT = N->getValueType(0);
6698   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6699     return SDValue();
6700   // The first operand node must be a MUL and has no other use.
6701   SDValue N0 = N->getOperand(0);
6702   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6703     return SDValue();
6704   // Check if c0 and c1 match above conditions.
6705   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6706   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6707   if (!N0C || !N1C)
6708     return SDValue();
6709   int64_t C0 = N0C->getSExtValue();
6710   int64_t C1 = N1C->getSExtValue();
6711   int64_t CA, CB;
6712   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6713     return SDValue();
6714   // Search for proper CA (non-zero) and CB that both are simm12.
6715   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6716       !isInt<12>(C0 * (C1 / C0))) {
6717     CA = C1 / C0;
6718     CB = C1 % C0;
6719   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6720              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6721     CA = C1 / C0 + 1;
6722     CB = C1 % C0 - C0;
6723   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6724              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6725     CA = C1 / C0 - 1;
6726     CB = C1 % C0 + C0;
6727   } else
6728     return SDValue();
6729   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6730   SDLoc DL(N);
6731   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6732                              DAG.getConstant(CA, DL, VT));
6733   SDValue New1 =
6734       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6735   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6736 }
6737 
6738 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6739                                  const RISCVSubtarget &Subtarget) {
6740   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6741     return V;
6742   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6743     return V;
6744   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6745   //      (select lhs, rhs, cc, x, (add x, y))
6746   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6747 }
6748 
6749 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6750   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6751   //      (select lhs, rhs, cc, x, (sub x, y))
6752   SDValue N0 = N->getOperand(0);
6753   SDValue N1 = N->getOperand(1);
6754   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6755 }
6756 
6757 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6758   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6759   //      (select lhs, rhs, cc, x, (and x, y))
6760   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6761 }
6762 
6763 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6764                                 const RISCVSubtarget &Subtarget) {
6765   if (Subtarget.hasStdExtZbp()) {
6766     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6767       return GREV;
6768     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6769       return GORC;
6770     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6771       return SHFL;
6772   }
6773 
6774   // fold (or (select cond, 0, y), x) ->
6775   //      (select cond, x, (or x, y))
6776   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6777 }
6778 
6779 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6780   // fold (xor (select cond, 0, y), x) ->
6781   //      (select cond, x, (xor x, y))
6782   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6783 }
6784 
6785 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6786 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6787 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6788 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6789 // ADDW/SUBW/MULW.
6790 static SDValue performANY_EXTENDCombine(SDNode *N,
6791                                         TargetLowering::DAGCombinerInfo &DCI,
6792                                         const RISCVSubtarget &Subtarget) {
6793   if (!Subtarget.is64Bit())
6794     return SDValue();
6795 
6796   SelectionDAG &DAG = DCI.DAG;
6797 
6798   SDValue Src = N->getOperand(0);
6799   EVT VT = N->getValueType(0);
6800   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6801     return SDValue();
6802 
6803   // The opcode must be one that can implicitly sign_extend.
6804   // FIXME: Additional opcodes.
6805   switch (Src.getOpcode()) {
6806   default:
6807     return SDValue();
6808   case ISD::MUL:
6809     if (!Subtarget.hasStdExtM())
6810       return SDValue();
6811     LLVM_FALLTHROUGH;
6812   case ISD::ADD:
6813   case ISD::SUB:
6814     break;
6815   }
6816 
6817   // Only handle cases where the result is used by a CopyToReg. That likely
6818   // means the value is a liveout of the basic block. This helps prevent
6819   // infinite combine loops like PR51206.
6820   if (none_of(N->uses(),
6821               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6822     return SDValue();
6823 
6824   SmallVector<SDNode *, 4> SetCCs;
6825   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6826                             UE = Src.getNode()->use_end();
6827        UI != UE; ++UI) {
6828     SDNode *User = *UI;
6829     if (User == N)
6830       continue;
6831     if (UI.getUse().getResNo() != Src.getResNo())
6832       continue;
6833     // All i32 setccs are legalized by sign extending operands.
6834     if (User->getOpcode() == ISD::SETCC) {
6835       SetCCs.push_back(User);
6836       continue;
6837     }
6838     // We don't know if we can extend this user.
6839     break;
6840   }
6841 
6842   // If we don't have any SetCCs, this isn't worthwhile.
6843   if (SetCCs.empty())
6844     return SDValue();
6845 
6846   SDLoc DL(N);
6847   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6848   DCI.CombineTo(N, SExt);
6849 
6850   // Promote all the setccs.
6851   for (SDNode *SetCC : SetCCs) {
6852     SmallVector<SDValue, 4> Ops;
6853 
6854     for (unsigned j = 0; j != 2; ++j) {
6855       SDValue SOp = SetCC->getOperand(j);
6856       if (SOp == Src)
6857         Ops.push_back(SExt);
6858       else
6859         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6860     }
6861 
6862     Ops.push_back(SetCC->getOperand(2));
6863     DCI.CombineTo(SetCC,
6864                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6865   }
6866   return SDValue(N, 0);
6867 }
6868 
6869 // Try to form VWMUL or VWMULU.
6870 // FIXME: Support VWMULSU.
6871 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6872                                     SelectionDAG &DAG) {
6873   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6874   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6875   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6876   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6877     return SDValue();
6878 
6879   SDValue Mask = N->getOperand(2);
6880   SDValue VL = N->getOperand(3);
6881 
6882   // Make sure the mask and VL match.
6883   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6884     return SDValue();
6885 
6886   MVT VT = N->getSimpleValueType(0);
6887 
6888   // Determine the narrow size for a widening multiply.
6889   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6890   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6891                                   VT.getVectorElementCount());
6892 
6893   SDLoc DL(N);
6894 
6895   // See if the other operand is the same opcode.
6896   if (Op0.getOpcode() == Op1.getOpcode()) {
6897     if (!Op1.hasOneUse())
6898       return SDValue();
6899 
6900     // Make sure the mask and VL match.
6901     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6902       return SDValue();
6903 
6904     Op1 = Op1.getOperand(0);
6905   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6906     // The operand is a splat of a scalar.
6907 
6908     // The VL must be the same.
6909     if (Op1.getOperand(1) != VL)
6910       return SDValue();
6911 
6912     // Get the scalar value.
6913     Op1 = Op1.getOperand(0);
6914 
6915     // See if have enough sign bits or zero bits in the scalar to use a
6916     // widening multiply by splatting to smaller element size.
6917     unsigned EltBits = VT.getScalarSizeInBits();
6918     unsigned ScalarBits = Op1.getValueSizeInBits();
6919     // Make sure we're getting all element bits from the scalar register.
6920     // FIXME: Support implicit sign extension of vmv.v.x?
6921     if (ScalarBits < EltBits)
6922       return SDValue();
6923 
6924     if (IsSignExt) {
6925       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6926         return SDValue();
6927     } else {
6928       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6929       if (!DAG.MaskedValueIsZero(Op1, Mask))
6930         return SDValue();
6931     }
6932 
6933     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6934   } else
6935     return SDValue();
6936 
6937   Op0 = Op0.getOperand(0);
6938 
6939   // Re-introduce narrower extends if needed.
6940   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6941   if (Op0.getValueType() != NarrowVT)
6942     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6943   if (Op1.getValueType() != NarrowVT)
6944     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6945 
6946   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6947   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6948 }
6949 
6950 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6951                                                DAGCombinerInfo &DCI) const {
6952   SelectionDAG &DAG = DCI.DAG;
6953 
6954   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6955   // bits are demanded. N will be added to the Worklist if it was not deleted.
6956   // Caller should return SDValue(N, 0) if this returns true.
6957   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6958     SDValue Op = N->getOperand(OpNo);
6959     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6960     if (!SimplifyDemandedBits(Op, Mask, DCI))
6961       return false;
6962 
6963     if (N->getOpcode() != ISD::DELETED_NODE)
6964       DCI.AddToWorklist(N);
6965     return true;
6966   };
6967 
6968   switch (N->getOpcode()) {
6969   default:
6970     break;
6971   case RISCVISD::SplitF64: {
6972     SDValue Op0 = N->getOperand(0);
6973     // If the input to SplitF64 is just BuildPairF64 then the operation is
6974     // redundant. Instead, use BuildPairF64's operands directly.
6975     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6976       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6977 
6978     SDLoc DL(N);
6979 
6980     // It's cheaper to materialise two 32-bit integers than to load a double
6981     // from the constant pool and transfer it to integer registers through the
6982     // stack.
6983     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6984       APInt V = C->getValueAPF().bitcastToAPInt();
6985       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6986       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6987       return DCI.CombineTo(N, Lo, Hi);
6988     }
6989 
6990     // This is a target-specific version of a DAGCombine performed in
6991     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6992     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6993     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6994     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6995         !Op0.getNode()->hasOneUse())
6996       break;
6997     SDValue NewSplitF64 =
6998         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6999                     Op0.getOperand(0));
7000     SDValue Lo = NewSplitF64.getValue(0);
7001     SDValue Hi = NewSplitF64.getValue(1);
7002     APInt SignBit = APInt::getSignMask(32);
7003     if (Op0.getOpcode() == ISD::FNEG) {
7004       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7005                                   DAG.getConstant(SignBit, DL, MVT::i32));
7006       return DCI.CombineTo(N, Lo, NewHi);
7007     }
7008     assert(Op0.getOpcode() == ISD::FABS);
7009     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7010                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7011     return DCI.CombineTo(N, Lo, NewHi);
7012   }
7013   case RISCVISD::SLLW:
7014   case RISCVISD::SRAW:
7015   case RISCVISD::SRLW:
7016   case RISCVISD::ROLW:
7017   case RISCVISD::RORW: {
7018     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7019     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7020         SimplifyDemandedLowBitsHelper(1, 5))
7021       return SDValue(N, 0);
7022     break;
7023   }
7024   case RISCVISD::CLZW:
7025   case RISCVISD::CTZW: {
7026     // Only the lower 32 bits of the first operand are read
7027     if (SimplifyDemandedLowBitsHelper(0, 32))
7028       return SDValue(N, 0);
7029     break;
7030   }
7031   case RISCVISD::FSL:
7032   case RISCVISD::FSR: {
7033     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7034     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7035     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7036     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7037       return SDValue(N, 0);
7038     break;
7039   }
7040   case RISCVISD::FSLW:
7041   case RISCVISD::FSRW: {
7042     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7043     // read.
7044     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7045         SimplifyDemandedLowBitsHelper(1, 32) ||
7046         SimplifyDemandedLowBitsHelper(2, 6))
7047       return SDValue(N, 0);
7048     break;
7049   }
7050   case RISCVISD::GREV:
7051   case RISCVISD::GORC: {
7052     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7053     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7054     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7055     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7056       return SDValue(N, 0);
7057 
7058     return combineGREVI_GORCI(N, DCI.DAG);
7059   }
7060   case RISCVISD::GREVW:
7061   case RISCVISD::GORCW: {
7062     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7063     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7064         SimplifyDemandedLowBitsHelper(1, 5))
7065       return SDValue(N, 0);
7066 
7067     return combineGREVI_GORCI(N, DCI.DAG);
7068   }
7069   case RISCVISD::SHFL:
7070   case RISCVISD::UNSHFL: {
7071     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7072     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7073     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7074     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7075       return SDValue(N, 0);
7076 
7077     break;
7078   }
7079   case RISCVISD::SHFLW:
7080   case RISCVISD::UNSHFLW: {
7081     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7082     SDValue LHS = N->getOperand(0);
7083     SDValue RHS = N->getOperand(1);
7084     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7085     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7086     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7087         SimplifyDemandedLowBitsHelper(1, 4))
7088       return SDValue(N, 0);
7089 
7090     break;
7091   }
7092   case RISCVISD::BCOMPRESSW:
7093   case RISCVISD::BDECOMPRESSW: {
7094     // Only the lower 32 bits of LHS and RHS are read.
7095     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7096         SimplifyDemandedLowBitsHelper(1, 32))
7097       return SDValue(N, 0);
7098 
7099     break;
7100   }
7101   case RISCVISD::FMV_X_ANYEXTH:
7102   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7103     SDLoc DL(N);
7104     SDValue Op0 = N->getOperand(0);
7105     MVT VT = N->getSimpleValueType(0);
7106     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7107     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7108     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7109     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7110          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7111         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7112          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7113       assert(Op0.getOperand(0).getValueType() == VT &&
7114              "Unexpected value type!");
7115       return Op0.getOperand(0);
7116     }
7117 
7118     // This is a target-specific version of a DAGCombine performed in
7119     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7120     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7121     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7122     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7123         !Op0.getNode()->hasOneUse())
7124       break;
7125     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7126     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7127     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7128     if (Op0.getOpcode() == ISD::FNEG)
7129       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7130                          DAG.getConstant(SignBit, DL, VT));
7131 
7132     assert(Op0.getOpcode() == ISD::FABS);
7133     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7134                        DAG.getConstant(~SignBit, DL, VT));
7135   }
7136   case ISD::ADD:
7137     return performADDCombine(N, DAG, Subtarget);
7138   case ISD::SUB:
7139     return performSUBCombine(N, DAG);
7140   case ISD::AND:
7141     return performANDCombine(N, DAG);
7142   case ISD::OR:
7143     return performORCombine(N, DAG, Subtarget);
7144   case ISD::XOR:
7145     return performXORCombine(N, DAG);
7146   case ISD::ANY_EXTEND:
7147     return performANY_EXTENDCombine(N, DCI, Subtarget);
7148   case ISD::ZERO_EXTEND:
7149     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7150     // type legalization. This is safe because fp_to_uint produces poison if
7151     // it overflows.
7152     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
7153         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
7154         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
7155       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7156                          N->getOperand(0).getOperand(0));
7157     return SDValue();
7158   case RISCVISD::SELECT_CC: {
7159     // Transform
7160     SDValue LHS = N->getOperand(0);
7161     SDValue RHS = N->getOperand(1);
7162     SDValue TrueV = N->getOperand(3);
7163     SDValue FalseV = N->getOperand(4);
7164 
7165     // If the True and False values are the same, we don't need a select_cc.
7166     if (TrueV == FalseV)
7167       return TrueV;
7168 
7169     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7170     if (!ISD::isIntEqualitySetCC(CCVal))
7171       break;
7172 
7173     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7174     //      (select_cc X, Y, lt, trueV, falseV)
7175     // Sometimes the setcc is introduced after select_cc has been formed.
7176     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7177         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7178       // If we're looking for eq 0 instead of ne 0, we need to invert the
7179       // condition.
7180       bool Invert = CCVal == ISD::SETEQ;
7181       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7182       if (Invert)
7183         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7184 
7185       SDLoc DL(N);
7186       RHS = LHS.getOperand(1);
7187       LHS = LHS.getOperand(0);
7188       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7189 
7190       SDValue TargetCC = DAG.getCondCode(CCVal);
7191       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7192                          {LHS, RHS, TargetCC, TrueV, FalseV});
7193     }
7194 
7195     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7196     //      (select_cc X, Y, eq/ne, trueV, falseV)
7197     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7198       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7199                          {LHS.getOperand(0), LHS.getOperand(1),
7200                           N->getOperand(2), TrueV, FalseV});
7201     // (select_cc X, 1, setne, trueV, falseV) ->
7202     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7203     // This can occur when legalizing some floating point comparisons.
7204     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7205     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7206       SDLoc DL(N);
7207       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7208       SDValue TargetCC = DAG.getCondCode(CCVal);
7209       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7210       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7211                          {LHS, RHS, TargetCC, TrueV, FalseV});
7212     }
7213 
7214     break;
7215   }
7216   case RISCVISD::BR_CC: {
7217     SDValue LHS = N->getOperand(1);
7218     SDValue RHS = N->getOperand(2);
7219     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7220     if (!ISD::isIntEqualitySetCC(CCVal))
7221       break;
7222 
7223     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7224     //      (br_cc X, Y, lt, dest)
7225     // Sometimes the setcc is introduced after br_cc has been formed.
7226     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7227         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7228       // If we're looking for eq 0 instead of ne 0, we need to invert the
7229       // condition.
7230       bool Invert = CCVal == ISD::SETEQ;
7231       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7232       if (Invert)
7233         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7234 
7235       SDLoc DL(N);
7236       RHS = LHS.getOperand(1);
7237       LHS = LHS.getOperand(0);
7238       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7239 
7240       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7241                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7242                          N->getOperand(4));
7243     }
7244 
7245     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7246     //      (br_cc X, Y, eq/ne, trueV, falseV)
7247     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7248       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7249                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7250                          N->getOperand(3), N->getOperand(4));
7251 
7252     // (br_cc X, 1, setne, br_cc) ->
7253     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7254     // This can occur when legalizing some floating point comparisons.
7255     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7256     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7257       SDLoc DL(N);
7258       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7259       SDValue TargetCC = DAG.getCondCode(CCVal);
7260       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7261       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7262                          N->getOperand(0), LHS, RHS, TargetCC,
7263                          N->getOperand(4));
7264     }
7265     break;
7266   }
7267   case ISD::FCOPYSIGN: {
7268     EVT VT = N->getValueType(0);
7269     if (!VT.isVector())
7270       break;
7271     // There is a form of VFSGNJ which injects the negated sign of its second
7272     // operand. Try and bubble any FNEG up after the extend/round to produce
7273     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7274     // TRUNC=1.
7275     SDValue In2 = N->getOperand(1);
7276     // Avoid cases where the extend/round has multiple uses, as duplicating
7277     // those is typically more expensive than removing a fneg.
7278     if (!In2.hasOneUse())
7279       break;
7280     if (In2.getOpcode() != ISD::FP_EXTEND &&
7281         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7282       break;
7283     In2 = In2.getOperand(0);
7284     if (In2.getOpcode() != ISD::FNEG)
7285       break;
7286     SDLoc DL(N);
7287     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7288     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7289                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7290   }
7291   case ISD::MGATHER:
7292   case ISD::MSCATTER:
7293   case ISD::VP_GATHER:
7294   case ISD::VP_SCATTER: {
7295     if (!DCI.isBeforeLegalize())
7296       break;
7297     SDValue Index, ScaleOp;
7298     bool IsIndexScaled = false;
7299     bool IsIndexSigned = false;
7300     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7301       Index = VPGSN->getIndex();
7302       ScaleOp = VPGSN->getScale();
7303       IsIndexScaled = VPGSN->isIndexScaled();
7304       IsIndexSigned = VPGSN->isIndexSigned();
7305     } else {
7306       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7307       Index = MGSN->getIndex();
7308       ScaleOp = MGSN->getScale();
7309       IsIndexScaled = MGSN->isIndexScaled();
7310       IsIndexSigned = MGSN->isIndexSigned();
7311     }
7312     EVT IndexVT = Index.getValueType();
7313     MVT XLenVT = Subtarget.getXLenVT();
7314     // RISCV indexed loads only support the "unsigned unscaled" addressing
7315     // mode, so anything else must be manually legalized.
7316     bool NeedsIdxLegalization =
7317         IsIndexScaled ||
7318         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7319     if (!NeedsIdxLegalization)
7320       break;
7321 
7322     SDLoc DL(N);
7323 
7324     // Any index legalization should first promote to XLenVT, so we don't lose
7325     // bits when scaling. This may create an illegal index type so we let
7326     // LLVM's legalization take care of the splitting.
7327     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7328     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7329       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7330       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7331                           DL, IndexVT, Index);
7332     }
7333 
7334     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7335     if (IsIndexScaled && Scale != 1) {
7336       // Manually scale the indices by the element size.
7337       // TODO: Sanitize the scale operand here?
7338       // TODO: For VP nodes, should we use VP_SHL here?
7339       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7340       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7341       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7342     }
7343 
7344     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7345     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7346       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7347                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7348                               VPGN->getScale(), VPGN->getMask(),
7349                               VPGN->getVectorLength()},
7350                              VPGN->getMemOperand(), NewIndexTy);
7351     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7352       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7353                               {VPSN->getChain(), VPSN->getValue(),
7354                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7355                                VPSN->getMask(), VPSN->getVectorLength()},
7356                               VPSN->getMemOperand(), NewIndexTy);
7357     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7358       return DAG.getMaskedGather(
7359           N->getVTList(), MGN->getMemoryVT(), DL,
7360           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7361            MGN->getBasePtr(), Index, MGN->getScale()},
7362           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7363     const auto *MSN = cast<MaskedScatterSDNode>(N);
7364     return DAG.getMaskedScatter(
7365         N->getVTList(), MSN->getMemoryVT(), DL,
7366         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7367          Index, MSN->getScale()},
7368         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7369   }
7370   case RISCVISD::SRA_VL:
7371   case RISCVISD::SRL_VL:
7372   case RISCVISD::SHL_VL: {
7373     SDValue ShAmt = N->getOperand(1);
7374     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7375       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7376       SDLoc DL(N);
7377       SDValue VL = N->getOperand(3);
7378       EVT VT = N->getValueType(0);
7379       ShAmt =
7380           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7381       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7382                          N->getOperand(2), N->getOperand(3));
7383     }
7384     break;
7385   }
7386   case ISD::SRA:
7387   case ISD::SRL:
7388   case ISD::SHL: {
7389     SDValue ShAmt = N->getOperand(1);
7390     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7391       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7392       SDLoc DL(N);
7393       EVT VT = N->getValueType(0);
7394       ShAmt =
7395           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7396       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7397     }
7398     break;
7399   }
7400   case RISCVISD::MUL_VL: {
7401     SDValue Op0 = N->getOperand(0);
7402     SDValue Op1 = N->getOperand(1);
7403     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7404       return V;
7405     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7406       return V;
7407     return SDValue();
7408   }
7409   case ISD::STORE: {
7410     auto *Store = cast<StoreSDNode>(N);
7411     SDValue Val = Store->getValue();
7412     // Combine store of vmv.x.s to vse with VL of 1.
7413     // FIXME: Support FP.
7414     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7415       SDValue Src = Val.getOperand(0);
7416       EVT VecVT = Src.getValueType();
7417       EVT MemVT = Store->getMemoryVT();
7418       // The memory VT and the element type must match.
7419       if (VecVT.getVectorElementType() == MemVT) {
7420         SDLoc DL(N);
7421         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7422         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7423                               DAG.getConstant(1, DL, MaskVT),
7424                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7425                               Store->getPointerInfo(),
7426                               Store->getOriginalAlign(),
7427                               Store->getMemOperand()->getFlags());
7428       }
7429     }
7430 
7431     break;
7432   }
7433   }
7434 
7435   return SDValue();
7436 }
7437 
7438 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7439     const SDNode *N, CombineLevel Level) const {
7440   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7441   // materialised in fewer instructions than `(OP _, c1)`:
7442   //
7443   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7444   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7445   SDValue N0 = N->getOperand(0);
7446   EVT Ty = N0.getValueType();
7447   if (Ty.isScalarInteger() &&
7448       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7449     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7450     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7451     if (C1 && C2) {
7452       const APInt &C1Int = C1->getAPIntValue();
7453       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7454 
7455       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7456       // and the combine should happen, to potentially allow further combines
7457       // later.
7458       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7459           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7460         return true;
7461 
7462       // We can materialise `c1` in an add immediate, so it's "free", and the
7463       // combine should be prevented.
7464       if (C1Int.getMinSignedBits() <= 64 &&
7465           isLegalAddImmediate(C1Int.getSExtValue()))
7466         return false;
7467 
7468       // Neither constant will fit into an immediate, so find materialisation
7469       // costs.
7470       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7471                                               Subtarget.getFeatureBits(),
7472                                               /*CompressionCost*/true);
7473       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7474           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7475           /*CompressionCost*/true);
7476 
7477       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7478       // combine should be prevented.
7479       if (C1Cost < ShiftedC1Cost)
7480         return false;
7481     }
7482   }
7483   return true;
7484 }
7485 
7486 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7487     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7488     TargetLoweringOpt &TLO) const {
7489   // Delay this optimization as late as possible.
7490   if (!TLO.LegalOps)
7491     return false;
7492 
7493   EVT VT = Op.getValueType();
7494   if (VT.isVector())
7495     return false;
7496 
7497   // Only handle AND for now.
7498   if (Op.getOpcode() != ISD::AND)
7499     return false;
7500 
7501   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7502   if (!C)
7503     return false;
7504 
7505   const APInt &Mask = C->getAPIntValue();
7506 
7507   // Clear all non-demanded bits initially.
7508   APInt ShrunkMask = Mask & DemandedBits;
7509 
7510   // Try to make a smaller immediate by setting undemanded bits.
7511 
7512   APInt ExpandedMask = Mask | ~DemandedBits;
7513 
7514   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7515     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7516   };
7517   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7518     if (NewMask == Mask)
7519       return true;
7520     SDLoc DL(Op);
7521     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7522     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7523     return TLO.CombineTo(Op, NewOp);
7524   };
7525 
7526   // If the shrunk mask fits in sign extended 12 bits, let the target
7527   // independent code apply it.
7528   if (ShrunkMask.isSignedIntN(12))
7529     return false;
7530 
7531   // Preserve (and X, 0xffff) when zext.h is supported.
7532   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7533     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7534     if (IsLegalMask(NewMask))
7535       return UseMask(NewMask);
7536   }
7537 
7538   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7539   if (VT == MVT::i64) {
7540     APInt NewMask = APInt(64, 0xffffffff);
7541     if (IsLegalMask(NewMask))
7542       return UseMask(NewMask);
7543   }
7544 
7545   // For the remaining optimizations, we need to be able to make a negative
7546   // number through a combination of mask and undemanded bits.
7547   if (!ExpandedMask.isNegative())
7548     return false;
7549 
7550   // What is the fewest number of bits we need to represent the negative number.
7551   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7552 
7553   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7554   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7555   APInt NewMask = ShrunkMask;
7556   if (MinSignedBits <= 12)
7557     NewMask.setBitsFrom(11);
7558   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7559     NewMask.setBitsFrom(31);
7560   else
7561     return false;
7562 
7563   // Check that our new mask is a subset of the demanded mask.
7564   assert(IsLegalMask(NewMask));
7565   return UseMask(NewMask);
7566 }
7567 
7568 static void computeGREV(APInt &Src, unsigned ShAmt) {
7569   ShAmt &= Src.getBitWidth() - 1;
7570   uint64_t x = Src.getZExtValue();
7571   if (ShAmt & 1)
7572     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7573   if (ShAmt & 2)
7574     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7575   if (ShAmt & 4)
7576     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7577   if (ShAmt & 8)
7578     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7579   if (ShAmt & 16)
7580     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7581   if (ShAmt & 32)
7582     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7583   Src = x;
7584 }
7585 
7586 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7587                                                         KnownBits &Known,
7588                                                         const APInt &DemandedElts,
7589                                                         const SelectionDAG &DAG,
7590                                                         unsigned Depth) const {
7591   unsigned BitWidth = Known.getBitWidth();
7592   unsigned Opc = Op.getOpcode();
7593   assert((Opc >= ISD::BUILTIN_OP_END ||
7594           Opc == ISD::INTRINSIC_WO_CHAIN ||
7595           Opc == ISD::INTRINSIC_W_CHAIN ||
7596           Opc == ISD::INTRINSIC_VOID) &&
7597          "Should use MaskedValueIsZero if you don't know whether Op"
7598          " is a target node!");
7599 
7600   Known.resetAll();
7601   switch (Opc) {
7602   default: break;
7603   case RISCVISD::SELECT_CC: {
7604     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7605     // If we don't know any bits, early out.
7606     if (Known.isUnknown())
7607       break;
7608     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7609 
7610     // Only known if known in both the LHS and RHS.
7611     Known = KnownBits::commonBits(Known, Known2);
7612     break;
7613   }
7614   case RISCVISD::REMUW: {
7615     KnownBits Known2;
7616     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7617     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7618     // We only care about the lower 32 bits.
7619     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7620     // Restore the original width by sign extending.
7621     Known = Known.sext(BitWidth);
7622     break;
7623   }
7624   case RISCVISD::DIVUW: {
7625     KnownBits Known2;
7626     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7627     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7628     // We only care about the lower 32 bits.
7629     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7630     // Restore the original width by sign extending.
7631     Known = Known.sext(BitWidth);
7632     break;
7633   }
7634   case RISCVISD::CTZW: {
7635     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7636     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7637     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7638     Known.Zero.setBitsFrom(LowBits);
7639     break;
7640   }
7641   case RISCVISD::CLZW: {
7642     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7643     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7644     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7645     Known.Zero.setBitsFrom(LowBits);
7646     break;
7647   }
7648   case RISCVISD::GREV:
7649   case RISCVISD::GREVW: {
7650     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7651       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7652       if (Opc == RISCVISD::GREVW)
7653         Known = Known.trunc(32);
7654       unsigned ShAmt = C->getZExtValue();
7655       computeGREV(Known.Zero, ShAmt);
7656       computeGREV(Known.One, ShAmt);
7657       if (Opc == RISCVISD::GREVW)
7658         Known = Known.sext(BitWidth);
7659     }
7660     break;
7661   }
7662   case RISCVISD::READ_VLENB:
7663     // We assume VLENB is at least 16 bytes.
7664     Known.Zero.setLowBits(4);
7665     // We assume VLENB is no more than 65536 / 8 bytes.
7666     Known.Zero.setBitsFrom(14);
7667     break;
7668   case ISD::INTRINSIC_W_CHAIN: {
7669     unsigned IntNo = Op.getConstantOperandVal(1);
7670     switch (IntNo) {
7671     default:
7672       // We can't do anything for most intrinsics.
7673       break;
7674     case Intrinsic::riscv_vsetvli:
7675     case Intrinsic::riscv_vsetvlimax:
7676       // Assume that VL output is positive and would fit in an int32_t.
7677       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7678       if (BitWidth >= 32)
7679         Known.Zero.setBitsFrom(31);
7680       break;
7681     }
7682     break;
7683   }
7684   }
7685 }
7686 
7687 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7688     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7689     unsigned Depth) const {
7690   switch (Op.getOpcode()) {
7691   default:
7692     break;
7693   case RISCVISD::SELECT_CC: {
7694     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7695     if (Tmp == 1) return 1;  // Early out.
7696     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7697     return std::min(Tmp, Tmp2);
7698   }
7699   case RISCVISD::SLLW:
7700   case RISCVISD::SRAW:
7701   case RISCVISD::SRLW:
7702   case RISCVISD::DIVW:
7703   case RISCVISD::DIVUW:
7704   case RISCVISD::REMUW:
7705   case RISCVISD::ROLW:
7706   case RISCVISD::RORW:
7707   case RISCVISD::GREVW:
7708   case RISCVISD::GORCW:
7709   case RISCVISD::FSLW:
7710   case RISCVISD::FSRW:
7711   case RISCVISD::SHFLW:
7712   case RISCVISD::UNSHFLW:
7713   case RISCVISD::BCOMPRESSW:
7714   case RISCVISD::BDECOMPRESSW:
7715   case RISCVISD::FCVT_W_RTZ_RV64:
7716   case RISCVISD::FCVT_WU_RTZ_RV64:
7717     // TODO: As the result is sign-extended, this is conservatively correct. A
7718     // more precise answer could be calculated for SRAW depending on known
7719     // bits in the shift amount.
7720     return 33;
7721   case RISCVISD::SHFL:
7722   case RISCVISD::UNSHFL: {
7723     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7724     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7725     // will stay within the upper 32 bits. If there were more than 32 sign bits
7726     // before there will be at least 33 sign bits after.
7727     if (Op.getValueType() == MVT::i64 &&
7728         isa<ConstantSDNode>(Op.getOperand(1)) &&
7729         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7730       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7731       if (Tmp > 32)
7732         return 33;
7733     }
7734     break;
7735   }
7736   case RISCVISD::VMV_X_S:
7737     // The number of sign bits of the scalar result is computed by obtaining the
7738     // element type of the input vector operand, subtracting its width from the
7739     // XLEN, and then adding one (sign bit within the element type). If the
7740     // element type is wider than XLen, the least-significant XLEN bits are
7741     // taken.
7742     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7743       return 1;
7744     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7745   }
7746 
7747   return 1;
7748 }
7749 
7750 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7751                                                   MachineBasicBlock *BB) {
7752   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7753 
7754   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7755   // Should the count have wrapped while it was being read, we need to try
7756   // again.
7757   // ...
7758   // read:
7759   // rdcycleh x3 # load high word of cycle
7760   // rdcycle  x2 # load low word of cycle
7761   // rdcycleh x4 # load high word of cycle
7762   // bne x3, x4, read # check if high word reads match, otherwise try again
7763   // ...
7764 
7765   MachineFunction &MF = *BB->getParent();
7766   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7767   MachineFunction::iterator It = ++BB->getIterator();
7768 
7769   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7770   MF.insert(It, LoopMBB);
7771 
7772   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7773   MF.insert(It, DoneMBB);
7774 
7775   // Transfer the remainder of BB and its successor edges to DoneMBB.
7776   DoneMBB->splice(DoneMBB->begin(), BB,
7777                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7778   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7779 
7780   BB->addSuccessor(LoopMBB);
7781 
7782   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7783   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7784   Register LoReg = MI.getOperand(0).getReg();
7785   Register HiReg = MI.getOperand(1).getReg();
7786   DebugLoc DL = MI.getDebugLoc();
7787 
7788   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7789   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7790       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7791       .addReg(RISCV::X0);
7792   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7793       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7794       .addReg(RISCV::X0);
7795   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7796       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7797       .addReg(RISCV::X0);
7798 
7799   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7800       .addReg(HiReg)
7801       .addReg(ReadAgainReg)
7802       .addMBB(LoopMBB);
7803 
7804   LoopMBB->addSuccessor(LoopMBB);
7805   LoopMBB->addSuccessor(DoneMBB);
7806 
7807   MI.eraseFromParent();
7808 
7809   return DoneMBB;
7810 }
7811 
7812 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7813                                              MachineBasicBlock *BB) {
7814   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7815 
7816   MachineFunction &MF = *BB->getParent();
7817   DebugLoc DL = MI.getDebugLoc();
7818   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7819   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7820   Register LoReg = MI.getOperand(0).getReg();
7821   Register HiReg = MI.getOperand(1).getReg();
7822   Register SrcReg = MI.getOperand(2).getReg();
7823   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7824   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7825 
7826   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7827                           RI);
7828   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7829   MachineMemOperand *MMOLo =
7830       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7831   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7832       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7833   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7834       .addFrameIndex(FI)
7835       .addImm(0)
7836       .addMemOperand(MMOLo);
7837   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7838       .addFrameIndex(FI)
7839       .addImm(4)
7840       .addMemOperand(MMOHi);
7841   MI.eraseFromParent(); // The pseudo instruction is gone now.
7842   return BB;
7843 }
7844 
7845 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7846                                                  MachineBasicBlock *BB) {
7847   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7848          "Unexpected instruction");
7849 
7850   MachineFunction &MF = *BB->getParent();
7851   DebugLoc DL = MI.getDebugLoc();
7852   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7853   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7854   Register DstReg = MI.getOperand(0).getReg();
7855   Register LoReg = MI.getOperand(1).getReg();
7856   Register HiReg = MI.getOperand(2).getReg();
7857   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7858   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7859 
7860   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7861   MachineMemOperand *MMOLo =
7862       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7863   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7864       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7865   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7866       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7867       .addFrameIndex(FI)
7868       .addImm(0)
7869       .addMemOperand(MMOLo);
7870   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7871       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7872       .addFrameIndex(FI)
7873       .addImm(4)
7874       .addMemOperand(MMOHi);
7875   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7876   MI.eraseFromParent(); // The pseudo instruction is gone now.
7877   return BB;
7878 }
7879 
7880 static bool isSelectPseudo(MachineInstr &MI) {
7881   switch (MI.getOpcode()) {
7882   default:
7883     return false;
7884   case RISCV::Select_GPR_Using_CC_GPR:
7885   case RISCV::Select_FPR16_Using_CC_GPR:
7886   case RISCV::Select_FPR32_Using_CC_GPR:
7887   case RISCV::Select_FPR64_Using_CC_GPR:
7888     return true;
7889   }
7890 }
7891 
7892 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7893                                            MachineBasicBlock *BB,
7894                                            const RISCVSubtarget &Subtarget) {
7895   // To "insert" Select_* instructions, we actually have to insert the triangle
7896   // control-flow pattern.  The incoming instructions know the destination vreg
7897   // to set, the condition code register to branch on, the true/false values to
7898   // select between, and the condcode to use to select the appropriate branch.
7899   //
7900   // We produce the following control flow:
7901   //     HeadMBB
7902   //     |  \
7903   //     |  IfFalseMBB
7904   //     | /
7905   //    TailMBB
7906   //
7907   // When we find a sequence of selects we attempt to optimize their emission
7908   // by sharing the control flow. Currently we only handle cases where we have
7909   // multiple selects with the exact same condition (same LHS, RHS and CC).
7910   // The selects may be interleaved with other instructions if the other
7911   // instructions meet some requirements we deem safe:
7912   // - They are debug instructions. Otherwise,
7913   // - They do not have side-effects, do not access memory and their inputs do
7914   //   not depend on the results of the select pseudo-instructions.
7915   // The TrueV/FalseV operands of the selects cannot depend on the result of
7916   // previous selects in the sequence.
7917   // These conditions could be further relaxed. See the X86 target for a
7918   // related approach and more information.
7919   Register LHS = MI.getOperand(1).getReg();
7920   Register RHS = MI.getOperand(2).getReg();
7921   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7922 
7923   SmallVector<MachineInstr *, 4> SelectDebugValues;
7924   SmallSet<Register, 4> SelectDests;
7925   SelectDests.insert(MI.getOperand(0).getReg());
7926 
7927   MachineInstr *LastSelectPseudo = &MI;
7928 
7929   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7930        SequenceMBBI != E; ++SequenceMBBI) {
7931     if (SequenceMBBI->isDebugInstr())
7932       continue;
7933     else if (isSelectPseudo(*SequenceMBBI)) {
7934       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7935           SequenceMBBI->getOperand(2).getReg() != RHS ||
7936           SequenceMBBI->getOperand(3).getImm() != CC ||
7937           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7938           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7939         break;
7940       LastSelectPseudo = &*SequenceMBBI;
7941       SequenceMBBI->collectDebugValues(SelectDebugValues);
7942       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7943     } else {
7944       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7945           SequenceMBBI->mayLoadOrStore())
7946         break;
7947       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7948             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7949           }))
7950         break;
7951     }
7952   }
7953 
7954   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7955   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7956   DebugLoc DL = MI.getDebugLoc();
7957   MachineFunction::iterator I = ++BB->getIterator();
7958 
7959   MachineBasicBlock *HeadMBB = BB;
7960   MachineFunction *F = BB->getParent();
7961   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7962   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7963 
7964   F->insert(I, IfFalseMBB);
7965   F->insert(I, TailMBB);
7966 
7967   // Transfer debug instructions associated with the selects to TailMBB.
7968   for (MachineInstr *DebugInstr : SelectDebugValues) {
7969     TailMBB->push_back(DebugInstr->removeFromParent());
7970   }
7971 
7972   // Move all instructions after the sequence to TailMBB.
7973   TailMBB->splice(TailMBB->end(), HeadMBB,
7974                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7975   // Update machine-CFG edges by transferring all successors of the current
7976   // block to the new block which will contain the Phi nodes for the selects.
7977   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7978   // Set the successors for HeadMBB.
7979   HeadMBB->addSuccessor(IfFalseMBB);
7980   HeadMBB->addSuccessor(TailMBB);
7981 
7982   // Insert appropriate branch.
7983   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7984     .addReg(LHS)
7985     .addReg(RHS)
7986     .addMBB(TailMBB);
7987 
7988   // IfFalseMBB just falls through to TailMBB.
7989   IfFalseMBB->addSuccessor(TailMBB);
7990 
7991   // Create PHIs for all of the select pseudo-instructions.
7992   auto SelectMBBI = MI.getIterator();
7993   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7994   auto InsertionPoint = TailMBB->begin();
7995   while (SelectMBBI != SelectEnd) {
7996     auto Next = std::next(SelectMBBI);
7997     if (isSelectPseudo(*SelectMBBI)) {
7998       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7999       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8000               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8001           .addReg(SelectMBBI->getOperand(4).getReg())
8002           .addMBB(HeadMBB)
8003           .addReg(SelectMBBI->getOperand(5).getReg())
8004           .addMBB(IfFalseMBB);
8005       SelectMBBI->eraseFromParent();
8006     }
8007     SelectMBBI = Next;
8008   }
8009 
8010   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8011   return TailMBB;
8012 }
8013 
8014 MachineBasicBlock *
8015 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8016                                                  MachineBasicBlock *BB) const {
8017   switch (MI.getOpcode()) {
8018   default:
8019     llvm_unreachable("Unexpected instr type to insert");
8020   case RISCV::ReadCycleWide:
8021     assert(!Subtarget.is64Bit() &&
8022            "ReadCycleWrite is only to be used on riscv32");
8023     return emitReadCycleWidePseudo(MI, BB);
8024   case RISCV::Select_GPR_Using_CC_GPR:
8025   case RISCV::Select_FPR16_Using_CC_GPR:
8026   case RISCV::Select_FPR32_Using_CC_GPR:
8027   case RISCV::Select_FPR64_Using_CC_GPR:
8028     return emitSelectPseudo(MI, BB, Subtarget);
8029   case RISCV::BuildPairF64Pseudo:
8030     return emitBuildPairF64Pseudo(MI, BB);
8031   case RISCV::SplitF64Pseudo:
8032     return emitSplitF64Pseudo(MI, BB);
8033   }
8034 }
8035 
8036 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8037                                                         SDNode *Node) const {
8038   // Add FRM dependency to any instructions with dynamic rounding mode.
8039   unsigned Opc = MI.getOpcode();
8040   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8041   if (Idx < 0)
8042     return;
8043   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8044     return;
8045   // If the instruction already reads FRM, don't add another read.
8046   if (MI.readsRegister(RISCV::FRM))
8047     return;
8048   MI.addOperand(
8049       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8050 }
8051 
8052 // Calling Convention Implementation.
8053 // The expectations for frontend ABI lowering vary from target to target.
8054 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8055 // details, but this is a longer term goal. For now, we simply try to keep the
8056 // role of the frontend as simple and well-defined as possible. The rules can
8057 // be summarised as:
8058 // * Never split up large scalar arguments. We handle them here.
8059 // * If a hardfloat calling convention is being used, and the struct may be
8060 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8061 // available, then pass as two separate arguments. If either the GPRs or FPRs
8062 // are exhausted, then pass according to the rule below.
8063 // * If a struct could never be passed in registers or directly in a stack
8064 // slot (as it is larger than 2*XLEN and the floating point rules don't
8065 // apply), then pass it using a pointer with the byval attribute.
8066 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8067 // word-sized array or a 2*XLEN scalar (depending on alignment).
8068 // * The frontend can determine whether a struct is returned by reference or
8069 // not based on its size and fields. If it will be returned by reference, the
8070 // frontend must modify the prototype so a pointer with the sret annotation is
8071 // passed as the first argument. This is not necessary for large scalar
8072 // returns.
8073 // * Struct return values and varargs should be coerced to structs containing
8074 // register-size fields in the same situations they would be for fixed
8075 // arguments.
8076 
8077 static const MCPhysReg ArgGPRs[] = {
8078   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8079   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8080 };
8081 static const MCPhysReg ArgFPR16s[] = {
8082   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8083   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8084 };
8085 static const MCPhysReg ArgFPR32s[] = {
8086   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8087   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8088 };
8089 static const MCPhysReg ArgFPR64s[] = {
8090   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8091   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8092 };
8093 // This is an interim calling convention and it may be changed in the future.
8094 static const MCPhysReg ArgVRs[] = {
8095     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8096     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8097     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8098 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8099                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8100                                      RISCV::V20M2, RISCV::V22M2};
8101 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8102                                      RISCV::V20M4};
8103 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8104 
8105 // Pass a 2*XLEN argument that has been split into two XLEN values through
8106 // registers or the stack as necessary.
8107 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8108                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8109                                 MVT ValVT2, MVT LocVT2,
8110                                 ISD::ArgFlagsTy ArgFlags2) {
8111   unsigned XLenInBytes = XLen / 8;
8112   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8113     // At least one half can be passed via register.
8114     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8115                                      VA1.getLocVT(), CCValAssign::Full));
8116   } else {
8117     // Both halves must be passed on the stack, with proper alignment.
8118     Align StackAlign =
8119         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8120     State.addLoc(
8121         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8122                             State.AllocateStack(XLenInBytes, StackAlign),
8123                             VA1.getLocVT(), CCValAssign::Full));
8124     State.addLoc(CCValAssign::getMem(
8125         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8126         LocVT2, CCValAssign::Full));
8127     return false;
8128   }
8129 
8130   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8131     // The second half can also be passed via register.
8132     State.addLoc(
8133         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8134   } else {
8135     // The second half is passed via the stack, without additional alignment.
8136     State.addLoc(CCValAssign::getMem(
8137         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8138         LocVT2, CCValAssign::Full));
8139   }
8140 
8141   return false;
8142 }
8143 
8144 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8145                                Optional<unsigned> FirstMaskArgument,
8146                                CCState &State, const RISCVTargetLowering &TLI) {
8147   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8148   if (RC == &RISCV::VRRegClass) {
8149     // Assign the first mask argument to V0.
8150     // This is an interim calling convention and it may be changed in the
8151     // future.
8152     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8153       return State.AllocateReg(RISCV::V0);
8154     return State.AllocateReg(ArgVRs);
8155   }
8156   if (RC == &RISCV::VRM2RegClass)
8157     return State.AllocateReg(ArgVRM2s);
8158   if (RC == &RISCV::VRM4RegClass)
8159     return State.AllocateReg(ArgVRM4s);
8160   if (RC == &RISCV::VRM8RegClass)
8161     return State.AllocateReg(ArgVRM8s);
8162   llvm_unreachable("Unhandled register class for ValueType");
8163 }
8164 
8165 // Implements the RISC-V calling convention. Returns true upon failure.
8166 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8167                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8168                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8169                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8170                      Optional<unsigned> FirstMaskArgument) {
8171   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8172   assert(XLen == 32 || XLen == 64);
8173   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8174 
8175   // Any return value split in to more than two values can't be returned
8176   // directly. Vectors are returned via the available vector registers.
8177   if (!LocVT.isVector() && IsRet && ValNo > 1)
8178     return true;
8179 
8180   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8181   // variadic argument, or if no F16/F32 argument registers are available.
8182   bool UseGPRForF16_F32 = true;
8183   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8184   // variadic argument, or if no F64 argument registers are available.
8185   bool UseGPRForF64 = true;
8186 
8187   switch (ABI) {
8188   default:
8189     llvm_unreachable("Unexpected ABI");
8190   case RISCVABI::ABI_ILP32:
8191   case RISCVABI::ABI_LP64:
8192     break;
8193   case RISCVABI::ABI_ILP32F:
8194   case RISCVABI::ABI_LP64F:
8195     UseGPRForF16_F32 = !IsFixed;
8196     break;
8197   case RISCVABI::ABI_ILP32D:
8198   case RISCVABI::ABI_LP64D:
8199     UseGPRForF16_F32 = !IsFixed;
8200     UseGPRForF64 = !IsFixed;
8201     break;
8202   }
8203 
8204   // FPR16, FPR32, and FPR64 alias each other.
8205   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8206     UseGPRForF16_F32 = true;
8207     UseGPRForF64 = true;
8208   }
8209 
8210   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8211   // similar local variables rather than directly checking against the target
8212   // ABI.
8213 
8214   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8215     LocVT = XLenVT;
8216     LocInfo = CCValAssign::BCvt;
8217   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8218     LocVT = MVT::i64;
8219     LocInfo = CCValAssign::BCvt;
8220   }
8221 
8222   // If this is a variadic argument, the RISC-V calling convention requires
8223   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8224   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8225   // be used regardless of whether the original argument was split during
8226   // legalisation or not. The argument will not be passed by registers if the
8227   // original type is larger than 2*XLEN, so the register alignment rule does
8228   // not apply.
8229   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8230   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8231       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8232     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8233     // Skip 'odd' register if necessary.
8234     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8235       State.AllocateReg(ArgGPRs);
8236   }
8237 
8238   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8239   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8240       State.getPendingArgFlags();
8241 
8242   assert(PendingLocs.size() == PendingArgFlags.size() &&
8243          "PendingLocs and PendingArgFlags out of sync");
8244 
8245   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8246   // registers are exhausted.
8247   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8248     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8249            "Can't lower f64 if it is split");
8250     // Depending on available argument GPRS, f64 may be passed in a pair of
8251     // GPRs, split between a GPR and the stack, or passed completely on the
8252     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8253     // cases.
8254     Register Reg = State.AllocateReg(ArgGPRs);
8255     LocVT = MVT::i32;
8256     if (!Reg) {
8257       unsigned StackOffset = State.AllocateStack(8, Align(8));
8258       State.addLoc(
8259           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8260       return false;
8261     }
8262     if (!State.AllocateReg(ArgGPRs))
8263       State.AllocateStack(4, Align(4));
8264     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8265     return false;
8266   }
8267 
8268   // Fixed-length vectors are located in the corresponding scalable-vector
8269   // container types.
8270   if (ValVT.isFixedLengthVector())
8271     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8272 
8273   // Split arguments might be passed indirectly, so keep track of the pending
8274   // values. Split vectors are passed via a mix of registers and indirectly, so
8275   // treat them as we would any other argument.
8276   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8277     LocVT = XLenVT;
8278     LocInfo = CCValAssign::Indirect;
8279     PendingLocs.push_back(
8280         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8281     PendingArgFlags.push_back(ArgFlags);
8282     if (!ArgFlags.isSplitEnd()) {
8283       return false;
8284     }
8285   }
8286 
8287   // If the split argument only had two elements, it should be passed directly
8288   // in registers or on the stack.
8289   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8290       PendingLocs.size() <= 2) {
8291     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8292     // Apply the normal calling convention rules to the first half of the
8293     // split argument.
8294     CCValAssign VA = PendingLocs[0];
8295     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8296     PendingLocs.clear();
8297     PendingArgFlags.clear();
8298     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8299                                ArgFlags);
8300   }
8301 
8302   // Allocate to a register if possible, or else a stack slot.
8303   Register Reg;
8304   unsigned StoreSizeBytes = XLen / 8;
8305   Align StackAlign = Align(XLen / 8);
8306 
8307   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8308     Reg = State.AllocateReg(ArgFPR16s);
8309   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8310     Reg = State.AllocateReg(ArgFPR32s);
8311   else if (ValVT == MVT::f64 && !UseGPRForF64)
8312     Reg = State.AllocateReg(ArgFPR64s);
8313   else if (ValVT.isVector()) {
8314     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8315     if (!Reg) {
8316       // For return values, the vector must be passed fully via registers or
8317       // via the stack.
8318       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8319       // but we're using all of them.
8320       if (IsRet)
8321         return true;
8322       // Try using a GPR to pass the address
8323       if ((Reg = State.AllocateReg(ArgGPRs))) {
8324         LocVT = XLenVT;
8325         LocInfo = CCValAssign::Indirect;
8326       } else if (ValVT.isScalableVector()) {
8327         report_fatal_error("Unable to pass scalable vector types on the stack");
8328       } else {
8329         // Pass fixed-length vectors on the stack.
8330         LocVT = ValVT;
8331         StoreSizeBytes = ValVT.getStoreSize();
8332         // Align vectors to their element sizes, being careful for vXi1
8333         // vectors.
8334         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8335       }
8336     }
8337   } else {
8338     Reg = State.AllocateReg(ArgGPRs);
8339   }
8340 
8341   unsigned StackOffset =
8342       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8343 
8344   // If we reach this point and PendingLocs is non-empty, we must be at the
8345   // end of a split argument that must be passed indirectly.
8346   if (!PendingLocs.empty()) {
8347     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8348     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8349 
8350     for (auto &It : PendingLocs) {
8351       if (Reg)
8352         It.convertToReg(Reg);
8353       else
8354         It.convertToMem(StackOffset);
8355       State.addLoc(It);
8356     }
8357     PendingLocs.clear();
8358     PendingArgFlags.clear();
8359     return false;
8360   }
8361 
8362   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8363           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8364          "Expected an XLenVT or vector types at this stage");
8365 
8366   if (Reg) {
8367     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8368     return false;
8369   }
8370 
8371   // When a floating-point value is passed on the stack, no bit-conversion is
8372   // needed.
8373   if (ValVT.isFloatingPoint()) {
8374     LocVT = ValVT;
8375     LocInfo = CCValAssign::Full;
8376   }
8377   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8378   return false;
8379 }
8380 
8381 template <typename ArgTy>
8382 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8383   for (const auto &ArgIdx : enumerate(Args)) {
8384     MVT ArgVT = ArgIdx.value().VT;
8385     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8386       return ArgIdx.index();
8387   }
8388   return None;
8389 }
8390 
8391 void RISCVTargetLowering::analyzeInputArgs(
8392     MachineFunction &MF, CCState &CCInfo,
8393     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8394     RISCVCCAssignFn Fn) const {
8395   unsigned NumArgs = Ins.size();
8396   FunctionType *FType = MF.getFunction().getFunctionType();
8397 
8398   Optional<unsigned> FirstMaskArgument;
8399   if (Subtarget.hasVInstructions())
8400     FirstMaskArgument = preAssignMask(Ins);
8401 
8402   for (unsigned i = 0; i != NumArgs; ++i) {
8403     MVT ArgVT = Ins[i].VT;
8404     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8405 
8406     Type *ArgTy = nullptr;
8407     if (IsRet)
8408       ArgTy = FType->getReturnType();
8409     else if (Ins[i].isOrigArg())
8410       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8411 
8412     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8413     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8414            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8415            FirstMaskArgument)) {
8416       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8417                         << EVT(ArgVT).getEVTString() << '\n');
8418       llvm_unreachable(nullptr);
8419     }
8420   }
8421 }
8422 
8423 void RISCVTargetLowering::analyzeOutputArgs(
8424     MachineFunction &MF, CCState &CCInfo,
8425     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8426     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8427   unsigned NumArgs = Outs.size();
8428 
8429   Optional<unsigned> FirstMaskArgument;
8430   if (Subtarget.hasVInstructions())
8431     FirstMaskArgument = preAssignMask(Outs);
8432 
8433   for (unsigned i = 0; i != NumArgs; i++) {
8434     MVT ArgVT = Outs[i].VT;
8435     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8436     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8437 
8438     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8439     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8440            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8441            FirstMaskArgument)) {
8442       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8443                         << EVT(ArgVT).getEVTString() << "\n");
8444       llvm_unreachable(nullptr);
8445     }
8446   }
8447 }
8448 
8449 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8450 // values.
8451 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8452                                    const CCValAssign &VA, const SDLoc &DL,
8453                                    const RISCVSubtarget &Subtarget) {
8454   switch (VA.getLocInfo()) {
8455   default:
8456     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8457   case CCValAssign::Full:
8458     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8459       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8460     break;
8461   case CCValAssign::BCvt:
8462     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8463       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8464     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8465       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8466     else
8467       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8468     break;
8469   }
8470   return Val;
8471 }
8472 
8473 // The caller is responsible for loading the full value if the argument is
8474 // passed with CCValAssign::Indirect.
8475 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8476                                 const CCValAssign &VA, const SDLoc &DL,
8477                                 const RISCVTargetLowering &TLI) {
8478   MachineFunction &MF = DAG.getMachineFunction();
8479   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8480   EVT LocVT = VA.getLocVT();
8481   SDValue Val;
8482   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8483   Register VReg = RegInfo.createVirtualRegister(RC);
8484   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8485   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8486 
8487   if (VA.getLocInfo() == CCValAssign::Indirect)
8488     return Val;
8489 
8490   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8491 }
8492 
8493 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8494                                    const CCValAssign &VA, const SDLoc &DL,
8495                                    const RISCVSubtarget &Subtarget) {
8496   EVT LocVT = VA.getLocVT();
8497 
8498   switch (VA.getLocInfo()) {
8499   default:
8500     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8501   case CCValAssign::Full:
8502     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8503       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8504     break;
8505   case CCValAssign::BCvt:
8506     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8507       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8508     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8509       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8510     else
8511       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8512     break;
8513   }
8514   return Val;
8515 }
8516 
8517 // The caller is responsible for loading the full value if the argument is
8518 // passed with CCValAssign::Indirect.
8519 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8520                                 const CCValAssign &VA, const SDLoc &DL) {
8521   MachineFunction &MF = DAG.getMachineFunction();
8522   MachineFrameInfo &MFI = MF.getFrameInfo();
8523   EVT LocVT = VA.getLocVT();
8524   EVT ValVT = VA.getValVT();
8525   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8526   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8527                                  /*Immutable=*/true);
8528   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8529   SDValue Val;
8530 
8531   ISD::LoadExtType ExtType;
8532   switch (VA.getLocInfo()) {
8533   default:
8534     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8535   case CCValAssign::Full:
8536   case CCValAssign::Indirect:
8537   case CCValAssign::BCvt:
8538     ExtType = ISD::NON_EXTLOAD;
8539     break;
8540   }
8541   Val = DAG.getExtLoad(
8542       ExtType, DL, LocVT, Chain, FIN,
8543       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8544   return Val;
8545 }
8546 
8547 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8548                                        const CCValAssign &VA, const SDLoc &DL) {
8549   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8550          "Unexpected VA");
8551   MachineFunction &MF = DAG.getMachineFunction();
8552   MachineFrameInfo &MFI = MF.getFrameInfo();
8553   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8554 
8555   if (VA.isMemLoc()) {
8556     // f64 is passed on the stack.
8557     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8558     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8559     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8560                        MachinePointerInfo::getFixedStack(MF, FI));
8561   }
8562 
8563   assert(VA.isRegLoc() && "Expected register VA assignment");
8564 
8565   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8566   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8567   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8568   SDValue Hi;
8569   if (VA.getLocReg() == RISCV::X17) {
8570     // Second half of f64 is passed on the stack.
8571     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8572     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8573     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8574                      MachinePointerInfo::getFixedStack(MF, FI));
8575   } else {
8576     // Second half of f64 is passed in another GPR.
8577     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8578     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8579     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8580   }
8581   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8582 }
8583 
8584 // FastCC has less than 1% performance improvement for some particular
8585 // benchmark. But theoretically, it may has benenfit for some cases.
8586 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8587                             unsigned ValNo, MVT ValVT, MVT LocVT,
8588                             CCValAssign::LocInfo LocInfo,
8589                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8590                             bool IsFixed, bool IsRet, Type *OrigTy,
8591                             const RISCVTargetLowering &TLI,
8592                             Optional<unsigned> FirstMaskArgument) {
8593 
8594   // X5 and X6 might be used for save-restore libcall.
8595   static const MCPhysReg GPRList[] = {
8596       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8597       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8598       RISCV::X29, RISCV::X30, RISCV::X31};
8599 
8600   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8601     if (unsigned Reg = State.AllocateReg(GPRList)) {
8602       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8603       return false;
8604     }
8605   }
8606 
8607   if (LocVT == MVT::f16) {
8608     static const MCPhysReg FPR16List[] = {
8609         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8610         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8611         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8612         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8613     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8614       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8615       return false;
8616     }
8617   }
8618 
8619   if (LocVT == MVT::f32) {
8620     static const MCPhysReg FPR32List[] = {
8621         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8622         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8623         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8624         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8625     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8626       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8627       return false;
8628     }
8629   }
8630 
8631   if (LocVT == MVT::f64) {
8632     static const MCPhysReg FPR64List[] = {
8633         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8634         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8635         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8636         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8637     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8638       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8639       return false;
8640     }
8641   }
8642 
8643   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8644     unsigned Offset4 = State.AllocateStack(4, Align(4));
8645     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8646     return false;
8647   }
8648 
8649   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8650     unsigned Offset5 = State.AllocateStack(8, Align(8));
8651     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8652     return false;
8653   }
8654 
8655   if (LocVT.isVector()) {
8656     if (unsigned Reg =
8657             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8658       // Fixed-length vectors are located in the corresponding scalable-vector
8659       // container types.
8660       if (ValVT.isFixedLengthVector())
8661         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8662       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8663     } else {
8664       // Try and pass the address via a "fast" GPR.
8665       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8666         LocInfo = CCValAssign::Indirect;
8667         LocVT = TLI.getSubtarget().getXLenVT();
8668         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8669       } else if (ValVT.isFixedLengthVector()) {
8670         auto StackAlign =
8671             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8672         unsigned StackOffset =
8673             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8674         State.addLoc(
8675             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8676       } else {
8677         // Can't pass scalable vectors on the stack.
8678         return true;
8679       }
8680     }
8681 
8682     return false;
8683   }
8684 
8685   return true; // CC didn't match.
8686 }
8687 
8688 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8689                          CCValAssign::LocInfo LocInfo,
8690                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8691 
8692   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8693     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8694     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8695     static const MCPhysReg GPRList[] = {
8696         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8697         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8698     if (unsigned Reg = State.AllocateReg(GPRList)) {
8699       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8700       return false;
8701     }
8702   }
8703 
8704   if (LocVT == MVT::f32) {
8705     // Pass in STG registers: F1, ..., F6
8706     //                        fs0 ... fs5
8707     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8708                                           RISCV::F18_F, RISCV::F19_F,
8709                                           RISCV::F20_F, RISCV::F21_F};
8710     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8711       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8712       return false;
8713     }
8714   }
8715 
8716   if (LocVT == MVT::f64) {
8717     // Pass in STG registers: D1, ..., D6
8718     //                        fs6 ... fs11
8719     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8720                                           RISCV::F24_D, RISCV::F25_D,
8721                                           RISCV::F26_D, RISCV::F27_D};
8722     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8723       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8724       return false;
8725     }
8726   }
8727 
8728   report_fatal_error("No registers left in GHC calling convention");
8729   return true;
8730 }
8731 
8732 // Transform physical registers into virtual registers.
8733 SDValue RISCVTargetLowering::LowerFormalArguments(
8734     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8735     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8736     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8737 
8738   MachineFunction &MF = DAG.getMachineFunction();
8739 
8740   switch (CallConv) {
8741   default:
8742     report_fatal_error("Unsupported calling convention");
8743   case CallingConv::C:
8744   case CallingConv::Fast:
8745     break;
8746   case CallingConv::GHC:
8747     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8748         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8749       report_fatal_error(
8750         "GHC calling convention requires the F and D instruction set extensions");
8751   }
8752 
8753   const Function &Func = MF.getFunction();
8754   if (Func.hasFnAttribute("interrupt")) {
8755     if (!Func.arg_empty())
8756       report_fatal_error(
8757         "Functions with the interrupt attribute cannot have arguments!");
8758 
8759     StringRef Kind =
8760       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8761 
8762     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8763       report_fatal_error(
8764         "Function interrupt attribute argument not supported!");
8765   }
8766 
8767   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8768   MVT XLenVT = Subtarget.getXLenVT();
8769   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8770   // Used with vargs to acumulate store chains.
8771   std::vector<SDValue> OutChains;
8772 
8773   // Assign locations to all of the incoming arguments.
8774   SmallVector<CCValAssign, 16> ArgLocs;
8775   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8776 
8777   if (CallConv == CallingConv::GHC)
8778     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8779   else
8780     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8781                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8782                                                    : CC_RISCV);
8783 
8784   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8785     CCValAssign &VA = ArgLocs[i];
8786     SDValue ArgValue;
8787     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8788     // case.
8789     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8790       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8791     else if (VA.isRegLoc())
8792       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8793     else
8794       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8795 
8796     if (VA.getLocInfo() == CCValAssign::Indirect) {
8797       // If the original argument was split and passed by reference (e.g. i128
8798       // on RV32), we need to load all parts of it here (using the same
8799       // address). Vectors may be partly split to registers and partly to the
8800       // stack, in which case the base address is partly offset and subsequent
8801       // stores are relative to that.
8802       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8803                                    MachinePointerInfo()));
8804       unsigned ArgIndex = Ins[i].OrigArgIndex;
8805       unsigned ArgPartOffset = Ins[i].PartOffset;
8806       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8807       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8808         CCValAssign &PartVA = ArgLocs[i + 1];
8809         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8810         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8811         if (PartVA.getValVT().isScalableVector())
8812           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8813         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8814         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8815                                      MachinePointerInfo()));
8816         ++i;
8817       }
8818       continue;
8819     }
8820     InVals.push_back(ArgValue);
8821   }
8822 
8823   if (IsVarArg) {
8824     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8825     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8826     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8827     MachineFrameInfo &MFI = MF.getFrameInfo();
8828     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8829     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8830 
8831     // Offset of the first variable argument from stack pointer, and size of
8832     // the vararg save area. For now, the varargs save area is either zero or
8833     // large enough to hold a0-a7.
8834     int VaArgOffset, VarArgsSaveSize;
8835 
8836     // If all registers are allocated, then all varargs must be passed on the
8837     // stack and we don't need to save any argregs.
8838     if (ArgRegs.size() == Idx) {
8839       VaArgOffset = CCInfo.getNextStackOffset();
8840       VarArgsSaveSize = 0;
8841     } else {
8842       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8843       VaArgOffset = -VarArgsSaveSize;
8844     }
8845 
8846     // Record the frame index of the first variable argument
8847     // which is a value necessary to VASTART.
8848     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8849     RVFI->setVarArgsFrameIndex(FI);
8850 
8851     // If saving an odd number of registers then create an extra stack slot to
8852     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8853     // offsets to even-numbered registered remain 2*XLEN-aligned.
8854     if (Idx % 2) {
8855       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8856       VarArgsSaveSize += XLenInBytes;
8857     }
8858 
8859     // Copy the integer registers that may have been used for passing varargs
8860     // to the vararg save area.
8861     for (unsigned I = Idx; I < ArgRegs.size();
8862          ++I, VaArgOffset += XLenInBytes) {
8863       const Register Reg = RegInfo.createVirtualRegister(RC);
8864       RegInfo.addLiveIn(ArgRegs[I], Reg);
8865       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8866       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8867       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8868       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8869                                    MachinePointerInfo::getFixedStack(MF, FI));
8870       cast<StoreSDNode>(Store.getNode())
8871           ->getMemOperand()
8872           ->setValue((Value *)nullptr);
8873       OutChains.push_back(Store);
8874     }
8875     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8876   }
8877 
8878   // All stores are grouped in one node to allow the matching between
8879   // the size of Ins and InVals. This only happens for vararg functions.
8880   if (!OutChains.empty()) {
8881     OutChains.push_back(Chain);
8882     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8883   }
8884 
8885   return Chain;
8886 }
8887 
8888 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8889 /// for tail call optimization.
8890 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8891 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8892     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8893     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8894 
8895   auto &Callee = CLI.Callee;
8896   auto CalleeCC = CLI.CallConv;
8897   auto &Outs = CLI.Outs;
8898   auto &Caller = MF.getFunction();
8899   auto CallerCC = Caller.getCallingConv();
8900 
8901   // Exception-handling functions need a special set of instructions to
8902   // indicate a return to the hardware. Tail-calling another function would
8903   // probably break this.
8904   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8905   // should be expanded as new function attributes are introduced.
8906   if (Caller.hasFnAttribute("interrupt"))
8907     return false;
8908 
8909   // Do not tail call opt if the stack is used to pass parameters.
8910   if (CCInfo.getNextStackOffset() != 0)
8911     return false;
8912 
8913   // Do not tail call opt if any parameters need to be passed indirectly.
8914   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8915   // passed indirectly. So the address of the value will be passed in a
8916   // register, or if not available, then the address is put on the stack. In
8917   // order to pass indirectly, space on the stack often needs to be allocated
8918   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8919   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8920   // are passed CCValAssign::Indirect.
8921   for (auto &VA : ArgLocs)
8922     if (VA.getLocInfo() == CCValAssign::Indirect)
8923       return false;
8924 
8925   // Do not tail call opt if either caller or callee uses struct return
8926   // semantics.
8927   auto IsCallerStructRet = Caller.hasStructRetAttr();
8928   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8929   if (IsCallerStructRet || IsCalleeStructRet)
8930     return false;
8931 
8932   // Externally-defined functions with weak linkage should not be
8933   // tail-called. The behaviour of branch instructions in this situation (as
8934   // used for tail calls) is implementation-defined, so we cannot rely on the
8935   // linker replacing the tail call with a return.
8936   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8937     const GlobalValue *GV = G->getGlobal();
8938     if (GV->hasExternalWeakLinkage())
8939       return false;
8940   }
8941 
8942   // The callee has to preserve all registers the caller needs to preserve.
8943   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8944   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8945   if (CalleeCC != CallerCC) {
8946     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8947     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8948       return false;
8949   }
8950 
8951   // Byval parameters hand the function a pointer directly into the stack area
8952   // we want to reuse during a tail call. Working around this *is* possible
8953   // but less efficient and uglier in LowerCall.
8954   for (auto &Arg : Outs)
8955     if (Arg.Flags.isByVal())
8956       return false;
8957 
8958   return true;
8959 }
8960 
8961 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8962   return DAG.getDataLayout().getPrefTypeAlign(
8963       VT.getTypeForEVT(*DAG.getContext()));
8964 }
8965 
8966 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8967 // and output parameter nodes.
8968 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8969                                        SmallVectorImpl<SDValue> &InVals) const {
8970   SelectionDAG &DAG = CLI.DAG;
8971   SDLoc &DL = CLI.DL;
8972   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8973   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8974   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8975   SDValue Chain = CLI.Chain;
8976   SDValue Callee = CLI.Callee;
8977   bool &IsTailCall = CLI.IsTailCall;
8978   CallingConv::ID CallConv = CLI.CallConv;
8979   bool IsVarArg = CLI.IsVarArg;
8980   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8981   MVT XLenVT = Subtarget.getXLenVT();
8982 
8983   MachineFunction &MF = DAG.getMachineFunction();
8984 
8985   // Analyze the operands of the call, assigning locations to each operand.
8986   SmallVector<CCValAssign, 16> ArgLocs;
8987   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8988 
8989   if (CallConv == CallingConv::GHC)
8990     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8991   else
8992     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8993                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8994                                                     : CC_RISCV);
8995 
8996   // Check if it's really possible to do a tail call.
8997   if (IsTailCall)
8998     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8999 
9000   if (IsTailCall)
9001     ++NumTailCalls;
9002   else if (CLI.CB && CLI.CB->isMustTailCall())
9003     report_fatal_error("failed to perform tail call elimination on a call "
9004                        "site marked musttail");
9005 
9006   // Get a count of how many bytes are to be pushed on the stack.
9007   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9008 
9009   // Create local copies for byval args
9010   SmallVector<SDValue, 8> ByValArgs;
9011   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9012     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9013     if (!Flags.isByVal())
9014       continue;
9015 
9016     SDValue Arg = OutVals[i];
9017     unsigned Size = Flags.getByValSize();
9018     Align Alignment = Flags.getNonZeroByValAlign();
9019 
9020     int FI =
9021         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9022     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9023     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9024 
9025     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9026                           /*IsVolatile=*/false,
9027                           /*AlwaysInline=*/false, IsTailCall,
9028                           MachinePointerInfo(), MachinePointerInfo());
9029     ByValArgs.push_back(FIPtr);
9030   }
9031 
9032   if (!IsTailCall)
9033     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9034 
9035   // Copy argument values to their designated locations.
9036   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9037   SmallVector<SDValue, 8> MemOpChains;
9038   SDValue StackPtr;
9039   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9040     CCValAssign &VA = ArgLocs[i];
9041     SDValue ArgValue = OutVals[i];
9042     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9043 
9044     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9045     bool IsF64OnRV32DSoftABI =
9046         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9047     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9048       SDValue SplitF64 = DAG.getNode(
9049           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9050       SDValue Lo = SplitF64.getValue(0);
9051       SDValue Hi = SplitF64.getValue(1);
9052 
9053       Register RegLo = VA.getLocReg();
9054       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9055 
9056       if (RegLo == RISCV::X17) {
9057         // Second half of f64 is passed on the stack.
9058         // Work out the address of the stack slot.
9059         if (!StackPtr.getNode())
9060           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9061         // Emit the store.
9062         MemOpChains.push_back(
9063             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9064       } else {
9065         // Second half of f64 is passed in another GPR.
9066         assert(RegLo < RISCV::X31 && "Invalid register pair");
9067         Register RegHigh = RegLo + 1;
9068         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9069       }
9070       continue;
9071     }
9072 
9073     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9074     // as any other MemLoc.
9075 
9076     // Promote the value if needed.
9077     // For now, only handle fully promoted and indirect arguments.
9078     if (VA.getLocInfo() == CCValAssign::Indirect) {
9079       // Store the argument in a stack slot and pass its address.
9080       Align StackAlign =
9081           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9082                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9083       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9084       // If the original argument was split (e.g. i128), we need
9085       // to store the required parts of it here (and pass just one address).
9086       // Vectors may be partly split to registers and partly to the stack, in
9087       // which case the base address is partly offset and subsequent stores are
9088       // relative to that.
9089       unsigned ArgIndex = Outs[i].OrigArgIndex;
9090       unsigned ArgPartOffset = Outs[i].PartOffset;
9091       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9092       // Calculate the total size to store. We don't have access to what we're
9093       // actually storing other than performing the loop and collecting the
9094       // info.
9095       SmallVector<std::pair<SDValue, SDValue>> Parts;
9096       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9097         SDValue PartValue = OutVals[i + 1];
9098         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9099         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9100         EVT PartVT = PartValue.getValueType();
9101         if (PartVT.isScalableVector())
9102           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9103         StoredSize += PartVT.getStoreSize();
9104         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9105         Parts.push_back(std::make_pair(PartValue, Offset));
9106         ++i;
9107       }
9108       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9109       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9110       MemOpChains.push_back(
9111           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9112                        MachinePointerInfo::getFixedStack(MF, FI)));
9113       for (const auto &Part : Parts) {
9114         SDValue PartValue = Part.first;
9115         SDValue PartOffset = Part.second;
9116         SDValue Address =
9117             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9118         MemOpChains.push_back(
9119             DAG.getStore(Chain, DL, PartValue, Address,
9120                          MachinePointerInfo::getFixedStack(MF, FI)));
9121       }
9122       ArgValue = SpillSlot;
9123     } else {
9124       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9125     }
9126 
9127     // Use local copy if it is a byval arg.
9128     if (Flags.isByVal())
9129       ArgValue = ByValArgs[j++];
9130 
9131     if (VA.isRegLoc()) {
9132       // Queue up the argument copies and emit them at the end.
9133       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9134     } else {
9135       assert(VA.isMemLoc() && "Argument not register or memory");
9136       assert(!IsTailCall && "Tail call not allowed if stack is used "
9137                             "for passing parameters");
9138 
9139       // Work out the address of the stack slot.
9140       if (!StackPtr.getNode())
9141         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9142       SDValue Address =
9143           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9144                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9145 
9146       // Emit the store.
9147       MemOpChains.push_back(
9148           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9149     }
9150   }
9151 
9152   // Join the stores, which are independent of one another.
9153   if (!MemOpChains.empty())
9154     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9155 
9156   SDValue Glue;
9157 
9158   // Build a sequence of copy-to-reg nodes, chained and glued together.
9159   for (auto &Reg : RegsToPass) {
9160     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9161     Glue = Chain.getValue(1);
9162   }
9163 
9164   // Validate that none of the argument registers have been marked as
9165   // reserved, if so report an error. Do the same for the return address if this
9166   // is not a tailcall.
9167   validateCCReservedRegs(RegsToPass, MF);
9168   if (!IsTailCall &&
9169       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9170     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9171         MF.getFunction(),
9172         "Return address register required, but has been reserved."});
9173 
9174   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9175   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9176   // split it and then direct call can be matched by PseudoCALL.
9177   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9178     const GlobalValue *GV = S->getGlobal();
9179 
9180     unsigned OpFlags = RISCVII::MO_CALL;
9181     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9182       OpFlags = RISCVII::MO_PLT;
9183 
9184     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9185   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9186     unsigned OpFlags = RISCVII::MO_CALL;
9187 
9188     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9189                                                  nullptr))
9190       OpFlags = RISCVII::MO_PLT;
9191 
9192     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9193   }
9194 
9195   // The first call operand is the chain and the second is the target address.
9196   SmallVector<SDValue, 8> Ops;
9197   Ops.push_back(Chain);
9198   Ops.push_back(Callee);
9199 
9200   // Add argument registers to the end of the list so that they are
9201   // known live into the call.
9202   for (auto &Reg : RegsToPass)
9203     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9204 
9205   if (!IsTailCall) {
9206     // Add a register mask operand representing the call-preserved registers.
9207     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9208     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9209     assert(Mask && "Missing call preserved mask for calling convention");
9210     Ops.push_back(DAG.getRegisterMask(Mask));
9211   }
9212 
9213   // Glue the call to the argument copies, if any.
9214   if (Glue.getNode())
9215     Ops.push_back(Glue);
9216 
9217   // Emit the call.
9218   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9219 
9220   if (IsTailCall) {
9221     MF.getFrameInfo().setHasTailCall();
9222     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9223   }
9224 
9225   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9226   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9227   Glue = Chain.getValue(1);
9228 
9229   // Mark the end of the call, which is glued to the call itself.
9230   Chain = DAG.getCALLSEQ_END(Chain,
9231                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9232                              DAG.getConstant(0, DL, PtrVT, true),
9233                              Glue, DL);
9234   Glue = Chain.getValue(1);
9235 
9236   // Assign locations to each value returned by this call.
9237   SmallVector<CCValAssign, 16> RVLocs;
9238   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9239   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9240 
9241   // Copy all of the result registers out of their specified physreg.
9242   for (auto &VA : RVLocs) {
9243     // Copy the value out
9244     SDValue RetValue =
9245         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9246     // Glue the RetValue to the end of the call sequence
9247     Chain = RetValue.getValue(1);
9248     Glue = RetValue.getValue(2);
9249 
9250     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9251       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9252       SDValue RetValue2 =
9253           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9254       Chain = RetValue2.getValue(1);
9255       Glue = RetValue2.getValue(2);
9256       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9257                              RetValue2);
9258     }
9259 
9260     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9261 
9262     InVals.push_back(RetValue);
9263   }
9264 
9265   return Chain;
9266 }
9267 
9268 bool RISCVTargetLowering::CanLowerReturn(
9269     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9270     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9271   SmallVector<CCValAssign, 16> RVLocs;
9272   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9273 
9274   Optional<unsigned> FirstMaskArgument;
9275   if (Subtarget.hasVInstructions())
9276     FirstMaskArgument = preAssignMask(Outs);
9277 
9278   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9279     MVT VT = Outs[i].VT;
9280     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9281     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9282     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9283                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9284                  *this, FirstMaskArgument))
9285       return false;
9286   }
9287   return true;
9288 }
9289 
9290 SDValue
9291 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9292                                  bool IsVarArg,
9293                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9294                                  const SmallVectorImpl<SDValue> &OutVals,
9295                                  const SDLoc &DL, SelectionDAG &DAG) const {
9296   const MachineFunction &MF = DAG.getMachineFunction();
9297   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9298 
9299   // Stores the assignment of the return value to a location.
9300   SmallVector<CCValAssign, 16> RVLocs;
9301 
9302   // Info about the registers and stack slot.
9303   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9304                  *DAG.getContext());
9305 
9306   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9307                     nullptr, CC_RISCV);
9308 
9309   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9310     report_fatal_error("GHC functions return void only");
9311 
9312   SDValue Glue;
9313   SmallVector<SDValue, 4> RetOps(1, Chain);
9314 
9315   // Copy the result values into the output registers.
9316   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9317     SDValue Val = OutVals[i];
9318     CCValAssign &VA = RVLocs[i];
9319     assert(VA.isRegLoc() && "Can only return in registers!");
9320 
9321     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9322       // Handle returning f64 on RV32D with a soft float ABI.
9323       assert(VA.isRegLoc() && "Expected return via registers");
9324       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9325                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9326       SDValue Lo = SplitF64.getValue(0);
9327       SDValue Hi = SplitF64.getValue(1);
9328       Register RegLo = VA.getLocReg();
9329       assert(RegLo < RISCV::X31 && "Invalid register pair");
9330       Register RegHi = RegLo + 1;
9331 
9332       if (STI.isRegisterReservedByUser(RegLo) ||
9333           STI.isRegisterReservedByUser(RegHi))
9334         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9335             MF.getFunction(),
9336             "Return value register required, but has been reserved."});
9337 
9338       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9339       Glue = Chain.getValue(1);
9340       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9341       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9342       Glue = Chain.getValue(1);
9343       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9344     } else {
9345       // Handle a 'normal' return.
9346       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9347       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9348 
9349       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9350         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9351             MF.getFunction(),
9352             "Return value register required, but has been reserved."});
9353 
9354       // Guarantee that all emitted copies are stuck together.
9355       Glue = Chain.getValue(1);
9356       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9357     }
9358   }
9359 
9360   RetOps[0] = Chain; // Update chain.
9361 
9362   // Add the glue node if we have it.
9363   if (Glue.getNode()) {
9364     RetOps.push_back(Glue);
9365   }
9366 
9367   unsigned RetOpc = RISCVISD::RET_FLAG;
9368   // Interrupt service routines use different return instructions.
9369   const Function &Func = DAG.getMachineFunction().getFunction();
9370   if (Func.hasFnAttribute("interrupt")) {
9371     if (!Func.getReturnType()->isVoidTy())
9372       report_fatal_error(
9373           "Functions with the interrupt attribute must have void return type!");
9374 
9375     MachineFunction &MF = DAG.getMachineFunction();
9376     StringRef Kind =
9377       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9378 
9379     if (Kind == "user")
9380       RetOpc = RISCVISD::URET_FLAG;
9381     else if (Kind == "supervisor")
9382       RetOpc = RISCVISD::SRET_FLAG;
9383     else
9384       RetOpc = RISCVISD::MRET_FLAG;
9385   }
9386 
9387   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9388 }
9389 
9390 void RISCVTargetLowering::validateCCReservedRegs(
9391     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9392     MachineFunction &MF) const {
9393   const Function &F = MF.getFunction();
9394   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9395 
9396   if (llvm::any_of(Regs, [&STI](auto Reg) {
9397         return STI.isRegisterReservedByUser(Reg.first);
9398       }))
9399     F.getContext().diagnose(DiagnosticInfoUnsupported{
9400         F, "Argument register required, but has been reserved."});
9401 }
9402 
9403 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9404   return CI->isTailCall();
9405 }
9406 
9407 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9408 #define NODE_NAME_CASE(NODE)                                                   \
9409   case RISCVISD::NODE:                                                         \
9410     return "RISCVISD::" #NODE;
9411   // clang-format off
9412   switch ((RISCVISD::NodeType)Opcode) {
9413   case RISCVISD::FIRST_NUMBER:
9414     break;
9415   NODE_NAME_CASE(RET_FLAG)
9416   NODE_NAME_CASE(URET_FLAG)
9417   NODE_NAME_CASE(SRET_FLAG)
9418   NODE_NAME_CASE(MRET_FLAG)
9419   NODE_NAME_CASE(CALL)
9420   NODE_NAME_CASE(SELECT_CC)
9421   NODE_NAME_CASE(BR_CC)
9422   NODE_NAME_CASE(BuildPairF64)
9423   NODE_NAME_CASE(SplitF64)
9424   NODE_NAME_CASE(TAIL)
9425   NODE_NAME_CASE(MULHSU)
9426   NODE_NAME_CASE(SLLW)
9427   NODE_NAME_CASE(SRAW)
9428   NODE_NAME_CASE(SRLW)
9429   NODE_NAME_CASE(DIVW)
9430   NODE_NAME_CASE(DIVUW)
9431   NODE_NAME_CASE(REMUW)
9432   NODE_NAME_CASE(ROLW)
9433   NODE_NAME_CASE(RORW)
9434   NODE_NAME_CASE(CLZW)
9435   NODE_NAME_CASE(CTZW)
9436   NODE_NAME_CASE(FSLW)
9437   NODE_NAME_CASE(FSRW)
9438   NODE_NAME_CASE(FSL)
9439   NODE_NAME_CASE(FSR)
9440   NODE_NAME_CASE(FMV_H_X)
9441   NODE_NAME_CASE(FMV_X_ANYEXTH)
9442   NODE_NAME_CASE(FMV_W_X_RV64)
9443   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9444   NODE_NAME_CASE(FCVT_X_RTZ)
9445   NODE_NAME_CASE(FCVT_XU_RTZ)
9446   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9447   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9448   NODE_NAME_CASE(READ_CYCLE_WIDE)
9449   NODE_NAME_CASE(GREV)
9450   NODE_NAME_CASE(GREVW)
9451   NODE_NAME_CASE(GORC)
9452   NODE_NAME_CASE(GORCW)
9453   NODE_NAME_CASE(SHFL)
9454   NODE_NAME_CASE(SHFLW)
9455   NODE_NAME_CASE(UNSHFL)
9456   NODE_NAME_CASE(UNSHFLW)
9457   NODE_NAME_CASE(BCOMPRESS)
9458   NODE_NAME_CASE(BCOMPRESSW)
9459   NODE_NAME_CASE(BDECOMPRESS)
9460   NODE_NAME_CASE(BDECOMPRESSW)
9461   NODE_NAME_CASE(VMV_V_X_VL)
9462   NODE_NAME_CASE(VFMV_V_F_VL)
9463   NODE_NAME_CASE(VMV_X_S)
9464   NODE_NAME_CASE(VMV_S_X_VL)
9465   NODE_NAME_CASE(VFMV_S_F_VL)
9466   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9467   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9468   NODE_NAME_CASE(READ_VLENB)
9469   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9470   NODE_NAME_CASE(VSLIDEUP_VL)
9471   NODE_NAME_CASE(VSLIDE1UP_VL)
9472   NODE_NAME_CASE(VSLIDEDOWN_VL)
9473   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9474   NODE_NAME_CASE(VID_VL)
9475   NODE_NAME_CASE(VFNCVT_ROD_VL)
9476   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9477   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9478   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9479   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9480   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9481   NODE_NAME_CASE(VECREDUCE_AND_VL)
9482   NODE_NAME_CASE(VECREDUCE_OR_VL)
9483   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9484   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9485   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9486   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9487   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9488   NODE_NAME_CASE(ADD_VL)
9489   NODE_NAME_CASE(AND_VL)
9490   NODE_NAME_CASE(MUL_VL)
9491   NODE_NAME_CASE(OR_VL)
9492   NODE_NAME_CASE(SDIV_VL)
9493   NODE_NAME_CASE(SHL_VL)
9494   NODE_NAME_CASE(SREM_VL)
9495   NODE_NAME_CASE(SRA_VL)
9496   NODE_NAME_CASE(SRL_VL)
9497   NODE_NAME_CASE(SUB_VL)
9498   NODE_NAME_CASE(UDIV_VL)
9499   NODE_NAME_CASE(UREM_VL)
9500   NODE_NAME_CASE(XOR_VL)
9501   NODE_NAME_CASE(SADDSAT_VL)
9502   NODE_NAME_CASE(UADDSAT_VL)
9503   NODE_NAME_CASE(SSUBSAT_VL)
9504   NODE_NAME_CASE(USUBSAT_VL)
9505   NODE_NAME_CASE(FADD_VL)
9506   NODE_NAME_CASE(FSUB_VL)
9507   NODE_NAME_CASE(FMUL_VL)
9508   NODE_NAME_CASE(FDIV_VL)
9509   NODE_NAME_CASE(FNEG_VL)
9510   NODE_NAME_CASE(FABS_VL)
9511   NODE_NAME_CASE(FSQRT_VL)
9512   NODE_NAME_CASE(FMA_VL)
9513   NODE_NAME_CASE(FCOPYSIGN_VL)
9514   NODE_NAME_CASE(SMIN_VL)
9515   NODE_NAME_CASE(SMAX_VL)
9516   NODE_NAME_CASE(UMIN_VL)
9517   NODE_NAME_CASE(UMAX_VL)
9518   NODE_NAME_CASE(FMINNUM_VL)
9519   NODE_NAME_CASE(FMAXNUM_VL)
9520   NODE_NAME_CASE(MULHS_VL)
9521   NODE_NAME_CASE(MULHU_VL)
9522   NODE_NAME_CASE(FP_TO_SINT_VL)
9523   NODE_NAME_CASE(FP_TO_UINT_VL)
9524   NODE_NAME_CASE(SINT_TO_FP_VL)
9525   NODE_NAME_CASE(UINT_TO_FP_VL)
9526   NODE_NAME_CASE(FP_EXTEND_VL)
9527   NODE_NAME_CASE(FP_ROUND_VL)
9528   NODE_NAME_CASE(VWMUL_VL)
9529   NODE_NAME_CASE(VWMULU_VL)
9530   NODE_NAME_CASE(SETCC_VL)
9531   NODE_NAME_CASE(VSELECT_VL)
9532   NODE_NAME_CASE(VMAND_VL)
9533   NODE_NAME_CASE(VMOR_VL)
9534   NODE_NAME_CASE(VMXOR_VL)
9535   NODE_NAME_CASE(VMCLR_VL)
9536   NODE_NAME_CASE(VMSET_VL)
9537   NODE_NAME_CASE(VRGATHER_VX_VL)
9538   NODE_NAME_CASE(VRGATHER_VV_VL)
9539   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9540   NODE_NAME_CASE(VSEXT_VL)
9541   NODE_NAME_CASE(VZEXT_VL)
9542   NODE_NAME_CASE(VCPOP_VL)
9543   NODE_NAME_CASE(VLE_VL)
9544   NODE_NAME_CASE(VSE_VL)
9545   NODE_NAME_CASE(READ_CSR)
9546   NODE_NAME_CASE(WRITE_CSR)
9547   NODE_NAME_CASE(SWAP_CSR)
9548   }
9549   // clang-format on
9550   return nullptr;
9551 #undef NODE_NAME_CASE
9552 }
9553 
9554 /// getConstraintType - Given a constraint letter, return the type of
9555 /// constraint it is for this target.
9556 RISCVTargetLowering::ConstraintType
9557 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9558   if (Constraint.size() == 1) {
9559     switch (Constraint[0]) {
9560     default:
9561       break;
9562     case 'f':
9563       return C_RegisterClass;
9564     case 'I':
9565     case 'J':
9566     case 'K':
9567       return C_Immediate;
9568     case 'A':
9569       return C_Memory;
9570     case 'S': // A symbolic address
9571       return C_Other;
9572     }
9573   } else {
9574     if (Constraint == "vr" || Constraint == "vm")
9575       return C_RegisterClass;
9576   }
9577   return TargetLowering::getConstraintType(Constraint);
9578 }
9579 
9580 std::pair<unsigned, const TargetRegisterClass *>
9581 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9582                                                   StringRef Constraint,
9583                                                   MVT VT) const {
9584   // First, see if this is a constraint that directly corresponds to a
9585   // RISCV register class.
9586   if (Constraint.size() == 1) {
9587     switch (Constraint[0]) {
9588     case 'r':
9589       return std::make_pair(0U, &RISCV::GPRRegClass);
9590     case 'f':
9591       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9592         return std::make_pair(0U, &RISCV::FPR16RegClass);
9593       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9594         return std::make_pair(0U, &RISCV::FPR32RegClass);
9595       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9596         return std::make_pair(0U, &RISCV::FPR64RegClass);
9597       break;
9598     default:
9599       break;
9600     }
9601   } else {
9602     if (Constraint == "vr") {
9603       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9604                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9605         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9606           return std::make_pair(0U, RC);
9607       }
9608     } else if (Constraint == "vm") {
9609       if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
9610         return std::make_pair(0U, &RISCV::VMV0RegClass);
9611     }
9612   }
9613 
9614   // Clang will correctly decode the usage of register name aliases into their
9615   // official names. However, other frontends like `rustc` do not. This allows
9616   // users of these frontends to use the ABI names for registers in LLVM-style
9617   // register constraints.
9618   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9619                                .Case("{zero}", RISCV::X0)
9620                                .Case("{ra}", RISCV::X1)
9621                                .Case("{sp}", RISCV::X2)
9622                                .Case("{gp}", RISCV::X3)
9623                                .Case("{tp}", RISCV::X4)
9624                                .Case("{t0}", RISCV::X5)
9625                                .Case("{t1}", RISCV::X6)
9626                                .Case("{t2}", RISCV::X7)
9627                                .Cases("{s0}", "{fp}", RISCV::X8)
9628                                .Case("{s1}", RISCV::X9)
9629                                .Case("{a0}", RISCV::X10)
9630                                .Case("{a1}", RISCV::X11)
9631                                .Case("{a2}", RISCV::X12)
9632                                .Case("{a3}", RISCV::X13)
9633                                .Case("{a4}", RISCV::X14)
9634                                .Case("{a5}", RISCV::X15)
9635                                .Case("{a6}", RISCV::X16)
9636                                .Case("{a7}", RISCV::X17)
9637                                .Case("{s2}", RISCV::X18)
9638                                .Case("{s3}", RISCV::X19)
9639                                .Case("{s4}", RISCV::X20)
9640                                .Case("{s5}", RISCV::X21)
9641                                .Case("{s6}", RISCV::X22)
9642                                .Case("{s7}", RISCV::X23)
9643                                .Case("{s8}", RISCV::X24)
9644                                .Case("{s9}", RISCV::X25)
9645                                .Case("{s10}", RISCV::X26)
9646                                .Case("{s11}", RISCV::X27)
9647                                .Case("{t3}", RISCV::X28)
9648                                .Case("{t4}", RISCV::X29)
9649                                .Case("{t5}", RISCV::X30)
9650                                .Case("{t6}", RISCV::X31)
9651                                .Default(RISCV::NoRegister);
9652   if (XRegFromAlias != RISCV::NoRegister)
9653     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9654 
9655   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9656   // TableGen record rather than the AsmName to choose registers for InlineAsm
9657   // constraints, plus we want to match those names to the widest floating point
9658   // register type available, manually select floating point registers here.
9659   //
9660   // The second case is the ABI name of the register, so that frontends can also
9661   // use the ABI names in register constraint lists.
9662   if (Subtarget.hasStdExtF()) {
9663     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9664                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9665                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9666                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9667                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9668                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9669                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9670                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9671                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9672                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9673                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9674                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9675                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9676                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9677                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9678                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9679                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9680                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9681                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9682                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9683                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9684                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9685                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9686                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9687                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9688                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9689                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9690                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9691                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9692                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9693                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9694                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9695                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9696                         .Default(RISCV::NoRegister);
9697     if (FReg != RISCV::NoRegister) {
9698       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9699       if (Subtarget.hasStdExtD()) {
9700         unsigned RegNo = FReg - RISCV::F0_F;
9701         unsigned DReg = RISCV::F0_D + RegNo;
9702         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9703       }
9704       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9705     }
9706   }
9707 
9708   if (Subtarget.hasVInstructions()) {
9709     Register VReg = StringSwitch<Register>(Constraint.lower())
9710                         .Case("{v0}", RISCV::V0)
9711                         .Case("{v1}", RISCV::V1)
9712                         .Case("{v2}", RISCV::V2)
9713                         .Case("{v3}", RISCV::V3)
9714                         .Case("{v4}", RISCV::V4)
9715                         .Case("{v5}", RISCV::V5)
9716                         .Case("{v6}", RISCV::V6)
9717                         .Case("{v7}", RISCV::V7)
9718                         .Case("{v8}", RISCV::V8)
9719                         .Case("{v9}", RISCV::V9)
9720                         .Case("{v10}", RISCV::V10)
9721                         .Case("{v11}", RISCV::V11)
9722                         .Case("{v12}", RISCV::V12)
9723                         .Case("{v13}", RISCV::V13)
9724                         .Case("{v14}", RISCV::V14)
9725                         .Case("{v15}", RISCV::V15)
9726                         .Case("{v16}", RISCV::V16)
9727                         .Case("{v17}", RISCV::V17)
9728                         .Case("{v18}", RISCV::V18)
9729                         .Case("{v19}", RISCV::V19)
9730                         .Case("{v20}", RISCV::V20)
9731                         .Case("{v21}", RISCV::V21)
9732                         .Case("{v22}", RISCV::V22)
9733                         .Case("{v23}", RISCV::V23)
9734                         .Case("{v24}", RISCV::V24)
9735                         .Case("{v25}", RISCV::V25)
9736                         .Case("{v26}", RISCV::V26)
9737                         .Case("{v27}", RISCV::V27)
9738                         .Case("{v28}", RISCV::V28)
9739                         .Case("{v29}", RISCV::V29)
9740                         .Case("{v30}", RISCV::V30)
9741                         .Case("{v31}", RISCV::V31)
9742                         .Default(RISCV::NoRegister);
9743     if (VReg != RISCV::NoRegister) {
9744       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9745         return std::make_pair(VReg, &RISCV::VMRegClass);
9746       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9747         return std::make_pair(VReg, &RISCV::VRRegClass);
9748       for (const auto *RC :
9749            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9750         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9751           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9752           return std::make_pair(VReg, RC);
9753         }
9754       }
9755     }
9756   }
9757 
9758   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9759 }
9760 
9761 unsigned
9762 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9763   // Currently only support length 1 constraints.
9764   if (ConstraintCode.size() == 1) {
9765     switch (ConstraintCode[0]) {
9766     case 'A':
9767       return InlineAsm::Constraint_A;
9768     default:
9769       break;
9770     }
9771   }
9772 
9773   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9774 }
9775 
9776 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9777     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9778     SelectionDAG &DAG) const {
9779   // Currently only support length 1 constraints.
9780   if (Constraint.length() == 1) {
9781     switch (Constraint[0]) {
9782     case 'I':
9783       // Validate & create a 12-bit signed immediate operand.
9784       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9785         uint64_t CVal = C->getSExtValue();
9786         if (isInt<12>(CVal))
9787           Ops.push_back(
9788               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9789       }
9790       return;
9791     case 'J':
9792       // Validate & create an integer zero operand.
9793       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9794         if (C->getZExtValue() == 0)
9795           Ops.push_back(
9796               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9797       return;
9798     case 'K':
9799       // Validate & create a 5-bit unsigned immediate operand.
9800       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9801         uint64_t CVal = C->getZExtValue();
9802         if (isUInt<5>(CVal))
9803           Ops.push_back(
9804               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9805       }
9806       return;
9807     case 'S':
9808       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9809         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9810                                                  GA->getValueType(0)));
9811       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9812         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9813                                                 BA->getValueType(0)));
9814       }
9815       return;
9816     default:
9817       break;
9818     }
9819   }
9820   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9821 }
9822 
9823 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9824                                                    Instruction *Inst,
9825                                                    AtomicOrdering Ord) const {
9826   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9827     return Builder.CreateFence(Ord);
9828   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9829     return Builder.CreateFence(AtomicOrdering::Release);
9830   return nullptr;
9831 }
9832 
9833 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9834                                                     Instruction *Inst,
9835                                                     AtomicOrdering Ord) const {
9836   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9837     return Builder.CreateFence(AtomicOrdering::Acquire);
9838   return nullptr;
9839 }
9840 
9841 TargetLowering::AtomicExpansionKind
9842 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9843   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9844   // point operations can't be used in an lr/sc sequence without breaking the
9845   // forward-progress guarantee.
9846   if (AI->isFloatingPointOperation())
9847     return AtomicExpansionKind::CmpXChg;
9848 
9849   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9850   if (Size == 8 || Size == 16)
9851     return AtomicExpansionKind::MaskedIntrinsic;
9852   return AtomicExpansionKind::None;
9853 }
9854 
9855 static Intrinsic::ID
9856 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9857   if (XLen == 32) {
9858     switch (BinOp) {
9859     default:
9860       llvm_unreachable("Unexpected AtomicRMW BinOp");
9861     case AtomicRMWInst::Xchg:
9862       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9863     case AtomicRMWInst::Add:
9864       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9865     case AtomicRMWInst::Sub:
9866       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9867     case AtomicRMWInst::Nand:
9868       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9869     case AtomicRMWInst::Max:
9870       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9871     case AtomicRMWInst::Min:
9872       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9873     case AtomicRMWInst::UMax:
9874       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9875     case AtomicRMWInst::UMin:
9876       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9877     }
9878   }
9879 
9880   if (XLen == 64) {
9881     switch (BinOp) {
9882     default:
9883       llvm_unreachable("Unexpected AtomicRMW BinOp");
9884     case AtomicRMWInst::Xchg:
9885       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9886     case AtomicRMWInst::Add:
9887       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9888     case AtomicRMWInst::Sub:
9889       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9890     case AtomicRMWInst::Nand:
9891       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9892     case AtomicRMWInst::Max:
9893       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9894     case AtomicRMWInst::Min:
9895       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9896     case AtomicRMWInst::UMax:
9897       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9898     case AtomicRMWInst::UMin:
9899       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9900     }
9901   }
9902 
9903   llvm_unreachable("Unexpected XLen\n");
9904 }
9905 
9906 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9907     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9908     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9909   unsigned XLen = Subtarget.getXLen();
9910   Value *Ordering =
9911       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9912   Type *Tys[] = {AlignedAddr->getType()};
9913   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9914       AI->getModule(),
9915       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9916 
9917   if (XLen == 64) {
9918     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9919     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9920     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9921   }
9922 
9923   Value *Result;
9924 
9925   // Must pass the shift amount needed to sign extend the loaded value prior
9926   // to performing a signed comparison for min/max. ShiftAmt is the number of
9927   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9928   // is the number of bits to left+right shift the value in order to
9929   // sign-extend.
9930   if (AI->getOperation() == AtomicRMWInst::Min ||
9931       AI->getOperation() == AtomicRMWInst::Max) {
9932     const DataLayout &DL = AI->getModule()->getDataLayout();
9933     unsigned ValWidth =
9934         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9935     Value *SextShamt =
9936         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9937     Result = Builder.CreateCall(LrwOpScwLoop,
9938                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9939   } else {
9940     Result =
9941         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9942   }
9943 
9944   if (XLen == 64)
9945     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9946   return Result;
9947 }
9948 
9949 TargetLowering::AtomicExpansionKind
9950 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9951     AtomicCmpXchgInst *CI) const {
9952   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9953   if (Size == 8 || Size == 16)
9954     return AtomicExpansionKind::MaskedIntrinsic;
9955   return AtomicExpansionKind::None;
9956 }
9957 
9958 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9959     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9960     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9961   unsigned XLen = Subtarget.getXLen();
9962   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9963   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9964   if (XLen == 64) {
9965     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9966     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9967     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9968     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9969   }
9970   Type *Tys[] = {AlignedAddr->getType()};
9971   Function *MaskedCmpXchg =
9972       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9973   Value *Result = Builder.CreateCall(
9974       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9975   if (XLen == 64)
9976     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9977   return Result;
9978 }
9979 
9980 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9981   return false;
9982 }
9983 
9984 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
9985                                                EVT VT) const {
9986   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
9987     return false;
9988 
9989   switch (FPVT.getSimpleVT().SimpleTy) {
9990   case MVT::f16:
9991     return Subtarget.hasStdExtZfh();
9992   case MVT::f32:
9993     return Subtarget.hasStdExtF();
9994   case MVT::f64:
9995     return Subtarget.hasStdExtD();
9996   default:
9997     return false;
9998   }
9999 }
10000 
10001 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10002                                                      EVT VT) const {
10003   VT = VT.getScalarType();
10004 
10005   if (!VT.isSimple())
10006     return false;
10007 
10008   switch (VT.getSimpleVT().SimpleTy) {
10009   case MVT::f16:
10010     return Subtarget.hasStdExtZfh();
10011   case MVT::f32:
10012     return Subtarget.hasStdExtF();
10013   case MVT::f64:
10014     return Subtarget.hasStdExtD();
10015   default:
10016     break;
10017   }
10018 
10019   return false;
10020 }
10021 
10022 Register RISCVTargetLowering::getExceptionPointerRegister(
10023     const Constant *PersonalityFn) const {
10024   return RISCV::X10;
10025 }
10026 
10027 Register RISCVTargetLowering::getExceptionSelectorRegister(
10028     const Constant *PersonalityFn) const {
10029   return RISCV::X11;
10030 }
10031 
10032 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10033   // Return false to suppress the unnecessary extensions if the LibCall
10034   // arguments or return value is f32 type for LP64 ABI.
10035   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10036   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10037     return false;
10038 
10039   return true;
10040 }
10041 
10042 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10043   if (Subtarget.is64Bit() && Type == MVT::i32)
10044     return true;
10045 
10046   return IsSigned;
10047 }
10048 
10049 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10050                                                  SDValue C) const {
10051   // Check integral scalar types.
10052   if (VT.isScalarInteger()) {
10053     // Omit the optimization if the sub target has the M extension and the data
10054     // size exceeds XLen.
10055     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10056       return false;
10057     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10058       // Break the MUL to a SLLI and an ADD/SUB.
10059       const APInt &Imm = ConstNode->getAPIntValue();
10060       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10061           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10062         return true;
10063       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10064       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10065           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10066            (Imm - 8).isPowerOf2()))
10067         return true;
10068       // Omit the following optimization if the sub target has the M extension
10069       // and the data size >= XLen.
10070       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10071         return false;
10072       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10073       // a pair of LUI/ADDI.
10074       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10075         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10076         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10077             (1 - ImmS).isPowerOf2())
10078         return true;
10079       }
10080     }
10081   }
10082 
10083   return false;
10084 }
10085 
10086 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10087     const SDValue &AddNode, const SDValue &ConstNode) const {
10088   // Let the DAGCombiner decide for vectors.
10089   EVT VT = AddNode.getValueType();
10090   if (VT.isVector())
10091     return true;
10092 
10093   // Let the DAGCombiner decide for larger types.
10094   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10095     return true;
10096 
10097   // It is worse if c1 is simm12 while c1*c2 is not.
10098   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10099   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10100   const APInt &C1 = C1Node->getAPIntValue();
10101   const APInt &C2 = C2Node->getAPIntValue();
10102   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10103     return false;
10104 
10105   // Default to true and let the DAGCombiner decide.
10106   return true;
10107 }
10108 
10109 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10110     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10111     bool *Fast) const {
10112   if (!VT.isVector())
10113     return false;
10114 
10115   EVT ElemVT = VT.getVectorElementType();
10116   if (Alignment >= ElemVT.getStoreSize()) {
10117     if (Fast)
10118       *Fast = true;
10119     return true;
10120   }
10121 
10122   return false;
10123 }
10124 
10125 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10126     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10127     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10128   bool IsABIRegCopy = CC.hasValue();
10129   EVT ValueVT = Val.getValueType();
10130   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10131     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10132     // and cast to f32.
10133     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10134     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10135     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10136                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10137     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10138     Parts[0] = Val;
10139     return true;
10140   }
10141 
10142   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10143     LLVMContext &Context = *DAG.getContext();
10144     EVT ValueEltVT = ValueVT.getVectorElementType();
10145     EVT PartEltVT = PartVT.getVectorElementType();
10146     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10147     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10148     if (PartVTBitSize % ValueVTBitSize == 0) {
10149       assert(PartVTBitSize >= ValueVTBitSize);
10150       // If the element types are different, bitcast to the same element type of
10151       // PartVT first.
10152       // Give an example here, we want copy a <vscale x 1 x i8> value to
10153       // <vscale x 4 x i16>.
10154       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10155       // subvector, then we can bitcast to <vscale x 4 x i16>.
10156       if (ValueEltVT != PartEltVT) {
10157         if (PartVTBitSize > ValueVTBitSize) {
10158           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10159           assert(Count != 0 && "The number of element should not be zero.");
10160           EVT SameEltTypeVT =
10161               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10162           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10163                             DAG.getUNDEF(SameEltTypeVT), Val,
10164                             DAG.getVectorIdxConstant(0, DL));
10165         }
10166         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10167       } else {
10168         Val =
10169             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10170                         Val, DAG.getVectorIdxConstant(0, DL));
10171       }
10172       Parts[0] = Val;
10173       return true;
10174     }
10175   }
10176   return false;
10177 }
10178 
10179 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10180     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10181     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10182   bool IsABIRegCopy = CC.hasValue();
10183   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10184     SDValue Val = Parts[0];
10185 
10186     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10187     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10188     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10189     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10190     return Val;
10191   }
10192 
10193   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10194     LLVMContext &Context = *DAG.getContext();
10195     SDValue Val = Parts[0];
10196     EVT ValueEltVT = ValueVT.getVectorElementType();
10197     EVT PartEltVT = PartVT.getVectorElementType();
10198     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10199     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10200     if (PartVTBitSize % ValueVTBitSize == 0) {
10201       assert(PartVTBitSize >= ValueVTBitSize);
10202       EVT SameEltTypeVT = ValueVT;
10203       // If the element types are different, convert it to the same element type
10204       // of PartVT.
10205       // Give an example here, we want copy a <vscale x 1 x i8> value from
10206       // <vscale x 4 x i16>.
10207       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10208       // then we can extract <vscale x 1 x i8>.
10209       if (ValueEltVT != PartEltVT) {
10210         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10211         assert(Count != 0 && "The number of element should not be zero.");
10212         SameEltTypeVT =
10213             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10214         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10215       }
10216       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10217                         DAG.getVectorIdxConstant(0, DL));
10218       return Val;
10219     }
10220   }
10221   return SDValue();
10222 }
10223 
10224 #define GET_REGISTER_MATCHER
10225 #include "RISCVGenAsmMatcher.inc"
10226 
10227 Register
10228 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10229                                        const MachineFunction &MF) const {
10230   Register Reg = MatchRegisterAltName(RegName);
10231   if (Reg == RISCV::NoRegister)
10232     Reg = MatchRegisterName(RegName);
10233   if (Reg == RISCV::NoRegister)
10234     report_fatal_error(
10235         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10236   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10237   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10238     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10239                              StringRef(RegName) + "\"."));
10240   return Reg;
10241 }
10242 
10243 namespace llvm {
10244 namespace RISCVVIntrinsicsTable {
10245 
10246 #define GET_RISCVVIntrinsicsTable_IMPL
10247 #include "RISCVGenSearchableTables.inc"
10248 
10249 } // namespace RISCVVIntrinsicsTable
10250 
10251 } // namespace llvm
10252