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