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