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