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