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