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