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