1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasVInstructions()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs) {
132       if (VT.getVectorElementType() == MVT::i64 &&
133           !Subtarget.hasVInstructionsI64())
134         continue;
135       addRegClassForRVV(VT);
136     }
137 
138     if (Subtarget.hasVInstructionsF16())
139       for (MVT VT : F16VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasVInstructionsF32())
143       for (MVT VT : F32VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.hasVInstructionsF64())
147       for (MVT VT : F64VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.useRVVForFixedLengthVectors()) {
151       auto addRegClassForFixedVectors = [this](MVT VT) {
152         MVT ContainerVT = getContainerForFixedLengthVector(VT);
153         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
154         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
155         addRegisterClass(VT, TRI.getRegClass(RCID));
156       };
157       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160 
161       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
162         if (useRVVForFixedLengthVectorVT(VT))
163           addRegClassForFixedVectors(VT);
164     }
165   }
166 
167   // Compute derived properties from the register classes.
168   computeRegisterProperties(STI.getRegisterInfo());
169 
170   setStackPointerRegisterToSaveRestore(RISCV::X2);
171 
172   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
173     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
174 
175   // TODO: add all necessary setOperationAction calls.
176   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
177 
178   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179   setOperationAction(ISD::BR_CC, XLenVT, Expand);
180   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
181   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
182 
183   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
184   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction(ISD::VAARG, MVT::Other, Expand);
188   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
189   setOperationAction(ISD::VAEND, MVT::Other, Expand);
190 
191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
192   if (!Subtarget.hasStdExtZbb()) {
193     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195   }
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::ADD, MVT::i32, Custom);
199     setOperationAction(ISD::SUB, MVT::i32, Custom);
200     setOperationAction(ISD::SHL, MVT::i32, Custom);
201     setOperationAction(ISD::SRA, MVT::i32, Custom);
202     setOperationAction(ISD::SRL, MVT::i32, Custom);
203 
204     setOperationAction(ISD::UADDO, MVT::i32, Custom);
205     setOperationAction(ISD::USUBO, MVT::i32, Custom);
206     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
207     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
208   } else {
209     setLibcallName(RTLIB::SHL_I128, nullptr);
210     setLibcallName(RTLIB::SRL_I128, nullptr);
211     setLibcallName(RTLIB::SRA_I128, nullptr);
212     setLibcallName(RTLIB::MUL_I128, nullptr);
213     setLibcallName(RTLIB::MULO_I64, nullptr);
214   }
215 
216   if (!Subtarget.hasStdExtM()) {
217     setOperationAction(ISD::MUL, XLenVT, Expand);
218     setOperationAction(ISD::MULHS, XLenVT, Expand);
219     setOperationAction(ISD::MULHU, XLenVT, Expand);
220     setOperationAction(ISD::SDIV, XLenVT, Expand);
221     setOperationAction(ISD::UDIV, XLenVT, Expand);
222     setOperationAction(ISD::SREM, XLenVT, Expand);
223     setOperationAction(ISD::UREM, XLenVT, Expand);
224   } else {
225     if (Subtarget.is64Bit()) {
226       setOperationAction(ISD::MUL, MVT::i32, Custom);
227       setOperationAction(ISD::MUL, MVT::i128, Custom);
228 
229       setOperationAction(ISD::SDIV, MVT::i8, Custom);
230       setOperationAction(ISD::UDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UREM, MVT::i8, Custom);
232       setOperationAction(ISD::SDIV, MVT::i16, Custom);
233       setOperationAction(ISD::UDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UREM, MVT::i16, Custom);
235       setOperationAction(ISD::SDIV, MVT::i32, Custom);
236       setOperationAction(ISD::UDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UREM, MVT::i32, Custom);
238     } else {
239       setOperationAction(ISD::MUL, MVT::i64, Custom);
240     }
241   }
242 
243   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
244   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
246   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
247 
248   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
249   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
251 
252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
253     if (Subtarget.is64Bit()) {
254       setOperationAction(ISD::ROTL, MVT::i32, Custom);
255       setOperationAction(ISD::ROTR, MVT::i32, Custom);
256     }
257   } else {
258     setOperationAction(ISD::ROTL, XLenVT, Expand);
259     setOperationAction(ISD::ROTR, XLenVT, Expand);
260   }
261 
262   if (Subtarget.hasStdExtZbp()) {
263     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
264     // more combining.
265     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
266     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
267     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
268     // BSWAP i8 doesn't exist.
269     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
270     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
271 
272     if (Subtarget.is64Bit()) {
273       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
274       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
275     }
276   } else {
277     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
278     // pattern match it directly in isel.
279     setOperationAction(ISD::BSWAP, XLenVT,
280                        Subtarget.hasStdExtZbb() ? Legal : Expand);
281   }
282 
283   if (Subtarget.hasStdExtZbb()) {
284     setOperationAction(ISD::SMIN, XLenVT, Legal);
285     setOperationAction(ISD::SMAX, XLenVT, Legal);
286     setOperationAction(ISD::UMIN, XLenVT, Legal);
287     setOperationAction(ISD::UMAX, XLenVT, Legal);
288 
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
291       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
292       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
294     }
295   } else {
296     setOperationAction(ISD::CTTZ, XLenVT, Expand);
297     setOperationAction(ISD::CTLZ, XLenVT, Expand);
298     setOperationAction(ISD::CTPOP, XLenVT, Expand);
299   }
300 
301   if (Subtarget.hasStdExtZbt()) {
302     setOperationAction(ISD::FSHL, XLenVT, Custom);
303     setOperationAction(ISD::FSHR, XLenVT, Custom);
304     setOperationAction(ISD::SELECT, XLenVT, Legal);
305 
306     if (Subtarget.is64Bit()) {
307       setOperationAction(ISD::FSHL, MVT::i32, Custom);
308       setOperationAction(ISD::FSHR, MVT::i32, Custom);
309     }
310   } else {
311     setOperationAction(ISD::SELECT, XLenVT, Custom);
312   }
313 
314   static const ISD::CondCode FPCCToExpand[] = {
315       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
316       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
317       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
318 
319   static const ISD::NodeType FPOpToExpand[] = {
320       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
321       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
322 
323   if (Subtarget.hasStdExtZfh())
324     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
325 
326   if (Subtarget.hasStdExtZfh()) {
327     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
328     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
329     setOperationAction(ISD::LRINT, MVT::f16, Legal);
330     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LROUND, MVT::f16, Legal);
332     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
333     for (auto CC : FPCCToExpand)
334       setCondCodeAction(CC, MVT::f16, Expand);
335     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
336     setOperationAction(ISD::SELECT, MVT::f16, Custom);
337     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
338 
339     setOperationAction(ISD::FREM,       MVT::f16, Promote);
340     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
341     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
342     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
343     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
344     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
345     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
346     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
347     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
348     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
349     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
350     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
351     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
352     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
353     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
354     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
355     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
356     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
357 
358     // We need to custom promote this.
359     if (Subtarget.is64Bit())
360       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
361   }
362 
363   if (Subtarget.hasStdExtF()) {
364     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
365     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
366     setOperationAction(ISD::LRINT, MVT::f32, Legal);
367     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
368     setOperationAction(ISD::LROUND, MVT::f32, Legal);
369     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
370     for (auto CC : FPCCToExpand)
371       setCondCodeAction(CC, MVT::f32, Expand);
372     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
373     setOperationAction(ISD::SELECT, MVT::f32, Custom);
374     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
375     for (auto Op : FPOpToExpand)
376       setOperationAction(Op, MVT::f32, Expand);
377     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
378     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
379   }
380 
381   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
382     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
383 
384   if (Subtarget.hasStdExtD()) {
385     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
386     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
387     setOperationAction(ISD::LRINT, MVT::f64, Legal);
388     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
389     setOperationAction(ISD::LROUND, MVT::f64, Legal);
390     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
391     for (auto CC : FPCCToExpand)
392       setCondCodeAction(CC, MVT::f64, Expand);
393     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
394     setOperationAction(ISD::SELECT, MVT::f64, Custom);
395     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
396     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
397     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
398     for (auto Op : FPOpToExpand)
399       setOperationAction(Op, MVT::f64, Expand);
400     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
401     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
402   }
403 
404   if (Subtarget.is64Bit()) {
405     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
406     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
407     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
408     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
409   }
410 
411   if (Subtarget.hasStdExtF()) {
412     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
413     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
414 
415     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
416     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
417   }
418 
419   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
420   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
421   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
422   setOperationAction(ISD::JumpTable, XLenVT, Custom);
423 
424   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
425 
426   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
427   // Unfortunately this can't be determined just from the ISA naming string.
428   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
429                      Subtarget.is64Bit() ? Legal : Custom);
430 
431   setOperationAction(ISD::TRAP, MVT::Other, Legal);
432   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
433   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
434   if (Subtarget.is64Bit())
435     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
436 
437   if (Subtarget.hasStdExtA()) {
438     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
439     setMinCmpXchgSizeInBits(32);
440   } else {
441     setMaxAtomicSizeInBitsSupported(0);
442   }
443 
444   setBooleanContents(ZeroOrOneBooleanContent);
445 
446   if (Subtarget.hasVInstructions()) {
447     setBooleanVectorContents(ZeroOrOneBooleanContent);
448 
449     setOperationAction(ISD::VSCALE, XLenVT, Custom);
450 
451     // RVV intrinsics may have illegal operands.
452     // We also need to custom legalize vmv.x.s.
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
454     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
455     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
456     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
457     if (Subtarget.is64Bit()) {
458       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
459     } else {
460       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
461       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
462     }
463 
464     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
465     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
466 
467     static const unsigned IntegerVPOps[] = {
468         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
469         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
470         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
471         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
472         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
473         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
474         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
475         ISD::VP_SELECT};
476 
477     static const unsigned FloatingPointVPOps[] = {
478         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
479         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
480         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
481 
482     if (!Subtarget.is64Bit()) {
483       // We must custom-lower certain vXi64 operations on RV32 due to the vector
484       // element type being illegal.
485       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
486       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
487 
488       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
489       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
490       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
491       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
492       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
493       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
494       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
495       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
496 
497       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
498       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
499       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
500       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
501       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
502       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
503       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
504       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
505     }
506 
507     for (MVT VT : BoolVecVTs) {
508       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
509 
510       // Mask VTs are custom-expanded into a series of standard nodes
511       setOperationAction(ISD::TRUNCATE, VT, Custom);
512       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
513       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
514       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
515 
516       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
517       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
518 
519       setOperationAction(ISD::SELECT, VT, Custom);
520       setOperationAction(ISD::SELECT_CC, VT, Expand);
521       setOperationAction(ISD::VSELECT, VT, Expand);
522 
523       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
524       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
525       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
526 
527       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
528       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
529       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
530 
531       // RVV has native int->float & float->int conversions where the
532       // element type sizes are within one power-of-two of each other. Any
533       // wider distances between type sizes have to be lowered as sequences
534       // which progressively narrow the gap in stages.
535       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
536       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
537       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
538       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
539 
540       // Expand all extending loads to types larger than this, and truncating
541       // stores from types larger than this.
542       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
543         setTruncStoreAction(OtherVT, VT, Expand);
544         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
545         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
546         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
547       }
548     }
549 
550     for (MVT VT : IntVecVTs) {
551       if (VT.getVectorElementType() == MVT::i64 &&
552           !Subtarget.hasVInstructionsI64())
553         continue;
554 
555       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
556       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
557 
558       // Vectors implement MULHS/MULHU.
559       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
560       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
561 
562       setOperationAction(ISD::SMIN, VT, Legal);
563       setOperationAction(ISD::SMAX, VT, Legal);
564       setOperationAction(ISD::UMIN, VT, Legal);
565       setOperationAction(ISD::UMAX, VT, Legal);
566 
567       setOperationAction(ISD::ROTL, VT, Expand);
568       setOperationAction(ISD::ROTR, VT, Expand);
569 
570       setOperationAction(ISD::CTTZ, VT, Expand);
571       setOperationAction(ISD::CTLZ, VT, Expand);
572       setOperationAction(ISD::CTPOP, VT, Expand);
573 
574       setOperationAction(ISD::BSWAP, VT, Expand);
575 
576       // Custom-lower extensions and truncations from/to mask types.
577       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
578       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
579       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
580 
581       // RVV has native int->float & float->int conversions where the
582       // element type sizes are within one power-of-two of each other. Any
583       // wider distances between type sizes have to be lowered as sequences
584       // which progressively narrow the gap in stages.
585       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
586       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
587       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
588       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
589 
590       setOperationAction(ISD::SADDSAT, VT, Legal);
591       setOperationAction(ISD::UADDSAT, VT, Legal);
592       setOperationAction(ISD::SSUBSAT, VT, Legal);
593       setOperationAction(ISD::USUBSAT, VT, Legal);
594 
595       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
596       // nodes which truncate by one power of two at a time.
597       setOperationAction(ISD::TRUNCATE, VT, Custom);
598 
599       // Custom-lower insert/extract operations to simplify patterns.
600       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
601       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
602 
603       // Custom-lower reduction operations to set up the corresponding custom
604       // nodes' operands.
605       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
606       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
607       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
608       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
609       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
610       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
611       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
612       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
613 
614       for (unsigned VPOpc : IntegerVPOps)
615         setOperationAction(VPOpc, VT, Custom);
616 
617       setOperationAction(ISD::LOAD, VT, Custom);
618       setOperationAction(ISD::STORE, VT, Custom);
619 
620       setOperationAction(ISD::MLOAD, VT, Custom);
621       setOperationAction(ISD::MSTORE, VT, Custom);
622       setOperationAction(ISD::MGATHER, VT, Custom);
623       setOperationAction(ISD::MSCATTER, VT, Custom);
624 
625       setOperationAction(ISD::VP_LOAD, VT, Custom);
626       setOperationAction(ISD::VP_STORE, VT, Custom);
627       setOperationAction(ISD::VP_GATHER, VT, Custom);
628       setOperationAction(ISD::VP_SCATTER, VT, Custom);
629 
630       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
631       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
632       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
633 
634       setOperationAction(ISD::SELECT, VT, Custom);
635       setOperationAction(ISD::SELECT_CC, VT, Expand);
636 
637       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
638       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
639 
640       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
641         setTruncStoreAction(VT, OtherVT, Expand);
642         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
643         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
644         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
645       }
646 
647       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
648       // type that can represent the value exactly.
649       if (VT.getVectorElementType() != MVT::i64) {
650         MVT FloatEltVT =
651             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
652         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
653         if (isTypeLegal(FloatVT)) {
654           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
655           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
656         }
657       }
658     }
659 
660     // Expand various CCs to best match the RVV ISA, which natively supports UNE
661     // but no other unordered comparisons, and supports all ordered comparisons
662     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
663     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
664     // and we pattern-match those back to the "original", swapping operands once
665     // more. This way we catch both operations and both "vf" and "fv" forms with
666     // fewer patterns.
667     static const ISD::CondCode VFPCCToExpand[] = {
668         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
669         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
670         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
671     };
672 
673     // Sets common operation actions on RVV floating-point vector types.
674     const auto SetCommonVFPActions = [&](MVT VT) {
675       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
676       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
677       // sizes are within one power-of-two of each other. Therefore conversions
678       // between vXf16 and vXf64 must be lowered as sequences which convert via
679       // vXf32.
680       setOperationAction(ISD::FP_ROUND, VT, Custom);
681       setOperationAction(ISD::FP_EXTEND, VT, Custom);
682       // Custom-lower insert/extract operations to simplify patterns.
683       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
684       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
685       // Expand various condition codes (explained above).
686       for (auto CC : VFPCCToExpand)
687         setCondCodeAction(CC, VT, Expand);
688 
689       setOperationAction(ISD::FMINNUM, VT, Legal);
690       setOperationAction(ISD::FMAXNUM, VT, Legal);
691 
692       setOperationAction(ISD::FTRUNC, VT, Custom);
693       setOperationAction(ISD::FCEIL, VT, Custom);
694       setOperationAction(ISD::FFLOOR, VT, Custom);
695 
696       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
697       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
698       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
699       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
700 
701       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
702 
703       setOperationAction(ISD::LOAD, VT, Custom);
704       setOperationAction(ISD::STORE, VT, Custom);
705 
706       setOperationAction(ISD::MLOAD, VT, Custom);
707       setOperationAction(ISD::MSTORE, VT, Custom);
708       setOperationAction(ISD::MGATHER, VT, Custom);
709       setOperationAction(ISD::MSCATTER, VT, Custom);
710 
711       setOperationAction(ISD::VP_LOAD, VT, Custom);
712       setOperationAction(ISD::VP_STORE, VT, Custom);
713       setOperationAction(ISD::VP_GATHER, VT, Custom);
714       setOperationAction(ISD::VP_SCATTER, VT, Custom);
715 
716       setOperationAction(ISD::SELECT, VT, Custom);
717       setOperationAction(ISD::SELECT_CC, VT, Expand);
718 
719       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
720       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
721       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
722 
723       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
724 
725       for (unsigned VPOpc : FloatingPointVPOps)
726         setOperationAction(VPOpc, VT, Custom);
727     };
728 
729     // Sets common extload/truncstore actions on RVV floating-point vector
730     // types.
731     const auto SetCommonVFPExtLoadTruncStoreActions =
732         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
733           for (auto SmallVT : SmallerVTs) {
734             setTruncStoreAction(VT, SmallVT, Expand);
735             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
736           }
737         };
738 
739     if (Subtarget.hasVInstructionsF16())
740       for (MVT VT : F16VecVTs)
741         SetCommonVFPActions(VT);
742 
743     for (MVT VT : F32VecVTs) {
744       if (Subtarget.hasVInstructionsF32())
745         SetCommonVFPActions(VT);
746       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
747     }
748 
749     for (MVT VT : F64VecVTs) {
750       if (Subtarget.hasVInstructionsF64())
751         SetCommonVFPActions(VT);
752       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
753       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
754     }
755 
756     if (Subtarget.useRVVForFixedLengthVectors()) {
757       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
758         if (!useRVVForFixedLengthVectorVT(VT))
759           continue;
760 
761         // By default everything must be expanded.
762         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
763           setOperationAction(Op, VT, Expand);
764         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
765           setTruncStoreAction(VT, OtherVT, Expand);
766           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
767           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
768           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
769         }
770 
771         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
772         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
773         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
774 
775         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
776         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
777 
778         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
779         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
780 
781         setOperationAction(ISD::LOAD, VT, Custom);
782         setOperationAction(ISD::STORE, VT, Custom);
783 
784         setOperationAction(ISD::SETCC, VT, Custom);
785 
786         setOperationAction(ISD::SELECT, VT, Custom);
787 
788         setOperationAction(ISD::TRUNCATE, VT, Custom);
789 
790         setOperationAction(ISD::BITCAST, VT, Custom);
791 
792         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
793         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
794         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
795 
796         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
797         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
798         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
799 
800         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
801         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
802         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
803         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
804 
805         // Operations below are different for between masks and other vectors.
806         if (VT.getVectorElementType() == MVT::i1) {
807           setOperationAction(ISD::AND, VT, Custom);
808           setOperationAction(ISD::OR, VT, Custom);
809           setOperationAction(ISD::XOR, VT, Custom);
810           continue;
811         }
812 
813         // Use SPLAT_VECTOR to prevent type legalization from destroying the
814         // splats when type legalizing i64 scalar on RV32.
815         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
816         // improvements first.
817         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
818           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
819           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
820         }
821 
822         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
823         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
824 
825         setOperationAction(ISD::MLOAD, VT, Custom);
826         setOperationAction(ISD::MSTORE, VT, Custom);
827         setOperationAction(ISD::MGATHER, VT, Custom);
828         setOperationAction(ISD::MSCATTER, VT, Custom);
829 
830         setOperationAction(ISD::VP_LOAD, VT, Custom);
831         setOperationAction(ISD::VP_STORE, VT, Custom);
832         setOperationAction(ISD::VP_GATHER, VT, Custom);
833         setOperationAction(ISD::VP_SCATTER, VT, Custom);
834 
835         setOperationAction(ISD::ADD, VT, Custom);
836         setOperationAction(ISD::MUL, VT, Custom);
837         setOperationAction(ISD::SUB, VT, Custom);
838         setOperationAction(ISD::AND, VT, Custom);
839         setOperationAction(ISD::OR, VT, Custom);
840         setOperationAction(ISD::XOR, VT, Custom);
841         setOperationAction(ISD::SDIV, VT, Custom);
842         setOperationAction(ISD::SREM, VT, Custom);
843         setOperationAction(ISD::UDIV, VT, Custom);
844         setOperationAction(ISD::UREM, VT, Custom);
845         setOperationAction(ISD::SHL, VT, Custom);
846         setOperationAction(ISD::SRA, VT, Custom);
847         setOperationAction(ISD::SRL, VT, Custom);
848 
849         setOperationAction(ISD::SMIN, VT, Custom);
850         setOperationAction(ISD::SMAX, VT, Custom);
851         setOperationAction(ISD::UMIN, VT, Custom);
852         setOperationAction(ISD::UMAX, VT, Custom);
853         setOperationAction(ISD::ABS,  VT, Custom);
854 
855         setOperationAction(ISD::MULHS, VT, Custom);
856         setOperationAction(ISD::MULHU, VT, Custom);
857 
858         setOperationAction(ISD::SADDSAT, VT, Custom);
859         setOperationAction(ISD::UADDSAT, VT, Custom);
860         setOperationAction(ISD::SSUBSAT, VT, Custom);
861         setOperationAction(ISD::USUBSAT, VT, Custom);
862 
863         setOperationAction(ISD::VSELECT, VT, Custom);
864         setOperationAction(ISD::SELECT_CC, VT, Expand);
865 
866         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
867         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
868         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
869 
870         // Custom-lower reduction operations to set up the corresponding custom
871         // nodes' operands.
872         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
873         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
874         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
875         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
876         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
877 
878         for (unsigned VPOpc : IntegerVPOps)
879           setOperationAction(VPOpc, VT, Custom);
880 
881         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
882         // type that can represent the value exactly.
883         if (VT.getVectorElementType() != MVT::i64) {
884           MVT FloatEltVT =
885               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
886           EVT FloatVT =
887               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
888           if (isTypeLegal(FloatVT)) {
889             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
890             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
891           }
892         }
893       }
894 
895       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
896         if (!useRVVForFixedLengthVectorVT(VT))
897           continue;
898 
899         // By default everything must be expanded.
900         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
901           setOperationAction(Op, VT, Expand);
902         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
903           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
904           setTruncStoreAction(VT, OtherVT, Expand);
905         }
906 
907         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
908         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
909         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
910 
911         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
912         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
913         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
914         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
915         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
916 
917         setOperationAction(ISD::LOAD, VT, Custom);
918         setOperationAction(ISD::STORE, VT, Custom);
919         setOperationAction(ISD::MLOAD, VT, Custom);
920         setOperationAction(ISD::MSTORE, VT, Custom);
921         setOperationAction(ISD::MGATHER, VT, Custom);
922         setOperationAction(ISD::MSCATTER, VT, Custom);
923 
924         setOperationAction(ISD::VP_LOAD, VT, Custom);
925         setOperationAction(ISD::VP_STORE, VT, Custom);
926         setOperationAction(ISD::VP_GATHER, VT, Custom);
927         setOperationAction(ISD::VP_SCATTER, VT, Custom);
928 
929         setOperationAction(ISD::FADD, VT, Custom);
930         setOperationAction(ISD::FSUB, VT, Custom);
931         setOperationAction(ISD::FMUL, VT, Custom);
932         setOperationAction(ISD::FDIV, VT, Custom);
933         setOperationAction(ISD::FNEG, VT, Custom);
934         setOperationAction(ISD::FABS, VT, Custom);
935         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
936         setOperationAction(ISD::FSQRT, VT, Custom);
937         setOperationAction(ISD::FMA, VT, Custom);
938         setOperationAction(ISD::FMINNUM, VT, Custom);
939         setOperationAction(ISD::FMAXNUM, VT, Custom);
940 
941         setOperationAction(ISD::FP_ROUND, VT, Custom);
942         setOperationAction(ISD::FP_EXTEND, VT, Custom);
943 
944         setOperationAction(ISD::FTRUNC, VT, Custom);
945         setOperationAction(ISD::FCEIL, VT, Custom);
946         setOperationAction(ISD::FFLOOR, VT, Custom);
947 
948         for (auto CC : VFPCCToExpand)
949           setCondCodeAction(CC, VT, Expand);
950 
951         setOperationAction(ISD::VSELECT, VT, Custom);
952         setOperationAction(ISD::SELECT, VT, Custom);
953         setOperationAction(ISD::SELECT_CC, VT, Expand);
954 
955         setOperationAction(ISD::BITCAST, VT, Custom);
956 
957         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
958         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
959         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
960         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
961 
962         for (unsigned VPOpc : FloatingPointVPOps)
963           setOperationAction(VPOpc, VT, Custom);
964       }
965 
966       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
967       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
968       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
969       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
970       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
971       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
972       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
973       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
974     }
975   }
976 
977   // Function alignments.
978   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
979   setMinFunctionAlignment(FunctionAlignment);
980   setPrefFunctionAlignment(FunctionAlignment);
981 
982   setMinimumJumpTableEntries(5);
983 
984   // Jumps are expensive, compared to logic
985   setJumpIsExpensive();
986 
987   setTargetDAGCombine(ISD::ADD);
988   setTargetDAGCombine(ISD::SUB);
989   setTargetDAGCombine(ISD::AND);
990   setTargetDAGCombine(ISD::OR);
991   setTargetDAGCombine(ISD::XOR);
992   setTargetDAGCombine(ISD::ANY_EXTEND);
993   setTargetDAGCombine(ISD::ZERO_EXTEND);
994   if (Subtarget.hasVInstructions()) {
995     setTargetDAGCombine(ISD::FCOPYSIGN);
996     setTargetDAGCombine(ISD::MGATHER);
997     setTargetDAGCombine(ISD::MSCATTER);
998     setTargetDAGCombine(ISD::VP_GATHER);
999     setTargetDAGCombine(ISD::VP_SCATTER);
1000     setTargetDAGCombine(ISD::SRA);
1001     setTargetDAGCombine(ISD::SRL);
1002     setTargetDAGCombine(ISD::SHL);
1003     setTargetDAGCombine(ISD::STORE);
1004   }
1005 }
1006 
1007 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1008                                             LLVMContext &Context,
1009                                             EVT VT) const {
1010   if (!VT.isVector())
1011     return getPointerTy(DL);
1012   if (Subtarget.hasVInstructions() &&
1013       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1014     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1015   return VT.changeVectorElementTypeToInteger();
1016 }
1017 
1018 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1019   return Subtarget.getXLenVT();
1020 }
1021 
1022 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1023                                              const CallInst &I,
1024                                              MachineFunction &MF,
1025                                              unsigned Intrinsic) const {
1026   auto &DL = I.getModule()->getDataLayout();
1027   switch (Intrinsic) {
1028   default:
1029     return false;
1030   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1031   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1032   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1033   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1034   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1035   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1036   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1037   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1038   case Intrinsic::riscv_masked_cmpxchg_i32: {
1039     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1040     Info.opc = ISD::INTRINSIC_W_CHAIN;
1041     Info.memVT = MVT::getVT(PtrTy->getElementType());
1042     Info.ptrVal = I.getArgOperand(0);
1043     Info.offset = 0;
1044     Info.align = Align(4);
1045     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1046                  MachineMemOperand::MOVolatile;
1047     return true;
1048   }
1049   case Intrinsic::riscv_masked_strided_load:
1050     Info.opc = ISD::INTRINSIC_W_CHAIN;
1051     Info.ptrVal = I.getArgOperand(1);
1052     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1053     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1054     Info.size = MemoryLocation::UnknownSize;
1055     Info.flags |= MachineMemOperand::MOLoad;
1056     return true;
1057   case Intrinsic::riscv_masked_strided_store:
1058     Info.opc = ISD::INTRINSIC_VOID;
1059     Info.ptrVal = I.getArgOperand(1);
1060     Info.memVT =
1061         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1062     Info.align = Align(
1063         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1064         8);
1065     Info.size = MemoryLocation::UnknownSize;
1066     Info.flags |= MachineMemOperand::MOStore;
1067     return true;
1068   }
1069 }
1070 
1071 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1072                                                 const AddrMode &AM, Type *Ty,
1073                                                 unsigned AS,
1074                                                 Instruction *I) const {
1075   // No global is ever allowed as a base.
1076   if (AM.BaseGV)
1077     return false;
1078 
1079   // Require a 12-bit signed offset.
1080   if (!isInt<12>(AM.BaseOffs))
1081     return false;
1082 
1083   switch (AM.Scale) {
1084   case 0: // "r+i" or just "i", depending on HasBaseReg.
1085     break;
1086   case 1:
1087     if (!AM.HasBaseReg) // allow "r+i".
1088       break;
1089     return false; // disallow "r+r" or "r+r+i".
1090   default:
1091     return false;
1092   }
1093 
1094   return true;
1095 }
1096 
1097 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1098   return isInt<12>(Imm);
1099 }
1100 
1101 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1102   return isInt<12>(Imm);
1103 }
1104 
1105 // On RV32, 64-bit integers are split into their high and low parts and held
1106 // in two different registers, so the trunc is free since the low register can
1107 // just be used.
1108 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1109   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1110     return false;
1111   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1112   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1113   return (SrcBits == 64 && DestBits == 32);
1114 }
1115 
1116 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1117   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1118       !SrcVT.isInteger() || !DstVT.isInteger())
1119     return false;
1120   unsigned SrcBits = SrcVT.getSizeInBits();
1121   unsigned DestBits = DstVT.getSizeInBits();
1122   return (SrcBits == 64 && DestBits == 32);
1123 }
1124 
1125 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1126   // Zexts are free if they can be combined with a load.
1127   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1128     EVT MemVT = LD->getMemoryVT();
1129     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1130          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1131         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1132          LD->getExtensionType() == ISD::ZEXTLOAD))
1133       return true;
1134   }
1135 
1136   return TargetLowering::isZExtFree(Val, VT2);
1137 }
1138 
1139 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1140   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1141 }
1142 
1143 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1144   return Subtarget.hasStdExtZbb();
1145 }
1146 
1147 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1148   return Subtarget.hasStdExtZbb();
1149 }
1150 
1151 bool RISCVTargetLowering::hasAndNot(SDValue Y) const {
1152   EVT VT = Y.getValueType();
1153 
1154   // FIXME: Support vectors once we have tests.
1155   if (VT.isVector())
1156     return false;
1157 
1158   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1159 }
1160 
1161 /// Check if sinking \p I's operands to I's basic block is profitable, because
1162 /// the operands can be folded into a target instruction, e.g.
1163 /// splats of scalars can fold into vector instructions.
1164 bool RISCVTargetLowering::shouldSinkOperands(
1165     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1166   using namespace llvm::PatternMatch;
1167 
1168   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1169     return false;
1170 
1171   auto IsSinker = [&](Instruction *I, int Operand) {
1172     switch (I->getOpcode()) {
1173     case Instruction::Add:
1174     case Instruction::Sub:
1175     case Instruction::Mul:
1176     case Instruction::And:
1177     case Instruction::Or:
1178     case Instruction::Xor:
1179     case Instruction::FAdd:
1180     case Instruction::FSub:
1181     case Instruction::FMul:
1182     case Instruction::FDiv:
1183     case Instruction::ICmp:
1184     case Instruction::FCmp:
1185       return true;
1186     case Instruction::Shl:
1187     case Instruction::LShr:
1188     case Instruction::AShr:
1189     case Instruction::UDiv:
1190     case Instruction::SDiv:
1191     case Instruction::URem:
1192     case Instruction::SRem:
1193       return Operand == 1;
1194     case Instruction::Call:
1195       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1196         switch (II->getIntrinsicID()) {
1197         case Intrinsic::fma:
1198           return Operand == 0 || Operand == 1;
1199         default:
1200           return false;
1201         }
1202       }
1203       return false;
1204     default:
1205       return false;
1206     }
1207   };
1208 
1209   for (auto OpIdx : enumerate(I->operands())) {
1210     if (!IsSinker(I, OpIdx.index()))
1211       continue;
1212 
1213     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1214     // Make sure we are not already sinking this operand
1215     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1216       continue;
1217 
1218     // We are looking for a splat that can be sunk.
1219     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1220                              m_Undef(), m_ZeroMask())))
1221       continue;
1222 
1223     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1224     // and vector registers
1225     for (Use &U : Op->uses()) {
1226       Instruction *Insn = cast<Instruction>(U.getUser());
1227       if (!IsSinker(Insn, U.getOperandNo()))
1228         return false;
1229     }
1230 
1231     Ops.push_back(&Op->getOperandUse(0));
1232     Ops.push_back(&OpIdx.value());
1233   }
1234   return true;
1235 }
1236 
1237 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1238                                        bool ForCodeSize) const {
1239   if (VT == MVT::f16 && !Subtarget.hasStdExtZfhmin())
1240     return false;
1241   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1242     return false;
1243   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1244     return false;
1245   if (Imm.isNegZero())
1246     return false;
1247   return Imm.isZero();
1248 }
1249 
1250 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1251   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1252          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1253          (VT == MVT::f64 && Subtarget.hasStdExtD());
1254 }
1255 
1256 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1257                                                       CallingConv::ID CC,
1258                                                       EVT VT) const {
1259   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1260   // We might still end up using a GPR but that will be decided based on ABI.
1261   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1262     return MVT::f32;
1263 
1264   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1265 }
1266 
1267 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1268                                                            CallingConv::ID CC,
1269                                                            EVT VT) const {
1270   // Use f32 to pass f16 if it is legal and Zfhmin/Zfh is not enabled.
1271   // We might still end up using a GPR but that will be decided based on ABI.
1272   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfhmin())
1273     return 1;
1274 
1275   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1276 }
1277 
1278 // Changes the condition code and swaps operands if necessary, so the SetCC
1279 // operation matches one of the comparisons supported directly by branches
1280 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1281 // with 1/-1.
1282 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1283                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1284   // Convert X > -1 to X >= 0.
1285   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1286     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1287     CC = ISD::SETGE;
1288     return;
1289   }
1290   // Convert X < 1 to 0 >= X.
1291   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1292     RHS = LHS;
1293     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1294     CC = ISD::SETGE;
1295     return;
1296   }
1297 
1298   switch (CC) {
1299   default:
1300     break;
1301   case ISD::SETGT:
1302   case ISD::SETLE:
1303   case ISD::SETUGT:
1304   case ISD::SETULE:
1305     CC = ISD::getSetCCSwappedOperands(CC);
1306     std::swap(LHS, RHS);
1307     break;
1308   }
1309 }
1310 
1311 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1312   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1313   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1314   if (VT.getVectorElementType() == MVT::i1)
1315     KnownSize *= 8;
1316 
1317   switch (KnownSize) {
1318   default:
1319     llvm_unreachable("Invalid LMUL.");
1320   case 8:
1321     return RISCVII::VLMUL::LMUL_F8;
1322   case 16:
1323     return RISCVII::VLMUL::LMUL_F4;
1324   case 32:
1325     return RISCVII::VLMUL::LMUL_F2;
1326   case 64:
1327     return RISCVII::VLMUL::LMUL_1;
1328   case 128:
1329     return RISCVII::VLMUL::LMUL_2;
1330   case 256:
1331     return RISCVII::VLMUL::LMUL_4;
1332   case 512:
1333     return RISCVII::VLMUL::LMUL_8;
1334   }
1335 }
1336 
1337 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1338   switch (LMul) {
1339   default:
1340     llvm_unreachable("Invalid LMUL.");
1341   case RISCVII::VLMUL::LMUL_F8:
1342   case RISCVII::VLMUL::LMUL_F4:
1343   case RISCVII::VLMUL::LMUL_F2:
1344   case RISCVII::VLMUL::LMUL_1:
1345     return RISCV::VRRegClassID;
1346   case RISCVII::VLMUL::LMUL_2:
1347     return RISCV::VRM2RegClassID;
1348   case RISCVII::VLMUL::LMUL_4:
1349     return RISCV::VRM4RegClassID;
1350   case RISCVII::VLMUL::LMUL_8:
1351     return RISCV::VRM8RegClassID;
1352   }
1353 }
1354 
1355 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1356   RISCVII::VLMUL LMUL = getLMUL(VT);
1357   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1358       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1359       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1360       LMUL == RISCVII::VLMUL::LMUL_1) {
1361     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1362                   "Unexpected subreg numbering");
1363     return RISCV::sub_vrm1_0 + Index;
1364   }
1365   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1366     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1367                   "Unexpected subreg numbering");
1368     return RISCV::sub_vrm2_0 + Index;
1369   }
1370   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1371     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1372                   "Unexpected subreg numbering");
1373     return RISCV::sub_vrm4_0 + Index;
1374   }
1375   llvm_unreachable("Invalid vector type.");
1376 }
1377 
1378 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1379   if (VT.getVectorElementType() == MVT::i1)
1380     return RISCV::VRRegClassID;
1381   return getRegClassIDForLMUL(getLMUL(VT));
1382 }
1383 
1384 // Attempt to decompose a subvector insert/extract between VecVT and
1385 // SubVecVT via subregister indices. Returns the subregister index that
1386 // can perform the subvector insert/extract with the given element index, as
1387 // well as the index corresponding to any leftover subvectors that must be
1388 // further inserted/extracted within the register class for SubVecVT.
1389 std::pair<unsigned, unsigned>
1390 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1391     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1392     const RISCVRegisterInfo *TRI) {
1393   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1394                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1395                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1396                 "Register classes not ordered");
1397   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1398   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1399   // Try to compose a subregister index that takes us from the incoming
1400   // LMUL>1 register class down to the outgoing one. At each step we half
1401   // the LMUL:
1402   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1403   // Note that this is not guaranteed to find a subregister index, such as
1404   // when we are extracting from one VR type to another.
1405   unsigned SubRegIdx = RISCV::NoSubRegister;
1406   for (const unsigned RCID :
1407        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1408     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1409       VecVT = VecVT.getHalfNumVectorElementsVT();
1410       bool IsHi =
1411           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1412       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1413                                             getSubregIndexByMVT(VecVT, IsHi));
1414       if (IsHi)
1415         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1416     }
1417   return {SubRegIdx, InsertExtractIdx};
1418 }
1419 
1420 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1421 // stores for those types.
1422 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1423   return !Subtarget.useRVVForFixedLengthVectors() ||
1424          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1425 }
1426 
1427 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1428   if (ScalarTy->isPointerTy())
1429     return true;
1430 
1431   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1432       ScalarTy->isIntegerTy(32))
1433     return true;
1434 
1435   if (ScalarTy->isIntegerTy(64))
1436     return Subtarget.hasVInstructionsI64();
1437 
1438   if (ScalarTy->isHalfTy())
1439     return Subtarget.hasVInstructionsF16();
1440   if (ScalarTy->isFloatTy())
1441     return Subtarget.hasVInstructionsF32();
1442   if (ScalarTy->isDoubleTy())
1443     return Subtarget.hasVInstructionsF64();
1444 
1445   return false;
1446 }
1447 
1448 static bool useRVVForFixedLengthVectorVT(MVT VT,
1449                                          const RISCVSubtarget &Subtarget) {
1450   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1451   if (!Subtarget.useRVVForFixedLengthVectors())
1452     return false;
1453 
1454   // We only support a set of vector types with a consistent maximum fixed size
1455   // across all supported vector element types to avoid legalization issues.
1456   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1457   // fixed-length vector type we support is 1024 bytes.
1458   if (VT.getFixedSizeInBits() > 1024 * 8)
1459     return false;
1460 
1461   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1462 
1463   MVT EltVT = VT.getVectorElementType();
1464 
1465   // Don't use RVV for vectors we cannot scalarize if required.
1466   switch (EltVT.SimpleTy) {
1467   // i1 is supported but has different rules.
1468   default:
1469     return false;
1470   case MVT::i1:
1471     // Masks can only use a single register.
1472     if (VT.getVectorNumElements() > MinVLen)
1473       return false;
1474     MinVLen /= 8;
1475     break;
1476   case MVT::i8:
1477   case MVT::i16:
1478   case MVT::i32:
1479     break;
1480   case MVT::i64:
1481     if (!Subtarget.hasVInstructionsI64())
1482       return false;
1483     break;
1484   case MVT::f16:
1485     if (!Subtarget.hasVInstructionsF16())
1486       return false;
1487     break;
1488   case MVT::f32:
1489     if (!Subtarget.hasVInstructionsF32())
1490       return false;
1491     break;
1492   case MVT::f64:
1493     if (!Subtarget.hasVInstructionsF64())
1494       return false;
1495     break;
1496   }
1497 
1498   // Reject elements larger than ELEN.
1499   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1500     return false;
1501 
1502   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1503   // Don't use RVV for types that don't fit.
1504   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1505     return false;
1506 
1507   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1508   // the base fixed length RVV support in place.
1509   if (!VT.isPow2VectorType())
1510     return false;
1511 
1512   return true;
1513 }
1514 
1515 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1516   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1517 }
1518 
1519 // Return the largest legal scalable vector type that matches VT's element type.
1520 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1521                                             const RISCVSubtarget &Subtarget) {
1522   // This may be called before legal types are setup.
1523   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1524           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1525          "Expected legal fixed length vector!");
1526 
1527   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1528   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1529 
1530   MVT EltVT = VT.getVectorElementType();
1531   switch (EltVT.SimpleTy) {
1532   default:
1533     llvm_unreachable("unexpected element type for RVV container");
1534   case MVT::i1:
1535   case MVT::i8:
1536   case MVT::i16:
1537   case MVT::i32:
1538   case MVT::i64:
1539   case MVT::f16:
1540   case MVT::f32:
1541   case MVT::f64: {
1542     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1543     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1544     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1545     unsigned NumElts =
1546         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1547     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1548     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1549     return MVT::getScalableVectorVT(EltVT, NumElts);
1550   }
1551   }
1552 }
1553 
1554 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1555                                             const RISCVSubtarget &Subtarget) {
1556   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1557                                           Subtarget);
1558 }
1559 
1560 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1561   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1562 }
1563 
1564 // Grow V to consume an entire RVV register.
1565 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1566                                        const RISCVSubtarget &Subtarget) {
1567   assert(VT.isScalableVector() &&
1568          "Expected to convert into a scalable vector!");
1569   assert(V.getValueType().isFixedLengthVector() &&
1570          "Expected a fixed length vector operand!");
1571   SDLoc DL(V);
1572   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1573   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1574 }
1575 
1576 // Shrink V so it's just big enough to maintain a VT's worth of data.
1577 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1578                                          const RISCVSubtarget &Subtarget) {
1579   assert(VT.isFixedLengthVector() &&
1580          "Expected to convert into a fixed length vector!");
1581   assert(V.getValueType().isScalableVector() &&
1582          "Expected a scalable vector operand!");
1583   SDLoc DL(V);
1584   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1585   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1586 }
1587 
1588 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1589 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1590 // the vector type that it is contained in.
1591 static std::pair<SDValue, SDValue>
1592 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1593                 const RISCVSubtarget &Subtarget) {
1594   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1595   MVT XLenVT = Subtarget.getXLenVT();
1596   SDValue VL = VecVT.isFixedLengthVector()
1597                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1598                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1599   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1600   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1601   return {Mask, VL};
1602 }
1603 
1604 // As above but assuming the given type is a scalable vector type.
1605 static std::pair<SDValue, SDValue>
1606 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1607                         const RISCVSubtarget &Subtarget) {
1608   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1609   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1610 }
1611 
1612 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1613 // of either is (currently) supported. This can get us into an infinite loop
1614 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1615 // as a ..., etc.
1616 // Until either (or both) of these can reliably lower any node, reporting that
1617 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1618 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1619 // which is not desirable.
1620 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1621     EVT VT, unsigned DefinedValues) const {
1622   return false;
1623 }
1624 
1625 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1626   // Only splats are currently supported.
1627   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1628     return true;
1629 
1630   return false;
1631 }
1632 
1633 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1634   // RISCV FP-to-int conversions saturate to the destination register size, but
1635   // don't produce 0 for nan. We can use a conversion instruction and fix the
1636   // nan case with a compare and a select.
1637   SDValue Src = Op.getOperand(0);
1638 
1639   EVT DstVT = Op.getValueType();
1640   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1641 
1642   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1643   unsigned Opc;
1644   if (SatVT == DstVT)
1645     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1646   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1647     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1648   else
1649     return SDValue();
1650   // FIXME: Support other SatVTs by clamping before or after the conversion.
1651 
1652   SDLoc DL(Op);
1653   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1654 
1655   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1656   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1657 }
1658 
1659 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1660 // and back. Taking care to avoid converting values that are nan or already
1661 // correct.
1662 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1663 // have FRM dependencies modeled yet.
1664 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1665   MVT VT = Op.getSimpleValueType();
1666   assert(VT.isVector() && "Unexpected type");
1667 
1668   SDLoc DL(Op);
1669 
1670   // Freeze the source since we are increasing the number of uses.
1671   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1672 
1673   // Truncate to integer and convert back to FP.
1674   MVT IntVT = VT.changeVectorElementTypeToInteger();
1675   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1676   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1677 
1678   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1679 
1680   if (Op.getOpcode() == ISD::FCEIL) {
1681     // If the truncated value is the greater than or equal to the original
1682     // value, we've computed the ceil. Otherwise, we went the wrong way and
1683     // need to increase by 1.
1684     // FIXME: This should use a masked operation. Handle here or in isel?
1685     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1686                                  DAG.getConstantFP(1.0, DL, VT));
1687     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1688     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1689   } else if (Op.getOpcode() == ISD::FFLOOR) {
1690     // If the truncated value is the less than or equal to the original value,
1691     // we've computed the floor. Otherwise, we went the wrong way and need to
1692     // decrease by 1.
1693     // FIXME: This should use a masked operation. Handle here or in isel?
1694     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1695                                  DAG.getConstantFP(1.0, DL, VT));
1696     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1697     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1698   }
1699 
1700   // Restore the original sign so that -0.0 is preserved.
1701   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1702 
1703   // Determine the largest integer that can be represented exactly. This and
1704   // values larger than it don't have any fractional bits so don't need to
1705   // be converted.
1706   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1707   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1708   APFloat MaxVal = APFloat(FltSem);
1709   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1710                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1711   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1712 
1713   // If abs(Src) was larger than MaxVal or nan, keep it.
1714   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1715   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1716   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1717 }
1718 
1719 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1720                                  const RISCVSubtarget &Subtarget) {
1721   MVT VT = Op.getSimpleValueType();
1722   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1723 
1724   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1725 
1726   SDLoc DL(Op);
1727   SDValue Mask, VL;
1728   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1729 
1730   unsigned Opc =
1731       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1732   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1733   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1734 }
1735 
1736 struct VIDSequence {
1737   int64_t StepNumerator;
1738   unsigned StepDenominator;
1739   int64_t Addend;
1740 };
1741 
1742 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1743 // to the (non-zero) step S and start value X. This can be then lowered as the
1744 // RVV sequence (VID * S) + X, for example.
1745 // The step S is represented as an integer numerator divided by a positive
1746 // denominator. Note that the implementation currently only identifies
1747 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1748 // cannot detect 2/3, for example.
1749 // Note that this method will also match potentially unappealing index
1750 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1751 // determine whether this is worth generating code for.
1752 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1753   unsigned NumElts = Op.getNumOperands();
1754   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1755   if (!Op.getValueType().isInteger())
1756     return None;
1757 
1758   Optional<unsigned> SeqStepDenom;
1759   Optional<int64_t> SeqStepNum, SeqAddend;
1760   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1761   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1762   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1763     // Assume undef elements match the sequence; we just have to be careful
1764     // when interpolating across them.
1765     if (Op.getOperand(Idx).isUndef())
1766       continue;
1767     // The BUILD_VECTOR must be all constants.
1768     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1769       return None;
1770 
1771     uint64_t Val = Op.getConstantOperandVal(Idx) &
1772                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1773 
1774     if (PrevElt) {
1775       // Calculate the step since the last non-undef element, and ensure
1776       // it's consistent across the entire sequence.
1777       unsigned IdxDiff = Idx - PrevElt->second;
1778       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1779 
1780       // A zero-value value difference means that we're somewhere in the middle
1781       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1782       // step change before evaluating the sequence.
1783       if (ValDiff != 0) {
1784         int64_t Remainder = ValDiff % IdxDiff;
1785         // Normalize the step if it's greater than 1.
1786         if (Remainder != ValDiff) {
1787           // The difference must cleanly divide the element span.
1788           if (Remainder != 0)
1789             return None;
1790           ValDiff /= IdxDiff;
1791           IdxDiff = 1;
1792         }
1793 
1794         if (!SeqStepNum)
1795           SeqStepNum = ValDiff;
1796         else if (ValDiff != SeqStepNum)
1797           return None;
1798 
1799         if (!SeqStepDenom)
1800           SeqStepDenom = IdxDiff;
1801         else if (IdxDiff != *SeqStepDenom)
1802           return None;
1803       }
1804     }
1805 
1806     // Record and/or check any addend.
1807     if (SeqStepNum && SeqStepDenom) {
1808       uint64_t ExpectedVal =
1809           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1810       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1811       if (!SeqAddend)
1812         SeqAddend = Addend;
1813       else if (SeqAddend != Addend)
1814         return None;
1815     }
1816 
1817     // Record this non-undef element for later.
1818     if (!PrevElt || PrevElt->first != Val)
1819       PrevElt = std::make_pair(Val, Idx);
1820   }
1821   // We need to have logged both a step and an addend for this to count as
1822   // a legal index sequence.
1823   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1824     return None;
1825 
1826   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1827 }
1828 
1829 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1830                                  const RISCVSubtarget &Subtarget) {
1831   MVT VT = Op.getSimpleValueType();
1832   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1833 
1834   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1835 
1836   SDLoc DL(Op);
1837   SDValue Mask, VL;
1838   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1839 
1840   MVT XLenVT = Subtarget.getXLenVT();
1841   unsigned NumElts = Op.getNumOperands();
1842 
1843   if (VT.getVectorElementType() == MVT::i1) {
1844     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1845       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1846       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1847     }
1848 
1849     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1850       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1851       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1852     }
1853 
1854     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1855     // scalar integer chunks whose bit-width depends on the number of mask
1856     // bits and XLEN.
1857     // First, determine the most appropriate scalar integer type to use. This
1858     // is at most XLenVT, but may be shrunk to a smaller vector element type
1859     // according to the size of the final vector - use i8 chunks rather than
1860     // XLenVT if we're producing a v8i1. This results in more consistent
1861     // codegen across RV32 and RV64.
1862     unsigned NumViaIntegerBits =
1863         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1864     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1865       // If we have to use more than one INSERT_VECTOR_ELT then this
1866       // optimization is likely to increase code size; avoid peforming it in
1867       // such a case. We can use a load from a constant pool in this case.
1868       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1869         return SDValue();
1870       // Now we can create our integer vector type. Note that it may be larger
1871       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1872       MVT IntegerViaVecVT =
1873           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1874                            divideCeil(NumElts, NumViaIntegerBits));
1875 
1876       uint64_t Bits = 0;
1877       unsigned BitPos = 0, IntegerEltIdx = 0;
1878       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1879 
1880       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1881         // Once we accumulate enough bits to fill our scalar type, insert into
1882         // our vector and clear our accumulated data.
1883         if (I != 0 && I % NumViaIntegerBits == 0) {
1884           if (NumViaIntegerBits <= 32)
1885             Bits = SignExtend64(Bits, 32);
1886           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1887           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1888                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1889           Bits = 0;
1890           BitPos = 0;
1891           IntegerEltIdx++;
1892         }
1893         SDValue V = Op.getOperand(I);
1894         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1895         Bits |= ((uint64_t)BitValue << BitPos);
1896       }
1897 
1898       // Insert the (remaining) scalar value into position in our integer
1899       // vector type.
1900       if (NumViaIntegerBits <= 32)
1901         Bits = SignExtend64(Bits, 32);
1902       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1903       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1904                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1905 
1906       if (NumElts < NumViaIntegerBits) {
1907         // If we're producing a smaller vector than our minimum legal integer
1908         // type, bitcast to the equivalent (known-legal) mask type, and extract
1909         // our final mask.
1910         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1911         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1912         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1913                           DAG.getConstant(0, DL, XLenVT));
1914       } else {
1915         // Else we must have produced an integer type with the same size as the
1916         // mask type; bitcast for the final result.
1917         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1918         Vec = DAG.getBitcast(VT, Vec);
1919       }
1920 
1921       return Vec;
1922     }
1923 
1924     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1925     // vector type, we have a legal equivalently-sized i8 type, so we can use
1926     // that.
1927     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1928     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1929 
1930     SDValue WideVec;
1931     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1932       // For a splat, perform a scalar truncate before creating the wider
1933       // vector.
1934       assert(Splat.getValueType() == XLenVT &&
1935              "Unexpected type for i1 splat value");
1936       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1937                           DAG.getConstant(1, DL, XLenVT));
1938       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1939     } else {
1940       SmallVector<SDValue, 8> Ops(Op->op_values());
1941       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1942       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1943       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1944     }
1945 
1946     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1947   }
1948 
1949   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1950     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1951                                         : RISCVISD::VMV_V_X_VL;
1952     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1953     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1954   }
1955 
1956   // Try and match index sequences, which we can lower to the vid instruction
1957   // with optional modifications. An all-undef vector is matched by
1958   // getSplatValue, above.
1959   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1960     int64_t StepNumerator = SimpleVID->StepNumerator;
1961     unsigned StepDenominator = SimpleVID->StepDenominator;
1962     int64_t Addend = SimpleVID->Addend;
1963 
1964     assert(StepNumerator != 0 && "Invalid step");
1965     bool Negate = false;
1966     int64_t SplatStepVal = StepNumerator;
1967     unsigned StepOpcode = ISD::MUL;
1968     if (StepNumerator != 1) {
1969       if (isPowerOf2_64(std::abs(StepNumerator))) {
1970         Negate = StepNumerator < 0;
1971         StepOpcode = ISD::SHL;
1972         SplatStepVal = Log2_64(std::abs(StepNumerator));
1973       }
1974     }
1975 
1976     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1977     // threshold since it's the immediate value many RVV instructions accept.
1978     // There is no vmul.vi instruction so ensure multiply constant can fit in
1979     // a single addi instruction.
1980     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
1981          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
1982         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
1983       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1984       // Convert right out of the scalable type so we can use standard ISD
1985       // nodes for the rest of the computation. If we used scalable types with
1986       // these, we'd lose the fixed-length vector info and generate worse
1987       // vsetvli code.
1988       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1989       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
1990           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
1991         SDValue SplatStep = DAG.getSplatVector(
1992             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1993         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
1994       }
1995       if (StepDenominator != 1) {
1996         SDValue SplatStep = DAG.getSplatVector(
1997             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1998         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1999       }
2000       if (Addend != 0 || Negate) {
2001         SDValue SplatAddend =
2002             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2003         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2004       }
2005       return VID;
2006     }
2007   }
2008 
2009   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2010   // when re-interpreted as a vector with a larger element type. For example,
2011   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2012   // could be instead splat as
2013   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2014   // TODO: This optimization could also work on non-constant splats, but it
2015   // would require bit-manipulation instructions to construct the splat value.
2016   SmallVector<SDValue> Sequence;
2017   unsigned EltBitSize = VT.getScalarSizeInBits();
2018   const auto *BV = cast<BuildVectorSDNode>(Op);
2019   if (VT.isInteger() && EltBitSize < 64 &&
2020       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2021       BV->getRepeatedSequence(Sequence) &&
2022       (Sequence.size() * EltBitSize) <= 64) {
2023     unsigned SeqLen = Sequence.size();
2024     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2025     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2026     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2027             ViaIntVT == MVT::i64) &&
2028            "Unexpected sequence type");
2029 
2030     unsigned EltIdx = 0;
2031     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2032     uint64_t SplatValue = 0;
2033     // Construct the amalgamated value which can be splatted as this larger
2034     // vector type.
2035     for (const auto &SeqV : Sequence) {
2036       if (!SeqV.isUndef())
2037         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2038                        << (EltIdx * EltBitSize));
2039       EltIdx++;
2040     }
2041 
2042     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2043     // achieve better constant materializion.
2044     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2045       SplatValue = SignExtend64(SplatValue, 32);
2046 
2047     // Since we can't introduce illegal i64 types at this stage, we can only
2048     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2049     // way we can use RVV instructions to splat.
2050     assert((ViaIntVT.bitsLE(XLenVT) ||
2051             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2052            "Unexpected bitcast sequence");
2053     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2054       SDValue ViaVL =
2055           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2056       MVT ViaContainerVT =
2057           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2058       SDValue Splat =
2059           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2060                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2061       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2062       return DAG.getBitcast(VT, Splat);
2063     }
2064   }
2065 
2066   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2067   // which constitute a large proportion of the elements. In such cases we can
2068   // splat a vector with the dominant element and make up the shortfall with
2069   // INSERT_VECTOR_ELTs.
2070   // Note that this includes vectors of 2 elements by association. The
2071   // upper-most element is the "dominant" one, allowing us to use a splat to
2072   // "insert" the upper element, and an insert of the lower element at position
2073   // 0, which improves codegen.
2074   SDValue DominantValue;
2075   unsigned MostCommonCount = 0;
2076   DenseMap<SDValue, unsigned> ValueCounts;
2077   unsigned NumUndefElts =
2078       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2079 
2080   // Track the number of scalar loads we know we'd be inserting, estimated as
2081   // any non-zero floating-point constant. Other kinds of element are either
2082   // already in registers or are materialized on demand. The threshold at which
2083   // a vector load is more desirable than several scalar materializion and
2084   // vector-insertion instructions is not known.
2085   unsigned NumScalarLoads = 0;
2086 
2087   for (SDValue V : Op->op_values()) {
2088     if (V.isUndef())
2089       continue;
2090 
2091     ValueCounts.insert(std::make_pair(V, 0));
2092     unsigned &Count = ValueCounts[V];
2093 
2094     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2095       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2096 
2097     // Is this value dominant? In case of a tie, prefer the highest element as
2098     // it's cheaper to insert near the beginning of a vector than it is at the
2099     // end.
2100     if (++Count >= MostCommonCount) {
2101       DominantValue = V;
2102       MostCommonCount = Count;
2103     }
2104   }
2105 
2106   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2107   unsigned NumDefElts = NumElts - NumUndefElts;
2108   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2109 
2110   // Don't perform this optimization when optimizing for size, since
2111   // materializing elements and inserting them tends to cause code bloat.
2112   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2113       ((MostCommonCount > DominantValueCountThreshold) ||
2114        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2115     // Start by splatting the most common element.
2116     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2117 
2118     DenseSet<SDValue> Processed{DominantValue};
2119     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2120     for (const auto &OpIdx : enumerate(Op->ops())) {
2121       const SDValue &V = OpIdx.value();
2122       if (V.isUndef() || !Processed.insert(V).second)
2123         continue;
2124       if (ValueCounts[V] == 1) {
2125         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2126                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2127       } else {
2128         // Blend in all instances of this value using a VSELECT, using a
2129         // mask where each bit signals whether that element is the one
2130         // we're after.
2131         SmallVector<SDValue> Ops;
2132         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2133           return DAG.getConstant(V == V1, DL, XLenVT);
2134         });
2135         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2136                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2137                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2138       }
2139     }
2140 
2141     return Vec;
2142   }
2143 
2144   return SDValue();
2145 }
2146 
2147 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2148                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2149   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2150     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2151     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2152     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2153     // node in order to try and match RVV vector/scalar instructions.
2154     if ((LoC >> 31) == HiC)
2155       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2156   }
2157 
2158   // Fall back to a stack store and stride x0 vector load.
2159   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2160 }
2161 
2162 // Called by type legalization to handle splat of i64 on RV32.
2163 // FIXME: We can optimize this when the type has sign or zero bits in one
2164 // of the halves.
2165 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2166                                    SDValue VL, SelectionDAG &DAG) {
2167   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2168   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2169                            DAG.getConstant(0, DL, MVT::i32));
2170   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2171                            DAG.getConstant(1, DL, MVT::i32));
2172   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2173 }
2174 
2175 // This function lowers a splat of a scalar operand Splat with the vector
2176 // length VL. It ensures the final sequence is type legal, which is useful when
2177 // lowering a splat after type legalization.
2178 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2179                                 SelectionDAG &DAG,
2180                                 const RISCVSubtarget &Subtarget) {
2181   if (VT.isFloatingPoint())
2182     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2183 
2184   MVT XLenVT = Subtarget.getXLenVT();
2185 
2186   // Simplest case is that the operand needs to be promoted to XLenVT.
2187   if (Scalar.getValueType().bitsLE(XLenVT)) {
2188     // If the operand is a constant, sign extend to increase our chances
2189     // of being able to use a .vi instruction. ANY_EXTEND would become a
2190     // a zero extend and the simm5 check in isel would fail.
2191     // FIXME: Should we ignore the upper bits in isel instead?
2192     unsigned ExtOpc =
2193         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2194     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2195     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2196   }
2197 
2198   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2199          "Unexpected scalar for splat lowering!");
2200 
2201   // Otherwise use the more complicated splatting algorithm.
2202   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2203 }
2204 
2205 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2206                                    const RISCVSubtarget &Subtarget) {
2207   SDValue V1 = Op.getOperand(0);
2208   SDValue V2 = Op.getOperand(1);
2209   SDLoc DL(Op);
2210   MVT XLenVT = Subtarget.getXLenVT();
2211   MVT VT = Op.getSimpleValueType();
2212   unsigned NumElts = VT.getVectorNumElements();
2213   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2214 
2215   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2216 
2217   SDValue TrueMask, VL;
2218   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2219 
2220   if (SVN->isSplat()) {
2221     const int Lane = SVN->getSplatIndex();
2222     if (Lane >= 0) {
2223       MVT SVT = VT.getVectorElementType();
2224 
2225       // Turn splatted vector load into a strided load with an X0 stride.
2226       SDValue V = V1;
2227       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2228       // with undef.
2229       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2230       int Offset = Lane;
2231       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2232         int OpElements =
2233             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2234         V = V.getOperand(Offset / OpElements);
2235         Offset %= OpElements;
2236       }
2237 
2238       // We need to ensure the load isn't atomic or volatile.
2239       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2240         auto *Ld = cast<LoadSDNode>(V);
2241         Offset *= SVT.getStoreSize();
2242         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2243                                                    TypeSize::Fixed(Offset), DL);
2244 
2245         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2246         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2247           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2248           SDValue IntID =
2249               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2250           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2251                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2252           SDValue NewLoad = DAG.getMemIntrinsicNode(
2253               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2254               DAG.getMachineFunction().getMachineMemOperand(
2255                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2256           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2257           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2258         }
2259 
2260         // Otherwise use a scalar load and splat. This will give the best
2261         // opportunity to fold a splat into the operation. ISel can turn it into
2262         // the x0 strided load if we aren't able to fold away the select.
2263         if (SVT.isFloatingPoint())
2264           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2265                           Ld->getPointerInfo().getWithOffset(Offset),
2266                           Ld->getOriginalAlign(),
2267                           Ld->getMemOperand()->getFlags());
2268         else
2269           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2270                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2271                              Ld->getOriginalAlign(),
2272                              Ld->getMemOperand()->getFlags());
2273         DAG.makeEquivalentMemoryOrdering(Ld, V);
2274 
2275         unsigned Opc =
2276             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2277         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2278         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2279       }
2280 
2281       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2282       assert(Lane < (int)NumElts && "Unexpected lane!");
2283       SDValue Gather =
2284           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2285                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2286       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2287     }
2288   }
2289 
2290   // Detect shuffles which can be re-expressed as vector selects; these are
2291   // shuffles in which each element in the destination is taken from an element
2292   // at the corresponding index in either source vectors.
2293   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2294     int MaskIndex = MaskIdx.value();
2295     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2296   });
2297 
2298   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2299 
2300   SmallVector<SDValue> MaskVals;
2301   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2302   // merged with a second vrgather.
2303   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2304 
2305   // By default we preserve the original operand order, and use a mask to
2306   // select LHS as true and RHS as false. However, since RVV vector selects may
2307   // feature splats but only on the LHS, we may choose to invert our mask and
2308   // instead select between RHS and LHS.
2309   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2310   bool InvertMask = IsSelect == SwapOps;
2311 
2312   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2313   // half.
2314   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2315 
2316   // Now construct the mask that will be used by the vselect or blended
2317   // vrgather operation. For vrgathers, construct the appropriate indices into
2318   // each vector.
2319   for (int MaskIndex : SVN->getMask()) {
2320     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2321     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2322     if (!IsSelect) {
2323       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2324       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2325                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2326                                      : DAG.getUNDEF(XLenVT));
2327       GatherIndicesRHS.push_back(
2328           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2329                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2330       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2331         ++LHSIndexCounts[MaskIndex];
2332       if (!IsLHSOrUndefIndex)
2333         ++RHSIndexCounts[MaskIndex - NumElts];
2334     }
2335   }
2336 
2337   if (SwapOps) {
2338     std::swap(V1, V2);
2339     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2340   }
2341 
2342   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2343   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2344   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2345 
2346   if (IsSelect)
2347     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2348 
2349   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2350     // On such a large vector we're unable to use i8 as the index type.
2351     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2352     // may involve vector splitting if we're already at LMUL=8, or our
2353     // user-supplied maximum fixed-length LMUL.
2354     return SDValue();
2355   }
2356 
2357   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2358   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2359   MVT IndexVT = VT.changeTypeToInteger();
2360   // Since we can't introduce illegal index types at this stage, use i16 and
2361   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2362   // than XLenVT.
2363   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2364     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2365     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2366   }
2367 
2368   MVT IndexContainerVT =
2369       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2370 
2371   SDValue Gather;
2372   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2373   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2374   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2375     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2376   } else {
2377     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2378     // If only one index is used, we can use a "splat" vrgather.
2379     // TODO: We can splat the most-common index and fix-up any stragglers, if
2380     // that's beneficial.
2381     if (LHSIndexCounts.size() == 1) {
2382       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2383       Gather =
2384           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2385                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2386     } else {
2387       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2388       LHSIndices =
2389           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2390 
2391       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2392                            TrueMask, VL);
2393     }
2394   }
2395 
2396   // If a second vector operand is used by this shuffle, blend it in with an
2397   // additional vrgather.
2398   if (!V2.isUndef()) {
2399     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2400     // If only one index is used, we can use a "splat" vrgather.
2401     // TODO: We can splat the most-common index and fix-up any stragglers, if
2402     // that's beneficial.
2403     if (RHSIndexCounts.size() == 1) {
2404       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2405       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2406                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2407     } else {
2408       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2409       RHSIndices =
2410           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2411       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2412                        VL);
2413     }
2414 
2415     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2416     SelectMask =
2417         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2418 
2419     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2420                          Gather, VL);
2421   }
2422 
2423   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2424 }
2425 
2426 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2427                                      SDLoc DL, SelectionDAG &DAG,
2428                                      const RISCVSubtarget &Subtarget) {
2429   if (VT.isScalableVector())
2430     return DAG.getFPExtendOrRound(Op, DL, VT);
2431   assert(VT.isFixedLengthVector() &&
2432          "Unexpected value type for RVV FP extend/round lowering");
2433   SDValue Mask, VL;
2434   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2435   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2436                         ? RISCVISD::FP_EXTEND_VL
2437                         : RISCVISD::FP_ROUND_VL;
2438   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2439 }
2440 
2441 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2442 // the exponent.
2443 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2444   MVT VT = Op.getSimpleValueType();
2445   unsigned EltSize = VT.getScalarSizeInBits();
2446   SDValue Src = Op.getOperand(0);
2447   SDLoc DL(Op);
2448 
2449   // We need a FP type that can represent the value.
2450   // TODO: Use f16 for i8 when possible?
2451   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2452   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2453 
2454   // Legal types should have been checked in the RISCVTargetLowering
2455   // constructor.
2456   // TODO: Splitting may make sense in some cases.
2457   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2458          "Expected legal float type!");
2459 
2460   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2461   // The trailing zero count is equal to log2 of this single bit value.
2462   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2463     SDValue Neg =
2464         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2465     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2466   }
2467 
2468   // We have a legal FP type, convert to it.
2469   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2470   // Bitcast to integer and shift the exponent to the LSB.
2471   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2472   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2473   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2474   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2475                               DAG.getConstant(ShiftAmt, DL, IntVT));
2476   // Truncate back to original type to allow vnsrl.
2477   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2478   // The exponent contains log2 of the value in biased form.
2479   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2480 
2481   // For trailing zeros, we just need to subtract the bias.
2482   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2483     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2484                        DAG.getConstant(ExponentBias, DL, VT));
2485 
2486   // For leading zeros, we need to remove the bias and convert from log2 to
2487   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2488   unsigned Adjust = ExponentBias + (EltSize - 1);
2489   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2490 }
2491 
2492 // While RVV has alignment restrictions, we should always be able to load as a
2493 // legal equivalently-sized byte-typed vector instead. This method is
2494 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2495 // the load is already correctly-aligned, it returns SDValue().
2496 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2497                                                     SelectionDAG &DAG) const {
2498   auto *Load = cast<LoadSDNode>(Op);
2499   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2500 
2501   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2502                                      Load->getMemoryVT(),
2503                                      *Load->getMemOperand()))
2504     return SDValue();
2505 
2506   SDLoc DL(Op);
2507   MVT VT = Op.getSimpleValueType();
2508   unsigned EltSizeBits = VT.getScalarSizeInBits();
2509   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2510          "Unexpected unaligned RVV load type");
2511   MVT NewVT =
2512       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2513   assert(NewVT.isValid() &&
2514          "Expecting equally-sized RVV vector types to be legal");
2515   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2516                           Load->getPointerInfo(), Load->getOriginalAlign(),
2517                           Load->getMemOperand()->getFlags());
2518   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2519 }
2520 
2521 // While RVV has alignment restrictions, we should always be able to store as a
2522 // legal equivalently-sized byte-typed vector instead. This method is
2523 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2524 // returns SDValue() if the store is already correctly aligned.
2525 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2526                                                      SelectionDAG &DAG) const {
2527   auto *Store = cast<StoreSDNode>(Op);
2528   assert(Store && Store->getValue().getValueType().isVector() &&
2529          "Expected vector store");
2530 
2531   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2532                                      Store->getMemoryVT(),
2533                                      *Store->getMemOperand()))
2534     return SDValue();
2535 
2536   SDLoc DL(Op);
2537   SDValue StoredVal = Store->getValue();
2538   MVT VT = StoredVal.getSimpleValueType();
2539   unsigned EltSizeBits = VT.getScalarSizeInBits();
2540   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2541          "Unexpected unaligned RVV store type");
2542   MVT NewVT =
2543       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2544   assert(NewVT.isValid() &&
2545          "Expecting equally-sized RVV vector types to be legal");
2546   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2547   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2548                       Store->getPointerInfo(), Store->getOriginalAlign(),
2549                       Store->getMemOperand()->getFlags());
2550 }
2551 
2552 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2553                                             SelectionDAG &DAG) const {
2554   switch (Op.getOpcode()) {
2555   default:
2556     report_fatal_error("unimplemented operand");
2557   case ISD::GlobalAddress:
2558     return lowerGlobalAddress(Op, DAG);
2559   case ISD::BlockAddress:
2560     return lowerBlockAddress(Op, DAG);
2561   case ISD::ConstantPool:
2562     return lowerConstantPool(Op, DAG);
2563   case ISD::JumpTable:
2564     return lowerJumpTable(Op, DAG);
2565   case ISD::GlobalTLSAddress:
2566     return lowerGlobalTLSAddress(Op, DAG);
2567   case ISD::SELECT:
2568     return lowerSELECT(Op, DAG);
2569   case ISD::BRCOND:
2570     return lowerBRCOND(Op, DAG);
2571   case ISD::VASTART:
2572     return lowerVASTART(Op, DAG);
2573   case ISD::FRAMEADDR:
2574     return lowerFRAMEADDR(Op, DAG);
2575   case ISD::RETURNADDR:
2576     return lowerRETURNADDR(Op, DAG);
2577   case ISD::SHL_PARTS:
2578     return lowerShiftLeftParts(Op, DAG);
2579   case ISD::SRA_PARTS:
2580     return lowerShiftRightParts(Op, DAG, true);
2581   case ISD::SRL_PARTS:
2582     return lowerShiftRightParts(Op, DAG, false);
2583   case ISD::BITCAST: {
2584     SDLoc DL(Op);
2585     EVT VT = Op.getValueType();
2586     SDValue Op0 = Op.getOperand(0);
2587     EVT Op0VT = Op0.getValueType();
2588     MVT XLenVT = Subtarget.getXLenVT();
2589     if (VT.isFixedLengthVector()) {
2590       // We can handle fixed length vector bitcasts with a simple replacement
2591       // in isel.
2592       if (Op0VT.isFixedLengthVector())
2593         return Op;
2594       // When bitcasting from scalar to fixed-length vector, insert the scalar
2595       // into a one-element vector of the result type, and perform a vector
2596       // bitcast.
2597       if (!Op0VT.isVector()) {
2598         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2599         if (!isTypeLegal(BVT))
2600           return SDValue();
2601         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2602                                               DAG.getUNDEF(BVT), Op0,
2603                                               DAG.getConstant(0, DL, XLenVT)));
2604       }
2605       return SDValue();
2606     }
2607     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2608     // thus: bitcast the vector to a one-element vector type whose element type
2609     // is the same as the result type, and extract the first element.
2610     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2611       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2612       if (!isTypeLegal(BVT))
2613         return SDValue();
2614       SDValue BVec = DAG.getBitcast(BVT, Op0);
2615       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2616                          DAG.getConstant(0, DL, XLenVT));
2617     }
2618     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2619       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2620       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2621       return FPConv;
2622     }
2623     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2624         Subtarget.hasStdExtF()) {
2625       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2626       SDValue FPConv =
2627           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2628       return FPConv;
2629     }
2630     return SDValue();
2631   }
2632   case ISD::INTRINSIC_WO_CHAIN:
2633     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2634   case ISD::INTRINSIC_W_CHAIN:
2635     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2636   case ISD::INTRINSIC_VOID:
2637     return LowerINTRINSIC_VOID(Op, DAG);
2638   case ISD::BSWAP:
2639   case ISD::BITREVERSE: {
2640     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2641     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2642     MVT VT = Op.getSimpleValueType();
2643     SDLoc DL(Op);
2644     // Start with the maximum immediate value which is the bitwidth - 1.
2645     unsigned Imm = VT.getSizeInBits() - 1;
2646     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2647     if (Op.getOpcode() == ISD::BSWAP)
2648       Imm &= ~0x7U;
2649     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2650                        DAG.getConstant(Imm, DL, VT));
2651   }
2652   case ISD::FSHL:
2653   case ISD::FSHR: {
2654     MVT VT = Op.getSimpleValueType();
2655     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2656     SDLoc DL(Op);
2657     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2658       return Op;
2659     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2660     // use log(XLen) bits. Mask the shift amount accordingly.
2661     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2662     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2663                                 DAG.getConstant(ShAmtWidth, DL, VT));
2664     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2665     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2666   }
2667   case ISD::TRUNCATE: {
2668     SDLoc DL(Op);
2669     MVT VT = Op.getSimpleValueType();
2670     // Only custom-lower vector truncates
2671     if (!VT.isVector())
2672       return Op;
2673 
2674     // Truncates to mask types are handled differently
2675     if (VT.getVectorElementType() == MVT::i1)
2676       return lowerVectorMaskTrunc(Op, DAG);
2677 
2678     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2679     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2680     // truncate by one power of two at a time.
2681     MVT DstEltVT = VT.getVectorElementType();
2682 
2683     SDValue Src = Op.getOperand(0);
2684     MVT SrcVT = Src.getSimpleValueType();
2685     MVT SrcEltVT = SrcVT.getVectorElementType();
2686 
2687     assert(DstEltVT.bitsLT(SrcEltVT) &&
2688            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2689            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2690            "Unexpected vector truncate lowering");
2691 
2692     MVT ContainerVT = SrcVT;
2693     if (SrcVT.isFixedLengthVector()) {
2694       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2695       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2696     }
2697 
2698     SDValue Result = Src;
2699     SDValue Mask, VL;
2700     std::tie(Mask, VL) =
2701         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2702     LLVMContext &Context = *DAG.getContext();
2703     const ElementCount Count = ContainerVT.getVectorElementCount();
2704     do {
2705       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2706       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2707       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2708                            Mask, VL);
2709     } while (SrcEltVT != DstEltVT);
2710 
2711     if (SrcVT.isFixedLengthVector())
2712       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2713 
2714     return Result;
2715   }
2716   case ISD::ANY_EXTEND:
2717   case ISD::ZERO_EXTEND:
2718     if (Op.getOperand(0).getValueType().isVector() &&
2719         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2720       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2721     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2722   case ISD::SIGN_EXTEND:
2723     if (Op.getOperand(0).getValueType().isVector() &&
2724         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2725       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2726     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2727   case ISD::SPLAT_VECTOR_PARTS:
2728     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2729   case ISD::INSERT_VECTOR_ELT:
2730     return lowerINSERT_VECTOR_ELT(Op, DAG);
2731   case ISD::EXTRACT_VECTOR_ELT:
2732     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2733   case ISD::VSCALE: {
2734     MVT VT = Op.getSimpleValueType();
2735     SDLoc DL(Op);
2736     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2737     // We define our scalable vector types for lmul=1 to use a 64 bit known
2738     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2739     // vscale as VLENB / 8.
2740     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2741     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2742       // We assume VLENB is a multiple of 8. We manually choose the best shift
2743       // here because SimplifyDemandedBits isn't always able to simplify it.
2744       uint64_t Val = Op.getConstantOperandVal(0);
2745       if (isPowerOf2_64(Val)) {
2746         uint64_t Log2 = Log2_64(Val);
2747         if (Log2 < 3)
2748           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2749                              DAG.getConstant(3 - Log2, DL, VT));
2750         if (Log2 > 3)
2751           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2752                              DAG.getConstant(Log2 - 3, DL, VT));
2753         return VLENB;
2754       }
2755       // If the multiplier is a multiple of 8, scale it down to avoid needing
2756       // to shift the VLENB value.
2757       if ((Val % 8) == 0)
2758         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2759                            DAG.getConstant(Val / 8, DL, VT));
2760     }
2761 
2762     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2763                                  DAG.getConstant(3, DL, VT));
2764     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2765   }
2766   case ISD::FPOWI: {
2767     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2768     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2769     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2770         Op.getOperand(1).getValueType() == MVT::i32) {
2771       SDLoc DL(Op);
2772       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2773       SDValue Powi =
2774           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2775       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2776                          DAG.getIntPtrConstant(0, DL));
2777     }
2778     return SDValue();
2779   }
2780   case ISD::FP_EXTEND: {
2781     // RVV can only do fp_extend to types double the size as the source. We
2782     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2783     // via f32.
2784     SDLoc DL(Op);
2785     MVT VT = Op.getSimpleValueType();
2786     SDValue Src = Op.getOperand(0);
2787     MVT SrcVT = Src.getSimpleValueType();
2788 
2789     // Prepare any fixed-length vector operands.
2790     MVT ContainerVT = VT;
2791     if (SrcVT.isFixedLengthVector()) {
2792       ContainerVT = getContainerForFixedLengthVector(VT);
2793       MVT SrcContainerVT =
2794           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2795       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2796     }
2797 
2798     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2799         SrcVT.getVectorElementType() != MVT::f16) {
2800       // For scalable vectors, we only need to close the gap between
2801       // vXf16->vXf64.
2802       if (!VT.isFixedLengthVector())
2803         return Op;
2804       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2805       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2806       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2807     }
2808 
2809     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2810     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2811     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2812         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2813 
2814     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2815                                            DL, DAG, Subtarget);
2816     if (VT.isFixedLengthVector())
2817       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2818     return Extend;
2819   }
2820   case ISD::FP_ROUND: {
2821     // RVV can only do fp_round to types half the size as the source. We
2822     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2823     // conversion instruction.
2824     SDLoc DL(Op);
2825     MVT VT = Op.getSimpleValueType();
2826     SDValue Src = Op.getOperand(0);
2827     MVT SrcVT = Src.getSimpleValueType();
2828 
2829     // Prepare any fixed-length vector operands.
2830     MVT ContainerVT = VT;
2831     if (VT.isFixedLengthVector()) {
2832       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2833       ContainerVT =
2834           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2835       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2836     }
2837 
2838     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2839         SrcVT.getVectorElementType() != MVT::f64) {
2840       // For scalable vectors, we only need to close the gap between
2841       // vXf64<->vXf16.
2842       if (!VT.isFixedLengthVector())
2843         return Op;
2844       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2845       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2846       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2847     }
2848 
2849     SDValue Mask, VL;
2850     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2851 
2852     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2853     SDValue IntermediateRound =
2854         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2855     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2856                                           DL, DAG, Subtarget);
2857 
2858     if (VT.isFixedLengthVector())
2859       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2860     return Round;
2861   }
2862   case ISD::FP_TO_SINT:
2863   case ISD::FP_TO_UINT:
2864   case ISD::SINT_TO_FP:
2865   case ISD::UINT_TO_FP: {
2866     // RVV can only do fp<->int conversions to types half/double the size as
2867     // the source. We custom-lower any conversions that do two hops into
2868     // sequences.
2869     MVT VT = Op.getSimpleValueType();
2870     if (!VT.isVector())
2871       return Op;
2872     SDLoc DL(Op);
2873     SDValue Src = Op.getOperand(0);
2874     MVT EltVT = VT.getVectorElementType();
2875     MVT SrcVT = Src.getSimpleValueType();
2876     MVT SrcEltVT = SrcVT.getVectorElementType();
2877     unsigned EltSize = EltVT.getSizeInBits();
2878     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2879     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2880            "Unexpected vector element types");
2881 
2882     bool IsInt2FP = SrcEltVT.isInteger();
2883     // Widening conversions
2884     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2885       if (IsInt2FP) {
2886         // Do a regular integer sign/zero extension then convert to float.
2887         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2888                                       VT.getVectorElementCount());
2889         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2890                                  ? ISD::ZERO_EXTEND
2891                                  : ISD::SIGN_EXTEND;
2892         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2893         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2894       }
2895       // FP2Int
2896       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2897       // Do one doubling fp_extend then complete the operation by converting
2898       // to int.
2899       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2900       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2901       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2902     }
2903 
2904     // Narrowing conversions
2905     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2906       if (IsInt2FP) {
2907         // One narrowing int_to_fp, then an fp_round.
2908         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2909         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2910         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2911         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2912       }
2913       // FP2Int
2914       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2915       // representable by the integer, the result is poison.
2916       MVT IVecVT =
2917           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2918                            VT.getVectorElementCount());
2919       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2920       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2921     }
2922 
2923     // Scalable vectors can exit here. Patterns will handle equally-sized
2924     // conversions halving/doubling ones.
2925     if (!VT.isFixedLengthVector())
2926       return Op;
2927 
2928     // For fixed-length vectors we lower to a custom "VL" node.
2929     unsigned RVVOpc = 0;
2930     switch (Op.getOpcode()) {
2931     default:
2932       llvm_unreachable("Impossible opcode");
2933     case ISD::FP_TO_SINT:
2934       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2935       break;
2936     case ISD::FP_TO_UINT:
2937       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2938       break;
2939     case ISD::SINT_TO_FP:
2940       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2941       break;
2942     case ISD::UINT_TO_FP:
2943       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2944       break;
2945     }
2946 
2947     MVT ContainerVT, SrcContainerVT;
2948     // Derive the reference container type from the larger vector type.
2949     if (SrcEltSize > EltSize) {
2950       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2951       ContainerVT =
2952           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2953     } else {
2954       ContainerVT = getContainerForFixedLengthVector(VT);
2955       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2956     }
2957 
2958     SDValue Mask, VL;
2959     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2960 
2961     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2962     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2963     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2964   }
2965   case ISD::FP_TO_SINT_SAT:
2966   case ISD::FP_TO_UINT_SAT:
2967     return lowerFP_TO_INT_SAT(Op, DAG);
2968   case ISD::FTRUNC:
2969   case ISD::FCEIL:
2970   case ISD::FFLOOR:
2971     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
2972   case ISD::VECREDUCE_ADD:
2973   case ISD::VECREDUCE_UMAX:
2974   case ISD::VECREDUCE_SMAX:
2975   case ISD::VECREDUCE_UMIN:
2976   case ISD::VECREDUCE_SMIN:
2977     return lowerVECREDUCE(Op, DAG);
2978   case ISD::VECREDUCE_AND:
2979   case ISD::VECREDUCE_OR:
2980   case ISD::VECREDUCE_XOR:
2981     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2982       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2983     return lowerVECREDUCE(Op, DAG);
2984   case ISD::VECREDUCE_FADD:
2985   case ISD::VECREDUCE_SEQ_FADD:
2986   case ISD::VECREDUCE_FMIN:
2987   case ISD::VECREDUCE_FMAX:
2988     return lowerFPVECREDUCE(Op, DAG);
2989   case ISD::VP_REDUCE_ADD:
2990   case ISD::VP_REDUCE_UMAX:
2991   case ISD::VP_REDUCE_SMAX:
2992   case ISD::VP_REDUCE_UMIN:
2993   case ISD::VP_REDUCE_SMIN:
2994   case ISD::VP_REDUCE_FADD:
2995   case ISD::VP_REDUCE_SEQ_FADD:
2996   case ISD::VP_REDUCE_FMIN:
2997   case ISD::VP_REDUCE_FMAX:
2998     return lowerVPREDUCE(Op, DAG);
2999   case ISD::VP_REDUCE_AND:
3000   case ISD::VP_REDUCE_OR:
3001   case ISD::VP_REDUCE_XOR:
3002     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3003       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3004     return lowerVPREDUCE(Op, DAG);
3005   case ISD::INSERT_SUBVECTOR:
3006     return lowerINSERT_SUBVECTOR(Op, DAG);
3007   case ISD::EXTRACT_SUBVECTOR:
3008     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3009   case ISD::STEP_VECTOR:
3010     return lowerSTEP_VECTOR(Op, DAG);
3011   case ISD::VECTOR_REVERSE:
3012     return lowerVECTOR_REVERSE(Op, DAG);
3013   case ISD::BUILD_VECTOR:
3014     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3015   case ISD::SPLAT_VECTOR:
3016     if (Op.getValueType().getVectorElementType() == MVT::i1)
3017       return lowerVectorMaskSplat(Op, DAG);
3018     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3019   case ISD::VECTOR_SHUFFLE:
3020     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3021   case ISD::CONCAT_VECTORS: {
3022     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3023     // better than going through the stack, as the default expansion does.
3024     SDLoc DL(Op);
3025     MVT VT = Op.getSimpleValueType();
3026     unsigned NumOpElts =
3027         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3028     SDValue Vec = DAG.getUNDEF(VT);
3029     for (const auto &OpIdx : enumerate(Op->ops()))
3030       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3031                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3032     return Vec;
3033   }
3034   case ISD::LOAD:
3035     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3036       return V;
3037     if (Op.getValueType().isFixedLengthVector())
3038       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3039     return Op;
3040   case ISD::STORE:
3041     if (auto V = expandUnalignedRVVStore(Op, DAG))
3042       return V;
3043     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3044       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3045     return Op;
3046   case ISD::MLOAD:
3047   case ISD::VP_LOAD:
3048     return lowerMaskedLoad(Op, DAG);
3049   case ISD::MSTORE:
3050   case ISD::VP_STORE:
3051     return lowerMaskedStore(Op, DAG);
3052   case ISD::SETCC:
3053     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3054   case ISD::ADD:
3055     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3056   case ISD::SUB:
3057     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3058   case ISD::MUL:
3059     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3060   case ISD::MULHS:
3061     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3062   case ISD::MULHU:
3063     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3064   case ISD::AND:
3065     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3066                                               RISCVISD::AND_VL);
3067   case ISD::OR:
3068     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3069                                               RISCVISD::OR_VL);
3070   case ISD::XOR:
3071     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3072                                               RISCVISD::XOR_VL);
3073   case ISD::SDIV:
3074     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3075   case ISD::SREM:
3076     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3077   case ISD::UDIV:
3078     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3079   case ISD::UREM:
3080     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3081   case ISD::SHL:
3082   case ISD::SRA:
3083   case ISD::SRL:
3084     if (Op.getSimpleValueType().isFixedLengthVector())
3085       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3086     // This can be called for an i32 shift amount that needs to be promoted.
3087     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3088            "Unexpected custom legalisation");
3089     return SDValue();
3090   case ISD::SADDSAT:
3091     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3092   case ISD::UADDSAT:
3093     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3094   case ISD::SSUBSAT:
3095     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3096   case ISD::USUBSAT:
3097     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3098   case ISD::FADD:
3099     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3100   case ISD::FSUB:
3101     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3102   case ISD::FMUL:
3103     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3104   case ISD::FDIV:
3105     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3106   case ISD::FNEG:
3107     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3108   case ISD::FABS:
3109     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3110   case ISD::FSQRT:
3111     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3112   case ISD::FMA:
3113     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3114   case ISD::SMIN:
3115     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3116   case ISD::SMAX:
3117     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3118   case ISD::UMIN:
3119     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3120   case ISD::UMAX:
3121     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3122   case ISD::FMINNUM:
3123     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3124   case ISD::FMAXNUM:
3125     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3126   case ISD::ABS:
3127     return lowerABS(Op, DAG);
3128   case ISD::CTLZ_ZERO_UNDEF:
3129   case ISD::CTTZ_ZERO_UNDEF:
3130     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3131   case ISD::VSELECT:
3132     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3133   case ISD::FCOPYSIGN:
3134     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3135   case ISD::MGATHER:
3136   case ISD::VP_GATHER:
3137     return lowerMaskedGather(Op, DAG);
3138   case ISD::MSCATTER:
3139   case ISD::VP_SCATTER:
3140     return lowerMaskedScatter(Op, DAG);
3141   case ISD::FLT_ROUNDS_:
3142     return lowerGET_ROUNDING(Op, DAG);
3143   case ISD::SET_ROUNDING:
3144     return lowerSET_ROUNDING(Op, DAG);
3145   case ISD::VP_SELECT:
3146     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3147   case ISD::VP_ADD:
3148     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3149   case ISD::VP_SUB:
3150     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3151   case ISD::VP_MUL:
3152     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3153   case ISD::VP_SDIV:
3154     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3155   case ISD::VP_UDIV:
3156     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3157   case ISD::VP_SREM:
3158     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3159   case ISD::VP_UREM:
3160     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3161   case ISD::VP_AND:
3162     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
3163   case ISD::VP_OR:
3164     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
3165   case ISD::VP_XOR:
3166     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
3167   case ISD::VP_ASHR:
3168     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3169   case ISD::VP_LSHR:
3170     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3171   case ISD::VP_SHL:
3172     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3173   case ISD::VP_FADD:
3174     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3175   case ISD::VP_FSUB:
3176     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3177   case ISD::VP_FMUL:
3178     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3179   case ISD::VP_FDIV:
3180     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3181   }
3182 }
3183 
3184 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3185                              SelectionDAG &DAG, unsigned Flags) {
3186   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3187 }
3188 
3189 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3190                              SelectionDAG &DAG, unsigned Flags) {
3191   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3192                                    Flags);
3193 }
3194 
3195 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3196                              SelectionDAG &DAG, unsigned Flags) {
3197   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3198                                    N->getOffset(), Flags);
3199 }
3200 
3201 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3202                              SelectionDAG &DAG, unsigned Flags) {
3203   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3204 }
3205 
3206 template <class NodeTy>
3207 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3208                                      bool IsLocal) const {
3209   SDLoc DL(N);
3210   EVT Ty = getPointerTy(DAG.getDataLayout());
3211 
3212   if (isPositionIndependent()) {
3213     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3214     if (IsLocal)
3215       // Use PC-relative addressing to access the symbol. This generates the
3216       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3217       // %pcrel_lo(auipc)).
3218       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3219 
3220     // Use PC-relative addressing to access the GOT for this symbol, then load
3221     // the address from the GOT. This generates the pattern (PseudoLA sym),
3222     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3223     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3224   }
3225 
3226   switch (getTargetMachine().getCodeModel()) {
3227   default:
3228     report_fatal_error("Unsupported code model for lowering");
3229   case CodeModel::Small: {
3230     // Generate a sequence for accessing addresses within the first 2 GiB of
3231     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3232     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3233     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3234     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3235     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3236   }
3237   case CodeModel::Medium: {
3238     // Generate a sequence for accessing addresses within any 2GiB range within
3239     // the address space. This generates the pattern (PseudoLLA sym), which
3240     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3241     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3242     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3243   }
3244   }
3245 }
3246 
3247 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3248                                                 SelectionDAG &DAG) const {
3249   SDLoc DL(Op);
3250   EVT Ty = Op.getValueType();
3251   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3252   int64_t Offset = N->getOffset();
3253   MVT XLenVT = Subtarget.getXLenVT();
3254 
3255   const GlobalValue *GV = N->getGlobal();
3256   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3257   SDValue Addr = getAddr(N, DAG, IsLocal);
3258 
3259   // In order to maximise the opportunity for common subexpression elimination,
3260   // emit a separate ADD node for the global address offset instead of folding
3261   // it in the global address node. Later peephole optimisations may choose to
3262   // fold it back in when profitable.
3263   if (Offset != 0)
3264     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3265                        DAG.getConstant(Offset, DL, XLenVT));
3266   return Addr;
3267 }
3268 
3269 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3270                                                SelectionDAG &DAG) const {
3271   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3272 
3273   return getAddr(N, DAG);
3274 }
3275 
3276 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3277                                                SelectionDAG &DAG) const {
3278   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3279 
3280   return getAddr(N, DAG);
3281 }
3282 
3283 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3284                                             SelectionDAG &DAG) const {
3285   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3286 
3287   return getAddr(N, DAG);
3288 }
3289 
3290 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3291                                               SelectionDAG &DAG,
3292                                               bool UseGOT) const {
3293   SDLoc DL(N);
3294   EVT Ty = getPointerTy(DAG.getDataLayout());
3295   const GlobalValue *GV = N->getGlobal();
3296   MVT XLenVT = Subtarget.getXLenVT();
3297 
3298   if (UseGOT) {
3299     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3300     // load the address from the GOT and add the thread pointer. This generates
3301     // the pattern (PseudoLA_TLS_IE sym), which expands to
3302     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3303     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3304     SDValue Load =
3305         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3306 
3307     // Add the thread pointer.
3308     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3309     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3310   }
3311 
3312   // Generate a sequence for accessing the address relative to the thread
3313   // pointer, with the appropriate adjustment for the thread pointer offset.
3314   // This generates the pattern
3315   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3316   SDValue AddrHi =
3317       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3318   SDValue AddrAdd =
3319       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3320   SDValue AddrLo =
3321       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3322 
3323   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3324   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3325   SDValue MNAdd = SDValue(
3326       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3327       0);
3328   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3329 }
3330 
3331 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3332                                                SelectionDAG &DAG) const {
3333   SDLoc DL(N);
3334   EVT Ty = getPointerTy(DAG.getDataLayout());
3335   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3336   const GlobalValue *GV = N->getGlobal();
3337 
3338   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3339   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3340   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3341   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3342   SDValue Load =
3343       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3344 
3345   // Prepare argument list to generate call.
3346   ArgListTy Args;
3347   ArgListEntry Entry;
3348   Entry.Node = Load;
3349   Entry.Ty = CallTy;
3350   Args.push_back(Entry);
3351 
3352   // Setup call to __tls_get_addr.
3353   TargetLowering::CallLoweringInfo CLI(DAG);
3354   CLI.setDebugLoc(DL)
3355       .setChain(DAG.getEntryNode())
3356       .setLibCallee(CallingConv::C, CallTy,
3357                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3358                     std::move(Args));
3359 
3360   return LowerCallTo(CLI).first;
3361 }
3362 
3363 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3364                                                    SelectionDAG &DAG) const {
3365   SDLoc DL(Op);
3366   EVT Ty = Op.getValueType();
3367   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3368   int64_t Offset = N->getOffset();
3369   MVT XLenVT = Subtarget.getXLenVT();
3370 
3371   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3372 
3373   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3374       CallingConv::GHC)
3375     report_fatal_error("In GHC calling convention TLS is not supported");
3376 
3377   SDValue Addr;
3378   switch (Model) {
3379   case TLSModel::LocalExec:
3380     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3381     break;
3382   case TLSModel::InitialExec:
3383     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3384     break;
3385   case TLSModel::LocalDynamic:
3386   case TLSModel::GeneralDynamic:
3387     Addr = getDynamicTLSAddr(N, DAG);
3388     break;
3389   }
3390 
3391   // In order to maximise the opportunity for common subexpression elimination,
3392   // emit a separate ADD node for the global address offset instead of folding
3393   // it in the global address node. Later peephole optimisations may choose to
3394   // fold it back in when profitable.
3395   if (Offset != 0)
3396     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3397                        DAG.getConstant(Offset, DL, XLenVT));
3398   return Addr;
3399 }
3400 
3401 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3402   SDValue CondV = Op.getOperand(0);
3403   SDValue TrueV = Op.getOperand(1);
3404   SDValue FalseV = Op.getOperand(2);
3405   SDLoc DL(Op);
3406   MVT VT = Op.getSimpleValueType();
3407   MVT XLenVT = Subtarget.getXLenVT();
3408 
3409   // Lower vector SELECTs to VSELECTs by splatting the condition.
3410   if (VT.isVector()) {
3411     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3412     SDValue CondSplat = VT.isScalableVector()
3413                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3414                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3415     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3416   }
3417 
3418   // If the result type is XLenVT and CondV is the output of a SETCC node
3419   // which also operated on XLenVT inputs, then merge the SETCC node into the
3420   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3421   // compare+branch instructions. i.e.:
3422   // (select (setcc lhs, rhs, cc), truev, falsev)
3423   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3424   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3425       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3426     SDValue LHS = CondV.getOperand(0);
3427     SDValue RHS = CondV.getOperand(1);
3428     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3429     ISD::CondCode CCVal = CC->get();
3430 
3431     // Special case for a select of 2 constants that have a diffence of 1.
3432     // Normally this is done by DAGCombine, but if the select is introduced by
3433     // type legalization or op legalization, we miss it. Restricting to SETLT
3434     // case for now because that is what signed saturating add/sub need.
3435     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3436     // but we would probably want to swap the true/false values if the condition
3437     // is SETGE/SETLE to avoid an XORI.
3438     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3439         CCVal == ISD::SETLT) {
3440       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3441       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3442       if (TrueVal - 1 == FalseVal)
3443         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3444       if (TrueVal + 1 == FalseVal)
3445         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3446     }
3447 
3448     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3449 
3450     SDValue TargetCC = DAG.getCondCode(CCVal);
3451     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3452     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3453   }
3454 
3455   // Otherwise:
3456   // (select condv, truev, falsev)
3457   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3458   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3459   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3460 
3461   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3462 
3463   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3464 }
3465 
3466 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3467   SDValue CondV = Op.getOperand(1);
3468   SDLoc DL(Op);
3469   MVT XLenVT = Subtarget.getXLenVT();
3470 
3471   if (CondV.getOpcode() == ISD::SETCC &&
3472       CondV.getOperand(0).getValueType() == XLenVT) {
3473     SDValue LHS = CondV.getOperand(0);
3474     SDValue RHS = CondV.getOperand(1);
3475     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3476 
3477     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3478 
3479     SDValue TargetCC = DAG.getCondCode(CCVal);
3480     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3481                        LHS, RHS, TargetCC, Op.getOperand(2));
3482   }
3483 
3484   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3485                      CondV, DAG.getConstant(0, DL, XLenVT),
3486                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3487 }
3488 
3489 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3490   MachineFunction &MF = DAG.getMachineFunction();
3491   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3492 
3493   SDLoc DL(Op);
3494   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3495                                  getPointerTy(MF.getDataLayout()));
3496 
3497   // vastart just stores the address of the VarArgsFrameIndex slot into the
3498   // memory location argument.
3499   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3500   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3501                       MachinePointerInfo(SV));
3502 }
3503 
3504 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3505                                             SelectionDAG &DAG) const {
3506   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3507   MachineFunction &MF = DAG.getMachineFunction();
3508   MachineFrameInfo &MFI = MF.getFrameInfo();
3509   MFI.setFrameAddressIsTaken(true);
3510   Register FrameReg = RI.getFrameRegister(MF);
3511   int XLenInBytes = Subtarget.getXLen() / 8;
3512 
3513   EVT VT = Op.getValueType();
3514   SDLoc DL(Op);
3515   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3516   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3517   while (Depth--) {
3518     int Offset = -(XLenInBytes * 2);
3519     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3520                               DAG.getIntPtrConstant(Offset, DL));
3521     FrameAddr =
3522         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3523   }
3524   return FrameAddr;
3525 }
3526 
3527 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3528                                              SelectionDAG &DAG) const {
3529   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3530   MachineFunction &MF = DAG.getMachineFunction();
3531   MachineFrameInfo &MFI = MF.getFrameInfo();
3532   MFI.setReturnAddressIsTaken(true);
3533   MVT XLenVT = Subtarget.getXLenVT();
3534   int XLenInBytes = Subtarget.getXLen() / 8;
3535 
3536   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3537     return SDValue();
3538 
3539   EVT VT = Op.getValueType();
3540   SDLoc DL(Op);
3541   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3542   if (Depth) {
3543     int Off = -XLenInBytes;
3544     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3545     SDValue Offset = DAG.getConstant(Off, DL, VT);
3546     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3547                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3548                        MachinePointerInfo());
3549   }
3550 
3551   // Return the value of the return address register, marking it an implicit
3552   // live-in.
3553   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3554   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3555 }
3556 
3557 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3558                                                  SelectionDAG &DAG) const {
3559   SDLoc DL(Op);
3560   SDValue Lo = Op.getOperand(0);
3561   SDValue Hi = Op.getOperand(1);
3562   SDValue Shamt = Op.getOperand(2);
3563   EVT VT = Lo.getValueType();
3564 
3565   // if Shamt-XLEN < 0: // Shamt < XLEN
3566   //   Lo = Lo << Shamt
3567   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3568   // else:
3569   //   Lo = 0
3570   //   Hi = Lo << (Shamt-XLEN)
3571 
3572   SDValue Zero = DAG.getConstant(0, DL, VT);
3573   SDValue One = DAG.getConstant(1, DL, VT);
3574   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3575   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3576   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3577   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3578 
3579   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3580   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3581   SDValue ShiftRightLo =
3582       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3583   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3584   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3585   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3586 
3587   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3588 
3589   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3590   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3591 
3592   SDValue Parts[2] = {Lo, Hi};
3593   return DAG.getMergeValues(Parts, DL);
3594 }
3595 
3596 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3597                                                   bool IsSRA) const {
3598   SDLoc DL(Op);
3599   SDValue Lo = Op.getOperand(0);
3600   SDValue Hi = Op.getOperand(1);
3601   SDValue Shamt = Op.getOperand(2);
3602   EVT VT = Lo.getValueType();
3603 
3604   // SRA expansion:
3605   //   if Shamt-XLEN < 0: // Shamt < XLEN
3606   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3607   //     Hi = Hi >>s Shamt
3608   //   else:
3609   //     Lo = Hi >>s (Shamt-XLEN);
3610   //     Hi = Hi >>s (XLEN-1)
3611   //
3612   // SRL expansion:
3613   //   if Shamt-XLEN < 0: // Shamt < XLEN
3614   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3615   //     Hi = Hi >>u Shamt
3616   //   else:
3617   //     Lo = Hi >>u (Shamt-XLEN);
3618   //     Hi = 0;
3619 
3620   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3621 
3622   SDValue Zero = DAG.getConstant(0, DL, VT);
3623   SDValue One = DAG.getConstant(1, DL, VT);
3624   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3625   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3626   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3627   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3628 
3629   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3630   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3631   SDValue ShiftLeftHi =
3632       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3633   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3634   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3635   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3636   SDValue HiFalse =
3637       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3638 
3639   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3640 
3641   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3642   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3643 
3644   SDValue Parts[2] = {Lo, Hi};
3645   return DAG.getMergeValues(Parts, DL);
3646 }
3647 
3648 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3649 // legal equivalently-sized i8 type, so we can use that as a go-between.
3650 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3651                                                   SelectionDAG &DAG) const {
3652   SDLoc DL(Op);
3653   MVT VT = Op.getSimpleValueType();
3654   SDValue SplatVal = Op.getOperand(0);
3655   // All-zeros or all-ones splats are handled specially.
3656   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3657     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3658     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3659   }
3660   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3661     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3662     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3663   }
3664   MVT XLenVT = Subtarget.getXLenVT();
3665   assert(SplatVal.getValueType() == XLenVT &&
3666          "Unexpected type for i1 splat value");
3667   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3668   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3669                          DAG.getConstant(1, DL, XLenVT));
3670   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3671   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3672   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3673 }
3674 
3675 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3676 // illegal (currently only vXi64 RV32).
3677 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3678 // them to SPLAT_VECTOR_I64
3679 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3680                                                      SelectionDAG &DAG) const {
3681   SDLoc DL(Op);
3682   MVT VecVT = Op.getSimpleValueType();
3683   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3684          "Unexpected SPLAT_VECTOR_PARTS lowering");
3685 
3686   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3687   SDValue Lo = Op.getOperand(0);
3688   SDValue Hi = Op.getOperand(1);
3689 
3690   if (VecVT.isFixedLengthVector()) {
3691     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3692     SDLoc DL(Op);
3693     SDValue Mask, VL;
3694     std::tie(Mask, VL) =
3695         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3696 
3697     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3698     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3699   }
3700 
3701   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3702     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3703     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3704     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3705     // node in order to try and match RVV vector/scalar instructions.
3706     if ((LoC >> 31) == HiC)
3707       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3708   }
3709 
3710   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3711   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3712       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3713       Hi.getConstantOperandVal(1) == 31)
3714     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3715 
3716   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3717   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3718                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3719 }
3720 
3721 // Custom-lower extensions from mask vectors by using a vselect either with 1
3722 // for zero/any-extension or -1 for sign-extension:
3723 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3724 // Note that any-extension is lowered identically to zero-extension.
3725 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3726                                                 int64_t ExtTrueVal) const {
3727   SDLoc DL(Op);
3728   MVT VecVT = Op.getSimpleValueType();
3729   SDValue Src = Op.getOperand(0);
3730   // Only custom-lower extensions from mask types
3731   assert(Src.getValueType().isVector() &&
3732          Src.getValueType().getVectorElementType() == MVT::i1);
3733 
3734   MVT XLenVT = Subtarget.getXLenVT();
3735   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3736   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3737 
3738   if (VecVT.isScalableVector()) {
3739     // Be careful not to introduce illegal scalar types at this stage, and be
3740     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3741     // illegal and must be expanded. Since we know that the constants are
3742     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3743     bool IsRV32E64 =
3744         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3745 
3746     if (!IsRV32E64) {
3747       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3748       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3749     } else {
3750       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3751       SplatTrueVal =
3752           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3753     }
3754 
3755     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3756   }
3757 
3758   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3759   MVT I1ContainerVT =
3760       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3761 
3762   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3763 
3764   SDValue Mask, VL;
3765   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3766 
3767   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3768   SplatTrueVal =
3769       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3770   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3771                                SplatTrueVal, SplatZero, VL);
3772 
3773   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3774 }
3775 
3776 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3777     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3778   MVT ExtVT = Op.getSimpleValueType();
3779   // Only custom-lower extensions from fixed-length vector types.
3780   if (!ExtVT.isFixedLengthVector())
3781     return Op;
3782   MVT VT = Op.getOperand(0).getSimpleValueType();
3783   // Grab the canonical container type for the extended type. Infer the smaller
3784   // type from that to ensure the same number of vector elements, as we know
3785   // the LMUL will be sufficient to hold the smaller type.
3786   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3787   // Get the extended container type manually to ensure the same number of
3788   // vector elements between source and dest.
3789   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3790                                      ContainerExtVT.getVectorElementCount());
3791 
3792   SDValue Op1 =
3793       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3794 
3795   SDLoc DL(Op);
3796   SDValue Mask, VL;
3797   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3798 
3799   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3800 
3801   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3802 }
3803 
3804 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3805 // setcc operation:
3806 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3807 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3808                                                   SelectionDAG &DAG) const {
3809   SDLoc DL(Op);
3810   EVT MaskVT = Op.getValueType();
3811   // Only expect to custom-lower truncations to mask types
3812   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3813          "Unexpected type for vector mask lowering");
3814   SDValue Src = Op.getOperand(0);
3815   MVT VecVT = Src.getSimpleValueType();
3816 
3817   // If this is a fixed vector, we need to convert it to a scalable vector.
3818   MVT ContainerVT = VecVT;
3819   if (VecVT.isFixedLengthVector()) {
3820     ContainerVT = getContainerForFixedLengthVector(VecVT);
3821     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3822   }
3823 
3824   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3825   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3826 
3827   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3828   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3829 
3830   if (VecVT.isScalableVector()) {
3831     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3832     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3833   }
3834 
3835   SDValue Mask, VL;
3836   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3837 
3838   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3839   SDValue Trunc =
3840       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3841   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3842                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3843   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3844 }
3845 
3846 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3847 // first position of a vector, and that vector is slid up to the insert index.
3848 // By limiting the active vector length to index+1 and merging with the
3849 // original vector (with an undisturbed tail policy for elements >= VL), we
3850 // achieve the desired result of leaving all elements untouched except the one
3851 // at VL-1, which is replaced with the desired value.
3852 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3853                                                     SelectionDAG &DAG) const {
3854   SDLoc DL(Op);
3855   MVT VecVT = Op.getSimpleValueType();
3856   SDValue Vec = Op.getOperand(0);
3857   SDValue Val = Op.getOperand(1);
3858   SDValue Idx = Op.getOperand(2);
3859 
3860   if (VecVT.getVectorElementType() == MVT::i1) {
3861     // FIXME: For now we just promote to an i8 vector and insert into that,
3862     // but this is probably not optimal.
3863     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3864     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3865     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3866     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3867   }
3868 
3869   MVT ContainerVT = VecVT;
3870   // If the operand is a fixed-length vector, convert to a scalable one.
3871   if (VecVT.isFixedLengthVector()) {
3872     ContainerVT = getContainerForFixedLengthVector(VecVT);
3873     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3874   }
3875 
3876   MVT XLenVT = Subtarget.getXLenVT();
3877 
3878   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3879   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3880   // Even i64-element vectors on RV32 can be lowered without scalar
3881   // legalization if the most-significant 32 bits of the value are not affected
3882   // by the sign-extension of the lower 32 bits.
3883   // TODO: We could also catch sign extensions of a 32-bit value.
3884   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3885     const auto *CVal = cast<ConstantSDNode>(Val);
3886     if (isInt<32>(CVal->getSExtValue())) {
3887       IsLegalInsert = true;
3888       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3889     }
3890   }
3891 
3892   SDValue Mask, VL;
3893   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3894 
3895   SDValue ValInVec;
3896 
3897   if (IsLegalInsert) {
3898     unsigned Opc =
3899         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3900     if (isNullConstant(Idx)) {
3901       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3902       if (!VecVT.isFixedLengthVector())
3903         return Vec;
3904       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3905     }
3906     ValInVec =
3907         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3908   } else {
3909     // On RV32, i64-element vectors must be specially handled to place the
3910     // value at element 0, by using two vslide1up instructions in sequence on
3911     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3912     // this.
3913     SDValue One = DAG.getConstant(1, DL, XLenVT);
3914     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3915     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3916     MVT I32ContainerVT =
3917         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3918     SDValue I32Mask =
3919         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3920     // Limit the active VL to two.
3921     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3922     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3923     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3924     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3925                            InsertI64VL);
3926     // First slide in the hi value, then the lo in underneath it.
3927     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3928                            ValHi, I32Mask, InsertI64VL);
3929     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3930                            ValLo, I32Mask, InsertI64VL);
3931     // Bitcast back to the right container type.
3932     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3933   }
3934 
3935   // Now that the value is in a vector, slide it into position.
3936   SDValue InsertVL =
3937       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3938   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3939                                 ValInVec, Idx, Mask, InsertVL);
3940   if (!VecVT.isFixedLengthVector())
3941     return Slideup;
3942   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3943 }
3944 
3945 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3946 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3947 // types this is done using VMV_X_S to allow us to glean information about the
3948 // sign bits of the result.
3949 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3950                                                      SelectionDAG &DAG) const {
3951   SDLoc DL(Op);
3952   SDValue Idx = Op.getOperand(1);
3953   SDValue Vec = Op.getOperand(0);
3954   EVT EltVT = Op.getValueType();
3955   MVT VecVT = Vec.getSimpleValueType();
3956   MVT XLenVT = Subtarget.getXLenVT();
3957 
3958   if (VecVT.getVectorElementType() == MVT::i1) {
3959     // FIXME: For now we just promote to an i8 vector and extract from that,
3960     // but this is probably not optimal.
3961     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3962     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3963     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3964   }
3965 
3966   // If this is a fixed vector, we need to convert it to a scalable vector.
3967   MVT ContainerVT = VecVT;
3968   if (VecVT.isFixedLengthVector()) {
3969     ContainerVT = getContainerForFixedLengthVector(VecVT);
3970     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3971   }
3972 
3973   // If the index is 0, the vector is already in the right position.
3974   if (!isNullConstant(Idx)) {
3975     // Use a VL of 1 to avoid processing more elements than we need.
3976     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3977     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3978     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3979     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3980                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3981   }
3982 
3983   if (!EltVT.isInteger()) {
3984     // Floating-point extracts are handled in TableGen.
3985     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3986                        DAG.getConstant(0, DL, XLenVT));
3987   }
3988 
3989   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3990   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3991 }
3992 
3993 // Some RVV intrinsics may claim that they want an integer operand to be
3994 // promoted or expanded.
3995 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3996                                           const RISCVSubtarget &Subtarget) {
3997   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3998           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3999          "Unexpected opcode");
4000 
4001   if (!Subtarget.hasVInstructions())
4002     return SDValue();
4003 
4004   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4005   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4006   SDLoc DL(Op);
4007 
4008   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4009       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4010   if (!II || !II->SplatOperand)
4011     return SDValue();
4012 
4013   unsigned SplatOp = II->SplatOperand + HasChain;
4014   assert(SplatOp < Op.getNumOperands());
4015 
4016   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4017   SDValue &ScalarOp = Operands[SplatOp];
4018   MVT OpVT = ScalarOp.getSimpleValueType();
4019   MVT XLenVT = Subtarget.getXLenVT();
4020 
4021   // If this isn't a scalar, or its type is XLenVT we're done.
4022   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4023     return SDValue();
4024 
4025   // Simplest case is that the operand needs to be promoted to XLenVT.
4026   if (OpVT.bitsLT(XLenVT)) {
4027     // If the operand is a constant, sign extend to increase our chances
4028     // of being able to use a .vi instruction. ANY_EXTEND would become a
4029     // a zero extend and the simm5 check in isel would fail.
4030     // FIXME: Should we ignore the upper bits in isel instead?
4031     unsigned ExtOpc =
4032         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4033     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4034     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4035   }
4036 
4037   // Use the previous operand to get the vXi64 VT. The result might be a mask
4038   // VT for compares. Using the previous operand assumes that the previous
4039   // operand will never have a smaller element size than a scalar operand and
4040   // that a widening operation never uses SEW=64.
4041   // NOTE: If this fails the below assert, we can probably just find the
4042   // element count from any operand or result and use it to construct the VT.
4043   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4044   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4045 
4046   // The more complex case is when the scalar is larger than XLenVT.
4047   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4048          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4049 
4050   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4051   // on the instruction to sign-extend since SEW>XLEN.
4052   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4053     if (isInt<32>(CVal->getSExtValue())) {
4054       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4055       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4056     }
4057   }
4058 
4059   // We need to convert the scalar to a splat vector.
4060   // FIXME: Can we implicitly truncate the scalar if it is known to
4061   // be sign extended?
4062   // VL should be the last operand.
4063   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4064   assert(VL.getValueType() == XLenVT);
4065   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4066   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4067 }
4068 
4069 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4070                                                      SelectionDAG &DAG) const {
4071   unsigned IntNo = Op.getConstantOperandVal(0);
4072   SDLoc DL(Op);
4073   MVT XLenVT = Subtarget.getXLenVT();
4074 
4075   switch (IntNo) {
4076   default:
4077     break; // Don't custom lower most intrinsics.
4078   case Intrinsic::thread_pointer: {
4079     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4080     return DAG.getRegister(RISCV::X4, PtrVT);
4081   }
4082   case Intrinsic::riscv_orc_b:
4083     // Lower to the GORCI encoding for orc.b.
4084     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4085                        DAG.getConstant(7, DL, XLenVT));
4086   case Intrinsic::riscv_grev:
4087   case Intrinsic::riscv_gorc: {
4088     unsigned Opc =
4089         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4090     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4091   }
4092   case Intrinsic::riscv_shfl:
4093   case Intrinsic::riscv_unshfl: {
4094     unsigned Opc =
4095         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4096     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4097   }
4098   case Intrinsic::riscv_bcompress:
4099   case Intrinsic::riscv_bdecompress: {
4100     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4101                                                        : RISCVISD::BDECOMPRESS;
4102     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4103   }
4104   case Intrinsic::riscv_vmv_x_s:
4105     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4106     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4107                        Op.getOperand(1));
4108   case Intrinsic::riscv_vmv_v_x:
4109     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4110                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4111   case Intrinsic::riscv_vfmv_v_f:
4112     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4113                        Op.getOperand(1), Op.getOperand(2));
4114   case Intrinsic::riscv_vmv_s_x: {
4115     SDValue Scalar = Op.getOperand(2);
4116 
4117     if (Scalar.getValueType().bitsLE(XLenVT)) {
4118       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4119       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4120                          Op.getOperand(1), Scalar, Op.getOperand(3));
4121     }
4122 
4123     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4124 
4125     // This is an i64 value that lives in two scalar registers. We have to
4126     // insert this in a convoluted way. First we build vXi64 splat containing
4127     // the/ two values that we assemble using some bit math. Next we'll use
4128     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4129     // to merge element 0 from our splat into the source vector.
4130     // FIXME: This is probably not the best way to do this, but it is
4131     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4132     // point.
4133     //   sw lo, (a0)
4134     //   sw hi, 4(a0)
4135     //   vlse vX, (a0)
4136     //
4137     //   vid.v      vVid
4138     //   vmseq.vx   mMask, vVid, 0
4139     //   vmerge.vvm vDest, vSrc, vVal, mMask
4140     MVT VT = Op.getSimpleValueType();
4141     SDValue Vec = Op.getOperand(1);
4142     SDValue VL = Op.getOperand(3);
4143 
4144     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4145     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4146                                       DAG.getConstant(0, DL, MVT::i32), VL);
4147 
4148     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4149     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4150     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4151     SDValue SelectCond =
4152         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4153                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4154     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4155                        Vec, VL);
4156   }
4157   case Intrinsic::riscv_vslide1up:
4158   case Intrinsic::riscv_vslide1down:
4159   case Intrinsic::riscv_vslide1up_mask:
4160   case Intrinsic::riscv_vslide1down_mask: {
4161     // We need to special case these when the scalar is larger than XLen.
4162     unsigned NumOps = Op.getNumOperands();
4163     bool IsMasked = NumOps == 7;
4164     unsigned OpOffset = IsMasked ? 1 : 0;
4165     SDValue Scalar = Op.getOperand(2 + OpOffset);
4166     if (Scalar.getValueType().bitsLE(XLenVT))
4167       break;
4168 
4169     // Splatting a sign extended constant is fine.
4170     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4171       if (isInt<32>(CVal->getSExtValue()))
4172         break;
4173 
4174     MVT VT = Op.getSimpleValueType();
4175     assert(VT.getVectorElementType() == MVT::i64 &&
4176            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4177 
4178     // Convert the vector source to the equivalent nxvXi32 vector.
4179     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4180     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4181 
4182     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4183                                    DAG.getConstant(0, DL, XLenVT));
4184     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4185                                    DAG.getConstant(1, DL, XLenVT));
4186 
4187     // Double the VL since we halved SEW.
4188     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4189     SDValue I32VL =
4190         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4191 
4192     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4193     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4194 
4195     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4196     // instructions.
4197     if (IntNo == Intrinsic::riscv_vslide1up ||
4198         IntNo == Intrinsic::riscv_vslide1up_mask) {
4199       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4200                         I32Mask, I32VL);
4201       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4202                         I32Mask, I32VL);
4203     } else {
4204       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4205                         I32Mask, I32VL);
4206       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4207                         I32Mask, I32VL);
4208     }
4209 
4210     // Convert back to nxvXi64.
4211     Vec = DAG.getBitcast(VT, Vec);
4212 
4213     if (!IsMasked)
4214       return Vec;
4215 
4216     // Apply mask after the operation.
4217     SDValue Mask = Op.getOperand(NumOps - 3);
4218     SDValue MaskedOff = Op.getOperand(1);
4219     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4220   }
4221   }
4222 
4223   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4224 }
4225 
4226 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4227                                                     SelectionDAG &DAG) const {
4228   unsigned IntNo = Op.getConstantOperandVal(1);
4229   switch (IntNo) {
4230   default:
4231     break;
4232   case Intrinsic::riscv_masked_strided_load: {
4233     SDLoc DL(Op);
4234     MVT XLenVT = Subtarget.getXLenVT();
4235 
4236     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4237     // the selection of the masked intrinsics doesn't do this for us.
4238     SDValue Mask = Op.getOperand(5);
4239     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4240 
4241     MVT VT = Op->getSimpleValueType(0);
4242     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4243 
4244     SDValue PassThru = Op.getOperand(2);
4245     if (!IsUnmasked) {
4246       MVT MaskVT =
4247           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4248       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4249       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4250     }
4251 
4252     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4253 
4254     SDValue IntID = DAG.getTargetConstant(
4255         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4256         XLenVT);
4257 
4258     auto *Load = cast<MemIntrinsicSDNode>(Op);
4259     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4260     if (!IsUnmasked)
4261       Ops.push_back(PassThru);
4262     Ops.push_back(Op.getOperand(3)); // Ptr
4263     Ops.push_back(Op.getOperand(4)); // Stride
4264     if (!IsUnmasked)
4265       Ops.push_back(Mask);
4266     Ops.push_back(VL);
4267     if (!IsUnmasked) {
4268       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4269       Ops.push_back(Policy);
4270     }
4271 
4272     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4273     SDValue Result =
4274         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4275                                 Load->getMemoryVT(), Load->getMemOperand());
4276     SDValue Chain = Result.getValue(1);
4277     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4278     return DAG.getMergeValues({Result, Chain}, DL);
4279   }
4280   }
4281 
4282   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4283 }
4284 
4285 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4286                                                  SelectionDAG &DAG) const {
4287   unsigned IntNo = Op.getConstantOperandVal(1);
4288   switch (IntNo) {
4289   default:
4290     break;
4291   case Intrinsic::riscv_masked_strided_store: {
4292     SDLoc DL(Op);
4293     MVT XLenVT = Subtarget.getXLenVT();
4294 
4295     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4296     // the selection of the masked intrinsics doesn't do this for us.
4297     SDValue Mask = Op.getOperand(5);
4298     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4299 
4300     SDValue Val = Op.getOperand(2);
4301     MVT VT = Val.getSimpleValueType();
4302     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4303 
4304     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4305     if (!IsUnmasked) {
4306       MVT MaskVT =
4307           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4308       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4309     }
4310 
4311     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4312 
4313     SDValue IntID = DAG.getTargetConstant(
4314         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4315         XLenVT);
4316 
4317     auto *Store = cast<MemIntrinsicSDNode>(Op);
4318     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4319     Ops.push_back(Val);
4320     Ops.push_back(Op.getOperand(3)); // Ptr
4321     Ops.push_back(Op.getOperand(4)); // Stride
4322     if (!IsUnmasked)
4323       Ops.push_back(Mask);
4324     Ops.push_back(VL);
4325 
4326     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4327                                    Ops, Store->getMemoryVT(),
4328                                    Store->getMemOperand());
4329   }
4330   }
4331 
4332   return SDValue();
4333 }
4334 
4335 static MVT getLMUL1VT(MVT VT) {
4336   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4337          "Unexpected vector MVT");
4338   return MVT::getScalableVectorVT(
4339       VT.getVectorElementType(),
4340       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4341 }
4342 
4343 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4344   switch (ISDOpcode) {
4345   default:
4346     llvm_unreachable("Unhandled reduction");
4347   case ISD::VECREDUCE_ADD:
4348     return RISCVISD::VECREDUCE_ADD_VL;
4349   case ISD::VECREDUCE_UMAX:
4350     return RISCVISD::VECREDUCE_UMAX_VL;
4351   case ISD::VECREDUCE_SMAX:
4352     return RISCVISD::VECREDUCE_SMAX_VL;
4353   case ISD::VECREDUCE_UMIN:
4354     return RISCVISD::VECREDUCE_UMIN_VL;
4355   case ISD::VECREDUCE_SMIN:
4356     return RISCVISD::VECREDUCE_SMIN_VL;
4357   case ISD::VECREDUCE_AND:
4358     return RISCVISD::VECREDUCE_AND_VL;
4359   case ISD::VECREDUCE_OR:
4360     return RISCVISD::VECREDUCE_OR_VL;
4361   case ISD::VECREDUCE_XOR:
4362     return RISCVISD::VECREDUCE_XOR_VL;
4363   }
4364 }
4365 
4366 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4367                                                          SelectionDAG &DAG,
4368                                                          bool IsVP) const {
4369   SDLoc DL(Op);
4370   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4371   MVT VecVT = Vec.getSimpleValueType();
4372   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4373           Op.getOpcode() == ISD::VECREDUCE_OR ||
4374           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4375           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4376           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4377           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4378          "Unexpected reduction lowering");
4379 
4380   MVT XLenVT = Subtarget.getXLenVT();
4381   assert(Op.getValueType() == XLenVT &&
4382          "Expected reduction output to be legalized to XLenVT");
4383 
4384   MVT ContainerVT = VecVT;
4385   if (VecVT.isFixedLengthVector()) {
4386     ContainerVT = getContainerForFixedLengthVector(VecVT);
4387     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4388   }
4389 
4390   SDValue Mask, VL;
4391   if (IsVP) {
4392     Mask = Op.getOperand(2);
4393     VL = Op.getOperand(3);
4394   } else {
4395     std::tie(Mask, VL) =
4396         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4397   }
4398 
4399   unsigned BaseOpc;
4400   ISD::CondCode CC;
4401   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4402 
4403   switch (Op.getOpcode()) {
4404   default:
4405     llvm_unreachable("Unhandled reduction");
4406   case ISD::VECREDUCE_AND:
4407   case ISD::VP_REDUCE_AND: {
4408     // vcpop ~x == 0
4409     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4410     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4411     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4412     CC = ISD::SETEQ;
4413     BaseOpc = ISD::AND;
4414     break;
4415   }
4416   case ISD::VECREDUCE_OR:
4417   case ISD::VP_REDUCE_OR:
4418     // vcpop x != 0
4419     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4420     CC = ISD::SETNE;
4421     BaseOpc = ISD::OR;
4422     break;
4423   case ISD::VECREDUCE_XOR:
4424   case ISD::VP_REDUCE_XOR: {
4425     // ((vcpop x) & 1) != 0
4426     SDValue One = DAG.getConstant(1, DL, XLenVT);
4427     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4428     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4429     CC = ISD::SETNE;
4430     BaseOpc = ISD::XOR;
4431     break;
4432   }
4433   }
4434 
4435   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4436 
4437   if (!IsVP)
4438     return SetCC;
4439 
4440   // Now include the start value in the operation.
4441   // Note that we must return the start value when no elements are operated
4442   // upon. The vcpop instructions we've emitted in each case above will return
4443   // 0 for an inactive vector, and so we've already received the neutral value:
4444   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4445   // can simply include the start value.
4446   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4447 }
4448 
4449 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4450                                             SelectionDAG &DAG) const {
4451   SDLoc DL(Op);
4452   SDValue Vec = Op.getOperand(0);
4453   EVT VecEVT = Vec.getValueType();
4454 
4455   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4456 
4457   // Due to ordering in legalize types we may have a vector type that needs to
4458   // be split. Do that manually so we can get down to a legal type.
4459   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4460          TargetLowering::TypeSplitVector) {
4461     SDValue Lo, Hi;
4462     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4463     VecEVT = Lo.getValueType();
4464     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4465   }
4466 
4467   // TODO: The type may need to be widened rather than split. Or widened before
4468   // it can be split.
4469   if (!isTypeLegal(VecEVT))
4470     return SDValue();
4471 
4472   MVT VecVT = VecEVT.getSimpleVT();
4473   MVT VecEltVT = VecVT.getVectorElementType();
4474   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4475 
4476   MVT ContainerVT = VecVT;
4477   if (VecVT.isFixedLengthVector()) {
4478     ContainerVT = getContainerForFixedLengthVector(VecVT);
4479     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4480   }
4481 
4482   MVT M1VT = getLMUL1VT(ContainerVT);
4483   MVT XLenVT = Subtarget.getXLenVT();
4484 
4485   SDValue Mask, VL;
4486   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4487 
4488   SDValue NeutralElem =
4489       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4490   SDValue IdentitySplat = lowerScalarSplat(
4491       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4492   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4493                                   IdentitySplat, Mask, VL);
4494   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4495                              DAG.getConstant(0, DL, XLenVT));
4496   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4497 }
4498 
4499 // Given a reduction op, this function returns the matching reduction opcode,
4500 // the vector SDValue and the scalar SDValue required to lower this to a
4501 // RISCVISD node.
4502 static std::tuple<unsigned, SDValue, SDValue>
4503 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4504   SDLoc DL(Op);
4505   auto Flags = Op->getFlags();
4506   unsigned Opcode = Op.getOpcode();
4507   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4508   switch (Opcode) {
4509   default:
4510     llvm_unreachable("Unhandled reduction");
4511   case ISD::VECREDUCE_FADD:
4512     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4513                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4514   case ISD::VECREDUCE_SEQ_FADD:
4515     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4516                            Op.getOperand(0));
4517   case ISD::VECREDUCE_FMIN:
4518     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4519                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4520   case ISD::VECREDUCE_FMAX:
4521     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4522                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4523   }
4524 }
4525 
4526 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4527                                               SelectionDAG &DAG) const {
4528   SDLoc DL(Op);
4529   MVT VecEltVT = Op.getSimpleValueType();
4530 
4531   unsigned RVVOpcode;
4532   SDValue VectorVal, ScalarVal;
4533   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4534       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4535   MVT VecVT = VectorVal.getSimpleValueType();
4536 
4537   MVT ContainerVT = VecVT;
4538   if (VecVT.isFixedLengthVector()) {
4539     ContainerVT = getContainerForFixedLengthVector(VecVT);
4540     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4541   }
4542 
4543   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4544   MVT XLenVT = Subtarget.getXLenVT();
4545 
4546   SDValue Mask, VL;
4547   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4548 
4549   SDValue ScalarSplat = lowerScalarSplat(
4550       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4551   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4552                                   VectorVal, ScalarSplat, Mask, VL);
4553   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4554                      DAG.getConstant(0, DL, XLenVT));
4555 }
4556 
4557 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4558   switch (ISDOpcode) {
4559   default:
4560     llvm_unreachable("Unhandled reduction");
4561   case ISD::VP_REDUCE_ADD:
4562     return RISCVISD::VECREDUCE_ADD_VL;
4563   case ISD::VP_REDUCE_UMAX:
4564     return RISCVISD::VECREDUCE_UMAX_VL;
4565   case ISD::VP_REDUCE_SMAX:
4566     return RISCVISD::VECREDUCE_SMAX_VL;
4567   case ISD::VP_REDUCE_UMIN:
4568     return RISCVISD::VECREDUCE_UMIN_VL;
4569   case ISD::VP_REDUCE_SMIN:
4570     return RISCVISD::VECREDUCE_SMIN_VL;
4571   case ISD::VP_REDUCE_AND:
4572     return RISCVISD::VECREDUCE_AND_VL;
4573   case ISD::VP_REDUCE_OR:
4574     return RISCVISD::VECREDUCE_OR_VL;
4575   case ISD::VP_REDUCE_XOR:
4576     return RISCVISD::VECREDUCE_XOR_VL;
4577   case ISD::VP_REDUCE_FADD:
4578     return RISCVISD::VECREDUCE_FADD_VL;
4579   case ISD::VP_REDUCE_SEQ_FADD:
4580     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4581   case ISD::VP_REDUCE_FMAX:
4582     return RISCVISD::VECREDUCE_FMAX_VL;
4583   case ISD::VP_REDUCE_FMIN:
4584     return RISCVISD::VECREDUCE_FMIN_VL;
4585   }
4586 }
4587 
4588 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4589                                            SelectionDAG &DAG) const {
4590   SDLoc DL(Op);
4591   SDValue Vec = Op.getOperand(1);
4592   EVT VecEVT = Vec.getValueType();
4593 
4594   // TODO: The type may need to be widened rather than split. Or widened before
4595   // it can be split.
4596   if (!isTypeLegal(VecEVT))
4597     return SDValue();
4598 
4599   MVT VecVT = VecEVT.getSimpleVT();
4600   MVT VecEltVT = VecVT.getVectorElementType();
4601   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4602 
4603   MVT ContainerVT = VecVT;
4604   if (VecVT.isFixedLengthVector()) {
4605     ContainerVT = getContainerForFixedLengthVector(VecVT);
4606     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4607   }
4608 
4609   SDValue VL = Op.getOperand(3);
4610   SDValue Mask = Op.getOperand(2);
4611 
4612   MVT M1VT = getLMUL1VT(ContainerVT);
4613   MVT XLenVT = Subtarget.getXLenVT();
4614   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4615 
4616   SDValue StartSplat =
4617       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4618                        DL, DAG, Subtarget);
4619   SDValue Reduction =
4620       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4621   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4622                              DAG.getConstant(0, DL, XLenVT));
4623   if (!VecVT.isInteger())
4624     return Elt0;
4625   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4626 }
4627 
4628 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4629                                                    SelectionDAG &DAG) const {
4630   SDValue Vec = Op.getOperand(0);
4631   SDValue SubVec = Op.getOperand(1);
4632   MVT VecVT = Vec.getSimpleValueType();
4633   MVT SubVecVT = SubVec.getSimpleValueType();
4634 
4635   SDLoc DL(Op);
4636   MVT XLenVT = Subtarget.getXLenVT();
4637   unsigned OrigIdx = Op.getConstantOperandVal(2);
4638   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4639 
4640   // We don't have the ability to slide mask vectors up indexed by their i1
4641   // elements; the smallest we can do is i8. Often we are able to bitcast to
4642   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4643   // into a scalable one, we might not necessarily have enough scalable
4644   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4645   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4646       (OrigIdx != 0 || !Vec.isUndef())) {
4647     if (VecVT.getVectorMinNumElements() >= 8 &&
4648         SubVecVT.getVectorMinNumElements() >= 8) {
4649       assert(OrigIdx % 8 == 0 && "Invalid index");
4650       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4651              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4652              "Unexpected mask vector lowering");
4653       OrigIdx /= 8;
4654       SubVecVT =
4655           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4656                            SubVecVT.isScalableVector());
4657       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4658                                VecVT.isScalableVector());
4659       Vec = DAG.getBitcast(VecVT, Vec);
4660       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4661     } else {
4662       // We can't slide this mask vector up indexed by its i1 elements.
4663       // This poses a problem when we wish to insert a scalable vector which
4664       // can't be re-expressed as a larger type. Just choose the slow path and
4665       // extend to a larger type, then truncate back down.
4666       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4667       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4668       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4669       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4670       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4671                         Op.getOperand(2));
4672       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4673       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4674     }
4675   }
4676 
4677   // If the subvector vector is a fixed-length type, we cannot use subregister
4678   // manipulation to simplify the codegen; we don't know which register of a
4679   // LMUL group contains the specific subvector as we only know the minimum
4680   // register size. Therefore we must slide the vector group up the full
4681   // amount.
4682   if (SubVecVT.isFixedLengthVector()) {
4683     if (OrigIdx == 0 && Vec.isUndef())
4684       return Op;
4685     MVT ContainerVT = VecVT;
4686     if (VecVT.isFixedLengthVector()) {
4687       ContainerVT = getContainerForFixedLengthVector(VecVT);
4688       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4689     }
4690     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4691                          DAG.getUNDEF(ContainerVT), SubVec,
4692                          DAG.getConstant(0, DL, XLenVT));
4693     SDValue Mask =
4694         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4695     // Set the vector length to only the number of elements we care about. Note
4696     // that for slideup this includes the offset.
4697     SDValue VL =
4698         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4699     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4700     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4701                                   SubVec, SlideupAmt, Mask, VL);
4702     if (VecVT.isFixedLengthVector())
4703       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4704     return DAG.getBitcast(Op.getValueType(), Slideup);
4705   }
4706 
4707   unsigned SubRegIdx, RemIdx;
4708   std::tie(SubRegIdx, RemIdx) =
4709       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4710           VecVT, SubVecVT, OrigIdx, TRI);
4711 
4712   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4713   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4714                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4715                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4716 
4717   // 1. If the Idx has been completely eliminated and this subvector's size is
4718   // a vector register or a multiple thereof, or the surrounding elements are
4719   // undef, then this is a subvector insert which naturally aligns to a vector
4720   // register. These can easily be handled using subregister manipulation.
4721   // 2. If the subvector is smaller than a vector register, then the insertion
4722   // must preserve the undisturbed elements of the register. We do this by
4723   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4724   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4725   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4726   // LMUL=1 type back into the larger vector (resolving to another subregister
4727   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4728   // to avoid allocating a large register group to hold our subvector.
4729   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4730     return Op;
4731 
4732   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4733   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4734   // (in our case undisturbed). This means we can set up a subvector insertion
4735   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4736   // size of the subvector.
4737   MVT InterSubVT = VecVT;
4738   SDValue AlignedExtract = Vec;
4739   unsigned AlignedIdx = OrigIdx - RemIdx;
4740   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4741     InterSubVT = getLMUL1VT(VecVT);
4742     // Extract a subvector equal to the nearest full vector register type. This
4743     // should resolve to a EXTRACT_SUBREG instruction.
4744     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4745                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4746   }
4747 
4748   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4749   // For scalable vectors this must be further multiplied by vscale.
4750   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4751 
4752   SDValue Mask, VL;
4753   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4754 
4755   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4756   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4757   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4758   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4759 
4760   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4761                        DAG.getUNDEF(InterSubVT), SubVec,
4762                        DAG.getConstant(0, DL, XLenVT));
4763 
4764   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4765                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4766 
4767   // If required, insert this subvector back into the correct vector register.
4768   // This should resolve to an INSERT_SUBREG instruction.
4769   if (VecVT.bitsGT(InterSubVT))
4770     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4771                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4772 
4773   // We might have bitcast from a mask type: cast back to the original type if
4774   // required.
4775   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4776 }
4777 
4778 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4779                                                     SelectionDAG &DAG) const {
4780   SDValue Vec = Op.getOperand(0);
4781   MVT SubVecVT = Op.getSimpleValueType();
4782   MVT VecVT = Vec.getSimpleValueType();
4783 
4784   SDLoc DL(Op);
4785   MVT XLenVT = Subtarget.getXLenVT();
4786   unsigned OrigIdx = Op.getConstantOperandVal(1);
4787   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4788 
4789   // We don't have the ability to slide mask vectors down indexed by their i1
4790   // elements; the smallest we can do is i8. Often we are able to bitcast to
4791   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4792   // from a scalable one, we might not necessarily have enough scalable
4793   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4794   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4795     if (VecVT.getVectorMinNumElements() >= 8 &&
4796         SubVecVT.getVectorMinNumElements() >= 8) {
4797       assert(OrigIdx % 8 == 0 && "Invalid index");
4798       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4799              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4800              "Unexpected mask vector lowering");
4801       OrigIdx /= 8;
4802       SubVecVT =
4803           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4804                            SubVecVT.isScalableVector());
4805       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4806                                VecVT.isScalableVector());
4807       Vec = DAG.getBitcast(VecVT, Vec);
4808     } else {
4809       // We can't slide this mask vector down, indexed by its i1 elements.
4810       // This poses a problem when we wish to extract a scalable vector which
4811       // can't be re-expressed as a larger type. Just choose the slow path and
4812       // extend to a larger type, then truncate back down.
4813       // TODO: We could probably improve this when extracting certain fixed
4814       // from fixed, where we can extract as i8 and shift the correct element
4815       // right to reach the desired subvector?
4816       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4817       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4818       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4819       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4820                         Op.getOperand(1));
4821       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4822       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4823     }
4824   }
4825 
4826   // If the subvector vector is a fixed-length type, we cannot use subregister
4827   // manipulation to simplify the codegen; we don't know which register of a
4828   // LMUL group contains the specific subvector as we only know the minimum
4829   // register size. Therefore we must slide the vector group down the full
4830   // amount.
4831   if (SubVecVT.isFixedLengthVector()) {
4832     // With an index of 0 this is a cast-like subvector, which can be performed
4833     // with subregister operations.
4834     if (OrigIdx == 0)
4835       return Op;
4836     MVT ContainerVT = VecVT;
4837     if (VecVT.isFixedLengthVector()) {
4838       ContainerVT = getContainerForFixedLengthVector(VecVT);
4839       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4840     }
4841     SDValue Mask =
4842         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4843     // Set the vector length to only the number of elements we care about. This
4844     // avoids sliding down elements we're going to discard straight away.
4845     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4846     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4847     SDValue Slidedown =
4848         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4849                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4850     // Now we can use a cast-like subvector extract to get the result.
4851     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4852                             DAG.getConstant(0, DL, XLenVT));
4853     return DAG.getBitcast(Op.getValueType(), Slidedown);
4854   }
4855 
4856   unsigned SubRegIdx, RemIdx;
4857   std::tie(SubRegIdx, RemIdx) =
4858       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4859           VecVT, SubVecVT, OrigIdx, TRI);
4860 
4861   // If the Idx has been completely eliminated then this is a subvector extract
4862   // which naturally aligns to a vector register. These can easily be handled
4863   // using subregister manipulation.
4864   if (RemIdx == 0)
4865     return Op;
4866 
4867   // Else we must shift our vector register directly to extract the subvector.
4868   // Do this using VSLIDEDOWN.
4869 
4870   // If the vector type is an LMUL-group type, extract a subvector equal to the
4871   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4872   // instruction.
4873   MVT InterSubVT = VecVT;
4874   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4875     InterSubVT = getLMUL1VT(VecVT);
4876     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4877                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4878   }
4879 
4880   // Slide this vector register down by the desired number of elements in order
4881   // to place the desired subvector starting at element 0.
4882   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4883   // For scalable vectors this must be further multiplied by vscale.
4884   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4885 
4886   SDValue Mask, VL;
4887   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4888   SDValue Slidedown =
4889       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4890                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4891 
4892   // Now the vector is in the right position, extract our final subvector. This
4893   // should resolve to a COPY.
4894   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4895                           DAG.getConstant(0, DL, XLenVT));
4896 
4897   // We might have bitcast from a mask type: cast back to the original type if
4898   // required.
4899   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4900 }
4901 
4902 // Lower step_vector to the vid instruction. Any non-identity step value must
4903 // be accounted for my manual expansion.
4904 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4905                                               SelectionDAG &DAG) const {
4906   SDLoc DL(Op);
4907   MVT VT = Op.getSimpleValueType();
4908   MVT XLenVT = Subtarget.getXLenVT();
4909   SDValue Mask, VL;
4910   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4911   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4912   uint64_t StepValImm = Op.getConstantOperandVal(0);
4913   if (StepValImm != 1) {
4914     if (isPowerOf2_64(StepValImm)) {
4915       SDValue StepVal =
4916           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4917                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4918       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4919     } else {
4920       SDValue StepVal = lowerScalarSplat(
4921           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4922           DL, DAG, Subtarget);
4923       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4924     }
4925   }
4926   return StepVec;
4927 }
4928 
4929 // Implement vector_reverse using vrgather.vv with indices determined by
4930 // subtracting the id of each element from (VLMAX-1). This will convert
4931 // the indices like so:
4932 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4933 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4934 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4935                                                  SelectionDAG &DAG) const {
4936   SDLoc DL(Op);
4937   MVT VecVT = Op.getSimpleValueType();
4938   unsigned EltSize = VecVT.getScalarSizeInBits();
4939   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4940 
4941   unsigned MaxVLMAX = 0;
4942   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4943   if (VectorBitsMax != 0)
4944     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4945 
4946   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4947   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4948 
4949   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4950   // to use vrgatherei16.vv.
4951   // TODO: It's also possible to use vrgatherei16.vv for other types to
4952   // decrease register width for the index calculation.
4953   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4954     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4955     // Reverse each half, then reassemble them in reverse order.
4956     // NOTE: It's also possible that after splitting that VLMAX no longer
4957     // requires vrgatherei16.vv.
4958     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4959       SDValue Lo, Hi;
4960       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4961       EVT LoVT, HiVT;
4962       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4963       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4964       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4965       // Reassemble the low and high pieces reversed.
4966       // FIXME: This is a CONCAT_VECTORS.
4967       SDValue Res =
4968           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4969                       DAG.getIntPtrConstant(0, DL));
4970       return DAG.getNode(
4971           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4972           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4973     }
4974 
4975     // Just promote the int type to i16 which will double the LMUL.
4976     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4977     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4978   }
4979 
4980   MVT XLenVT = Subtarget.getXLenVT();
4981   SDValue Mask, VL;
4982   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4983 
4984   // Calculate VLMAX-1 for the desired SEW.
4985   unsigned MinElts = VecVT.getVectorMinNumElements();
4986   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4987                               DAG.getConstant(MinElts, DL, XLenVT));
4988   SDValue VLMinus1 =
4989       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4990 
4991   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4992   bool IsRV32E64 =
4993       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4994   SDValue SplatVL;
4995   if (!IsRV32E64)
4996     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4997   else
4998     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4999 
5000   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5001   SDValue Indices =
5002       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5003 
5004   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5005 }
5006 
5007 SDValue
5008 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5009                                                      SelectionDAG &DAG) const {
5010   SDLoc DL(Op);
5011   auto *Load = cast<LoadSDNode>(Op);
5012 
5013   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5014                                         Load->getMemoryVT(),
5015                                         *Load->getMemOperand()) &&
5016          "Expecting a correctly-aligned load");
5017 
5018   MVT VT = Op.getSimpleValueType();
5019   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5020 
5021   SDValue VL =
5022       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5023 
5024   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5025   SDValue NewLoad = DAG.getMemIntrinsicNode(
5026       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5027       Load->getMemoryVT(), Load->getMemOperand());
5028 
5029   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5030   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5031 }
5032 
5033 SDValue
5034 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5035                                                       SelectionDAG &DAG) const {
5036   SDLoc DL(Op);
5037   auto *Store = cast<StoreSDNode>(Op);
5038 
5039   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5040                                         Store->getMemoryVT(),
5041                                         *Store->getMemOperand()) &&
5042          "Expecting a correctly-aligned store");
5043 
5044   SDValue StoreVal = Store->getValue();
5045   MVT VT = StoreVal.getSimpleValueType();
5046 
5047   // If the size less than a byte, we need to pad with zeros to make a byte.
5048   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5049     VT = MVT::v8i1;
5050     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5051                            DAG.getConstant(0, DL, VT), StoreVal,
5052                            DAG.getIntPtrConstant(0, DL));
5053   }
5054 
5055   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5056 
5057   SDValue VL =
5058       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5059 
5060   SDValue NewValue =
5061       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5062   return DAG.getMemIntrinsicNode(
5063       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5064       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5065       Store->getMemoryVT(), Store->getMemOperand());
5066 }
5067 
5068 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5069                                              SelectionDAG &DAG) const {
5070   SDLoc DL(Op);
5071   MVT VT = Op.getSimpleValueType();
5072 
5073   const auto *MemSD = cast<MemSDNode>(Op);
5074   EVT MemVT = MemSD->getMemoryVT();
5075   MachineMemOperand *MMO = MemSD->getMemOperand();
5076   SDValue Chain = MemSD->getChain();
5077   SDValue BasePtr = MemSD->getBasePtr();
5078 
5079   SDValue Mask, PassThru, VL;
5080   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5081     Mask = VPLoad->getMask();
5082     PassThru = DAG.getUNDEF(VT);
5083     VL = VPLoad->getVectorLength();
5084   } else {
5085     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5086     Mask = MLoad->getMask();
5087     PassThru = MLoad->getPassThru();
5088   }
5089 
5090   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5091 
5092   MVT XLenVT = Subtarget.getXLenVT();
5093 
5094   MVT ContainerVT = VT;
5095   if (VT.isFixedLengthVector()) {
5096     ContainerVT = getContainerForFixedLengthVector(VT);
5097     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5098     if (!IsUnmasked) {
5099       MVT MaskVT =
5100           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5101       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5102     }
5103   }
5104 
5105   if (!VL)
5106     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5107 
5108   unsigned IntID =
5109       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5110   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5111   if (!IsUnmasked)
5112     Ops.push_back(PassThru);
5113   Ops.push_back(BasePtr);
5114   if (!IsUnmasked)
5115     Ops.push_back(Mask);
5116   Ops.push_back(VL);
5117   if (!IsUnmasked)
5118     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5119 
5120   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5121 
5122   SDValue Result =
5123       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5124   Chain = Result.getValue(1);
5125 
5126   if (VT.isFixedLengthVector())
5127     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5128 
5129   return DAG.getMergeValues({Result, Chain}, DL);
5130 }
5131 
5132 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5133                                               SelectionDAG &DAG) const {
5134   SDLoc DL(Op);
5135 
5136   const auto *MemSD = cast<MemSDNode>(Op);
5137   EVT MemVT = MemSD->getMemoryVT();
5138   MachineMemOperand *MMO = MemSD->getMemOperand();
5139   SDValue Chain = MemSD->getChain();
5140   SDValue BasePtr = MemSD->getBasePtr();
5141   SDValue Val, Mask, VL;
5142 
5143   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5144     Val = VPStore->getValue();
5145     Mask = VPStore->getMask();
5146     VL = VPStore->getVectorLength();
5147   } else {
5148     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5149     Val = MStore->getValue();
5150     Mask = MStore->getMask();
5151   }
5152 
5153   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5154 
5155   MVT VT = Val.getSimpleValueType();
5156   MVT XLenVT = Subtarget.getXLenVT();
5157 
5158   MVT ContainerVT = VT;
5159   if (VT.isFixedLengthVector()) {
5160     ContainerVT = getContainerForFixedLengthVector(VT);
5161 
5162     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5163     if (!IsUnmasked) {
5164       MVT MaskVT =
5165           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5166       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5167     }
5168   }
5169 
5170   if (!VL)
5171     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5172 
5173   unsigned IntID =
5174       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5175   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5176   Ops.push_back(Val);
5177   Ops.push_back(BasePtr);
5178   if (!IsUnmasked)
5179     Ops.push_back(Mask);
5180   Ops.push_back(VL);
5181 
5182   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5183                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5184 }
5185 
5186 SDValue
5187 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5188                                                       SelectionDAG &DAG) const {
5189   MVT InVT = Op.getOperand(0).getSimpleValueType();
5190   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5191 
5192   MVT VT = Op.getSimpleValueType();
5193 
5194   SDValue Op1 =
5195       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5196   SDValue Op2 =
5197       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5198 
5199   SDLoc DL(Op);
5200   SDValue VL =
5201       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5202 
5203   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5204   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5205 
5206   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5207                             Op.getOperand(2), Mask, VL);
5208 
5209   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5210 }
5211 
5212 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5213     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5214   MVT VT = Op.getSimpleValueType();
5215 
5216   if (VT.getVectorElementType() == MVT::i1)
5217     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5218 
5219   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5220 }
5221 
5222 SDValue
5223 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5224                                                       SelectionDAG &DAG) const {
5225   unsigned Opc;
5226   switch (Op.getOpcode()) {
5227   default: llvm_unreachable("Unexpected opcode!");
5228   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5229   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5230   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5231   }
5232 
5233   return lowerToScalableOp(Op, DAG, Opc);
5234 }
5235 
5236 // Lower vector ABS to smax(X, sub(0, X)).
5237 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5238   SDLoc DL(Op);
5239   MVT VT = Op.getSimpleValueType();
5240   SDValue X = Op.getOperand(0);
5241 
5242   assert(VT.isFixedLengthVector() && "Unexpected type");
5243 
5244   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5245   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5246 
5247   SDValue Mask, VL;
5248   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5249 
5250   SDValue SplatZero =
5251       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5252                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5253   SDValue NegX =
5254       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5255   SDValue Max =
5256       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5257 
5258   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5259 }
5260 
5261 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5262     SDValue Op, SelectionDAG &DAG) const {
5263   SDLoc DL(Op);
5264   MVT VT = Op.getSimpleValueType();
5265   SDValue Mag = Op.getOperand(0);
5266   SDValue Sign = Op.getOperand(1);
5267   assert(Mag.getValueType() == Sign.getValueType() &&
5268          "Can only handle COPYSIGN with matching types.");
5269 
5270   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5271   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5272   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5273 
5274   SDValue Mask, VL;
5275   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5276 
5277   SDValue CopySign =
5278       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5279 
5280   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5281 }
5282 
5283 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5284     SDValue Op, SelectionDAG &DAG) const {
5285   MVT VT = Op.getSimpleValueType();
5286   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5287 
5288   MVT I1ContainerVT =
5289       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5290 
5291   SDValue CC =
5292       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5293   SDValue Op1 =
5294       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5295   SDValue Op2 =
5296       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5297 
5298   SDLoc DL(Op);
5299   SDValue Mask, VL;
5300   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5301 
5302   SDValue Select =
5303       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5304 
5305   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5306 }
5307 
5308 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5309                                                unsigned NewOpc,
5310                                                bool HasMask) const {
5311   MVT VT = Op.getSimpleValueType();
5312   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5313 
5314   // Create list of operands by converting existing ones to scalable types.
5315   SmallVector<SDValue, 6> Ops;
5316   for (const SDValue &V : Op->op_values()) {
5317     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5318 
5319     // Pass through non-vector operands.
5320     if (!V.getValueType().isVector()) {
5321       Ops.push_back(V);
5322       continue;
5323     }
5324 
5325     // "cast" fixed length vector to a scalable vector.
5326     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5327            "Only fixed length vectors are supported!");
5328     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5329   }
5330 
5331   SDLoc DL(Op);
5332   SDValue Mask, VL;
5333   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5334   if (HasMask)
5335     Ops.push_back(Mask);
5336   Ops.push_back(VL);
5337 
5338   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5339   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5340 }
5341 
5342 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5343 // * Operands of each node are assumed to be in the same order.
5344 // * The EVL operand is promoted from i32 to i64 on RV64.
5345 // * Fixed-length vectors are converted to their scalable-vector container
5346 //   types.
5347 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5348                                        unsigned RISCVISDOpc) const {
5349   SDLoc DL(Op);
5350   MVT VT = Op.getSimpleValueType();
5351   SmallVector<SDValue, 4> Ops;
5352 
5353   for (const auto &OpIdx : enumerate(Op->ops())) {
5354     SDValue V = OpIdx.value();
5355     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5356     // Pass through operands which aren't fixed-length vectors.
5357     if (!V.getValueType().isFixedLengthVector()) {
5358       Ops.push_back(V);
5359       continue;
5360     }
5361     // "cast" fixed length vector to a scalable vector.
5362     MVT OpVT = V.getSimpleValueType();
5363     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5364     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5365            "Only fixed length vectors are supported!");
5366     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5367   }
5368 
5369   if (!VT.isFixedLengthVector())
5370     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5371 
5372   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5373 
5374   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5375 
5376   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5377 }
5378 
5379 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5380 // matched to a RVV indexed load. The RVV indexed load instructions only
5381 // support the "unsigned unscaled" addressing mode; indices are implicitly
5382 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5383 // signed or scaled indexing is extended to the XLEN value type and scaled
5384 // accordingly.
5385 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5386                                                SelectionDAG &DAG) const {
5387   SDLoc DL(Op);
5388   MVT VT = Op.getSimpleValueType();
5389 
5390   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5391   EVT MemVT = MemSD->getMemoryVT();
5392   MachineMemOperand *MMO = MemSD->getMemOperand();
5393   SDValue Chain = MemSD->getChain();
5394   SDValue BasePtr = MemSD->getBasePtr();
5395 
5396   ISD::LoadExtType LoadExtType;
5397   SDValue Index, Mask, PassThru, VL;
5398 
5399   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5400     Index = VPGN->getIndex();
5401     Mask = VPGN->getMask();
5402     PassThru = DAG.getUNDEF(VT);
5403     VL = VPGN->getVectorLength();
5404     // VP doesn't support extending loads.
5405     LoadExtType = ISD::NON_EXTLOAD;
5406   } else {
5407     // Else it must be a MGATHER.
5408     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5409     Index = MGN->getIndex();
5410     Mask = MGN->getMask();
5411     PassThru = MGN->getPassThru();
5412     LoadExtType = MGN->getExtensionType();
5413   }
5414 
5415   MVT IndexVT = Index.getSimpleValueType();
5416   MVT XLenVT = Subtarget.getXLenVT();
5417 
5418   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5419          "Unexpected VTs!");
5420   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5421   // Targets have to explicitly opt-in for extending vector loads.
5422   assert(LoadExtType == ISD::NON_EXTLOAD &&
5423          "Unexpected extending MGATHER/VP_GATHER");
5424   (void)LoadExtType;
5425 
5426   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5427   // the selection of the masked intrinsics doesn't do this for us.
5428   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5429 
5430   MVT ContainerVT = VT;
5431   if (VT.isFixedLengthVector()) {
5432     // We need to use the larger of the result and index type to determine the
5433     // scalable type to use so we don't increase LMUL for any operand/result.
5434     if (VT.bitsGE(IndexVT)) {
5435       ContainerVT = getContainerForFixedLengthVector(VT);
5436       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5437                                  ContainerVT.getVectorElementCount());
5438     } else {
5439       IndexVT = getContainerForFixedLengthVector(IndexVT);
5440       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5441                                      IndexVT.getVectorElementCount());
5442     }
5443 
5444     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5445 
5446     if (!IsUnmasked) {
5447       MVT MaskVT =
5448           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5449       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5450       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5451     }
5452   }
5453 
5454   if (!VL)
5455     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5456 
5457   unsigned IntID =
5458       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5459   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5460   if (!IsUnmasked)
5461     Ops.push_back(PassThru);
5462   Ops.push_back(BasePtr);
5463   Ops.push_back(Index);
5464   if (!IsUnmasked)
5465     Ops.push_back(Mask);
5466   Ops.push_back(VL);
5467   if (!IsUnmasked)
5468     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5469 
5470   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5471   SDValue Result =
5472       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5473   Chain = Result.getValue(1);
5474 
5475   if (VT.isFixedLengthVector())
5476     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5477 
5478   return DAG.getMergeValues({Result, Chain}, DL);
5479 }
5480 
5481 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5482 // matched to a RVV indexed store. The RVV indexed store instructions only
5483 // support the "unsigned unscaled" addressing mode; indices are implicitly
5484 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5485 // signed or scaled indexing is extended to the XLEN value type and scaled
5486 // accordingly.
5487 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5488                                                 SelectionDAG &DAG) const {
5489   SDLoc DL(Op);
5490   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5491   EVT MemVT = MemSD->getMemoryVT();
5492   MachineMemOperand *MMO = MemSD->getMemOperand();
5493   SDValue Chain = MemSD->getChain();
5494   SDValue BasePtr = MemSD->getBasePtr();
5495 
5496   bool IsTruncatingStore = false;
5497   SDValue Index, Mask, Val, VL;
5498 
5499   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5500     Index = VPSN->getIndex();
5501     Mask = VPSN->getMask();
5502     Val = VPSN->getValue();
5503     VL = VPSN->getVectorLength();
5504     // VP doesn't support truncating stores.
5505     IsTruncatingStore = false;
5506   } else {
5507     // Else it must be a MSCATTER.
5508     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5509     Index = MSN->getIndex();
5510     Mask = MSN->getMask();
5511     Val = MSN->getValue();
5512     IsTruncatingStore = MSN->isTruncatingStore();
5513   }
5514 
5515   MVT VT = Val.getSimpleValueType();
5516   MVT IndexVT = Index.getSimpleValueType();
5517   MVT XLenVT = Subtarget.getXLenVT();
5518 
5519   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5520          "Unexpected VTs!");
5521   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5522   // Targets have to explicitly opt-in for extending vector loads and
5523   // truncating vector stores.
5524   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5525   (void)IsTruncatingStore;
5526 
5527   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5528   // the selection of the masked intrinsics doesn't do this for us.
5529   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5530 
5531   MVT ContainerVT = VT;
5532   if (VT.isFixedLengthVector()) {
5533     // We need to use the larger of the value and index type to determine the
5534     // scalable type to use so we don't increase LMUL for any operand/result.
5535     if (VT.bitsGE(IndexVT)) {
5536       ContainerVT = getContainerForFixedLengthVector(VT);
5537       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5538                                  ContainerVT.getVectorElementCount());
5539     } else {
5540       IndexVT = getContainerForFixedLengthVector(IndexVT);
5541       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5542                                      IndexVT.getVectorElementCount());
5543     }
5544 
5545     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5546     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5547 
5548     if (!IsUnmasked) {
5549       MVT MaskVT =
5550           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5551       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5552     }
5553   }
5554 
5555   if (!VL)
5556     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5557 
5558   unsigned IntID =
5559       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5560   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5561   Ops.push_back(Val);
5562   Ops.push_back(BasePtr);
5563   Ops.push_back(Index);
5564   if (!IsUnmasked)
5565     Ops.push_back(Mask);
5566   Ops.push_back(VL);
5567 
5568   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5569                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5570 }
5571 
5572 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5573                                                SelectionDAG &DAG) const {
5574   const MVT XLenVT = Subtarget.getXLenVT();
5575   SDLoc DL(Op);
5576   SDValue Chain = Op->getOperand(0);
5577   SDValue SysRegNo = DAG.getTargetConstant(
5578       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5579   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5580   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5581 
5582   // Encoding used for rounding mode in RISCV differs from that used in
5583   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5584   // table, which consists of a sequence of 4-bit fields, each representing
5585   // corresponding FLT_ROUNDS mode.
5586   static const int Table =
5587       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5588       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5589       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5590       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5591       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5592 
5593   SDValue Shift =
5594       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5595   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5596                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5597   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5598                                DAG.getConstant(7, DL, XLenVT));
5599 
5600   return DAG.getMergeValues({Masked, Chain}, DL);
5601 }
5602 
5603 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5604                                                SelectionDAG &DAG) const {
5605   const MVT XLenVT = Subtarget.getXLenVT();
5606   SDLoc DL(Op);
5607   SDValue Chain = Op->getOperand(0);
5608   SDValue RMValue = Op->getOperand(1);
5609   SDValue SysRegNo = DAG.getTargetConstant(
5610       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5611 
5612   // Encoding used for rounding mode in RISCV differs from that used in
5613   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5614   // a table, which consists of a sequence of 4-bit fields, each representing
5615   // corresponding RISCV mode.
5616   static const unsigned Table =
5617       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5618       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5619       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5620       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5621       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5622 
5623   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5624                               DAG.getConstant(2, DL, XLenVT));
5625   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5626                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5627   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5628                         DAG.getConstant(0x7, DL, XLenVT));
5629   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5630                      RMValue);
5631 }
5632 
5633 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5634 // form of the given Opcode.
5635 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5636   switch (Opcode) {
5637   default:
5638     llvm_unreachable("Unexpected opcode");
5639   case ISD::SHL:
5640     return RISCVISD::SLLW;
5641   case ISD::SRA:
5642     return RISCVISD::SRAW;
5643   case ISD::SRL:
5644     return RISCVISD::SRLW;
5645   case ISD::SDIV:
5646     return RISCVISD::DIVW;
5647   case ISD::UDIV:
5648     return RISCVISD::DIVUW;
5649   case ISD::UREM:
5650     return RISCVISD::REMUW;
5651   case ISD::ROTL:
5652     return RISCVISD::ROLW;
5653   case ISD::ROTR:
5654     return RISCVISD::RORW;
5655   case RISCVISD::GREV:
5656     return RISCVISD::GREVW;
5657   case RISCVISD::GORC:
5658     return RISCVISD::GORCW;
5659   }
5660 }
5661 
5662 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5663 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5664 // otherwise be promoted to i64, making it difficult to select the
5665 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5666 // type i8/i16/i32 is lost.
5667 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5668                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5669   SDLoc DL(N);
5670   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5671   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5672   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5673   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5674   // ReplaceNodeResults requires we maintain the same type for the return value.
5675   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5676 }
5677 
5678 // Converts the given 32-bit operation to a i64 operation with signed extension
5679 // semantic to reduce the signed extension instructions.
5680 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5681   SDLoc DL(N);
5682   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5683   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5684   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5685   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5686                                DAG.getValueType(MVT::i32));
5687   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5688 }
5689 
5690 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5691                                              SmallVectorImpl<SDValue> &Results,
5692                                              SelectionDAG &DAG) const {
5693   SDLoc DL(N);
5694   switch (N->getOpcode()) {
5695   default:
5696     llvm_unreachable("Don't know how to custom type legalize this operation!");
5697   case ISD::STRICT_FP_TO_SINT:
5698   case ISD::STRICT_FP_TO_UINT:
5699   case ISD::FP_TO_SINT:
5700   case ISD::FP_TO_UINT: {
5701     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5702            "Unexpected custom legalisation");
5703     bool IsStrict = N->isStrictFPOpcode();
5704     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5705                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5706     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5707     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5708         TargetLowering::TypeSoftenFloat) {
5709       // FIXME: Support strict FP.
5710       if (IsStrict)
5711         return;
5712       if (!isTypeLegal(Op0.getValueType()))
5713         return;
5714       unsigned Opc =
5715           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5716       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5717       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5718       return;
5719     }
5720     // If the FP type needs to be softened, emit a library call using the 'si'
5721     // version. If we left it to default legalization we'd end up with 'di'. If
5722     // the FP type doesn't need to be softened just let generic type
5723     // legalization promote the result type.
5724     RTLIB::Libcall LC;
5725     if (IsSigned)
5726       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5727     else
5728       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5729     MakeLibCallOptions CallOptions;
5730     EVT OpVT = Op0.getValueType();
5731     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5732     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5733     SDValue Result;
5734     std::tie(Result, Chain) =
5735         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5736     Results.push_back(Result);
5737     if (IsStrict)
5738       Results.push_back(Chain);
5739     break;
5740   }
5741   case ISD::READCYCLECOUNTER: {
5742     assert(!Subtarget.is64Bit() &&
5743            "READCYCLECOUNTER only has custom type legalization on riscv32");
5744 
5745     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5746     SDValue RCW =
5747         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5748 
5749     Results.push_back(
5750         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5751     Results.push_back(RCW.getValue(2));
5752     break;
5753   }
5754   case ISD::MUL: {
5755     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5756     unsigned XLen = Subtarget.getXLen();
5757     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5758     if (Size > XLen) {
5759       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5760       SDValue LHS = N->getOperand(0);
5761       SDValue RHS = N->getOperand(1);
5762       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5763 
5764       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5765       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5766       // We need exactly one side to be unsigned.
5767       if (LHSIsU == RHSIsU)
5768         return;
5769 
5770       auto MakeMULPair = [&](SDValue S, SDValue U) {
5771         MVT XLenVT = Subtarget.getXLenVT();
5772         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5773         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5774         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5775         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5776         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5777       };
5778 
5779       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5780       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5781 
5782       // The other operand should be signed, but still prefer MULH when
5783       // possible.
5784       if (RHSIsU && LHSIsS && !RHSIsS)
5785         Results.push_back(MakeMULPair(LHS, RHS));
5786       else if (LHSIsU && RHSIsS && !LHSIsS)
5787         Results.push_back(MakeMULPair(RHS, LHS));
5788 
5789       return;
5790     }
5791     LLVM_FALLTHROUGH;
5792   }
5793   case ISD::ADD:
5794   case ISD::SUB:
5795     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5796            "Unexpected custom legalisation");
5797     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5798     break;
5799   case ISD::SHL:
5800   case ISD::SRA:
5801   case ISD::SRL:
5802     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5803            "Unexpected custom legalisation");
5804     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5805       Results.push_back(customLegalizeToWOp(N, DAG));
5806       break;
5807     }
5808 
5809     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5810     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5811     // shift amount.
5812     if (N->getOpcode() == ISD::SHL) {
5813       SDLoc DL(N);
5814       SDValue NewOp0 =
5815           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5816       SDValue NewOp1 =
5817           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5818       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5819       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5820                                    DAG.getValueType(MVT::i32));
5821       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5822     }
5823 
5824     break;
5825   case ISD::ROTL:
5826   case ISD::ROTR:
5827     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5828            "Unexpected custom legalisation");
5829     Results.push_back(customLegalizeToWOp(N, DAG));
5830     break;
5831   case ISD::CTTZ:
5832   case ISD::CTTZ_ZERO_UNDEF:
5833   case ISD::CTLZ:
5834   case ISD::CTLZ_ZERO_UNDEF: {
5835     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5836            "Unexpected custom legalisation");
5837 
5838     SDValue NewOp0 =
5839         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5840     bool IsCTZ =
5841         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5842     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5843     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5844     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5845     return;
5846   }
5847   case ISD::SDIV:
5848   case ISD::UDIV:
5849   case ISD::UREM: {
5850     MVT VT = N->getSimpleValueType(0);
5851     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5852            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5853            "Unexpected custom legalisation");
5854     // Don't promote division/remainder by constant since we should expand those
5855     // to multiply by magic constant.
5856     // FIXME: What if the expansion is disabled for minsize.
5857     if (N->getOperand(1).getOpcode() == ISD::Constant)
5858       return;
5859 
5860     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5861     // the upper 32 bits. For other types we need to sign or zero extend
5862     // based on the opcode.
5863     unsigned ExtOpc = ISD::ANY_EXTEND;
5864     if (VT != MVT::i32)
5865       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5866                                            : ISD::ZERO_EXTEND;
5867 
5868     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5869     break;
5870   }
5871   case ISD::UADDO:
5872   case ISD::USUBO: {
5873     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5874            "Unexpected custom legalisation");
5875     bool IsAdd = N->getOpcode() == ISD::UADDO;
5876     // Create an ADDW or SUBW.
5877     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5878     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5879     SDValue Res =
5880         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5881     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5882                       DAG.getValueType(MVT::i32));
5883 
5884     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5885     // Since the inputs are sign extended from i32, this is equivalent to
5886     // comparing the lower 32 bits.
5887     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5888     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5889                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5890 
5891     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5892     Results.push_back(Overflow);
5893     return;
5894   }
5895   case ISD::UADDSAT:
5896   case ISD::USUBSAT: {
5897     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5898            "Unexpected custom legalisation");
5899     if (Subtarget.hasStdExtZbb()) {
5900       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5901       // sign extend allows overflow of the lower 32 bits to be detected on
5902       // the promoted size.
5903       SDValue LHS =
5904           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5905       SDValue RHS =
5906           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5907       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5908       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5909       return;
5910     }
5911 
5912     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5913     // promotion for UADDO/USUBO.
5914     Results.push_back(expandAddSubSat(N, DAG));
5915     return;
5916   }
5917   case ISD::BITCAST: {
5918     EVT VT = N->getValueType(0);
5919     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5920     SDValue Op0 = N->getOperand(0);
5921     EVT Op0VT = Op0.getValueType();
5922     MVT XLenVT = Subtarget.getXLenVT();
5923     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5924       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5925       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5926     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5927                Subtarget.hasStdExtF()) {
5928       SDValue FPConv =
5929           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5930       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5931     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5932                isTypeLegal(Op0VT)) {
5933       // Custom-legalize bitcasts from fixed-length vector types to illegal
5934       // scalar types in order to improve codegen. Bitcast the vector to a
5935       // one-element vector type whose element type is the same as the result
5936       // type, and extract the first element.
5937       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
5938       if (isTypeLegal(BVT)) {
5939         SDValue BVec = DAG.getBitcast(BVT, Op0);
5940         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5941                                       DAG.getConstant(0, DL, XLenVT)));
5942       }
5943     }
5944     break;
5945   }
5946   case RISCVISD::GREV:
5947   case RISCVISD::GORC: {
5948     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5949            "Unexpected custom legalisation");
5950     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5951     // This is similar to customLegalizeToWOp, except that we pass the second
5952     // operand (a TargetConstant) straight through: it is already of type
5953     // XLenVT.
5954     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5955     SDValue NewOp0 =
5956         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5957     SDValue NewOp1 =
5958         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5959     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5960     // ReplaceNodeResults requires we maintain the same type for the return
5961     // value.
5962     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5963     break;
5964   }
5965   case RISCVISD::SHFL: {
5966     // There is no SHFLIW instruction, but we can just promote the operation.
5967     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5968            "Unexpected custom legalisation");
5969     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5970     SDValue NewOp0 =
5971         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5972     SDValue NewOp1 =
5973         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5974     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5975     // ReplaceNodeResults requires we maintain the same type for the return
5976     // value.
5977     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5978     break;
5979   }
5980   case ISD::BSWAP:
5981   case ISD::BITREVERSE: {
5982     MVT VT = N->getSimpleValueType(0);
5983     MVT XLenVT = Subtarget.getXLenVT();
5984     assert((VT == MVT::i8 || VT == MVT::i16 ||
5985             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5986            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5987     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5988     unsigned Imm = VT.getSizeInBits() - 1;
5989     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5990     if (N->getOpcode() == ISD::BSWAP)
5991       Imm &= ~0x7U;
5992     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5993     SDValue GREVI =
5994         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5995     // ReplaceNodeResults requires we maintain the same type for the return
5996     // value.
5997     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5998     break;
5999   }
6000   case ISD::FSHL:
6001   case ISD::FSHR: {
6002     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6003            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6004     SDValue NewOp0 =
6005         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6006     SDValue NewOp1 =
6007         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6008     SDValue NewOp2 =
6009         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6010     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6011     // Mask the shift amount to 5 bits.
6012     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6013                          DAG.getConstant(0x1f, DL, MVT::i64));
6014     unsigned Opc =
6015         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6016     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6017     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6018     break;
6019   }
6020   case ISD::EXTRACT_VECTOR_ELT: {
6021     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6022     // type is illegal (currently only vXi64 RV32).
6023     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6024     // transferred to the destination register. We issue two of these from the
6025     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6026     // first element.
6027     SDValue Vec = N->getOperand(0);
6028     SDValue Idx = N->getOperand(1);
6029 
6030     // The vector type hasn't been legalized yet so we can't issue target
6031     // specific nodes if it needs legalization.
6032     // FIXME: We would manually legalize if it's important.
6033     if (!isTypeLegal(Vec.getValueType()))
6034       return;
6035 
6036     MVT VecVT = Vec.getSimpleValueType();
6037 
6038     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6039            VecVT.getVectorElementType() == MVT::i64 &&
6040            "Unexpected EXTRACT_VECTOR_ELT legalization");
6041 
6042     // If this is a fixed vector, we need to convert it to a scalable vector.
6043     MVT ContainerVT = VecVT;
6044     if (VecVT.isFixedLengthVector()) {
6045       ContainerVT = getContainerForFixedLengthVector(VecVT);
6046       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6047     }
6048 
6049     MVT XLenVT = Subtarget.getXLenVT();
6050 
6051     // Use a VL of 1 to avoid processing more elements than we need.
6052     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6053     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6054     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6055 
6056     // Unless the index is known to be 0, we must slide the vector down to get
6057     // the desired element into index 0.
6058     if (!isNullConstant(Idx)) {
6059       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6060                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6061     }
6062 
6063     // Extract the lower XLEN bits of the correct vector element.
6064     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6065 
6066     // To extract the upper XLEN bits of the vector element, shift the first
6067     // element right by 32 bits and re-extract the lower XLEN bits.
6068     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6069                                      DAG.getConstant(32, DL, XLenVT), VL);
6070     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6071                                  ThirtyTwoV, Mask, VL);
6072 
6073     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6074 
6075     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6076     break;
6077   }
6078   case ISD::INTRINSIC_WO_CHAIN: {
6079     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6080     switch (IntNo) {
6081     default:
6082       llvm_unreachable(
6083           "Don't know how to custom type legalize this intrinsic!");
6084     case Intrinsic::riscv_orc_b: {
6085       // Lower to the GORCI encoding for orc.b with the operand extended.
6086       SDValue NewOp =
6087           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6088       // If Zbp is enabled, use GORCIW which will sign extend the result.
6089       unsigned Opc =
6090           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6091       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6092                                 DAG.getConstant(7, DL, MVT::i64));
6093       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6094       return;
6095     }
6096     case Intrinsic::riscv_grev:
6097     case Intrinsic::riscv_gorc: {
6098       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6099              "Unexpected custom legalisation");
6100       SDValue NewOp1 =
6101           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6102       SDValue NewOp2 =
6103           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6104       unsigned Opc =
6105           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6106       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6107       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6108       break;
6109     }
6110     case Intrinsic::riscv_shfl:
6111     case Intrinsic::riscv_unshfl: {
6112       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6113              "Unexpected custom legalisation");
6114       SDValue NewOp1 =
6115           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6116       SDValue NewOp2 =
6117           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6118       unsigned Opc =
6119           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6120       if (isa<ConstantSDNode>(N->getOperand(2))) {
6121         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6122                              DAG.getConstant(0xf, DL, MVT::i64));
6123         Opc =
6124             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6125       }
6126       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6127       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6128       break;
6129     }
6130     case Intrinsic::riscv_bcompress:
6131     case Intrinsic::riscv_bdecompress: {
6132       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6133              "Unexpected custom legalisation");
6134       SDValue NewOp1 =
6135           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6136       SDValue NewOp2 =
6137           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6138       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6139                          ? RISCVISD::BCOMPRESSW
6140                          : RISCVISD::BDECOMPRESSW;
6141       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6142       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6143       break;
6144     }
6145     case Intrinsic::riscv_vmv_x_s: {
6146       EVT VT = N->getValueType(0);
6147       MVT XLenVT = Subtarget.getXLenVT();
6148       if (VT.bitsLT(XLenVT)) {
6149         // Simple case just extract using vmv.x.s and truncate.
6150         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6151                                       Subtarget.getXLenVT(), N->getOperand(1));
6152         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6153         return;
6154       }
6155 
6156       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6157              "Unexpected custom legalization");
6158 
6159       // We need to do the move in two steps.
6160       SDValue Vec = N->getOperand(1);
6161       MVT VecVT = Vec.getSimpleValueType();
6162 
6163       // First extract the lower XLEN bits of the element.
6164       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6165 
6166       // To extract the upper XLEN bits of the vector element, shift the first
6167       // element right by 32 bits and re-extract the lower XLEN bits.
6168       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6169       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6170       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6171       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6172                                        DAG.getConstant(32, DL, XLenVT), VL);
6173       SDValue LShr32 =
6174           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6175       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6176 
6177       Results.push_back(
6178           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6179       break;
6180     }
6181     }
6182     break;
6183   }
6184   case ISD::VECREDUCE_ADD:
6185   case ISD::VECREDUCE_AND:
6186   case ISD::VECREDUCE_OR:
6187   case ISD::VECREDUCE_XOR:
6188   case ISD::VECREDUCE_SMAX:
6189   case ISD::VECREDUCE_UMAX:
6190   case ISD::VECREDUCE_SMIN:
6191   case ISD::VECREDUCE_UMIN:
6192     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6193       Results.push_back(V);
6194     break;
6195   case ISD::VP_REDUCE_ADD:
6196   case ISD::VP_REDUCE_AND:
6197   case ISD::VP_REDUCE_OR:
6198   case ISD::VP_REDUCE_XOR:
6199   case ISD::VP_REDUCE_SMAX:
6200   case ISD::VP_REDUCE_UMAX:
6201   case ISD::VP_REDUCE_SMIN:
6202   case ISD::VP_REDUCE_UMIN:
6203     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6204       Results.push_back(V);
6205     break;
6206   case ISD::FLT_ROUNDS_: {
6207     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6208     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6209     Results.push_back(Res.getValue(0));
6210     Results.push_back(Res.getValue(1));
6211     break;
6212   }
6213   }
6214 }
6215 
6216 // A structure to hold one of the bit-manipulation patterns below. Together, a
6217 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6218 //   (or (and (shl x, 1), 0xAAAAAAAA),
6219 //       (and (srl x, 1), 0x55555555))
6220 struct RISCVBitmanipPat {
6221   SDValue Op;
6222   unsigned ShAmt;
6223   bool IsSHL;
6224 
6225   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6226     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6227   }
6228 };
6229 
6230 // Matches patterns of the form
6231 //   (and (shl x, C2), (C1 << C2))
6232 //   (and (srl x, C2), C1)
6233 //   (shl (and x, C1), C2)
6234 //   (srl (and x, (C1 << C2)), C2)
6235 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6236 // The expected masks for each shift amount are specified in BitmanipMasks where
6237 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6238 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6239 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6240 // XLen is 64.
6241 static Optional<RISCVBitmanipPat>
6242 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6243   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6244          "Unexpected number of masks");
6245   Optional<uint64_t> Mask;
6246   // Optionally consume a mask around the shift operation.
6247   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6248     Mask = Op.getConstantOperandVal(1);
6249     Op = Op.getOperand(0);
6250   }
6251   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6252     return None;
6253   bool IsSHL = Op.getOpcode() == ISD::SHL;
6254 
6255   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6256     return None;
6257   uint64_t ShAmt = Op.getConstantOperandVal(1);
6258 
6259   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6260   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6261     return None;
6262   // If we don't have enough masks for 64 bit, then we must be trying to
6263   // match SHFL so we're only allowed to shift 1/4 of the width.
6264   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6265     return None;
6266 
6267   SDValue Src = Op.getOperand(0);
6268 
6269   // The expected mask is shifted left when the AND is found around SHL
6270   // patterns.
6271   //   ((x >> 1) & 0x55555555)
6272   //   ((x << 1) & 0xAAAAAAAA)
6273   bool SHLExpMask = IsSHL;
6274 
6275   if (!Mask) {
6276     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6277     // the mask is all ones: consume that now.
6278     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6279       Mask = Src.getConstantOperandVal(1);
6280       Src = Src.getOperand(0);
6281       // The expected mask is now in fact shifted left for SRL, so reverse the
6282       // decision.
6283       //   ((x & 0xAAAAAAAA) >> 1)
6284       //   ((x & 0x55555555) << 1)
6285       SHLExpMask = !SHLExpMask;
6286     } else {
6287       // Use a default shifted mask of all-ones if there's no AND, truncated
6288       // down to the expected width. This simplifies the logic later on.
6289       Mask = maskTrailingOnes<uint64_t>(Width);
6290       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6291     }
6292   }
6293 
6294   unsigned MaskIdx = Log2_32(ShAmt);
6295   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6296 
6297   if (SHLExpMask)
6298     ExpMask <<= ShAmt;
6299 
6300   if (Mask != ExpMask)
6301     return None;
6302 
6303   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6304 }
6305 
6306 // Matches any of the following bit-manipulation patterns:
6307 //   (and (shl x, 1), (0x55555555 << 1))
6308 //   (and (srl x, 1), 0x55555555)
6309 //   (shl (and x, 0x55555555), 1)
6310 //   (srl (and x, (0x55555555 << 1)), 1)
6311 // where the shift amount and mask may vary thus:
6312 //   [1]  = 0x55555555 / 0xAAAAAAAA
6313 //   [2]  = 0x33333333 / 0xCCCCCCCC
6314 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6315 //   [8]  = 0x00FF00FF / 0xFF00FF00
6316 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6317 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6318 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6319   // These are the unshifted masks which we use to match bit-manipulation
6320   // patterns. They may be shifted left in certain circumstances.
6321   static const uint64_t BitmanipMasks[] = {
6322       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6323       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6324 
6325   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6326 }
6327 
6328 // Match the following pattern as a GREVI(W) operation
6329 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6330 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6331                                const RISCVSubtarget &Subtarget) {
6332   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6333   EVT VT = Op.getValueType();
6334 
6335   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6336     auto LHS = matchGREVIPat(Op.getOperand(0));
6337     auto RHS = matchGREVIPat(Op.getOperand(1));
6338     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6339       SDLoc DL(Op);
6340       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6341                          DAG.getConstant(LHS->ShAmt, DL, VT));
6342     }
6343   }
6344   return SDValue();
6345 }
6346 
6347 // Matches any the following pattern as a GORCI(W) operation
6348 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6349 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6350 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6351 // Note that with the variant of 3.,
6352 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6353 // the inner pattern will first be matched as GREVI and then the outer
6354 // pattern will be matched to GORC via the first rule above.
6355 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6356 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6357                                const RISCVSubtarget &Subtarget) {
6358   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6359   EVT VT = Op.getValueType();
6360 
6361   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6362     SDLoc DL(Op);
6363     SDValue Op0 = Op.getOperand(0);
6364     SDValue Op1 = Op.getOperand(1);
6365 
6366     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6367       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6368           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6369           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6370         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6371       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6372       if ((Reverse.getOpcode() == ISD::ROTL ||
6373            Reverse.getOpcode() == ISD::ROTR) &&
6374           Reverse.getOperand(0) == X &&
6375           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6376         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6377         if (RotAmt == (VT.getSizeInBits() / 2))
6378           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6379                              DAG.getConstant(RotAmt, DL, VT));
6380       }
6381       return SDValue();
6382     };
6383 
6384     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6385     if (SDValue V = MatchOROfReverse(Op0, Op1))
6386       return V;
6387     if (SDValue V = MatchOROfReverse(Op1, Op0))
6388       return V;
6389 
6390     // OR is commutable so canonicalize its OR operand to the left
6391     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6392       std::swap(Op0, Op1);
6393     if (Op0.getOpcode() != ISD::OR)
6394       return SDValue();
6395     SDValue OrOp0 = Op0.getOperand(0);
6396     SDValue OrOp1 = Op0.getOperand(1);
6397     auto LHS = matchGREVIPat(OrOp0);
6398     // OR is commutable so swap the operands and try again: x might have been
6399     // on the left
6400     if (!LHS) {
6401       std::swap(OrOp0, OrOp1);
6402       LHS = matchGREVIPat(OrOp0);
6403     }
6404     auto RHS = matchGREVIPat(Op1);
6405     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6406       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6407                          DAG.getConstant(LHS->ShAmt, DL, VT));
6408     }
6409   }
6410   return SDValue();
6411 }
6412 
6413 // Matches any of the following bit-manipulation patterns:
6414 //   (and (shl x, 1), (0x22222222 << 1))
6415 //   (and (srl x, 1), 0x22222222)
6416 //   (shl (and x, 0x22222222), 1)
6417 //   (srl (and x, (0x22222222 << 1)), 1)
6418 // where the shift amount and mask may vary thus:
6419 //   [1]  = 0x22222222 / 0x44444444
6420 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6421 //   [4]  = 0x00F000F0 / 0x0F000F00
6422 //   [8]  = 0x0000FF00 / 0x00FF0000
6423 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6424 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6425   // These are the unshifted masks which we use to match bit-manipulation
6426   // patterns. They may be shifted left in certain circumstances.
6427   static const uint64_t BitmanipMasks[] = {
6428       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6429       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6430 
6431   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6432 }
6433 
6434 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6435 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6436                                const RISCVSubtarget &Subtarget) {
6437   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6438   EVT VT = Op.getValueType();
6439 
6440   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6441     return SDValue();
6442 
6443   SDValue Op0 = Op.getOperand(0);
6444   SDValue Op1 = Op.getOperand(1);
6445 
6446   // Or is commutable so canonicalize the second OR to the LHS.
6447   if (Op0.getOpcode() != ISD::OR)
6448     std::swap(Op0, Op1);
6449   if (Op0.getOpcode() != ISD::OR)
6450     return SDValue();
6451 
6452   // We found an inner OR, so our operands are the operands of the inner OR
6453   // and the other operand of the outer OR.
6454   SDValue A = Op0.getOperand(0);
6455   SDValue B = Op0.getOperand(1);
6456   SDValue C = Op1;
6457 
6458   auto Match1 = matchSHFLPat(A);
6459   auto Match2 = matchSHFLPat(B);
6460 
6461   // If neither matched, we failed.
6462   if (!Match1 && !Match2)
6463     return SDValue();
6464 
6465   // We had at least one match. if one failed, try the remaining C operand.
6466   if (!Match1) {
6467     std::swap(A, C);
6468     Match1 = matchSHFLPat(A);
6469     if (!Match1)
6470       return SDValue();
6471   } else if (!Match2) {
6472     std::swap(B, C);
6473     Match2 = matchSHFLPat(B);
6474     if (!Match2)
6475       return SDValue();
6476   }
6477   assert(Match1 && Match2);
6478 
6479   // Make sure our matches pair up.
6480   if (!Match1->formsPairWith(*Match2))
6481     return SDValue();
6482 
6483   // All the remains is to make sure C is an AND with the same input, that masks
6484   // out the bits that are being shuffled.
6485   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6486       C.getOperand(0) != Match1->Op)
6487     return SDValue();
6488 
6489   uint64_t Mask = C.getConstantOperandVal(1);
6490 
6491   static const uint64_t BitmanipMasks[] = {
6492       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6493       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6494   };
6495 
6496   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6497   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6498   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6499 
6500   if (Mask != ExpMask)
6501     return SDValue();
6502 
6503   SDLoc DL(Op);
6504   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6505                      DAG.getConstant(Match1->ShAmt, DL, VT));
6506 }
6507 
6508 // Optimize (add (shl x, c0), (shl y, c1)) ->
6509 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6510 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6511                                   const RISCVSubtarget &Subtarget) {
6512   // Perform this optimization only in the zba extension.
6513   if (!Subtarget.hasStdExtZba())
6514     return SDValue();
6515 
6516   // Skip for vector types and larger types.
6517   EVT VT = N->getValueType(0);
6518   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6519     return SDValue();
6520 
6521   // The two operand nodes must be SHL and have no other use.
6522   SDValue N0 = N->getOperand(0);
6523   SDValue N1 = N->getOperand(1);
6524   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6525       !N0->hasOneUse() || !N1->hasOneUse())
6526     return SDValue();
6527 
6528   // Check c0 and c1.
6529   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6530   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6531   if (!N0C || !N1C)
6532     return SDValue();
6533   int64_t C0 = N0C->getSExtValue();
6534   int64_t C1 = N1C->getSExtValue();
6535   if (C0 <= 0 || C1 <= 0)
6536     return SDValue();
6537 
6538   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6539   int64_t Bits = std::min(C0, C1);
6540   int64_t Diff = std::abs(C0 - C1);
6541   if (Diff != 1 && Diff != 2 && Diff != 3)
6542     return SDValue();
6543 
6544   // Build nodes.
6545   SDLoc DL(N);
6546   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6547   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6548   SDValue NA0 =
6549       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6550   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6551   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6552 }
6553 
6554 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6555 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6556 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6557 // not undo itself, but they are redundant.
6558 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6559   SDValue Src = N->getOperand(0);
6560 
6561   if (Src.getOpcode() != N->getOpcode())
6562     return SDValue();
6563 
6564   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6565       !isa<ConstantSDNode>(Src.getOperand(1)))
6566     return SDValue();
6567 
6568   unsigned ShAmt1 = N->getConstantOperandVal(1);
6569   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6570   Src = Src.getOperand(0);
6571 
6572   unsigned CombinedShAmt;
6573   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6574     CombinedShAmt = ShAmt1 | ShAmt2;
6575   else
6576     CombinedShAmt = ShAmt1 ^ ShAmt2;
6577 
6578   if (CombinedShAmt == 0)
6579     return Src;
6580 
6581   SDLoc DL(N);
6582   return DAG.getNode(
6583       N->getOpcode(), DL, N->getValueType(0), Src,
6584       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6585 }
6586 
6587 // Combine a constant select operand into its use:
6588 //
6589 // (and (select cond, -1, c), x)
6590 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6591 // (or  (select cond, 0, c), x)
6592 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6593 // (xor (select cond, 0, c), x)
6594 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6595 // (add (select cond, 0, c), x)
6596 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6597 // (sub x, (select cond, 0, c))
6598 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6599 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6600                                    SelectionDAG &DAG, bool AllOnes) {
6601   EVT VT = N->getValueType(0);
6602 
6603   // Skip vectors.
6604   if (VT.isVector())
6605     return SDValue();
6606 
6607   if ((Slct.getOpcode() != ISD::SELECT &&
6608        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6609       !Slct.hasOneUse())
6610     return SDValue();
6611 
6612   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6613     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6614   };
6615 
6616   bool SwapSelectOps;
6617   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6618   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6619   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6620   SDValue NonConstantVal;
6621   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6622     SwapSelectOps = false;
6623     NonConstantVal = FalseVal;
6624   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6625     SwapSelectOps = true;
6626     NonConstantVal = TrueVal;
6627   } else
6628     return SDValue();
6629 
6630   // Slct is now know to be the desired identity constant when CC is true.
6631   TrueVal = OtherOp;
6632   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6633   // Unless SwapSelectOps says the condition should be false.
6634   if (SwapSelectOps)
6635     std::swap(TrueVal, FalseVal);
6636 
6637   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6638     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6639                        {Slct.getOperand(0), Slct.getOperand(1),
6640                         Slct.getOperand(2), TrueVal, FalseVal});
6641 
6642   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6643                      {Slct.getOperand(0), TrueVal, FalseVal});
6644 }
6645 
6646 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6647 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6648                                               bool AllOnes) {
6649   SDValue N0 = N->getOperand(0);
6650   SDValue N1 = N->getOperand(1);
6651   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6652     return Result;
6653   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6654     return Result;
6655   return SDValue();
6656 }
6657 
6658 // Transform (add (mul x, c0), c1) ->
6659 //           (add (mul (add x, c1/c0), c0), c1%c0).
6660 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6661 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6662 // to an infinite loop in DAGCombine if transformed.
6663 // Or transform (add (mul x, c0), c1) ->
6664 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6665 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6666 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6667 // lead to an infinite loop in DAGCombine if transformed.
6668 // Or transform (add (mul x, c0), c1) ->
6669 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6670 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6671 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6672 // lead to an infinite loop in DAGCombine if transformed.
6673 // Or transform (add (mul x, c0), c1) ->
6674 //              (mul (add x, c1/c0), c0).
6675 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6676 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6677                                      const RISCVSubtarget &Subtarget) {
6678   // Skip for vector types and larger types.
6679   EVT VT = N->getValueType(0);
6680   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6681     return SDValue();
6682   // The first operand node must be a MUL and has no other use.
6683   SDValue N0 = N->getOperand(0);
6684   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6685     return SDValue();
6686   // Check if c0 and c1 match above conditions.
6687   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6688   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6689   if (!N0C || !N1C)
6690     return SDValue();
6691   int64_t C0 = N0C->getSExtValue();
6692   int64_t C1 = N1C->getSExtValue();
6693   int64_t CA, CB;
6694   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6695     return SDValue();
6696   // Search for proper CA (non-zero) and CB that both are simm12.
6697   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6698       !isInt<12>(C0 * (C1 / C0))) {
6699     CA = C1 / C0;
6700     CB = C1 % C0;
6701   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6702              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6703     CA = C1 / C0 + 1;
6704     CB = C1 % C0 - C0;
6705   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6706              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6707     CA = C1 / C0 - 1;
6708     CB = C1 % C0 + C0;
6709   } else
6710     return SDValue();
6711   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6712   SDLoc DL(N);
6713   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6714                              DAG.getConstant(CA, DL, VT));
6715   SDValue New1 =
6716       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6717   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6718 }
6719 
6720 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6721                                  const RISCVSubtarget &Subtarget) {
6722   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6723     return V;
6724   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6725     return V;
6726   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6727   //      (select lhs, rhs, cc, x, (add x, y))
6728   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6729 }
6730 
6731 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6732   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6733   //      (select lhs, rhs, cc, x, (sub x, y))
6734   SDValue N0 = N->getOperand(0);
6735   SDValue N1 = N->getOperand(1);
6736   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6737 }
6738 
6739 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6740   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6741   //      (select lhs, rhs, cc, x, (and x, y))
6742   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6743 }
6744 
6745 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6746                                 const RISCVSubtarget &Subtarget) {
6747   if (Subtarget.hasStdExtZbp()) {
6748     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6749       return GREV;
6750     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6751       return GORC;
6752     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6753       return SHFL;
6754   }
6755 
6756   // fold (or (select cond, 0, y), x) ->
6757   //      (select cond, x, (or x, y))
6758   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6759 }
6760 
6761 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6762   // fold (xor (select cond, 0, y), x) ->
6763   //      (select cond, x, (xor x, y))
6764   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6765 }
6766 
6767 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6768 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6769 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6770 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6771 // ADDW/SUBW/MULW.
6772 static SDValue performANY_EXTENDCombine(SDNode *N,
6773                                         TargetLowering::DAGCombinerInfo &DCI,
6774                                         const RISCVSubtarget &Subtarget) {
6775   if (!Subtarget.is64Bit())
6776     return SDValue();
6777 
6778   SelectionDAG &DAG = DCI.DAG;
6779 
6780   SDValue Src = N->getOperand(0);
6781   EVT VT = N->getValueType(0);
6782   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6783     return SDValue();
6784 
6785   // The opcode must be one that can implicitly sign_extend.
6786   // FIXME: Additional opcodes.
6787   switch (Src.getOpcode()) {
6788   default:
6789     return SDValue();
6790   case ISD::MUL:
6791     if (!Subtarget.hasStdExtM())
6792       return SDValue();
6793     LLVM_FALLTHROUGH;
6794   case ISD::ADD:
6795   case ISD::SUB:
6796     break;
6797   }
6798 
6799   // Only handle cases where the result is used by a CopyToReg. That likely
6800   // means the value is a liveout of the basic block. This helps prevent
6801   // infinite combine loops like PR51206.
6802   if (none_of(N->uses(),
6803               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6804     return SDValue();
6805 
6806   SmallVector<SDNode *, 4> SetCCs;
6807   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6808                             UE = Src.getNode()->use_end();
6809        UI != UE; ++UI) {
6810     SDNode *User = *UI;
6811     if (User == N)
6812       continue;
6813     if (UI.getUse().getResNo() != Src.getResNo())
6814       continue;
6815     // All i32 setccs are legalized by sign extending operands.
6816     if (User->getOpcode() == ISD::SETCC) {
6817       SetCCs.push_back(User);
6818       continue;
6819     }
6820     // We don't know if we can extend this user.
6821     break;
6822   }
6823 
6824   // If we don't have any SetCCs, this isn't worthwhile.
6825   if (SetCCs.empty())
6826     return SDValue();
6827 
6828   SDLoc DL(N);
6829   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6830   DCI.CombineTo(N, SExt);
6831 
6832   // Promote all the setccs.
6833   for (SDNode *SetCC : SetCCs) {
6834     SmallVector<SDValue, 4> Ops;
6835 
6836     for (unsigned j = 0; j != 2; ++j) {
6837       SDValue SOp = SetCC->getOperand(j);
6838       if (SOp == Src)
6839         Ops.push_back(SExt);
6840       else
6841         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6842     }
6843 
6844     Ops.push_back(SetCC->getOperand(2));
6845     DCI.CombineTo(SetCC,
6846                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6847   }
6848   return SDValue(N, 0);
6849 }
6850 
6851 // Try to form VWMUL or VWMULU.
6852 // FIXME: Support VWMULSU.
6853 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6854                                     SelectionDAG &DAG) {
6855   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6856   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6857   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6858   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6859     return SDValue();
6860 
6861   SDValue Mask = N->getOperand(2);
6862   SDValue VL = N->getOperand(3);
6863 
6864   // Make sure the mask and VL match.
6865   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6866     return SDValue();
6867 
6868   MVT VT = N->getSimpleValueType(0);
6869 
6870   // Determine the narrow size for a widening multiply.
6871   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6872   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6873                                   VT.getVectorElementCount());
6874 
6875   SDLoc DL(N);
6876 
6877   // See if the other operand is the same opcode.
6878   if (Op0.getOpcode() == Op1.getOpcode()) {
6879     if (!Op1.hasOneUse())
6880       return SDValue();
6881 
6882     // Make sure the mask and VL match.
6883     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6884       return SDValue();
6885 
6886     Op1 = Op1.getOperand(0);
6887   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6888     // The operand is a splat of a scalar.
6889 
6890     // The VL must be the same.
6891     if (Op1.getOperand(1) != VL)
6892       return SDValue();
6893 
6894     // Get the scalar value.
6895     Op1 = Op1.getOperand(0);
6896 
6897     // See if have enough sign bits or zero bits in the scalar to use a
6898     // widening multiply by splatting to smaller element size.
6899     unsigned EltBits = VT.getScalarSizeInBits();
6900     unsigned ScalarBits = Op1.getValueSizeInBits();
6901     // Make sure we're getting all element bits from the scalar register.
6902     // FIXME: Support implicit sign extension of vmv.v.x?
6903     if (ScalarBits < EltBits)
6904       return SDValue();
6905 
6906     if (IsSignExt) {
6907       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6908         return SDValue();
6909     } else {
6910       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6911       if (!DAG.MaskedValueIsZero(Op1, Mask))
6912         return SDValue();
6913     }
6914 
6915     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6916   } else
6917     return SDValue();
6918 
6919   Op0 = Op0.getOperand(0);
6920 
6921   // Re-introduce narrower extends if needed.
6922   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6923   if (Op0.getValueType() != NarrowVT)
6924     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6925   if (Op1.getValueType() != NarrowVT)
6926     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6927 
6928   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6929   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6930 }
6931 
6932 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6933                                                DAGCombinerInfo &DCI) const {
6934   SelectionDAG &DAG = DCI.DAG;
6935 
6936   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6937   // bits are demanded. N will be added to the Worklist if it was not deleted.
6938   // Caller should return SDValue(N, 0) if this returns true.
6939   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6940     SDValue Op = N->getOperand(OpNo);
6941     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6942     if (!SimplifyDemandedBits(Op, Mask, DCI))
6943       return false;
6944 
6945     if (N->getOpcode() != ISD::DELETED_NODE)
6946       DCI.AddToWorklist(N);
6947     return true;
6948   };
6949 
6950   switch (N->getOpcode()) {
6951   default:
6952     break;
6953   case RISCVISD::SplitF64: {
6954     SDValue Op0 = N->getOperand(0);
6955     // If the input to SplitF64 is just BuildPairF64 then the operation is
6956     // redundant. Instead, use BuildPairF64's operands directly.
6957     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6958       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6959 
6960     SDLoc DL(N);
6961 
6962     // It's cheaper to materialise two 32-bit integers than to load a double
6963     // from the constant pool and transfer it to integer registers through the
6964     // stack.
6965     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6966       APInt V = C->getValueAPF().bitcastToAPInt();
6967       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6968       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6969       return DCI.CombineTo(N, Lo, Hi);
6970     }
6971 
6972     // This is a target-specific version of a DAGCombine performed in
6973     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6974     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6975     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6976     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6977         !Op0.getNode()->hasOneUse())
6978       break;
6979     SDValue NewSplitF64 =
6980         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6981                     Op0.getOperand(0));
6982     SDValue Lo = NewSplitF64.getValue(0);
6983     SDValue Hi = NewSplitF64.getValue(1);
6984     APInt SignBit = APInt::getSignMask(32);
6985     if (Op0.getOpcode() == ISD::FNEG) {
6986       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6987                                   DAG.getConstant(SignBit, DL, MVT::i32));
6988       return DCI.CombineTo(N, Lo, NewHi);
6989     }
6990     assert(Op0.getOpcode() == ISD::FABS);
6991     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6992                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6993     return DCI.CombineTo(N, Lo, NewHi);
6994   }
6995   case RISCVISD::SLLW:
6996   case RISCVISD::SRAW:
6997   case RISCVISD::SRLW:
6998   case RISCVISD::ROLW:
6999   case RISCVISD::RORW: {
7000     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7001     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7002         SimplifyDemandedLowBitsHelper(1, 5))
7003       return SDValue(N, 0);
7004     break;
7005   }
7006   case RISCVISD::CLZW:
7007   case RISCVISD::CTZW: {
7008     // Only the lower 32 bits of the first operand are read
7009     if (SimplifyDemandedLowBitsHelper(0, 32))
7010       return SDValue(N, 0);
7011     break;
7012   }
7013   case RISCVISD::FSL:
7014   case RISCVISD::FSR: {
7015     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7016     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7017     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7018     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7019       return SDValue(N, 0);
7020     break;
7021   }
7022   case RISCVISD::FSLW:
7023   case RISCVISD::FSRW: {
7024     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7025     // read.
7026     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7027         SimplifyDemandedLowBitsHelper(1, 32) ||
7028         SimplifyDemandedLowBitsHelper(2, 6))
7029       return SDValue(N, 0);
7030     break;
7031   }
7032   case RISCVISD::GREV:
7033   case RISCVISD::GORC: {
7034     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7035     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7036     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7037     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7038       return SDValue(N, 0);
7039 
7040     return combineGREVI_GORCI(N, DCI.DAG);
7041   }
7042   case RISCVISD::GREVW:
7043   case RISCVISD::GORCW: {
7044     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7045     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7046         SimplifyDemandedLowBitsHelper(1, 5))
7047       return SDValue(N, 0);
7048 
7049     return combineGREVI_GORCI(N, DCI.DAG);
7050   }
7051   case RISCVISD::SHFL:
7052   case RISCVISD::UNSHFL: {
7053     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7054     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7055     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7056     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7057       return SDValue(N, 0);
7058 
7059     break;
7060   }
7061   case RISCVISD::SHFLW:
7062   case RISCVISD::UNSHFLW: {
7063     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7064     SDValue LHS = N->getOperand(0);
7065     SDValue RHS = N->getOperand(1);
7066     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7067     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7068     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7069         SimplifyDemandedLowBitsHelper(1, 4))
7070       return SDValue(N, 0);
7071 
7072     break;
7073   }
7074   case RISCVISD::BCOMPRESSW:
7075   case RISCVISD::BDECOMPRESSW: {
7076     // Only the lower 32 bits of LHS and RHS are read.
7077     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7078         SimplifyDemandedLowBitsHelper(1, 32))
7079       return SDValue(N, 0);
7080 
7081     break;
7082   }
7083   case RISCVISD::FMV_X_ANYEXTH:
7084   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7085     SDLoc DL(N);
7086     SDValue Op0 = N->getOperand(0);
7087     MVT VT = N->getSimpleValueType(0);
7088     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7089     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7090     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7091     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7092          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7093         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7094          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7095       assert(Op0.getOperand(0).getValueType() == VT &&
7096              "Unexpected value type!");
7097       return Op0.getOperand(0);
7098     }
7099 
7100     // This is a target-specific version of a DAGCombine performed in
7101     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7102     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7103     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7104     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7105         !Op0.getNode()->hasOneUse())
7106       break;
7107     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7108     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7109     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7110     if (Op0.getOpcode() == ISD::FNEG)
7111       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7112                          DAG.getConstant(SignBit, DL, VT));
7113 
7114     assert(Op0.getOpcode() == ISD::FABS);
7115     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7116                        DAG.getConstant(~SignBit, DL, VT));
7117   }
7118   case ISD::ADD:
7119     return performADDCombine(N, DAG, Subtarget);
7120   case ISD::SUB:
7121     return performSUBCombine(N, DAG);
7122   case ISD::AND:
7123     return performANDCombine(N, DAG);
7124   case ISD::OR:
7125     return performORCombine(N, DAG, Subtarget);
7126   case ISD::XOR:
7127     return performXORCombine(N, DAG);
7128   case ISD::ANY_EXTEND:
7129     return performANY_EXTENDCombine(N, DCI, Subtarget);
7130   case ISD::ZERO_EXTEND:
7131     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7132     // type legalization. This is safe because fp_to_uint produces poison if
7133     // it overflows.
7134     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
7135         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
7136         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
7137       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7138                          N->getOperand(0).getOperand(0));
7139     return SDValue();
7140   case RISCVISD::SELECT_CC: {
7141     // Transform
7142     SDValue LHS = N->getOperand(0);
7143     SDValue RHS = N->getOperand(1);
7144     SDValue TrueV = N->getOperand(3);
7145     SDValue FalseV = N->getOperand(4);
7146 
7147     // If the True and False values are the same, we don't need a select_cc.
7148     if (TrueV == FalseV)
7149       return TrueV;
7150 
7151     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7152     if (!ISD::isIntEqualitySetCC(CCVal))
7153       break;
7154 
7155     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7156     //      (select_cc X, Y, lt, trueV, falseV)
7157     // Sometimes the setcc is introduced after select_cc has been formed.
7158     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7159         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7160       // If we're looking for eq 0 instead of ne 0, we need to invert the
7161       // condition.
7162       bool Invert = CCVal == ISD::SETEQ;
7163       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7164       if (Invert)
7165         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7166 
7167       SDLoc DL(N);
7168       RHS = LHS.getOperand(1);
7169       LHS = LHS.getOperand(0);
7170       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7171 
7172       SDValue TargetCC = DAG.getCondCode(CCVal);
7173       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7174                          {LHS, RHS, TargetCC, TrueV, FalseV});
7175     }
7176 
7177     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7178     //      (select_cc X, Y, eq/ne, trueV, falseV)
7179     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7180       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7181                          {LHS.getOperand(0), LHS.getOperand(1),
7182                           N->getOperand(2), TrueV, FalseV});
7183     // (select_cc X, 1, setne, trueV, falseV) ->
7184     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7185     // This can occur when legalizing some floating point comparisons.
7186     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7187     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7188       SDLoc DL(N);
7189       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7190       SDValue TargetCC = DAG.getCondCode(CCVal);
7191       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7192       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7193                          {LHS, RHS, TargetCC, TrueV, FalseV});
7194     }
7195 
7196     break;
7197   }
7198   case RISCVISD::BR_CC: {
7199     SDValue LHS = N->getOperand(1);
7200     SDValue RHS = N->getOperand(2);
7201     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7202     if (!ISD::isIntEqualitySetCC(CCVal))
7203       break;
7204 
7205     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7206     //      (br_cc X, Y, lt, dest)
7207     // Sometimes the setcc is introduced after br_cc has been formed.
7208     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7209         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7210       // If we're looking for eq 0 instead of ne 0, we need to invert the
7211       // condition.
7212       bool Invert = CCVal == ISD::SETEQ;
7213       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7214       if (Invert)
7215         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7216 
7217       SDLoc DL(N);
7218       RHS = LHS.getOperand(1);
7219       LHS = LHS.getOperand(0);
7220       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7221 
7222       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7223                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7224                          N->getOperand(4));
7225     }
7226 
7227     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7228     //      (br_cc X, Y, eq/ne, trueV, falseV)
7229     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7230       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7231                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7232                          N->getOperand(3), N->getOperand(4));
7233 
7234     // (br_cc X, 1, setne, br_cc) ->
7235     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7236     // This can occur when legalizing some floating point comparisons.
7237     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7238     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7239       SDLoc DL(N);
7240       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7241       SDValue TargetCC = DAG.getCondCode(CCVal);
7242       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7243       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7244                          N->getOperand(0), LHS, RHS, TargetCC,
7245                          N->getOperand(4));
7246     }
7247     break;
7248   }
7249   case ISD::FCOPYSIGN: {
7250     EVT VT = N->getValueType(0);
7251     if (!VT.isVector())
7252       break;
7253     // There is a form of VFSGNJ which injects the negated sign of its second
7254     // operand. Try and bubble any FNEG up after the extend/round to produce
7255     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7256     // TRUNC=1.
7257     SDValue In2 = N->getOperand(1);
7258     // Avoid cases where the extend/round has multiple uses, as duplicating
7259     // those is typically more expensive than removing a fneg.
7260     if (!In2.hasOneUse())
7261       break;
7262     if (In2.getOpcode() != ISD::FP_EXTEND &&
7263         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7264       break;
7265     In2 = In2.getOperand(0);
7266     if (In2.getOpcode() != ISD::FNEG)
7267       break;
7268     SDLoc DL(N);
7269     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7270     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7271                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7272   }
7273   case ISD::MGATHER:
7274   case ISD::MSCATTER:
7275   case ISD::VP_GATHER:
7276   case ISD::VP_SCATTER: {
7277     if (!DCI.isBeforeLegalize())
7278       break;
7279     SDValue Index, ScaleOp;
7280     bool IsIndexScaled = false;
7281     bool IsIndexSigned = false;
7282     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7283       Index = VPGSN->getIndex();
7284       ScaleOp = VPGSN->getScale();
7285       IsIndexScaled = VPGSN->isIndexScaled();
7286       IsIndexSigned = VPGSN->isIndexSigned();
7287     } else {
7288       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7289       Index = MGSN->getIndex();
7290       ScaleOp = MGSN->getScale();
7291       IsIndexScaled = MGSN->isIndexScaled();
7292       IsIndexSigned = MGSN->isIndexSigned();
7293     }
7294     EVT IndexVT = Index.getValueType();
7295     MVT XLenVT = Subtarget.getXLenVT();
7296     // RISCV indexed loads only support the "unsigned unscaled" addressing
7297     // mode, so anything else must be manually legalized.
7298     bool NeedsIdxLegalization =
7299         IsIndexScaled ||
7300         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7301     if (!NeedsIdxLegalization)
7302       break;
7303 
7304     SDLoc DL(N);
7305 
7306     // Any index legalization should first promote to XLenVT, so we don't lose
7307     // bits when scaling. This may create an illegal index type so we let
7308     // LLVM's legalization take care of the splitting.
7309     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7310     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7311       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7312       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7313                           DL, IndexVT, Index);
7314     }
7315 
7316     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7317     if (IsIndexScaled && Scale != 1) {
7318       // Manually scale the indices by the element size.
7319       // TODO: Sanitize the scale operand here?
7320       // TODO: For VP nodes, should we use VP_SHL here?
7321       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7322       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7323       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7324     }
7325 
7326     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7327     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7328       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7329                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7330                               VPGN->getScale(), VPGN->getMask(),
7331                               VPGN->getVectorLength()},
7332                              VPGN->getMemOperand(), NewIndexTy);
7333     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7334       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7335                               {VPSN->getChain(), VPSN->getValue(),
7336                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7337                                VPSN->getMask(), VPSN->getVectorLength()},
7338                               VPSN->getMemOperand(), NewIndexTy);
7339     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7340       return DAG.getMaskedGather(
7341           N->getVTList(), MGN->getMemoryVT(), DL,
7342           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7343            MGN->getBasePtr(), Index, MGN->getScale()},
7344           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7345     const auto *MSN = cast<MaskedScatterSDNode>(N);
7346     return DAG.getMaskedScatter(
7347         N->getVTList(), MSN->getMemoryVT(), DL,
7348         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7349          Index, MSN->getScale()},
7350         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7351   }
7352   case RISCVISD::SRA_VL:
7353   case RISCVISD::SRL_VL:
7354   case RISCVISD::SHL_VL: {
7355     SDValue ShAmt = N->getOperand(1);
7356     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7357       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7358       SDLoc DL(N);
7359       SDValue VL = N->getOperand(3);
7360       EVT VT = N->getValueType(0);
7361       ShAmt =
7362           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7363       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7364                          N->getOperand(2), N->getOperand(3));
7365     }
7366     break;
7367   }
7368   case ISD::SRA:
7369   case ISD::SRL:
7370   case ISD::SHL: {
7371     SDValue ShAmt = N->getOperand(1);
7372     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7373       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7374       SDLoc DL(N);
7375       EVT VT = N->getValueType(0);
7376       ShAmt =
7377           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7378       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7379     }
7380     break;
7381   }
7382   case RISCVISD::MUL_VL: {
7383     SDValue Op0 = N->getOperand(0);
7384     SDValue Op1 = N->getOperand(1);
7385     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7386       return V;
7387     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7388       return V;
7389     return SDValue();
7390   }
7391   case ISD::STORE: {
7392     auto *Store = cast<StoreSDNode>(N);
7393     SDValue Val = Store->getValue();
7394     // Combine store of vmv.x.s to vse with VL of 1.
7395     // FIXME: Support FP.
7396     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7397       SDValue Src = Val.getOperand(0);
7398       EVT VecVT = Src.getValueType();
7399       EVT MemVT = Store->getMemoryVT();
7400       // The memory VT and the element type must match.
7401       if (VecVT.getVectorElementType() == MemVT) {
7402         SDLoc DL(N);
7403         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7404         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7405                               DAG.getConstant(1, DL, MaskVT),
7406                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7407                               Store->getPointerInfo(),
7408                               Store->getOriginalAlign(),
7409                               Store->getMemOperand()->getFlags());
7410       }
7411     }
7412 
7413     break;
7414   }
7415   }
7416 
7417   return SDValue();
7418 }
7419 
7420 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7421     const SDNode *N, CombineLevel Level) const {
7422   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7423   // materialised in fewer instructions than `(OP _, c1)`:
7424   //
7425   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7426   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7427   SDValue N0 = N->getOperand(0);
7428   EVT Ty = N0.getValueType();
7429   if (Ty.isScalarInteger() &&
7430       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7431     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7432     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7433     if (C1 && C2) {
7434       const APInt &C1Int = C1->getAPIntValue();
7435       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7436 
7437       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7438       // and the combine should happen, to potentially allow further combines
7439       // later.
7440       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7441           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7442         return true;
7443 
7444       // We can materialise `c1` in an add immediate, so it's "free", and the
7445       // combine should be prevented.
7446       if (C1Int.getMinSignedBits() <= 64 &&
7447           isLegalAddImmediate(C1Int.getSExtValue()))
7448         return false;
7449 
7450       // Neither constant will fit into an immediate, so find materialisation
7451       // costs.
7452       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7453                                               Subtarget.getFeatureBits(),
7454                                               /*CompressionCost*/true);
7455       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7456           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7457           /*CompressionCost*/true);
7458 
7459       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7460       // combine should be prevented.
7461       if (C1Cost < ShiftedC1Cost)
7462         return false;
7463     }
7464   }
7465   return true;
7466 }
7467 
7468 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7469     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7470     TargetLoweringOpt &TLO) const {
7471   // Delay this optimization as late as possible.
7472   if (!TLO.LegalOps)
7473     return false;
7474 
7475   EVT VT = Op.getValueType();
7476   if (VT.isVector())
7477     return false;
7478 
7479   // Only handle AND for now.
7480   if (Op.getOpcode() != ISD::AND)
7481     return false;
7482 
7483   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7484   if (!C)
7485     return false;
7486 
7487   const APInt &Mask = C->getAPIntValue();
7488 
7489   // Clear all non-demanded bits initially.
7490   APInt ShrunkMask = Mask & DemandedBits;
7491 
7492   // Try to make a smaller immediate by setting undemanded bits.
7493 
7494   APInt ExpandedMask = Mask | ~DemandedBits;
7495 
7496   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7497     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7498   };
7499   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7500     if (NewMask == Mask)
7501       return true;
7502     SDLoc DL(Op);
7503     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7504     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7505     return TLO.CombineTo(Op, NewOp);
7506   };
7507 
7508   // If the shrunk mask fits in sign extended 12 bits, let the target
7509   // independent code apply it.
7510   if (ShrunkMask.isSignedIntN(12))
7511     return false;
7512 
7513   // Preserve (and X, 0xffff) when zext.h is supported.
7514   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7515     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7516     if (IsLegalMask(NewMask))
7517       return UseMask(NewMask);
7518   }
7519 
7520   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7521   if (VT == MVT::i64) {
7522     APInt NewMask = APInt(64, 0xffffffff);
7523     if (IsLegalMask(NewMask))
7524       return UseMask(NewMask);
7525   }
7526 
7527   // For the remaining optimizations, we need to be able to make a negative
7528   // number through a combination of mask and undemanded bits.
7529   if (!ExpandedMask.isNegative())
7530     return false;
7531 
7532   // What is the fewest number of bits we need to represent the negative number.
7533   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7534 
7535   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7536   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7537   APInt NewMask = ShrunkMask;
7538   if (MinSignedBits <= 12)
7539     NewMask.setBitsFrom(11);
7540   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7541     NewMask.setBitsFrom(31);
7542   else
7543     return false;
7544 
7545   // Check that our new mask is a subset of the demanded mask.
7546   assert(IsLegalMask(NewMask));
7547   return UseMask(NewMask);
7548 }
7549 
7550 static void computeGREV(APInt &Src, unsigned ShAmt) {
7551   ShAmt &= Src.getBitWidth() - 1;
7552   uint64_t x = Src.getZExtValue();
7553   if (ShAmt & 1)
7554     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7555   if (ShAmt & 2)
7556     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7557   if (ShAmt & 4)
7558     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7559   if (ShAmt & 8)
7560     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7561   if (ShAmt & 16)
7562     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7563   if (ShAmt & 32)
7564     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7565   Src = x;
7566 }
7567 
7568 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7569                                                         KnownBits &Known,
7570                                                         const APInt &DemandedElts,
7571                                                         const SelectionDAG &DAG,
7572                                                         unsigned Depth) const {
7573   unsigned BitWidth = Known.getBitWidth();
7574   unsigned Opc = Op.getOpcode();
7575   assert((Opc >= ISD::BUILTIN_OP_END ||
7576           Opc == ISD::INTRINSIC_WO_CHAIN ||
7577           Opc == ISD::INTRINSIC_W_CHAIN ||
7578           Opc == ISD::INTRINSIC_VOID) &&
7579          "Should use MaskedValueIsZero if you don't know whether Op"
7580          " is a target node!");
7581 
7582   Known.resetAll();
7583   switch (Opc) {
7584   default: break;
7585   case RISCVISD::SELECT_CC: {
7586     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7587     // If we don't know any bits, early out.
7588     if (Known.isUnknown())
7589       break;
7590     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7591 
7592     // Only known if known in both the LHS and RHS.
7593     Known = KnownBits::commonBits(Known, Known2);
7594     break;
7595   }
7596   case RISCVISD::REMUW: {
7597     KnownBits Known2;
7598     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7599     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7600     // We only care about the lower 32 bits.
7601     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7602     // Restore the original width by sign extending.
7603     Known = Known.sext(BitWidth);
7604     break;
7605   }
7606   case RISCVISD::DIVUW: {
7607     KnownBits Known2;
7608     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7609     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7610     // We only care about the lower 32 bits.
7611     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7612     // Restore the original width by sign extending.
7613     Known = Known.sext(BitWidth);
7614     break;
7615   }
7616   case RISCVISD::CTZW: {
7617     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7618     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7619     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7620     Known.Zero.setBitsFrom(LowBits);
7621     break;
7622   }
7623   case RISCVISD::CLZW: {
7624     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7625     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7626     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7627     Known.Zero.setBitsFrom(LowBits);
7628     break;
7629   }
7630   case RISCVISD::GREV:
7631   case RISCVISD::GREVW: {
7632     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7633       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7634       if (Opc == RISCVISD::GREVW)
7635         Known = Known.trunc(32);
7636       unsigned ShAmt = C->getZExtValue();
7637       computeGREV(Known.Zero, ShAmt);
7638       computeGREV(Known.One, ShAmt);
7639       if (Opc == RISCVISD::GREVW)
7640         Known = Known.sext(BitWidth);
7641     }
7642     break;
7643   }
7644   case RISCVISD::READ_VLENB:
7645     // We assume VLENB is at least 16 bytes.
7646     Known.Zero.setLowBits(4);
7647     // We assume VLENB is no more than 65536 / 8 bytes.
7648     Known.Zero.setBitsFrom(14);
7649     break;
7650   case ISD::INTRINSIC_W_CHAIN: {
7651     unsigned IntNo = Op.getConstantOperandVal(1);
7652     switch (IntNo) {
7653     default:
7654       // We can't do anything for most intrinsics.
7655       break;
7656     case Intrinsic::riscv_vsetvli:
7657     case Intrinsic::riscv_vsetvlimax:
7658       // Assume that VL output is positive and would fit in an int32_t.
7659       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7660       if (BitWidth >= 32)
7661         Known.Zero.setBitsFrom(31);
7662       break;
7663     }
7664     break;
7665   }
7666   }
7667 }
7668 
7669 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7670     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7671     unsigned Depth) const {
7672   switch (Op.getOpcode()) {
7673   default:
7674     break;
7675   case RISCVISD::SELECT_CC: {
7676     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7677     if (Tmp == 1) return 1;  // Early out.
7678     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7679     return std::min(Tmp, Tmp2);
7680   }
7681   case RISCVISD::SLLW:
7682   case RISCVISD::SRAW:
7683   case RISCVISD::SRLW:
7684   case RISCVISD::DIVW:
7685   case RISCVISD::DIVUW:
7686   case RISCVISD::REMUW:
7687   case RISCVISD::ROLW:
7688   case RISCVISD::RORW:
7689   case RISCVISD::GREVW:
7690   case RISCVISD::GORCW:
7691   case RISCVISD::FSLW:
7692   case RISCVISD::FSRW:
7693   case RISCVISD::SHFLW:
7694   case RISCVISD::UNSHFLW:
7695   case RISCVISD::BCOMPRESSW:
7696   case RISCVISD::BDECOMPRESSW:
7697   case RISCVISD::FCVT_W_RTZ_RV64:
7698   case RISCVISD::FCVT_WU_RTZ_RV64:
7699     // TODO: As the result is sign-extended, this is conservatively correct. A
7700     // more precise answer could be calculated for SRAW depending on known
7701     // bits in the shift amount.
7702     return 33;
7703   case RISCVISD::SHFL:
7704   case RISCVISD::UNSHFL: {
7705     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7706     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7707     // will stay within the upper 32 bits. If there were more than 32 sign bits
7708     // before there will be at least 33 sign bits after.
7709     if (Op.getValueType() == MVT::i64 &&
7710         isa<ConstantSDNode>(Op.getOperand(1)) &&
7711         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7712       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7713       if (Tmp > 32)
7714         return 33;
7715     }
7716     break;
7717   }
7718   case RISCVISD::VMV_X_S:
7719     // The number of sign bits of the scalar result is computed by obtaining the
7720     // element type of the input vector operand, subtracting its width from the
7721     // XLEN, and then adding one (sign bit within the element type). If the
7722     // element type is wider than XLen, the least-significant XLEN bits are
7723     // taken.
7724     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7725       return 1;
7726     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7727   }
7728 
7729   return 1;
7730 }
7731 
7732 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7733                                                   MachineBasicBlock *BB) {
7734   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7735 
7736   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7737   // Should the count have wrapped while it was being read, we need to try
7738   // again.
7739   // ...
7740   // read:
7741   // rdcycleh x3 # load high word of cycle
7742   // rdcycle  x2 # load low word of cycle
7743   // rdcycleh x4 # load high word of cycle
7744   // bne x3, x4, read # check if high word reads match, otherwise try again
7745   // ...
7746 
7747   MachineFunction &MF = *BB->getParent();
7748   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7749   MachineFunction::iterator It = ++BB->getIterator();
7750 
7751   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7752   MF.insert(It, LoopMBB);
7753 
7754   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7755   MF.insert(It, DoneMBB);
7756 
7757   // Transfer the remainder of BB and its successor edges to DoneMBB.
7758   DoneMBB->splice(DoneMBB->begin(), BB,
7759                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7760   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7761 
7762   BB->addSuccessor(LoopMBB);
7763 
7764   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7765   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7766   Register LoReg = MI.getOperand(0).getReg();
7767   Register HiReg = MI.getOperand(1).getReg();
7768   DebugLoc DL = MI.getDebugLoc();
7769 
7770   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7771   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7772       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7773       .addReg(RISCV::X0);
7774   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7775       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7776       .addReg(RISCV::X0);
7777   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7778       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7779       .addReg(RISCV::X0);
7780 
7781   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7782       .addReg(HiReg)
7783       .addReg(ReadAgainReg)
7784       .addMBB(LoopMBB);
7785 
7786   LoopMBB->addSuccessor(LoopMBB);
7787   LoopMBB->addSuccessor(DoneMBB);
7788 
7789   MI.eraseFromParent();
7790 
7791   return DoneMBB;
7792 }
7793 
7794 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7795                                              MachineBasicBlock *BB) {
7796   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7797 
7798   MachineFunction &MF = *BB->getParent();
7799   DebugLoc DL = MI.getDebugLoc();
7800   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7801   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7802   Register LoReg = MI.getOperand(0).getReg();
7803   Register HiReg = MI.getOperand(1).getReg();
7804   Register SrcReg = MI.getOperand(2).getReg();
7805   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7806   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7807 
7808   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7809                           RI);
7810   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7811   MachineMemOperand *MMOLo =
7812       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7813   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7814       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7815   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7816       .addFrameIndex(FI)
7817       .addImm(0)
7818       .addMemOperand(MMOLo);
7819   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7820       .addFrameIndex(FI)
7821       .addImm(4)
7822       .addMemOperand(MMOHi);
7823   MI.eraseFromParent(); // The pseudo instruction is gone now.
7824   return BB;
7825 }
7826 
7827 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7828                                                  MachineBasicBlock *BB) {
7829   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7830          "Unexpected instruction");
7831 
7832   MachineFunction &MF = *BB->getParent();
7833   DebugLoc DL = MI.getDebugLoc();
7834   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7835   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7836   Register DstReg = MI.getOperand(0).getReg();
7837   Register LoReg = MI.getOperand(1).getReg();
7838   Register HiReg = MI.getOperand(2).getReg();
7839   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7840   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7841 
7842   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7843   MachineMemOperand *MMOLo =
7844       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7845   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7846       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7847   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7848       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7849       .addFrameIndex(FI)
7850       .addImm(0)
7851       .addMemOperand(MMOLo);
7852   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7853       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7854       .addFrameIndex(FI)
7855       .addImm(4)
7856       .addMemOperand(MMOHi);
7857   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7858   MI.eraseFromParent(); // The pseudo instruction is gone now.
7859   return BB;
7860 }
7861 
7862 static bool isSelectPseudo(MachineInstr &MI) {
7863   switch (MI.getOpcode()) {
7864   default:
7865     return false;
7866   case RISCV::Select_GPR_Using_CC_GPR:
7867   case RISCV::Select_FPR16_Using_CC_GPR:
7868   case RISCV::Select_FPR32_Using_CC_GPR:
7869   case RISCV::Select_FPR64_Using_CC_GPR:
7870     return true;
7871   }
7872 }
7873 
7874 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7875                                            MachineBasicBlock *BB,
7876                                            const RISCVSubtarget &Subtarget) {
7877   // To "insert" Select_* instructions, we actually have to insert the triangle
7878   // control-flow pattern.  The incoming instructions know the destination vreg
7879   // to set, the condition code register to branch on, the true/false values to
7880   // select between, and the condcode to use to select the appropriate branch.
7881   //
7882   // We produce the following control flow:
7883   //     HeadMBB
7884   //     |  \
7885   //     |  IfFalseMBB
7886   //     | /
7887   //    TailMBB
7888   //
7889   // When we find a sequence of selects we attempt to optimize their emission
7890   // by sharing the control flow. Currently we only handle cases where we have
7891   // multiple selects with the exact same condition (same LHS, RHS and CC).
7892   // The selects may be interleaved with other instructions if the other
7893   // instructions meet some requirements we deem safe:
7894   // - They are debug instructions. Otherwise,
7895   // - They do not have side-effects, do not access memory and their inputs do
7896   //   not depend on the results of the select pseudo-instructions.
7897   // The TrueV/FalseV operands of the selects cannot depend on the result of
7898   // previous selects in the sequence.
7899   // These conditions could be further relaxed. See the X86 target for a
7900   // related approach and more information.
7901   Register LHS = MI.getOperand(1).getReg();
7902   Register RHS = MI.getOperand(2).getReg();
7903   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7904 
7905   SmallVector<MachineInstr *, 4> SelectDebugValues;
7906   SmallSet<Register, 4> SelectDests;
7907   SelectDests.insert(MI.getOperand(0).getReg());
7908 
7909   MachineInstr *LastSelectPseudo = &MI;
7910 
7911   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7912        SequenceMBBI != E; ++SequenceMBBI) {
7913     if (SequenceMBBI->isDebugInstr())
7914       continue;
7915     else if (isSelectPseudo(*SequenceMBBI)) {
7916       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7917           SequenceMBBI->getOperand(2).getReg() != RHS ||
7918           SequenceMBBI->getOperand(3).getImm() != CC ||
7919           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7920           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7921         break;
7922       LastSelectPseudo = &*SequenceMBBI;
7923       SequenceMBBI->collectDebugValues(SelectDebugValues);
7924       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7925     } else {
7926       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7927           SequenceMBBI->mayLoadOrStore())
7928         break;
7929       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7930             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7931           }))
7932         break;
7933     }
7934   }
7935 
7936   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7937   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7938   DebugLoc DL = MI.getDebugLoc();
7939   MachineFunction::iterator I = ++BB->getIterator();
7940 
7941   MachineBasicBlock *HeadMBB = BB;
7942   MachineFunction *F = BB->getParent();
7943   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7944   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7945 
7946   F->insert(I, IfFalseMBB);
7947   F->insert(I, TailMBB);
7948 
7949   // Transfer debug instructions associated with the selects to TailMBB.
7950   for (MachineInstr *DebugInstr : SelectDebugValues) {
7951     TailMBB->push_back(DebugInstr->removeFromParent());
7952   }
7953 
7954   // Move all instructions after the sequence to TailMBB.
7955   TailMBB->splice(TailMBB->end(), HeadMBB,
7956                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7957   // Update machine-CFG edges by transferring all successors of the current
7958   // block to the new block which will contain the Phi nodes for the selects.
7959   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7960   // Set the successors for HeadMBB.
7961   HeadMBB->addSuccessor(IfFalseMBB);
7962   HeadMBB->addSuccessor(TailMBB);
7963 
7964   // Insert appropriate branch.
7965   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7966     .addReg(LHS)
7967     .addReg(RHS)
7968     .addMBB(TailMBB);
7969 
7970   // IfFalseMBB just falls through to TailMBB.
7971   IfFalseMBB->addSuccessor(TailMBB);
7972 
7973   // Create PHIs for all of the select pseudo-instructions.
7974   auto SelectMBBI = MI.getIterator();
7975   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7976   auto InsertionPoint = TailMBB->begin();
7977   while (SelectMBBI != SelectEnd) {
7978     auto Next = std::next(SelectMBBI);
7979     if (isSelectPseudo(*SelectMBBI)) {
7980       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7981       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7982               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7983           .addReg(SelectMBBI->getOperand(4).getReg())
7984           .addMBB(HeadMBB)
7985           .addReg(SelectMBBI->getOperand(5).getReg())
7986           .addMBB(IfFalseMBB);
7987       SelectMBBI->eraseFromParent();
7988     }
7989     SelectMBBI = Next;
7990   }
7991 
7992   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7993   return TailMBB;
7994 }
7995 
7996 MachineBasicBlock *
7997 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7998                                                  MachineBasicBlock *BB) const {
7999   switch (MI.getOpcode()) {
8000   default:
8001     llvm_unreachable("Unexpected instr type to insert");
8002   case RISCV::ReadCycleWide:
8003     assert(!Subtarget.is64Bit() &&
8004            "ReadCycleWrite is only to be used on riscv32");
8005     return emitReadCycleWidePseudo(MI, BB);
8006   case RISCV::Select_GPR_Using_CC_GPR:
8007   case RISCV::Select_FPR16_Using_CC_GPR:
8008   case RISCV::Select_FPR32_Using_CC_GPR:
8009   case RISCV::Select_FPR64_Using_CC_GPR:
8010     return emitSelectPseudo(MI, BB, Subtarget);
8011   case RISCV::BuildPairF64Pseudo:
8012     return emitBuildPairF64Pseudo(MI, BB);
8013   case RISCV::SplitF64Pseudo:
8014     return emitSplitF64Pseudo(MI, BB);
8015   }
8016 }
8017 
8018 // Calling Convention Implementation.
8019 // The expectations for frontend ABI lowering vary from target to target.
8020 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8021 // details, but this is a longer term goal. For now, we simply try to keep the
8022 // role of the frontend as simple and well-defined as possible. The rules can
8023 // be summarised as:
8024 // * Never split up large scalar arguments. We handle them here.
8025 // * If a hardfloat calling convention is being used, and the struct may be
8026 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8027 // available, then pass as two separate arguments. If either the GPRs or FPRs
8028 // are exhausted, then pass according to the rule below.
8029 // * If a struct could never be passed in registers or directly in a stack
8030 // slot (as it is larger than 2*XLEN and the floating point rules don't
8031 // apply), then pass it using a pointer with the byval attribute.
8032 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8033 // word-sized array or a 2*XLEN scalar (depending on alignment).
8034 // * The frontend can determine whether a struct is returned by reference or
8035 // not based on its size and fields. If it will be returned by reference, the
8036 // frontend must modify the prototype so a pointer with the sret annotation is
8037 // passed as the first argument. This is not necessary for large scalar
8038 // returns.
8039 // * Struct return values and varargs should be coerced to structs containing
8040 // register-size fields in the same situations they would be for fixed
8041 // arguments.
8042 
8043 static const MCPhysReg ArgGPRs[] = {
8044   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8045   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8046 };
8047 static const MCPhysReg ArgFPR16s[] = {
8048   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8049   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8050 };
8051 static const MCPhysReg ArgFPR32s[] = {
8052   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8053   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8054 };
8055 static const MCPhysReg ArgFPR64s[] = {
8056   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8057   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8058 };
8059 // This is an interim calling convention and it may be changed in the future.
8060 static const MCPhysReg ArgVRs[] = {
8061     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8062     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8063     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8064 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8065                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8066                                      RISCV::V20M2, RISCV::V22M2};
8067 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8068                                      RISCV::V20M4};
8069 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8070 
8071 // Pass a 2*XLEN argument that has been split into two XLEN values through
8072 // registers or the stack as necessary.
8073 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8074                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8075                                 MVT ValVT2, MVT LocVT2,
8076                                 ISD::ArgFlagsTy ArgFlags2) {
8077   unsigned XLenInBytes = XLen / 8;
8078   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8079     // At least one half can be passed via register.
8080     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8081                                      VA1.getLocVT(), CCValAssign::Full));
8082   } else {
8083     // Both halves must be passed on the stack, with proper alignment.
8084     Align StackAlign =
8085         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8086     State.addLoc(
8087         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8088                             State.AllocateStack(XLenInBytes, StackAlign),
8089                             VA1.getLocVT(), CCValAssign::Full));
8090     State.addLoc(CCValAssign::getMem(
8091         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8092         LocVT2, CCValAssign::Full));
8093     return false;
8094   }
8095 
8096   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8097     // The second half can also be passed via register.
8098     State.addLoc(
8099         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8100   } else {
8101     // The second half is passed via the stack, without additional alignment.
8102     State.addLoc(CCValAssign::getMem(
8103         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8104         LocVT2, CCValAssign::Full));
8105   }
8106 
8107   return false;
8108 }
8109 
8110 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8111                                Optional<unsigned> FirstMaskArgument,
8112                                CCState &State, const RISCVTargetLowering &TLI) {
8113   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8114   if (RC == &RISCV::VRRegClass) {
8115     // Assign the first mask argument to V0.
8116     // This is an interim calling convention and it may be changed in the
8117     // future.
8118     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8119       return State.AllocateReg(RISCV::V0);
8120     return State.AllocateReg(ArgVRs);
8121   }
8122   if (RC == &RISCV::VRM2RegClass)
8123     return State.AllocateReg(ArgVRM2s);
8124   if (RC == &RISCV::VRM4RegClass)
8125     return State.AllocateReg(ArgVRM4s);
8126   if (RC == &RISCV::VRM8RegClass)
8127     return State.AllocateReg(ArgVRM8s);
8128   llvm_unreachable("Unhandled register class for ValueType");
8129 }
8130 
8131 // Implements the RISC-V calling convention. Returns true upon failure.
8132 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8133                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8134                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8135                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8136                      Optional<unsigned> FirstMaskArgument) {
8137   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8138   assert(XLen == 32 || XLen == 64);
8139   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8140 
8141   // Any return value split in to more than two values can't be returned
8142   // directly. Vectors are returned via the available vector registers.
8143   if (!LocVT.isVector() && IsRet && ValNo > 1)
8144     return true;
8145 
8146   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8147   // variadic argument, or if no F16/F32 argument registers are available.
8148   bool UseGPRForF16_F32 = true;
8149   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8150   // variadic argument, or if no F64 argument registers are available.
8151   bool UseGPRForF64 = true;
8152 
8153   switch (ABI) {
8154   default:
8155     llvm_unreachable("Unexpected ABI");
8156   case RISCVABI::ABI_ILP32:
8157   case RISCVABI::ABI_LP64:
8158     break;
8159   case RISCVABI::ABI_ILP32F:
8160   case RISCVABI::ABI_LP64F:
8161     UseGPRForF16_F32 = !IsFixed;
8162     break;
8163   case RISCVABI::ABI_ILP32D:
8164   case RISCVABI::ABI_LP64D:
8165     UseGPRForF16_F32 = !IsFixed;
8166     UseGPRForF64 = !IsFixed;
8167     break;
8168   }
8169 
8170   // FPR16, FPR32, and FPR64 alias each other.
8171   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8172     UseGPRForF16_F32 = true;
8173     UseGPRForF64 = true;
8174   }
8175 
8176   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8177   // similar local variables rather than directly checking against the target
8178   // ABI.
8179 
8180   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8181     LocVT = XLenVT;
8182     LocInfo = CCValAssign::BCvt;
8183   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8184     LocVT = MVT::i64;
8185     LocInfo = CCValAssign::BCvt;
8186   }
8187 
8188   // If this is a variadic argument, the RISC-V calling convention requires
8189   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8190   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8191   // be used regardless of whether the original argument was split during
8192   // legalisation or not. The argument will not be passed by registers if the
8193   // original type is larger than 2*XLEN, so the register alignment rule does
8194   // not apply.
8195   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8196   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8197       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8198     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8199     // Skip 'odd' register if necessary.
8200     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8201       State.AllocateReg(ArgGPRs);
8202   }
8203 
8204   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8205   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8206       State.getPendingArgFlags();
8207 
8208   assert(PendingLocs.size() == PendingArgFlags.size() &&
8209          "PendingLocs and PendingArgFlags out of sync");
8210 
8211   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8212   // registers are exhausted.
8213   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8214     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8215            "Can't lower f64 if it is split");
8216     // Depending on available argument GPRS, f64 may be passed in a pair of
8217     // GPRs, split between a GPR and the stack, or passed completely on the
8218     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8219     // cases.
8220     Register Reg = State.AllocateReg(ArgGPRs);
8221     LocVT = MVT::i32;
8222     if (!Reg) {
8223       unsigned StackOffset = State.AllocateStack(8, Align(8));
8224       State.addLoc(
8225           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8226       return false;
8227     }
8228     if (!State.AllocateReg(ArgGPRs))
8229       State.AllocateStack(4, Align(4));
8230     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8231     return false;
8232   }
8233 
8234   // Fixed-length vectors are located in the corresponding scalable-vector
8235   // container types.
8236   if (ValVT.isFixedLengthVector())
8237     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8238 
8239   // Split arguments might be passed indirectly, so keep track of the pending
8240   // values. Split vectors are passed via a mix of registers and indirectly, so
8241   // treat them as we would any other argument.
8242   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8243     LocVT = XLenVT;
8244     LocInfo = CCValAssign::Indirect;
8245     PendingLocs.push_back(
8246         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8247     PendingArgFlags.push_back(ArgFlags);
8248     if (!ArgFlags.isSplitEnd()) {
8249       return false;
8250     }
8251   }
8252 
8253   // If the split argument only had two elements, it should be passed directly
8254   // in registers or on the stack.
8255   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8256       PendingLocs.size() <= 2) {
8257     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8258     // Apply the normal calling convention rules to the first half of the
8259     // split argument.
8260     CCValAssign VA = PendingLocs[0];
8261     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8262     PendingLocs.clear();
8263     PendingArgFlags.clear();
8264     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8265                                ArgFlags);
8266   }
8267 
8268   // Allocate to a register if possible, or else a stack slot.
8269   Register Reg;
8270   unsigned StoreSizeBytes = XLen / 8;
8271   Align StackAlign = Align(XLen / 8);
8272 
8273   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8274     Reg = State.AllocateReg(ArgFPR16s);
8275   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8276     Reg = State.AllocateReg(ArgFPR32s);
8277   else if (ValVT == MVT::f64 && !UseGPRForF64)
8278     Reg = State.AllocateReg(ArgFPR64s);
8279   else if (ValVT.isVector()) {
8280     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8281     if (!Reg) {
8282       // For return values, the vector must be passed fully via registers or
8283       // via the stack.
8284       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8285       // but we're using all of them.
8286       if (IsRet)
8287         return true;
8288       // Try using a GPR to pass the address
8289       if ((Reg = State.AllocateReg(ArgGPRs))) {
8290         LocVT = XLenVT;
8291         LocInfo = CCValAssign::Indirect;
8292       } else if (ValVT.isScalableVector()) {
8293         report_fatal_error("Unable to pass scalable vector types on the stack");
8294       } else {
8295         // Pass fixed-length vectors on the stack.
8296         LocVT = ValVT;
8297         StoreSizeBytes = ValVT.getStoreSize();
8298         // Align vectors to their element sizes, being careful for vXi1
8299         // vectors.
8300         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8301       }
8302     }
8303   } else {
8304     Reg = State.AllocateReg(ArgGPRs);
8305   }
8306 
8307   unsigned StackOffset =
8308       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8309 
8310   // If we reach this point and PendingLocs is non-empty, we must be at the
8311   // end of a split argument that must be passed indirectly.
8312   if (!PendingLocs.empty()) {
8313     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8314     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8315 
8316     for (auto &It : PendingLocs) {
8317       if (Reg)
8318         It.convertToReg(Reg);
8319       else
8320         It.convertToMem(StackOffset);
8321       State.addLoc(It);
8322     }
8323     PendingLocs.clear();
8324     PendingArgFlags.clear();
8325     return false;
8326   }
8327 
8328   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8329           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8330          "Expected an XLenVT or vector types at this stage");
8331 
8332   if (Reg) {
8333     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8334     return false;
8335   }
8336 
8337   // When a floating-point value is passed on the stack, no bit-conversion is
8338   // needed.
8339   if (ValVT.isFloatingPoint()) {
8340     LocVT = ValVT;
8341     LocInfo = CCValAssign::Full;
8342   }
8343   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8344   return false;
8345 }
8346 
8347 template <typename ArgTy>
8348 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8349   for (const auto &ArgIdx : enumerate(Args)) {
8350     MVT ArgVT = ArgIdx.value().VT;
8351     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8352       return ArgIdx.index();
8353   }
8354   return None;
8355 }
8356 
8357 void RISCVTargetLowering::analyzeInputArgs(
8358     MachineFunction &MF, CCState &CCInfo,
8359     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8360     RISCVCCAssignFn Fn) const {
8361   unsigned NumArgs = Ins.size();
8362   FunctionType *FType = MF.getFunction().getFunctionType();
8363 
8364   Optional<unsigned> FirstMaskArgument;
8365   if (Subtarget.hasVInstructions())
8366     FirstMaskArgument = preAssignMask(Ins);
8367 
8368   for (unsigned i = 0; i != NumArgs; ++i) {
8369     MVT ArgVT = Ins[i].VT;
8370     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8371 
8372     Type *ArgTy = nullptr;
8373     if (IsRet)
8374       ArgTy = FType->getReturnType();
8375     else if (Ins[i].isOrigArg())
8376       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8377 
8378     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8379     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8380            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8381            FirstMaskArgument)) {
8382       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8383                         << EVT(ArgVT).getEVTString() << '\n');
8384       llvm_unreachable(nullptr);
8385     }
8386   }
8387 }
8388 
8389 void RISCVTargetLowering::analyzeOutputArgs(
8390     MachineFunction &MF, CCState &CCInfo,
8391     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8392     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8393   unsigned NumArgs = Outs.size();
8394 
8395   Optional<unsigned> FirstMaskArgument;
8396   if (Subtarget.hasVInstructions())
8397     FirstMaskArgument = preAssignMask(Outs);
8398 
8399   for (unsigned i = 0; i != NumArgs; i++) {
8400     MVT ArgVT = Outs[i].VT;
8401     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8402     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8403 
8404     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8405     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8406            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8407            FirstMaskArgument)) {
8408       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8409                         << EVT(ArgVT).getEVTString() << "\n");
8410       llvm_unreachable(nullptr);
8411     }
8412   }
8413 }
8414 
8415 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8416 // values.
8417 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8418                                    const CCValAssign &VA, const SDLoc &DL,
8419                                    const RISCVSubtarget &Subtarget) {
8420   switch (VA.getLocInfo()) {
8421   default:
8422     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8423   case CCValAssign::Full:
8424     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8425       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8426     break;
8427   case CCValAssign::BCvt:
8428     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8429       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8430     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8431       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8432     else
8433       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8434     break;
8435   }
8436   return Val;
8437 }
8438 
8439 // The caller is responsible for loading the full value if the argument is
8440 // passed with CCValAssign::Indirect.
8441 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8442                                 const CCValAssign &VA, const SDLoc &DL,
8443                                 const RISCVTargetLowering &TLI) {
8444   MachineFunction &MF = DAG.getMachineFunction();
8445   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8446   EVT LocVT = VA.getLocVT();
8447   SDValue Val;
8448   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8449   Register VReg = RegInfo.createVirtualRegister(RC);
8450   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8451   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8452 
8453   if (VA.getLocInfo() == CCValAssign::Indirect)
8454     return Val;
8455 
8456   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8457 }
8458 
8459 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8460                                    const CCValAssign &VA, const SDLoc &DL,
8461                                    const RISCVSubtarget &Subtarget) {
8462   EVT LocVT = VA.getLocVT();
8463 
8464   switch (VA.getLocInfo()) {
8465   default:
8466     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8467   case CCValAssign::Full:
8468     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8469       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8470     break;
8471   case CCValAssign::BCvt:
8472     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8473       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8474     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8475       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8476     else
8477       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8478     break;
8479   }
8480   return Val;
8481 }
8482 
8483 // The caller is responsible for loading the full value if the argument is
8484 // passed with CCValAssign::Indirect.
8485 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8486                                 const CCValAssign &VA, const SDLoc &DL) {
8487   MachineFunction &MF = DAG.getMachineFunction();
8488   MachineFrameInfo &MFI = MF.getFrameInfo();
8489   EVT LocVT = VA.getLocVT();
8490   EVT ValVT = VA.getValVT();
8491   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8492   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8493                                  /*Immutable=*/true);
8494   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8495   SDValue Val;
8496 
8497   ISD::LoadExtType ExtType;
8498   switch (VA.getLocInfo()) {
8499   default:
8500     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8501   case CCValAssign::Full:
8502   case CCValAssign::Indirect:
8503   case CCValAssign::BCvt:
8504     ExtType = ISD::NON_EXTLOAD;
8505     break;
8506   }
8507   Val = DAG.getExtLoad(
8508       ExtType, DL, LocVT, Chain, FIN,
8509       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8510   return Val;
8511 }
8512 
8513 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8514                                        const CCValAssign &VA, const SDLoc &DL) {
8515   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8516          "Unexpected VA");
8517   MachineFunction &MF = DAG.getMachineFunction();
8518   MachineFrameInfo &MFI = MF.getFrameInfo();
8519   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8520 
8521   if (VA.isMemLoc()) {
8522     // f64 is passed on the stack.
8523     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8524     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8525     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8526                        MachinePointerInfo::getFixedStack(MF, FI));
8527   }
8528 
8529   assert(VA.isRegLoc() && "Expected register VA assignment");
8530 
8531   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8532   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8533   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8534   SDValue Hi;
8535   if (VA.getLocReg() == RISCV::X17) {
8536     // Second half of f64 is passed on the stack.
8537     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8538     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8539     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8540                      MachinePointerInfo::getFixedStack(MF, FI));
8541   } else {
8542     // Second half of f64 is passed in another GPR.
8543     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8544     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8545     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8546   }
8547   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8548 }
8549 
8550 // FastCC has less than 1% performance improvement for some particular
8551 // benchmark. But theoretically, it may has benenfit for some cases.
8552 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8553                             unsigned ValNo, MVT ValVT, MVT LocVT,
8554                             CCValAssign::LocInfo LocInfo,
8555                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8556                             bool IsFixed, bool IsRet, Type *OrigTy,
8557                             const RISCVTargetLowering &TLI,
8558                             Optional<unsigned> FirstMaskArgument) {
8559 
8560   // X5 and X6 might be used for save-restore libcall.
8561   static const MCPhysReg GPRList[] = {
8562       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8563       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8564       RISCV::X29, RISCV::X30, RISCV::X31};
8565 
8566   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8567     if (unsigned Reg = State.AllocateReg(GPRList)) {
8568       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8569       return false;
8570     }
8571   }
8572 
8573   if (LocVT == MVT::f16) {
8574     static const MCPhysReg FPR16List[] = {
8575         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8576         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8577         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8578         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8579     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8580       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8581       return false;
8582     }
8583   }
8584 
8585   if (LocVT == MVT::f32) {
8586     static const MCPhysReg FPR32List[] = {
8587         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8588         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8589         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8590         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8591     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8592       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8593       return false;
8594     }
8595   }
8596 
8597   if (LocVT == MVT::f64) {
8598     static const MCPhysReg FPR64List[] = {
8599         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8600         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8601         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8602         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8603     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8604       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8605       return false;
8606     }
8607   }
8608 
8609   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8610     unsigned Offset4 = State.AllocateStack(4, Align(4));
8611     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8612     return false;
8613   }
8614 
8615   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8616     unsigned Offset5 = State.AllocateStack(8, Align(8));
8617     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8618     return false;
8619   }
8620 
8621   if (LocVT.isVector()) {
8622     if (unsigned Reg =
8623             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8624       // Fixed-length vectors are located in the corresponding scalable-vector
8625       // container types.
8626       if (ValVT.isFixedLengthVector())
8627         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8628       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8629     } else {
8630       // Try and pass the address via a "fast" GPR.
8631       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8632         LocInfo = CCValAssign::Indirect;
8633         LocVT = TLI.getSubtarget().getXLenVT();
8634         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8635       } else if (ValVT.isFixedLengthVector()) {
8636         auto StackAlign =
8637             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8638         unsigned StackOffset =
8639             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8640         State.addLoc(
8641             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8642       } else {
8643         // Can't pass scalable vectors on the stack.
8644         return true;
8645       }
8646     }
8647 
8648     return false;
8649   }
8650 
8651   return true; // CC didn't match.
8652 }
8653 
8654 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8655                          CCValAssign::LocInfo LocInfo,
8656                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8657 
8658   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8659     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8660     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8661     static const MCPhysReg GPRList[] = {
8662         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8663         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8664     if (unsigned Reg = State.AllocateReg(GPRList)) {
8665       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8666       return false;
8667     }
8668   }
8669 
8670   if (LocVT == MVT::f32) {
8671     // Pass in STG registers: F1, ..., F6
8672     //                        fs0 ... fs5
8673     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8674                                           RISCV::F18_F, RISCV::F19_F,
8675                                           RISCV::F20_F, RISCV::F21_F};
8676     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8677       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8678       return false;
8679     }
8680   }
8681 
8682   if (LocVT == MVT::f64) {
8683     // Pass in STG registers: D1, ..., D6
8684     //                        fs6 ... fs11
8685     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8686                                           RISCV::F24_D, RISCV::F25_D,
8687                                           RISCV::F26_D, RISCV::F27_D};
8688     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8689       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8690       return false;
8691     }
8692   }
8693 
8694   report_fatal_error("No registers left in GHC calling convention");
8695   return true;
8696 }
8697 
8698 // Transform physical registers into virtual registers.
8699 SDValue RISCVTargetLowering::LowerFormalArguments(
8700     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8701     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8702     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8703 
8704   MachineFunction &MF = DAG.getMachineFunction();
8705 
8706   switch (CallConv) {
8707   default:
8708     report_fatal_error("Unsupported calling convention");
8709   case CallingConv::C:
8710   case CallingConv::Fast:
8711     break;
8712   case CallingConv::GHC:
8713     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8714         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8715       report_fatal_error(
8716         "GHC calling convention requires the F and D instruction set extensions");
8717   }
8718 
8719   const Function &Func = MF.getFunction();
8720   if (Func.hasFnAttribute("interrupt")) {
8721     if (!Func.arg_empty())
8722       report_fatal_error(
8723         "Functions with the interrupt attribute cannot have arguments!");
8724 
8725     StringRef Kind =
8726       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8727 
8728     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8729       report_fatal_error(
8730         "Function interrupt attribute argument not supported!");
8731   }
8732 
8733   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8734   MVT XLenVT = Subtarget.getXLenVT();
8735   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8736   // Used with vargs to acumulate store chains.
8737   std::vector<SDValue> OutChains;
8738 
8739   // Assign locations to all of the incoming arguments.
8740   SmallVector<CCValAssign, 16> ArgLocs;
8741   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8742 
8743   if (CallConv == CallingConv::GHC)
8744     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8745   else
8746     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8747                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8748                                                    : CC_RISCV);
8749 
8750   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8751     CCValAssign &VA = ArgLocs[i];
8752     SDValue ArgValue;
8753     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8754     // case.
8755     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8756       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8757     else if (VA.isRegLoc())
8758       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8759     else
8760       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8761 
8762     if (VA.getLocInfo() == CCValAssign::Indirect) {
8763       // If the original argument was split and passed by reference (e.g. i128
8764       // on RV32), we need to load all parts of it here (using the same
8765       // address). Vectors may be partly split to registers and partly to the
8766       // stack, in which case the base address is partly offset and subsequent
8767       // stores are relative to that.
8768       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8769                                    MachinePointerInfo()));
8770       unsigned ArgIndex = Ins[i].OrigArgIndex;
8771       unsigned ArgPartOffset = Ins[i].PartOffset;
8772       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8773       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8774         CCValAssign &PartVA = ArgLocs[i + 1];
8775         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8776         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8777         if (PartVA.getValVT().isScalableVector())
8778           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8779         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8780         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8781                                      MachinePointerInfo()));
8782         ++i;
8783       }
8784       continue;
8785     }
8786     InVals.push_back(ArgValue);
8787   }
8788 
8789   if (IsVarArg) {
8790     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8791     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8792     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8793     MachineFrameInfo &MFI = MF.getFrameInfo();
8794     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8795     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8796 
8797     // Offset of the first variable argument from stack pointer, and size of
8798     // the vararg save area. For now, the varargs save area is either zero or
8799     // large enough to hold a0-a7.
8800     int VaArgOffset, VarArgsSaveSize;
8801 
8802     // If all registers are allocated, then all varargs must be passed on the
8803     // stack and we don't need to save any argregs.
8804     if (ArgRegs.size() == Idx) {
8805       VaArgOffset = CCInfo.getNextStackOffset();
8806       VarArgsSaveSize = 0;
8807     } else {
8808       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8809       VaArgOffset = -VarArgsSaveSize;
8810     }
8811 
8812     // Record the frame index of the first variable argument
8813     // which is a value necessary to VASTART.
8814     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8815     RVFI->setVarArgsFrameIndex(FI);
8816 
8817     // If saving an odd number of registers then create an extra stack slot to
8818     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8819     // offsets to even-numbered registered remain 2*XLEN-aligned.
8820     if (Idx % 2) {
8821       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8822       VarArgsSaveSize += XLenInBytes;
8823     }
8824 
8825     // Copy the integer registers that may have been used for passing varargs
8826     // to the vararg save area.
8827     for (unsigned I = Idx; I < ArgRegs.size();
8828          ++I, VaArgOffset += XLenInBytes) {
8829       const Register Reg = RegInfo.createVirtualRegister(RC);
8830       RegInfo.addLiveIn(ArgRegs[I], Reg);
8831       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8832       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8833       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8834       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8835                                    MachinePointerInfo::getFixedStack(MF, FI));
8836       cast<StoreSDNode>(Store.getNode())
8837           ->getMemOperand()
8838           ->setValue((Value *)nullptr);
8839       OutChains.push_back(Store);
8840     }
8841     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8842   }
8843 
8844   // All stores are grouped in one node to allow the matching between
8845   // the size of Ins and InVals. This only happens for vararg functions.
8846   if (!OutChains.empty()) {
8847     OutChains.push_back(Chain);
8848     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8849   }
8850 
8851   return Chain;
8852 }
8853 
8854 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8855 /// for tail call optimization.
8856 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8857 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8858     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8859     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8860 
8861   auto &Callee = CLI.Callee;
8862   auto CalleeCC = CLI.CallConv;
8863   auto &Outs = CLI.Outs;
8864   auto &Caller = MF.getFunction();
8865   auto CallerCC = Caller.getCallingConv();
8866 
8867   // Exception-handling functions need a special set of instructions to
8868   // indicate a return to the hardware. Tail-calling another function would
8869   // probably break this.
8870   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8871   // should be expanded as new function attributes are introduced.
8872   if (Caller.hasFnAttribute("interrupt"))
8873     return false;
8874 
8875   // Do not tail call opt if the stack is used to pass parameters.
8876   if (CCInfo.getNextStackOffset() != 0)
8877     return false;
8878 
8879   // Do not tail call opt if any parameters need to be passed indirectly.
8880   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8881   // passed indirectly. So the address of the value will be passed in a
8882   // register, or if not available, then the address is put on the stack. In
8883   // order to pass indirectly, space on the stack often needs to be allocated
8884   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8885   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8886   // are passed CCValAssign::Indirect.
8887   for (auto &VA : ArgLocs)
8888     if (VA.getLocInfo() == CCValAssign::Indirect)
8889       return false;
8890 
8891   // Do not tail call opt if either caller or callee uses struct return
8892   // semantics.
8893   auto IsCallerStructRet = Caller.hasStructRetAttr();
8894   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8895   if (IsCallerStructRet || IsCalleeStructRet)
8896     return false;
8897 
8898   // Externally-defined functions with weak linkage should not be
8899   // tail-called. The behaviour of branch instructions in this situation (as
8900   // used for tail calls) is implementation-defined, so we cannot rely on the
8901   // linker replacing the tail call with a return.
8902   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8903     const GlobalValue *GV = G->getGlobal();
8904     if (GV->hasExternalWeakLinkage())
8905       return false;
8906   }
8907 
8908   // The callee has to preserve all registers the caller needs to preserve.
8909   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8910   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8911   if (CalleeCC != CallerCC) {
8912     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8913     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8914       return false;
8915   }
8916 
8917   // Byval parameters hand the function a pointer directly into the stack area
8918   // we want to reuse during a tail call. Working around this *is* possible
8919   // but less efficient and uglier in LowerCall.
8920   for (auto &Arg : Outs)
8921     if (Arg.Flags.isByVal())
8922       return false;
8923 
8924   return true;
8925 }
8926 
8927 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8928   return DAG.getDataLayout().getPrefTypeAlign(
8929       VT.getTypeForEVT(*DAG.getContext()));
8930 }
8931 
8932 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8933 // and output parameter nodes.
8934 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8935                                        SmallVectorImpl<SDValue> &InVals) const {
8936   SelectionDAG &DAG = CLI.DAG;
8937   SDLoc &DL = CLI.DL;
8938   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8939   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8940   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8941   SDValue Chain = CLI.Chain;
8942   SDValue Callee = CLI.Callee;
8943   bool &IsTailCall = CLI.IsTailCall;
8944   CallingConv::ID CallConv = CLI.CallConv;
8945   bool IsVarArg = CLI.IsVarArg;
8946   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8947   MVT XLenVT = Subtarget.getXLenVT();
8948 
8949   MachineFunction &MF = DAG.getMachineFunction();
8950 
8951   // Analyze the operands of the call, assigning locations to each operand.
8952   SmallVector<CCValAssign, 16> ArgLocs;
8953   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8954 
8955   if (CallConv == CallingConv::GHC)
8956     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8957   else
8958     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8959                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8960                                                     : CC_RISCV);
8961 
8962   // Check if it's really possible to do a tail call.
8963   if (IsTailCall)
8964     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8965 
8966   if (IsTailCall)
8967     ++NumTailCalls;
8968   else if (CLI.CB && CLI.CB->isMustTailCall())
8969     report_fatal_error("failed to perform tail call elimination on a call "
8970                        "site marked musttail");
8971 
8972   // Get a count of how many bytes are to be pushed on the stack.
8973   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8974 
8975   // Create local copies for byval args
8976   SmallVector<SDValue, 8> ByValArgs;
8977   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8978     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8979     if (!Flags.isByVal())
8980       continue;
8981 
8982     SDValue Arg = OutVals[i];
8983     unsigned Size = Flags.getByValSize();
8984     Align Alignment = Flags.getNonZeroByValAlign();
8985 
8986     int FI =
8987         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8988     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8989     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8990 
8991     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8992                           /*IsVolatile=*/false,
8993                           /*AlwaysInline=*/false, IsTailCall,
8994                           MachinePointerInfo(), MachinePointerInfo());
8995     ByValArgs.push_back(FIPtr);
8996   }
8997 
8998   if (!IsTailCall)
8999     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9000 
9001   // Copy argument values to their designated locations.
9002   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9003   SmallVector<SDValue, 8> MemOpChains;
9004   SDValue StackPtr;
9005   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9006     CCValAssign &VA = ArgLocs[i];
9007     SDValue ArgValue = OutVals[i];
9008     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9009 
9010     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9011     bool IsF64OnRV32DSoftABI =
9012         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9013     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9014       SDValue SplitF64 = DAG.getNode(
9015           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9016       SDValue Lo = SplitF64.getValue(0);
9017       SDValue Hi = SplitF64.getValue(1);
9018 
9019       Register RegLo = VA.getLocReg();
9020       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9021 
9022       if (RegLo == RISCV::X17) {
9023         // Second half of f64 is passed on the stack.
9024         // Work out the address of the stack slot.
9025         if (!StackPtr.getNode())
9026           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9027         // Emit the store.
9028         MemOpChains.push_back(
9029             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9030       } else {
9031         // Second half of f64 is passed in another GPR.
9032         assert(RegLo < RISCV::X31 && "Invalid register pair");
9033         Register RegHigh = RegLo + 1;
9034         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9035       }
9036       continue;
9037     }
9038 
9039     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9040     // as any other MemLoc.
9041 
9042     // Promote the value if needed.
9043     // For now, only handle fully promoted and indirect arguments.
9044     if (VA.getLocInfo() == CCValAssign::Indirect) {
9045       // Store the argument in a stack slot and pass its address.
9046       Align StackAlign =
9047           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9048                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9049       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9050       // If the original argument was split (e.g. i128), we need
9051       // to store the required parts of it here (and pass just one address).
9052       // Vectors may be partly split to registers and partly to the stack, in
9053       // which case the base address is partly offset and subsequent stores are
9054       // relative to that.
9055       unsigned ArgIndex = Outs[i].OrigArgIndex;
9056       unsigned ArgPartOffset = Outs[i].PartOffset;
9057       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9058       // Calculate the total size to store. We don't have access to what we're
9059       // actually storing other than performing the loop and collecting the
9060       // info.
9061       SmallVector<std::pair<SDValue, SDValue>> Parts;
9062       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9063         SDValue PartValue = OutVals[i + 1];
9064         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9065         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9066         EVT PartVT = PartValue.getValueType();
9067         if (PartVT.isScalableVector())
9068           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9069         StoredSize += PartVT.getStoreSize();
9070         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9071         Parts.push_back(std::make_pair(PartValue, Offset));
9072         ++i;
9073       }
9074       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9075       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9076       MemOpChains.push_back(
9077           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9078                        MachinePointerInfo::getFixedStack(MF, FI)));
9079       for (const auto &Part : Parts) {
9080         SDValue PartValue = Part.first;
9081         SDValue PartOffset = Part.second;
9082         SDValue Address =
9083             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9084         MemOpChains.push_back(
9085             DAG.getStore(Chain, DL, PartValue, Address,
9086                          MachinePointerInfo::getFixedStack(MF, FI)));
9087       }
9088       ArgValue = SpillSlot;
9089     } else {
9090       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9091     }
9092 
9093     // Use local copy if it is a byval arg.
9094     if (Flags.isByVal())
9095       ArgValue = ByValArgs[j++];
9096 
9097     if (VA.isRegLoc()) {
9098       // Queue up the argument copies and emit them at the end.
9099       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9100     } else {
9101       assert(VA.isMemLoc() && "Argument not register or memory");
9102       assert(!IsTailCall && "Tail call not allowed if stack is used "
9103                             "for passing parameters");
9104 
9105       // Work out the address of the stack slot.
9106       if (!StackPtr.getNode())
9107         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9108       SDValue Address =
9109           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9110                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9111 
9112       // Emit the store.
9113       MemOpChains.push_back(
9114           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9115     }
9116   }
9117 
9118   // Join the stores, which are independent of one another.
9119   if (!MemOpChains.empty())
9120     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9121 
9122   SDValue Glue;
9123 
9124   // Build a sequence of copy-to-reg nodes, chained and glued together.
9125   for (auto &Reg : RegsToPass) {
9126     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9127     Glue = Chain.getValue(1);
9128   }
9129 
9130   // Validate that none of the argument registers have been marked as
9131   // reserved, if so report an error. Do the same for the return address if this
9132   // is not a tailcall.
9133   validateCCReservedRegs(RegsToPass, MF);
9134   if (!IsTailCall &&
9135       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9136     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9137         MF.getFunction(),
9138         "Return address register required, but has been reserved."});
9139 
9140   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9141   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9142   // split it and then direct call can be matched by PseudoCALL.
9143   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9144     const GlobalValue *GV = S->getGlobal();
9145 
9146     unsigned OpFlags = RISCVII::MO_CALL;
9147     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9148       OpFlags = RISCVII::MO_PLT;
9149 
9150     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9151   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9152     unsigned OpFlags = RISCVII::MO_CALL;
9153 
9154     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9155                                                  nullptr))
9156       OpFlags = RISCVII::MO_PLT;
9157 
9158     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9159   }
9160 
9161   // The first call operand is the chain and the second is the target address.
9162   SmallVector<SDValue, 8> Ops;
9163   Ops.push_back(Chain);
9164   Ops.push_back(Callee);
9165 
9166   // Add argument registers to the end of the list so that they are
9167   // known live into the call.
9168   for (auto &Reg : RegsToPass)
9169     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9170 
9171   if (!IsTailCall) {
9172     // Add a register mask operand representing the call-preserved registers.
9173     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9174     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9175     assert(Mask && "Missing call preserved mask for calling convention");
9176     Ops.push_back(DAG.getRegisterMask(Mask));
9177   }
9178 
9179   // Glue the call to the argument copies, if any.
9180   if (Glue.getNode())
9181     Ops.push_back(Glue);
9182 
9183   // Emit the call.
9184   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9185 
9186   if (IsTailCall) {
9187     MF.getFrameInfo().setHasTailCall();
9188     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9189   }
9190 
9191   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9192   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9193   Glue = Chain.getValue(1);
9194 
9195   // Mark the end of the call, which is glued to the call itself.
9196   Chain = DAG.getCALLSEQ_END(Chain,
9197                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9198                              DAG.getConstant(0, DL, PtrVT, true),
9199                              Glue, DL);
9200   Glue = Chain.getValue(1);
9201 
9202   // Assign locations to each value returned by this call.
9203   SmallVector<CCValAssign, 16> RVLocs;
9204   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9205   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9206 
9207   // Copy all of the result registers out of their specified physreg.
9208   for (auto &VA : RVLocs) {
9209     // Copy the value out
9210     SDValue RetValue =
9211         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9212     // Glue the RetValue to the end of the call sequence
9213     Chain = RetValue.getValue(1);
9214     Glue = RetValue.getValue(2);
9215 
9216     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9217       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9218       SDValue RetValue2 =
9219           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9220       Chain = RetValue2.getValue(1);
9221       Glue = RetValue2.getValue(2);
9222       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9223                              RetValue2);
9224     }
9225 
9226     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9227 
9228     InVals.push_back(RetValue);
9229   }
9230 
9231   return Chain;
9232 }
9233 
9234 bool RISCVTargetLowering::CanLowerReturn(
9235     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9236     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9237   SmallVector<CCValAssign, 16> RVLocs;
9238   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9239 
9240   Optional<unsigned> FirstMaskArgument;
9241   if (Subtarget.hasVInstructions())
9242     FirstMaskArgument = preAssignMask(Outs);
9243 
9244   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9245     MVT VT = Outs[i].VT;
9246     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9247     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9248     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9249                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9250                  *this, FirstMaskArgument))
9251       return false;
9252   }
9253   return true;
9254 }
9255 
9256 SDValue
9257 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9258                                  bool IsVarArg,
9259                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9260                                  const SmallVectorImpl<SDValue> &OutVals,
9261                                  const SDLoc &DL, SelectionDAG &DAG) const {
9262   const MachineFunction &MF = DAG.getMachineFunction();
9263   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9264 
9265   // Stores the assignment of the return value to a location.
9266   SmallVector<CCValAssign, 16> RVLocs;
9267 
9268   // Info about the registers and stack slot.
9269   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9270                  *DAG.getContext());
9271 
9272   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9273                     nullptr, CC_RISCV);
9274 
9275   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9276     report_fatal_error("GHC functions return void only");
9277 
9278   SDValue Glue;
9279   SmallVector<SDValue, 4> RetOps(1, Chain);
9280 
9281   // Copy the result values into the output registers.
9282   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9283     SDValue Val = OutVals[i];
9284     CCValAssign &VA = RVLocs[i];
9285     assert(VA.isRegLoc() && "Can only return in registers!");
9286 
9287     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9288       // Handle returning f64 on RV32D with a soft float ABI.
9289       assert(VA.isRegLoc() && "Expected return via registers");
9290       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9291                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9292       SDValue Lo = SplitF64.getValue(0);
9293       SDValue Hi = SplitF64.getValue(1);
9294       Register RegLo = VA.getLocReg();
9295       assert(RegLo < RISCV::X31 && "Invalid register pair");
9296       Register RegHi = RegLo + 1;
9297 
9298       if (STI.isRegisterReservedByUser(RegLo) ||
9299           STI.isRegisterReservedByUser(RegHi))
9300         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9301             MF.getFunction(),
9302             "Return value register required, but has been reserved."});
9303 
9304       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9305       Glue = Chain.getValue(1);
9306       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9307       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9308       Glue = Chain.getValue(1);
9309       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9310     } else {
9311       // Handle a 'normal' return.
9312       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9313       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9314 
9315       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9316         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9317             MF.getFunction(),
9318             "Return value register required, but has been reserved."});
9319 
9320       // Guarantee that all emitted copies are stuck together.
9321       Glue = Chain.getValue(1);
9322       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9323     }
9324   }
9325 
9326   RetOps[0] = Chain; // Update chain.
9327 
9328   // Add the glue node if we have it.
9329   if (Glue.getNode()) {
9330     RetOps.push_back(Glue);
9331   }
9332 
9333   unsigned RetOpc = RISCVISD::RET_FLAG;
9334   // Interrupt service routines use different return instructions.
9335   const Function &Func = DAG.getMachineFunction().getFunction();
9336   if (Func.hasFnAttribute("interrupt")) {
9337     if (!Func.getReturnType()->isVoidTy())
9338       report_fatal_error(
9339           "Functions with the interrupt attribute must have void return type!");
9340 
9341     MachineFunction &MF = DAG.getMachineFunction();
9342     StringRef Kind =
9343       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9344 
9345     if (Kind == "user")
9346       RetOpc = RISCVISD::URET_FLAG;
9347     else if (Kind == "supervisor")
9348       RetOpc = RISCVISD::SRET_FLAG;
9349     else
9350       RetOpc = RISCVISD::MRET_FLAG;
9351   }
9352 
9353   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9354 }
9355 
9356 void RISCVTargetLowering::validateCCReservedRegs(
9357     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9358     MachineFunction &MF) const {
9359   const Function &F = MF.getFunction();
9360   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9361 
9362   if (llvm::any_of(Regs, [&STI](auto Reg) {
9363         return STI.isRegisterReservedByUser(Reg.first);
9364       }))
9365     F.getContext().diagnose(DiagnosticInfoUnsupported{
9366         F, "Argument register required, but has been reserved."});
9367 }
9368 
9369 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9370   return CI->isTailCall();
9371 }
9372 
9373 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9374 #define NODE_NAME_CASE(NODE)                                                   \
9375   case RISCVISD::NODE:                                                         \
9376     return "RISCVISD::" #NODE;
9377   // clang-format off
9378   switch ((RISCVISD::NodeType)Opcode) {
9379   case RISCVISD::FIRST_NUMBER:
9380     break;
9381   NODE_NAME_CASE(RET_FLAG)
9382   NODE_NAME_CASE(URET_FLAG)
9383   NODE_NAME_CASE(SRET_FLAG)
9384   NODE_NAME_CASE(MRET_FLAG)
9385   NODE_NAME_CASE(CALL)
9386   NODE_NAME_CASE(SELECT_CC)
9387   NODE_NAME_CASE(BR_CC)
9388   NODE_NAME_CASE(BuildPairF64)
9389   NODE_NAME_CASE(SplitF64)
9390   NODE_NAME_CASE(TAIL)
9391   NODE_NAME_CASE(MULHSU)
9392   NODE_NAME_CASE(SLLW)
9393   NODE_NAME_CASE(SRAW)
9394   NODE_NAME_CASE(SRLW)
9395   NODE_NAME_CASE(DIVW)
9396   NODE_NAME_CASE(DIVUW)
9397   NODE_NAME_CASE(REMUW)
9398   NODE_NAME_CASE(ROLW)
9399   NODE_NAME_CASE(RORW)
9400   NODE_NAME_CASE(CLZW)
9401   NODE_NAME_CASE(CTZW)
9402   NODE_NAME_CASE(FSLW)
9403   NODE_NAME_CASE(FSRW)
9404   NODE_NAME_CASE(FSL)
9405   NODE_NAME_CASE(FSR)
9406   NODE_NAME_CASE(FMV_H_X)
9407   NODE_NAME_CASE(FMV_X_ANYEXTH)
9408   NODE_NAME_CASE(FMV_W_X_RV64)
9409   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9410   NODE_NAME_CASE(FCVT_X_RTZ)
9411   NODE_NAME_CASE(FCVT_XU_RTZ)
9412   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9413   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9414   NODE_NAME_CASE(READ_CYCLE_WIDE)
9415   NODE_NAME_CASE(GREV)
9416   NODE_NAME_CASE(GREVW)
9417   NODE_NAME_CASE(GORC)
9418   NODE_NAME_CASE(GORCW)
9419   NODE_NAME_CASE(SHFL)
9420   NODE_NAME_CASE(SHFLW)
9421   NODE_NAME_CASE(UNSHFL)
9422   NODE_NAME_CASE(UNSHFLW)
9423   NODE_NAME_CASE(BCOMPRESS)
9424   NODE_NAME_CASE(BCOMPRESSW)
9425   NODE_NAME_CASE(BDECOMPRESS)
9426   NODE_NAME_CASE(BDECOMPRESSW)
9427   NODE_NAME_CASE(VMV_V_X_VL)
9428   NODE_NAME_CASE(VFMV_V_F_VL)
9429   NODE_NAME_CASE(VMV_X_S)
9430   NODE_NAME_CASE(VMV_S_X_VL)
9431   NODE_NAME_CASE(VFMV_S_F_VL)
9432   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9433   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9434   NODE_NAME_CASE(READ_VLENB)
9435   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9436   NODE_NAME_CASE(VSLIDEUP_VL)
9437   NODE_NAME_CASE(VSLIDE1UP_VL)
9438   NODE_NAME_CASE(VSLIDEDOWN_VL)
9439   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9440   NODE_NAME_CASE(VID_VL)
9441   NODE_NAME_CASE(VFNCVT_ROD_VL)
9442   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9443   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9444   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9445   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9446   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9447   NODE_NAME_CASE(VECREDUCE_AND_VL)
9448   NODE_NAME_CASE(VECREDUCE_OR_VL)
9449   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9450   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9451   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9452   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9453   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9454   NODE_NAME_CASE(ADD_VL)
9455   NODE_NAME_CASE(AND_VL)
9456   NODE_NAME_CASE(MUL_VL)
9457   NODE_NAME_CASE(OR_VL)
9458   NODE_NAME_CASE(SDIV_VL)
9459   NODE_NAME_CASE(SHL_VL)
9460   NODE_NAME_CASE(SREM_VL)
9461   NODE_NAME_CASE(SRA_VL)
9462   NODE_NAME_CASE(SRL_VL)
9463   NODE_NAME_CASE(SUB_VL)
9464   NODE_NAME_CASE(UDIV_VL)
9465   NODE_NAME_CASE(UREM_VL)
9466   NODE_NAME_CASE(XOR_VL)
9467   NODE_NAME_CASE(SADDSAT_VL)
9468   NODE_NAME_CASE(UADDSAT_VL)
9469   NODE_NAME_CASE(SSUBSAT_VL)
9470   NODE_NAME_CASE(USUBSAT_VL)
9471   NODE_NAME_CASE(FADD_VL)
9472   NODE_NAME_CASE(FSUB_VL)
9473   NODE_NAME_CASE(FMUL_VL)
9474   NODE_NAME_CASE(FDIV_VL)
9475   NODE_NAME_CASE(FNEG_VL)
9476   NODE_NAME_CASE(FABS_VL)
9477   NODE_NAME_CASE(FSQRT_VL)
9478   NODE_NAME_CASE(FMA_VL)
9479   NODE_NAME_CASE(FCOPYSIGN_VL)
9480   NODE_NAME_CASE(SMIN_VL)
9481   NODE_NAME_CASE(SMAX_VL)
9482   NODE_NAME_CASE(UMIN_VL)
9483   NODE_NAME_CASE(UMAX_VL)
9484   NODE_NAME_CASE(FMINNUM_VL)
9485   NODE_NAME_CASE(FMAXNUM_VL)
9486   NODE_NAME_CASE(MULHS_VL)
9487   NODE_NAME_CASE(MULHU_VL)
9488   NODE_NAME_CASE(FP_TO_SINT_VL)
9489   NODE_NAME_CASE(FP_TO_UINT_VL)
9490   NODE_NAME_CASE(SINT_TO_FP_VL)
9491   NODE_NAME_CASE(UINT_TO_FP_VL)
9492   NODE_NAME_CASE(FP_EXTEND_VL)
9493   NODE_NAME_CASE(FP_ROUND_VL)
9494   NODE_NAME_CASE(VWMUL_VL)
9495   NODE_NAME_CASE(VWMULU_VL)
9496   NODE_NAME_CASE(SETCC_VL)
9497   NODE_NAME_CASE(VSELECT_VL)
9498   NODE_NAME_CASE(VMAND_VL)
9499   NODE_NAME_CASE(VMOR_VL)
9500   NODE_NAME_CASE(VMXOR_VL)
9501   NODE_NAME_CASE(VMCLR_VL)
9502   NODE_NAME_CASE(VMSET_VL)
9503   NODE_NAME_CASE(VRGATHER_VX_VL)
9504   NODE_NAME_CASE(VRGATHER_VV_VL)
9505   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9506   NODE_NAME_CASE(VSEXT_VL)
9507   NODE_NAME_CASE(VZEXT_VL)
9508   NODE_NAME_CASE(VCPOP_VL)
9509   NODE_NAME_CASE(VLE_VL)
9510   NODE_NAME_CASE(VSE_VL)
9511   NODE_NAME_CASE(READ_CSR)
9512   NODE_NAME_CASE(WRITE_CSR)
9513   NODE_NAME_CASE(SWAP_CSR)
9514   }
9515   // clang-format on
9516   return nullptr;
9517 #undef NODE_NAME_CASE
9518 }
9519 
9520 /// getConstraintType - Given a constraint letter, return the type of
9521 /// constraint it is for this target.
9522 RISCVTargetLowering::ConstraintType
9523 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9524   if (Constraint.size() == 1) {
9525     switch (Constraint[0]) {
9526     default:
9527       break;
9528     case 'f':
9529       return C_RegisterClass;
9530     case 'I':
9531     case 'J':
9532     case 'K':
9533       return C_Immediate;
9534     case 'A':
9535       return C_Memory;
9536     case 'S': // A symbolic address
9537       return C_Other;
9538     }
9539   } else {
9540     if (Constraint == "vr" || Constraint == "vm")
9541       return C_RegisterClass;
9542   }
9543   return TargetLowering::getConstraintType(Constraint);
9544 }
9545 
9546 std::pair<unsigned, const TargetRegisterClass *>
9547 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9548                                                   StringRef Constraint,
9549                                                   MVT VT) const {
9550   // First, see if this is a constraint that directly corresponds to a
9551   // RISCV register class.
9552   if (Constraint.size() == 1) {
9553     switch (Constraint[0]) {
9554     case 'r':
9555       return std::make_pair(0U, &RISCV::GPRRegClass);
9556     case 'f':
9557       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9558         return std::make_pair(0U, &RISCV::FPR16RegClass);
9559       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9560         return std::make_pair(0U, &RISCV::FPR32RegClass);
9561       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9562         return std::make_pair(0U, &RISCV::FPR64RegClass);
9563       break;
9564     default:
9565       break;
9566     }
9567   } else {
9568     if (Constraint == "vr") {
9569       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9570                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9571         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9572           return std::make_pair(0U, RC);
9573       }
9574     } else if (Constraint == "vm") {
9575       if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
9576         return std::make_pair(0U, &RISCV::VMV0RegClass);
9577     }
9578   }
9579 
9580   // Clang will correctly decode the usage of register name aliases into their
9581   // official names. However, other frontends like `rustc` do not. This allows
9582   // users of these frontends to use the ABI names for registers in LLVM-style
9583   // register constraints.
9584   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9585                                .Case("{zero}", RISCV::X0)
9586                                .Case("{ra}", RISCV::X1)
9587                                .Case("{sp}", RISCV::X2)
9588                                .Case("{gp}", RISCV::X3)
9589                                .Case("{tp}", RISCV::X4)
9590                                .Case("{t0}", RISCV::X5)
9591                                .Case("{t1}", RISCV::X6)
9592                                .Case("{t2}", RISCV::X7)
9593                                .Cases("{s0}", "{fp}", RISCV::X8)
9594                                .Case("{s1}", RISCV::X9)
9595                                .Case("{a0}", RISCV::X10)
9596                                .Case("{a1}", RISCV::X11)
9597                                .Case("{a2}", RISCV::X12)
9598                                .Case("{a3}", RISCV::X13)
9599                                .Case("{a4}", RISCV::X14)
9600                                .Case("{a5}", RISCV::X15)
9601                                .Case("{a6}", RISCV::X16)
9602                                .Case("{a7}", RISCV::X17)
9603                                .Case("{s2}", RISCV::X18)
9604                                .Case("{s3}", RISCV::X19)
9605                                .Case("{s4}", RISCV::X20)
9606                                .Case("{s5}", RISCV::X21)
9607                                .Case("{s6}", RISCV::X22)
9608                                .Case("{s7}", RISCV::X23)
9609                                .Case("{s8}", RISCV::X24)
9610                                .Case("{s9}", RISCV::X25)
9611                                .Case("{s10}", RISCV::X26)
9612                                .Case("{s11}", RISCV::X27)
9613                                .Case("{t3}", RISCV::X28)
9614                                .Case("{t4}", RISCV::X29)
9615                                .Case("{t5}", RISCV::X30)
9616                                .Case("{t6}", RISCV::X31)
9617                                .Default(RISCV::NoRegister);
9618   if (XRegFromAlias != RISCV::NoRegister)
9619     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9620 
9621   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9622   // TableGen record rather than the AsmName to choose registers for InlineAsm
9623   // constraints, plus we want to match those names to the widest floating point
9624   // register type available, manually select floating point registers here.
9625   //
9626   // The second case is the ABI name of the register, so that frontends can also
9627   // use the ABI names in register constraint lists.
9628   if (Subtarget.hasStdExtF()) {
9629     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9630                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9631                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9632                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9633                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9634                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9635                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9636                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9637                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9638                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9639                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9640                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9641                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9642                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9643                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9644                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9645                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9646                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9647                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9648                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9649                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9650                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9651                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9652                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9653                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9654                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9655                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9656                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9657                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9658                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9659                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9660                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9661                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9662                         .Default(RISCV::NoRegister);
9663     if (FReg != RISCV::NoRegister) {
9664       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9665       if (Subtarget.hasStdExtD()) {
9666         unsigned RegNo = FReg - RISCV::F0_F;
9667         unsigned DReg = RISCV::F0_D + RegNo;
9668         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9669       }
9670       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9671     }
9672   }
9673 
9674   if (Subtarget.hasVInstructions()) {
9675     Register VReg = StringSwitch<Register>(Constraint.lower())
9676                         .Case("{v0}", RISCV::V0)
9677                         .Case("{v1}", RISCV::V1)
9678                         .Case("{v2}", RISCV::V2)
9679                         .Case("{v3}", RISCV::V3)
9680                         .Case("{v4}", RISCV::V4)
9681                         .Case("{v5}", RISCV::V5)
9682                         .Case("{v6}", RISCV::V6)
9683                         .Case("{v7}", RISCV::V7)
9684                         .Case("{v8}", RISCV::V8)
9685                         .Case("{v9}", RISCV::V9)
9686                         .Case("{v10}", RISCV::V10)
9687                         .Case("{v11}", RISCV::V11)
9688                         .Case("{v12}", RISCV::V12)
9689                         .Case("{v13}", RISCV::V13)
9690                         .Case("{v14}", RISCV::V14)
9691                         .Case("{v15}", RISCV::V15)
9692                         .Case("{v16}", RISCV::V16)
9693                         .Case("{v17}", RISCV::V17)
9694                         .Case("{v18}", RISCV::V18)
9695                         .Case("{v19}", RISCV::V19)
9696                         .Case("{v20}", RISCV::V20)
9697                         .Case("{v21}", RISCV::V21)
9698                         .Case("{v22}", RISCV::V22)
9699                         .Case("{v23}", RISCV::V23)
9700                         .Case("{v24}", RISCV::V24)
9701                         .Case("{v25}", RISCV::V25)
9702                         .Case("{v26}", RISCV::V26)
9703                         .Case("{v27}", RISCV::V27)
9704                         .Case("{v28}", RISCV::V28)
9705                         .Case("{v29}", RISCV::V29)
9706                         .Case("{v30}", RISCV::V30)
9707                         .Case("{v31}", RISCV::V31)
9708                         .Default(RISCV::NoRegister);
9709     if (VReg != RISCV::NoRegister) {
9710       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9711         return std::make_pair(VReg, &RISCV::VMRegClass);
9712       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9713         return std::make_pair(VReg, &RISCV::VRRegClass);
9714       for (const auto *RC :
9715            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9716         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9717           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9718           return std::make_pair(VReg, RC);
9719         }
9720       }
9721     }
9722   }
9723 
9724   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9725 }
9726 
9727 unsigned
9728 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9729   // Currently only support length 1 constraints.
9730   if (ConstraintCode.size() == 1) {
9731     switch (ConstraintCode[0]) {
9732     case 'A':
9733       return InlineAsm::Constraint_A;
9734     default:
9735       break;
9736     }
9737   }
9738 
9739   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9740 }
9741 
9742 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9743     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9744     SelectionDAG &DAG) const {
9745   // Currently only support length 1 constraints.
9746   if (Constraint.length() == 1) {
9747     switch (Constraint[0]) {
9748     case 'I':
9749       // Validate & create a 12-bit signed immediate operand.
9750       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9751         uint64_t CVal = C->getSExtValue();
9752         if (isInt<12>(CVal))
9753           Ops.push_back(
9754               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9755       }
9756       return;
9757     case 'J':
9758       // Validate & create an integer zero operand.
9759       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9760         if (C->getZExtValue() == 0)
9761           Ops.push_back(
9762               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9763       return;
9764     case 'K':
9765       // Validate & create a 5-bit unsigned immediate operand.
9766       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9767         uint64_t CVal = C->getZExtValue();
9768         if (isUInt<5>(CVal))
9769           Ops.push_back(
9770               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9771       }
9772       return;
9773     case 'S':
9774       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9775         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9776                                                  GA->getValueType(0)));
9777       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9778         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9779                                                 BA->getValueType(0)));
9780       }
9781       return;
9782     default:
9783       break;
9784     }
9785   }
9786   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9787 }
9788 
9789 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9790                                                    Instruction *Inst,
9791                                                    AtomicOrdering Ord) const {
9792   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9793     return Builder.CreateFence(Ord);
9794   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9795     return Builder.CreateFence(AtomicOrdering::Release);
9796   return nullptr;
9797 }
9798 
9799 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9800                                                     Instruction *Inst,
9801                                                     AtomicOrdering Ord) const {
9802   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9803     return Builder.CreateFence(AtomicOrdering::Acquire);
9804   return nullptr;
9805 }
9806 
9807 TargetLowering::AtomicExpansionKind
9808 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9809   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9810   // point operations can't be used in an lr/sc sequence without breaking the
9811   // forward-progress guarantee.
9812   if (AI->isFloatingPointOperation())
9813     return AtomicExpansionKind::CmpXChg;
9814 
9815   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9816   if (Size == 8 || Size == 16)
9817     return AtomicExpansionKind::MaskedIntrinsic;
9818   return AtomicExpansionKind::None;
9819 }
9820 
9821 static Intrinsic::ID
9822 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9823   if (XLen == 32) {
9824     switch (BinOp) {
9825     default:
9826       llvm_unreachable("Unexpected AtomicRMW BinOp");
9827     case AtomicRMWInst::Xchg:
9828       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9829     case AtomicRMWInst::Add:
9830       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9831     case AtomicRMWInst::Sub:
9832       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9833     case AtomicRMWInst::Nand:
9834       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9835     case AtomicRMWInst::Max:
9836       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9837     case AtomicRMWInst::Min:
9838       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9839     case AtomicRMWInst::UMax:
9840       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9841     case AtomicRMWInst::UMin:
9842       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9843     }
9844   }
9845 
9846   if (XLen == 64) {
9847     switch (BinOp) {
9848     default:
9849       llvm_unreachable("Unexpected AtomicRMW BinOp");
9850     case AtomicRMWInst::Xchg:
9851       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9852     case AtomicRMWInst::Add:
9853       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9854     case AtomicRMWInst::Sub:
9855       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9856     case AtomicRMWInst::Nand:
9857       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9858     case AtomicRMWInst::Max:
9859       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9860     case AtomicRMWInst::Min:
9861       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9862     case AtomicRMWInst::UMax:
9863       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9864     case AtomicRMWInst::UMin:
9865       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9866     }
9867   }
9868 
9869   llvm_unreachable("Unexpected XLen\n");
9870 }
9871 
9872 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9873     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9874     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9875   unsigned XLen = Subtarget.getXLen();
9876   Value *Ordering =
9877       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9878   Type *Tys[] = {AlignedAddr->getType()};
9879   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9880       AI->getModule(),
9881       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9882 
9883   if (XLen == 64) {
9884     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9885     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9886     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9887   }
9888 
9889   Value *Result;
9890 
9891   // Must pass the shift amount needed to sign extend the loaded value prior
9892   // to performing a signed comparison for min/max. ShiftAmt is the number of
9893   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9894   // is the number of bits to left+right shift the value in order to
9895   // sign-extend.
9896   if (AI->getOperation() == AtomicRMWInst::Min ||
9897       AI->getOperation() == AtomicRMWInst::Max) {
9898     const DataLayout &DL = AI->getModule()->getDataLayout();
9899     unsigned ValWidth =
9900         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9901     Value *SextShamt =
9902         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9903     Result = Builder.CreateCall(LrwOpScwLoop,
9904                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9905   } else {
9906     Result =
9907         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9908   }
9909 
9910   if (XLen == 64)
9911     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9912   return Result;
9913 }
9914 
9915 TargetLowering::AtomicExpansionKind
9916 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9917     AtomicCmpXchgInst *CI) const {
9918   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9919   if (Size == 8 || Size == 16)
9920     return AtomicExpansionKind::MaskedIntrinsic;
9921   return AtomicExpansionKind::None;
9922 }
9923 
9924 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9925     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9926     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9927   unsigned XLen = Subtarget.getXLen();
9928   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9929   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9930   if (XLen == 64) {
9931     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9932     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9933     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9934     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9935   }
9936   Type *Tys[] = {AlignedAddr->getType()};
9937   Function *MaskedCmpXchg =
9938       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9939   Value *Result = Builder.CreateCall(
9940       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9941   if (XLen == 64)
9942     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9943   return Result;
9944 }
9945 
9946 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9947   return false;
9948 }
9949 
9950 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
9951                                                EVT VT) const {
9952   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
9953     return false;
9954 
9955   switch (FPVT.getSimpleVT().SimpleTy) {
9956   case MVT::f16:
9957     return Subtarget.hasStdExtZfh();
9958   case MVT::f32:
9959     return Subtarget.hasStdExtF();
9960   case MVT::f64:
9961     return Subtarget.hasStdExtD();
9962   default:
9963     return false;
9964   }
9965 }
9966 
9967 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9968                                                      EVT VT) const {
9969   VT = VT.getScalarType();
9970 
9971   if (!VT.isSimple())
9972     return false;
9973 
9974   switch (VT.getSimpleVT().SimpleTy) {
9975   case MVT::f16:
9976     return Subtarget.hasStdExtZfh();
9977   case MVT::f32:
9978     return Subtarget.hasStdExtF();
9979   case MVT::f64:
9980     return Subtarget.hasStdExtD();
9981   default:
9982     break;
9983   }
9984 
9985   return false;
9986 }
9987 
9988 Register RISCVTargetLowering::getExceptionPointerRegister(
9989     const Constant *PersonalityFn) const {
9990   return RISCV::X10;
9991 }
9992 
9993 Register RISCVTargetLowering::getExceptionSelectorRegister(
9994     const Constant *PersonalityFn) const {
9995   return RISCV::X11;
9996 }
9997 
9998 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9999   // Return false to suppress the unnecessary extensions if the LibCall
10000   // arguments or return value is f32 type for LP64 ABI.
10001   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10002   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10003     return false;
10004 
10005   return true;
10006 }
10007 
10008 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10009   if (Subtarget.is64Bit() && Type == MVT::i32)
10010     return true;
10011 
10012   return IsSigned;
10013 }
10014 
10015 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10016                                                  SDValue C) const {
10017   // Check integral scalar types.
10018   if (VT.isScalarInteger()) {
10019     // Omit the optimization if the sub target has the M extension and the data
10020     // size exceeds XLen.
10021     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10022       return false;
10023     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10024       // Break the MUL to a SLLI and an ADD/SUB.
10025       const APInt &Imm = ConstNode->getAPIntValue();
10026       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10027           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10028         return true;
10029       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10030       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10031           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10032            (Imm - 8).isPowerOf2()))
10033         return true;
10034       // Omit the following optimization if the sub target has the M extension
10035       // and the data size >= XLen.
10036       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10037         return false;
10038       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10039       // a pair of LUI/ADDI.
10040       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10041         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10042         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10043             (1 - ImmS).isPowerOf2())
10044         return true;
10045       }
10046     }
10047   }
10048 
10049   return false;
10050 }
10051 
10052 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10053     const SDValue &AddNode, const SDValue &ConstNode) const {
10054   // Let the DAGCombiner decide for vectors.
10055   EVT VT = AddNode.getValueType();
10056   if (VT.isVector())
10057     return true;
10058 
10059   // Let the DAGCombiner decide for larger types.
10060   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10061     return true;
10062 
10063   // It is worse if c1 is simm12 while c1*c2 is not.
10064   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10065   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10066   const APInt &C1 = C1Node->getAPIntValue();
10067   const APInt &C2 = C2Node->getAPIntValue();
10068   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10069     return false;
10070 
10071   // Default to true and let the DAGCombiner decide.
10072   return true;
10073 }
10074 
10075 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10076     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10077     bool *Fast) const {
10078   if (!VT.isVector())
10079     return false;
10080 
10081   EVT ElemVT = VT.getVectorElementType();
10082   if (Alignment >= ElemVT.getStoreSize()) {
10083     if (Fast)
10084       *Fast = true;
10085     return true;
10086   }
10087 
10088   return false;
10089 }
10090 
10091 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10092     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10093     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10094   bool IsABIRegCopy = CC.hasValue();
10095   EVT ValueVT = Val.getValueType();
10096   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10097     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10098     // and cast to f32.
10099     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10100     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10101     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10102                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10103     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10104     Parts[0] = Val;
10105     return true;
10106   }
10107 
10108   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10109     LLVMContext &Context = *DAG.getContext();
10110     EVT ValueEltVT = ValueVT.getVectorElementType();
10111     EVT PartEltVT = PartVT.getVectorElementType();
10112     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10113     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10114     if (PartVTBitSize % ValueVTBitSize == 0) {
10115       assert(PartVTBitSize >= ValueVTBitSize);
10116       // If the element types are different, bitcast to the same element type of
10117       // PartVT first.
10118       // Give an example here, we want copy a <vscale x 1 x i8> value to
10119       // <vscale x 4 x i16>.
10120       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10121       // subvector, then we can bitcast to <vscale x 4 x i16>.
10122       if (ValueEltVT != PartEltVT) {
10123         if (PartVTBitSize > ValueVTBitSize) {
10124           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10125           assert(Count != 0 && "The number of element should not be zero.");
10126           EVT SameEltTypeVT =
10127               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10128           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10129                             DAG.getUNDEF(SameEltTypeVT), Val,
10130                             DAG.getVectorIdxConstant(0, DL));
10131         }
10132         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10133       } else {
10134         Val =
10135             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10136                         Val, DAG.getVectorIdxConstant(0, DL));
10137       }
10138       Parts[0] = Val;
10139       return true;
10140     }
10141   }
10142   return false;
10143 }
10144 
10145 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10146     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10147     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10148   bool IsABIRegCopy = CC.hasValue();
10149   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10150     SDValue Val = Parts[0];
10151 
10152     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10153     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10154     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10155     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10156     return Val;
10157   }
10158 
10159   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10160     LLVMContext &Context = *DAG.getContext();
10161     SDValue Val = Parts[0];
10162     EVT ValueEltVT = ValueVT.getVectorElementType();
10163     EVT PartEltVT = PartVT.getVectorElementType();
10164     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10165     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10166     if (PartVTBitSize % ValueVTBitSize == 0) {
10167       assert(PartVTBitSize >= ValueVTBitSize);
10168       EVT SameEltTypeVT = ValueVT;
10169       // If the element types are different, convert it to the same element type
10170       // of PartVT.
10171       // Give an example here, we want copy a <vscale x 1 x i8> value from
10172       // <vscale x 4 x i16>.
10173       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10174       // then we can extract <vscale x 1 x i8>.
10175       if (ValueEltVT != PartEltVT) {
10176         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10177         assert(Count != 0 && "The number of element should not be zero.");
10178         SameEltTypeVT =
10179             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10180         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10181       }
10182       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10183                         DAG.getVectorIdxConstant(0, DL));
10184       return Val;
10185     }
10186   }
10187   return SDValue();
10188 }
10189 
10190 #define GET_REGISTER_MATCHER
10191 #include "RISCVGenAsmMatcher.inc"
10192 
10193 Register
10194 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10195                                        const MachineFunction &MF) const {
10196   Register Reg = MatchRegisterAltName(RegName);
10197   if (Reg == RISCV::NoRegister)
10198     Reg = MatchRegisterName(RegName);
10199   if (Reg == RISCV::NoRegister)
10200     report_fatal_error(
10201         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10202   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10203   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10204     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10205                              StringRef(RegName) + "\"."));
10206   return Reg;
10207 }
10208 
10209 namespace llvm {
10210 namespace RISCVVIntrinsicsTable {
10211 
10212 #define GET_RISCVVIntrinsicsTable_IMPL
10213 #include "RISCVGenSearchableTables.inc"
10214 
10215 } // namespace RISCVVIntrinsicsTable
10216 
10217 } // namespace llvm
10218