1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "aarch64-lower"
39 
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42 
43 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48 
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53 
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61 
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64 
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68 
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75 
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79 
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86 
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98 
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107 
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110 
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133 
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137 
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141 
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146 
147   // Virtually no operation on f128 is legal, but LLVM can't expand them when
148   // there's a valid register class, so we need custom operations in most cases.
149   setOperationAction(ISD::FABS, MVT::f128, Expand);
150   setOperationAction(ISD::FADD, MVT::f128, Custom);
151   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152   setOperationAction(ISD::FCOS, MVT::f128, Expand);
153   setOperationAction(ISD::FDIV, MVT::f128, Custom);
154   setOperationAction(ISD::FMA, MVT::f128, Expand);
155   setOperationAction(ISD::FMUL, MVT::f128, Custom);
156   setOperationAction(ISD::FNEG, MVT::f128, Expand);
157   setOperationAction(ISD::FPOW, MVT::f128, Expand);
158   setOperationAction(ISD::FREM, MVT::f128, Expand);
159   setOperationAction(ISD::FRINT, MVT::f128, Expand);
160   setOperationAction(ISD::FSIN, MVT::f128, Expand);
161   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163   setOperationAction(ISD::FSUB, MVT::f128, Custom);
164   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165   setOperationAction(ISD::SETCC, MVT::f128, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167   setOperationAction(ISD::SELECT, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170 
171   // Lowering for many of the conversions is actually specified by the non-f128
172   // type. The LowerXXX function will be trivial when f128 isn't involved.
173   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187 
188   // Variable arguments.
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Custom);
191   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193 
194   // Variable-sized objects.
195   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198 
199   // Constant pool entries
200   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201 
202   // BlockAddress
203   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204 
205   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206   setOperationAction(ISD::ADDC, MVT::i32, Custom);
207   setOperationAction(ISD::ADDE, MVT::i32, Custom);
208   setOperationAction(ISD::SUBC, MVT::i32, Custom);
209   setOperationAction(ISD::SUBE, MVT::i32, Custom);
210   setOperationAction(ISD::ADDC, MVT::i64, Custom);
211   setOperationAction(ISD::ADDE, MVT::i64, Custom);
212   setOperationAction(ISD::SUBC, MVT::i64, Custom);
213   setOperationAction(ISD::SUBE, MVT::i64, Custom);
214 
215   // AArch64 lacks both left-rotate and popcount instructions.
216   setOperationAction(ISD::ROTL, MVT::i32, Expand);
217   setOperationAction(ISD::ROTL, MVT::i64, Expand);
218   for (MVT VT : MVT::vector_valuetypes()) {
219     setOperationAction(ISD::ROTL, VT, Expand);
220     setOperationAction(ISD::ROTR, VT, Expand);
221   }
222 
223   // AArch64 doesn't have {U|S}MUL_LOHI.
224   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226 
227 
228   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229   // counterparts, which AArch64 supports directly.
230   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234 
235   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237 
238   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
240   for (MVT VT : MVT::vector_valuetypes()) {
241     setOperationAction(ISD::SDIVREM, VT, Expand);
242     setOperationAction(ISD::UDIVREM, VT, Expand);
243   }
244   setOperationAction(ISD::SREM, MVT::i32, Expand);
245   setOperationAction(ISD::SREM, MVT::i64, Expand);
246   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248   setOperationAction(ISD::UREM, MVT::i32, Expand);
249   setOperationAction(ISD::UREM, MVT::i64, Expand);
250 
251   // Custom lower Add/Sub/Mul with overflow.
252   setOperationAction(ISD::SADDO, MVT::i32, Custom);
253   setOperationAction(ISD::SADDO, MVT::i64, Custom);
254   setOperationAction(ISD::UADDO, MVT::i32, Custom);
255   setOperationAction(ISD::UADDO, MVT::i64, Custom);
256   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258   setOperationAction(ISD::USUBO, MVT::i32, Custom);
259   setOperationAction(ISD::USUBO, MVT::i64, Custom);
260   setOperationAction(ISD::SMULO, MVT::i32, Custom);
261   setOperationAction(ISD::SMULO, MVT::i64, Custom);
262   setOperationAction(ISD::UMULO, MVT::i32, Custom);
263   setOperationAction(ISD::UMULO, MVT::i64, Custom);
264 
265   setOperationAction(ISD::FSIN, MVT::f32, Expand);
266   setOperationAction(ISD::FSIN, MVT::f64, Expand);
267   setOperationAction(ISD::FCOS, MVT::f32, Expand);
268   setOperationAction(ISD::FCOS, MVT::f64, Expand);
269   setOperationAction(ISD::FPOW, MVT::f32, Expand);
270   setOperationAction(ISD::FPOW, MVT::f64, Expand);
271   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
273 
274   // f16 is a storage-only type, always promote it to f32.
275   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
276   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
277   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
278   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
279   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
280   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
281   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
282   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
283   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
284   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
285   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
286   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
287   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
288   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
289   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
290   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
291   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
292   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
293   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
294   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
295   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
296   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
297   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
298   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
299   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
300   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
301   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
302   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
303   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
304   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
305   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
306   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
307   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
308   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
309 
310   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
311   // known to be safe.
312   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
324 
325   // Expand all other v4f16 operations.
326   // FIXME: We could generate better code by promoting some operations to
327   // a pair of v4f32s
328   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
354 
355 
356   // v8f16 is also a storage-only type, so expand it.
357   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
388 
389   // AArch64 has implementations of a lot of rounding-like FP operations.
390   for (MVT Ty : {MVT::f32, MVT::f64}) {
391     setOperationAction(ISD::FFLOOR, Ty, Legal);
392     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393     setOperationAction(ISD::FCEIL, Ty, Legal);
394     setOperationAction(ISD::FRINT, Ty, Legal);
395     setOperationAction(ISD::FTRUNC, Ty, Legal);
396     setOperationAction(ISD::FROUND, Ty, Legal);
397     setOperationAction(ISD::FMINNUM, Ty, Legal);
398     setOperationAction(ISD::FMAXNUM, Ty, Legal);
399     setOperationAction(ISD::FMINNAN, Ty, Legal);
400     setOperationAction(ISD::FMAXNAN, Ty, Legal);
401   }
402 
403   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
404 
405   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406   // This requires the Performance Monitors extension.
407   if (Subtarget->hasPerfMon())
408     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
409 
410   if (Subtarget->isTargetMachO()) {
411     // For iOS, we don't want to the normal expansion of a libcall to
412     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413     // traffic.
414     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416   } else {
417     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
419   }
420 
421   // Make floating-point constants legal for the large code model, so they don't
422   // become loads from the constant pool.
423   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
426   }
427 
428   // AArch64 does not have floating-point extending loads, i1 sign-extending
429   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
430   for (MVT VT : MVT::fp_valuetypes()) {
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435   }
436   for (MVT VT : MVT::integer_valuetypes())
437     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438 
439   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
446 
447   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449 
450   // Indexed loads and stores are supported.
451   for (unsigned im = (unsigned)ISD::PRE_INC;
452        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453     setIndexedLoadAction(im, MVT::i8, Legal);
454     setIndexedLoadAction(im, MVT::i16, Legal);
455     setIndexedLoadAction(im, MVT::i32, Legal);
456     setIndexedLoadAction(im, MVT::i64, Legal);
457     setIndexedLoadAction(im, MVT::f64, Legal);
458     setIndexedLoadAction(im, MVT::f32, Legal);
459     setIndexedLoadAction(im, MVT::f16, Legal);
460     setIndexedStoreAction(im, MVT::i8, Legal);
461     setIndexedStoreAction(im, MVT::i16, Legal);
462     setIndexedStoreAction(im, MVT::i32, Legal);
463     setIndexedStoreAction(im, MVT::i64, Legal);
464     setIndexedStoreAction(im, MVT::f64, Legal);
465     setIndexedStoreAction(im, MVT::f32, Legal);
466     setIndexedStoreAction(im, MVT::f16, Legal);
467   }
468 
469   // Trap.
470   setOperationAction(ISD::TRAP, MVT::Other, Legal);
471 
472   // We combine OR nodes for bitfield operations.
473   setTargetDAGCombine(ISD::OR);
474 
475   // Vector add and sub nodes may conceal a high-half opportunity.
476   // Also, try to fold ADD into CSINC/CSINV..
477   setTargetDAGCombine(ISD::ADD);
478   setTargetDAGCombine(ISD::SUB);
479 
480   setTargetDAGCombine(ISD::XOR);
481   setTargetDAGCombine(ISD::SINT_TO_FP);
482   setTargetDAGCombine(ISD::UINT_TO_FP);
483 
484   setTargetDAGCombine(ISD::FP_TO_SINT);
485   setTargetDAGCombine(ISD::FP_TO_UINT);
486   setTargetDAGCombine(ISD::FDIV);
487 
488   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
489 
490   setTargetDAGCombine(ISD::ANY_EXTEND);
491   setTargetDAGCombine(ISD::ZERO_EXTEND);
492   setTargetDAGCombine(ISD::SIGN_EXTEND);
493   setTargetDAGCombine(ISD::BITCAST);
494   setTargetDAGCombine(ISD::CONCAT_VECTORS);
495   setTargetDAGCombine(ISD::STORE);
496   if (Subtarget->supportsAddressTopByteIgnored())
497     setTargetDAGCombine(ISD::LOAD);
498 
499   setTargetDAGCombine(ISD::MUL);
500 
501   setTargetDAGCombine(ISD::SELECT);
502   setTargetDAGCombine(ISD::VSELECT);
503 
504   setTargetDAGCombine(ISD::INTRINSIC_VOID);
505   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
507   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
508 
509   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
512 
513   setStackPointerRegisterToSaveRestore(AArch64::SP);
514 
515   setSchedulingPreference(Sched::Hybrid);
516 
517   // Enable TBZ/TBNZ
518   MaskAndBranchFoldingIsLegal = true;
519   EnableExtLdPromotion = true;
520 
521   setMinFunctionAlignment(2);
522 
523   setHasExtractBitsInsn(true);
524 
525   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526 
527   if (Subtarget->hasNEON()) {
528     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529     // silliness like this:
530     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555 
556     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561 
562     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563 
564     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565     // elements smaller than i32, so promote the input to i32 first.
566     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
570     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571     // -> v8f16 conversions.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
576     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
581     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
582     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
585 
586     // AArch64 doesn't have MUL.2d:
587     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
588     // Custom handling for some quad-vector types to detect MULL.
589     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
592 
593     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595     // Likewise, narrowing and extending vector loads/stores aren't handled
596     // directly.
597     for (MVT VT : MVT::vector_valuetypes()) {
598       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
599 
600       setOperationAction(ISD::MULHS, VT, Expand);
601       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602       setOperationAction(ISD::MULHU, VT, Expand);
603       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
604 
605       setOperationAction(ISD::BSWAP, VT, Expand);
606 
607       for (MVT InnerVT : MVT::vector_valuetypes()) {
608         setTruncStoreAction(VT, InnerVT, Expand);
609         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
612       }
613     }
614 
615     // AArch64 has implementations of a lot of rounding-like FP operations.
616     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
617       setOperationAction(ISD::FFLOOR, Ty, Legal);
618       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619       setOperationAction(ISD::FCEIL, Ty, Legal);
620       setOperationAction(ISD::FRINT, Ty, Legal);
621       setOperationAction(ISD::FTRUNC, Ty, Legal);
622       setOperationAction(ISD::FROUND, Ty, Legal);
623     }
624   }
625 
626   // Prefer likely predicted branches to selects on out-of-order cores.
627   if (Subtarget->isCortexA57())
628     PredictableSelectIsExpensive = true;
629 }
630 
631 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
632   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
633     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
635 
636     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
638   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
639     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
641 
642     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
644   }
645 
646   // Mark vector float intrinsics as expand.
647   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
657 
658     // But we do support custom-lowering for FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
660   }
661 
662   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
674 
675   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
678   for (MVT InnerVT : MVT::all_valuetypes())
679     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
680 
681   // CNT supports only B element sizes.
682   if (VT != MVT::v8i8 && VT != MVT::v16i8)
683     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
684 
685   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
690 
691   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
693 
694   // [SU][MIN|MAX] are available for all NEON types apart from i64.
695   if (!VT.isFloatingPoint() &&
696       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
697     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
698       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
699 
700   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
701   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
702     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
703                             ISD::FMINNUM, ISD::FMAXNUM})
704       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
705 
706   if (Subtarget->isLittleEndian()) {
707     for (unsigned im = (unsigned)ISD::PRE_INC;
708          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
710       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
711     }
712   }
713 }
714 
715 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
716   addRegisterClass(VT, &AArch64::FPR64RegClass);
717   addTypeForNEON(VT, MVT::v2i32);
718 }
719 
720 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
721   addRegisterClass(VT, &AArch64::FPR128RegClass);
722   addTypeForNEON(VT, MVT::v4i32);
723 }
724 
725 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
726                                               EVT VT) const {
727   if (!VT.isVector())
728     return MVT::i32;
729   return VT.changeVectorElementTypeToInteger();
730 }
731 
732 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
733 /// Mask are known to be either zero or one and return them in the
734 /// KnownZero/KnownOne bitsets.
735 void AArch64TargetLowering::computeKnownBitsForTargetNode(
736     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
737     const SelectionDAG &DAG, unsigned Depth) const {
738   switch (Op.getOpcode()) {
739   default:
740     break;
741   case AArch64ISD::CSEL: {
742     APInt KnownZero2, KnownOne2;
743     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
744     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
745     KnownZero &= KnownZero2;
746     KnownOne &= KnownOne2;
747     break;
748   }
749   case ISD::INTRINSIC_W_CHAIN: {
750     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
751     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
752     switch (IntID) {
753     default: return;
754     case Intrinsic::aarch64_ldaxr:
755     case Intrinsic::aarch64_ldxr: {
756       unsigned BitWidth = KnownOne.getBitWidth();
757       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
758       unsigned MemBits = VT.getScalarType().getSizeInBits();
759       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
760       return;
761     }
762     }
763     break;
764   }
765   case ISD::INTRINSIC_WO_CHAIN:
766   case ISD::INTRINSIC_VOID: {
767     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
768     switch (IntNo) {
769     default:
770       break;
771     case Intrinsic::aarch64_neon_umaxv:
772     case Intrinsic::aarch64_neon_uminv: {
773       // Figure out the datatype of the vector operand. The UMINV instruction
774       // will zero extend the result, so we can mark as known zero all the
775       // bits larger than the element datatype. 32-bit or larget doesn't need
776       // this as those are legal types and will be handled by isel directly.
777       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
778       unsigned BitWidth = KnownZero.getBitWidth();
779       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
780         assert(BitWidth >= 8 && "Unexpected width!");
781         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
782         KnownZero |= Mask;
783       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
784         assert(BitWidth >= 16 && "Unexpected width!");
785         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
786         KnownZero |= Mask;
787       }
788       break;
789     } break;
790     }
791   }
792   }
793 }
794 
795 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
796                                                   EVT) const {
797   return MVT::i64;
798 }
799 
800 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
801                                                            unsigned AddrSpace,
802                                                            unsigned Align,
803                                                            bool *Fast) const {
804   if (Subtarget->requiresStrictAlign())
805     return false;
806 
807   // FIXME: This is mostly true for Cyclone, but not necessarily others.
808   if (Fast) {
809     // FIXME: Define an attribute for slow unaligned accesses instead of
810     // relying on the CPU type as a proxy.
811     // On Cyclone, unaligned 128-bit stores are slow.
812     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
813             // See comments in performSTORECombine() for more details about
814             // these conditions.
815 
816             // Code that uses clang vector extensions can mark that it
817             // wants unaligned accesses to be treated as fast by
818             // underspecifying alignment to be 1 or 2.
819             Align <= 2 ||
820 
821             // Disregard v2i64. Memcpy lowering produces those and splitting
822             // them regresses performance on micro-benchmarks and olden/bh.
823             VT == MVT::v2i64;
824   }
825   return true;
826 }
827 
828 FastISel *
829 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
830                                       const TargetLibraryInfo *libInfo) const {
831   return AArch64::createFastISel(funcInfo, libInfo);
832 }
833 
834 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
835   switch ((AArch64ISD::NodeType)Opcode) {
836   case AArch64ISD::FIRST_NUMBER:      break;
837   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
838   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
839   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
840   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
841   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
842   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
843   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
844   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
845   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
846   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
847   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
848   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
849   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
850   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
851   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
852   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
853   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
854   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
855   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
856   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
857   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
858   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
859   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
860   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
861   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
862   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
863   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
864   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
865   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
866   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
867   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
868   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
869   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
870   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
871   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
872   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
873   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
874   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
875   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
876   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
877   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
878   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
879   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
880   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
881   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
882   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
883   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
884   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
885   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
886   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
887   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
888   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
889   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
890   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
891   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
892   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
893   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
894   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
895   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
896   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
897   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
898   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
899   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
900   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
901   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
902   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
903   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
904   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
905   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
906   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
907   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
908   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
909   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
910   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
911   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
912   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
913   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
914   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
915   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
916   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
917   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
918   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
919   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
920   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
921   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
922   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
923   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
924   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
925   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
926   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
927   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
928   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
929   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
930   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
931   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
932   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
933   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
934   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
935   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
936   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
937   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
938   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
939   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
940   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
941   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
942   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
943   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
944   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
945   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
946   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
947   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
948   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
949   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
950   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
951   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
952   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
953   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
954   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
955   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
956   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
957   }
958   return nullptr;
959 }
960 
961 MachineBasicBlock *
962 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
963                                     MachineBasicBlock *MBB) const {
964   // We materialise the F128CSEL pseudo-instruction as some control flow and a
965   // phi node:
966 
967   // OrigBB:
968   //     [... previous instrs leading to comparison ...]
969   //     b.ne TrueBB
970   //     b EndBB
971   // TrueBB:
972   //     ; Fallthrough
973   // EndBB:
974   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
975 
976   MachineFunction *MF = MBB->getParent();
977   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
978   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
979   DebugLoc DL = MI->getDebugLoc();
980   MachineFunction::iterator It = ++MBB->getIterator();
981 
982   unsigned DestReg = MI->getOperand(0).getReg();
983   unsigned IfTrueReg = MI->getOperand(1).getReg();
984   unsigned IfFalseReg = MI->getOperand(2).getReg();
985   unsigned CondCode = MI->getOperand(3).getImm();
986   bool NZCVKilled = MI->getOperand(4).isKill();
987 
988   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
989   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
990   MF->insert(It, TrueBB);
991   MF->insert(It, EndBB);
992 
993   // Transfer rest of current basic-block to EndBB
994   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
995                 MBB->end());
996   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
997 
998   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
999   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1000   MBB->addSuccessor(TrueBB);
1001   MBB->addSuccessor(EndBB);
1002 
1003   // TrueBB falls through to the end.
1004   TrueBB->addSuccessor(EndBB);
1005 
1006   if (!NZCVKilled) {
1007     TrueBB->addLiveIn(AArch64::NZCV);
1008     EndBB->addLiveIn(AArch64::NZCV);
1009   }
1010 
1011   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1012       .addReg(IfTrueReg)
1013       .addMBB(TrueBB)
1014       .addReg(IfFalseReg)
1015       .addMBB(MBB);
1016 
1017   MI->eraseFromParent();
1018   return EndBB;
1019 }
1020 
1021 MachineBasicBlock *
1022 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1023                                                  MachineBasicBlock *BB) const {
1024   switch (MI->getOpcode()) {
1025   default:
1026 #ifndef NDEBUG
1027     MI->dump();
1028 #endif
1029     llvm_unreachable("Unexpected instruction for custom inserter!");
1030 
1031   case AArch64::F128CSEL:
1032     return EmitF128CSEL(MI, BB);
1033 
1034   case TargetOpcode::STACKMAP:
1035   case TargetOpcode::PATCHPOINT:
1036     return emitPatchPoint(MI, BB);
1037   }
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 // AArch64 Lowering private implementation.
1042 //===----------------------------------------------------------------------===//
1043 
1044 //===----------------------------------------------------------------------===//
1045 // Lowering Code
1046 //===----------------------------------------------------------------------===//
1047 
1048 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1049 /// CC
1050 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1051   switch (CC) {
1052   default:
1053     llvm_unreachable("Unknown condition code!");
1054   case ISD::SETNE:
1055     return AArch64CC::NE;
1056   case ISD::SETEQ:
1057     return AArch64CC::EQ;
1058   case ISD::SETGT:
1059     return AArch64CC::GT;
1060   case ISD::SETGE:
1061     return AArch64CC::GE;
1062   case ISD::SETLT:
1063     return AArch64CC::LT;
1064   case ISD::SETLE:
1065     return AArch64CC::LE;
1066   case ISD::SETUGT:
1067     return AArch64CC::HI;
1068   case ISD::SETUGE:
1069     return AArch64CC::HS;
1070   case ISD::SETULT:
1071     return AArch64CC::LO;
1072   case ISD::SETULE:
1073     return AArch64CC::LS;
1074   }
1075 }
1076 
1077 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1078 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1079                                   AArch64CC::CondCode &CondCode,
1080                                   AArch64CC::CondCode &CondCode2) {
1081   CondCode2 = AArch64CC::AL;
1082   switch (CC) {
1083   default:
1084     llvm_unreachable("Unknown FP condition!");
1085   case ISD::SETEQ:
1086   case ISD::SETOEQ:
1087     CondCode = AArch64CC::EQ;
1088     break;
1089   case ISD::SETGT:
1090   case ISD::SETOGT:
1091     CondCode = AArch64CC::GT;
1092     break;
1093   case ISD::SETGE:
1094   case ISD::SETOGE:
1095     CondCode = AArch64CC::GE;
1096     break;
1097   case ISD::SETOLT:
1098     CondCode = AArch64CC::MI;
1099     break;
1100   case ISD::SETOLE:
1101     CondCode = AArch64CC::LS;
1102     break;
1103   case ISD::SETONE:
1104     CondCode = AArch64CC::MI;
1105     CondCode2 = AArch64CC::GT;
1106     break;
1107   case ISD::SETO:
1108     CondCode = AArch64CC::VC;
1109     break;
1110   case ISD::SETUO:
1111     CondCode = AArch64CC::VS;
1112     break;
1113   case ISD::SETUEQ:
1114     CondCode = AArch64CC::EQ;
1115     CondCode2 = AArch64CC::VS;
1116     break;
1117   case ISD::SETUGT:
1118     CondCode = AArch64CC::HI;
1119     break;
1120   case ISD::SETUGE:
1121     CondCode = AArch64CC::PL;
1122     break;
1123   case ISD::SETLT:
1124   case ISD::SETULT:
1125     CondCode = AArch64CC::LT;
1126     break;
1127   case ISD::SETLE:
1128   case ISD::SETULE:
1129     CondCode = AArch64CC::LE;
1130     break;
1131   case ISD::SETNE:
1132   case ISD::SETUNE:
1133     CondCode = AArch64CC::NE;
1134     break;
1135   }
1136 }
1137 
1138 /// Convert a DAG fp condition code to an AArch64 CC.
1139 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1140 /// should be AND'ed instead of OR'ed.
1141 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1142                                      AArch64CC::CondCode &CondCode,
1143                                      AArch64CC::CondCode &CondCode2) {
1144   CondCode2 = AArch64CC::AL;
1145   switch (CC) {
1146   default:
1147     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148     assert(CondCode2 == AArch64CC::AL);
1149     break;
1150   case ISD::SETONE:
1151     // (a one b)
1152     // == ((a olt b) || (a ogt b))
1153     // == ((a ord b) && (a une b))
1154     CondCode = AArch64CC::VC;
1155     CondCode2 = AArch64CC::NE;
1156     break;
1157   case ISD::SETUEQ:
1158     // (a ueq b)
1159     // == ((a uno b) || (a oeq b))
1160     // == ((a ule b) && (a uge b))
1161     CondCode = AArch64CC::PL;
1162     CondCode2 = AArch64CC::LE;
1163     break;
1164   }
1165 }
1166 
1167 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1168 /// CC usable with the vector instructions. Fewer operations are available
1169 /// without a real NZCV register, so we have to use less efficient combinations
1170 /// to get the same effect.
1171 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1172                                         AArch64CC::CondCode &CondCode,
1173                                         AArch64CC::CondCode &CondCode2,
1174                                         bool &Invert) {
1175   Invert = false;
1176   switch (CC) {
1177   default:
1178     // Mostly the scalar mappings work fine.
1179     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1180     break;
1181   case ISD::SETUO:
1182     Invert = true; // Fallthrough
1183   case ISD::SETO:
1184     CondCode = AArch64CC::MI;
1185     CondCode2 = AArch64CC::GE;
1186     break;
1187   case ISD::SETUEQ:
1188   case ISD::SETULT:
1189   case ISD::SETULE:
1190   case ISD::SETUGT:
1191   case ISD::SETUGE:
1192     // All of the compare-mask comparisons are ordered, but we can switch
1193     // between the two by a double inversion. E.g. ULE == !OGT.
1194     Invert = true;
1195     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1196     break;
1197   }
1198 }
1199 
1200 static bool isLegalArithImmed(uint64_t C) {
1201   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1202   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1203 }
1204 
1205 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1206                               SDLoc dl, SelectionDAG &DAG) {
1207   EVT VT = LHS.getValueType();
1208 
1209   if (VT.isFloatingPoint())
1210     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1211 
1212   // The CMP instruction is just an alias for SUBS, and representing it as
1213   // SUBS means that it's possible to get CSE with subtract operations.
1214   // A later phase can perform the optimization of setting the destination
1215   // register to WZR/XZR if it ends up being unused.
1216   unsigned Opcode = AArch64ISD::SUBS;
1217 
1218   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1219       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1220     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1221     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1222     // can be set differently by this operation. It comes down to whether
1223     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1224     // everything is fine. If not then the optimization is wrong. Thus general
1225     // comparisons are only valid if op2 != 0.
1226 
1227     // So, finally, the only LLVM-native comparisons that don't mention C and V
1228     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1229     // the absence of information about op2.
1230     Opcode = AArch64ISD::ADDS;
1231     RHS = RHS.getOperand(1);
1232   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1233              !isUnsignedIntSetCC(CC)) {
1234     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1235     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1236     // of the signed comparisons.
1237     Opcode = AArch64ISD::ANDS;
1238     RHS = LHS.getOperand(1);
1239     LHS = LHS.getOperand(0);
1240   }
1241 
1242   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1243       .getValue(1);
1244 }
1245 
1246 /// \defgroup AArch64CCMP CMP;CCMP matching
1247 ///
1248 /// These functions deal with the formation of CMP;CCMP;... sequences.
1249 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1250 /// a comparison. They set the NZCV flags to a predefined value if their
1251 /// predicate is false. This allows to express arbitrary conjunctions, for
1252 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1253 /// expressed as:
1254 ///   cmp A
1255 ///   ccmp B, inv(CB), CA
1256 ///   check for CB flags
1257 ///
1258 /// In general we can create code for arbitrary "... (and (and A B) C)"
1259 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1260 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1261 /// negation operations:
1262 /// We can negate the results of a single comparison by inverting the flags
1263 /// used when the predicate fails and inverting the flags tested in the next
1264 /// instruction; We can also negate the results of the whole previous
1265 /// conditional compare sequence by inverting the flags tested in the next
1266 /// instruction. However there is no way to negate the result of a partial
1267 /// sequence.
1268 ///
1269 /// Therefore on encountering an "or" expression we can negate the subtree on
1270 /// one side and have to be able to push the negate to the leafs of the subtree
1271 /// on the other side (see also the comments in code). As complete example:
1272 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1273 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1274 /// is transformed to
1275 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1276 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1277 /// and implemented as:
1278 ///   cmp C
1279 ///   ccmp D, inv(CD), CC
1280 ///   ccmp A, CA, inv(CD)
1281 ///   ccmp B, CB, inv(CA)
1282 ///   check for CB flags
1283 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1284 /// by conditional compare sequences.
1285 /// @{
1286 
1287 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1288 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1289                                          ISD::CondCode CC, SDValue CCOp,
1290                                          AArch64CC::CondCode Predicate,
1291                                          AArch64CC::CondCode OutCC,
1292                                          SDLoc DL, SelectionDAG &DAG) {
1293   unsigned Opcode = 0;
1294   if (LHS.getValueType().isFloatingPoint())
1295     Opcode = AArch64ISD::FCCMP;
1296   else if (RHS.getOpcode() == ISD::SUB) {
1297     SDValue SubOp0 = RHS.getOperand(0);
1298     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1299       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1300       Opcode = AArch64ISD::CCMN;
1301       RHS = RHS.getOperand(1);
1302     }
1303   }
1304   if (Opcode == 0)
1305     Opcode = AArch64ISD::CCMP;
1306 
1307   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1308   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1309   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1310   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1311   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1312 }
1313 
1314 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1315 /// CanPushNegate is set to true if we can push a negate operation through
1316 /// the tree in a was that we are left with AND operations and negate operations
1317 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1318 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1319 /// brought into such a form.
1320 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1321                                          unsigned Depth = 0) {
1322   if (!Val.hasOneUse())
1323     return false;
1324   unsigned Opcode = Val->getOpcode();
1325   if (Opcode == ISD::SETCC) {
1326     CanNegate = true;
1327     return true;
1328   }
1329   // Protect against exponential runtime and stack overflow.
1330   if (Depth > 6)
1331     return false;
1332   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1333     SDValue O0 = Val->getOperand(0);
1334     SDValue O1 = Val->getOperand(1);
1335     bool CanNegateL;
1336     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1337       return false;
1338     bool CanNegateR;
1339     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1340       return false;
1341 
1342     if (Opcode == ISD::OR) {
1343       // For an OR expression we need to be able to negate at least one side or
1344       // we cannot do the transformation at all.
1345       if (!CanNegateL && !CanNegateR)
1346         return false;
1347       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1348       // can negate the x and y subtrees.
1349       CanNegate = CanNegateL && CanNegateR;
1350     } else {
1351       // If the operands are OR expressions then we finally need to negate their
1352       // outputs, we can only do that for the operand with emitted last by
1353       // negating OutCC, not for both operands.
1354       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1355       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1356       if (NeedsNegOutL && NeedsNegOutR)
1357         return false;
1358       // We cannot negate an AND operation (it would become an OR),
1359       CanNegate = false;
1360     }
1361     return true;
1362   }
1363   return false;
1364 }
1365 
1366 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1367 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1368 /// Tries to transform the given i1 producing node @p Val to a series compare
1369 /// and conditional compare operations. @returns an NZCV flags producing node
1370 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1371 /// transformation was not possible.
1372 /// On recursive invocations @p PushNegate may be set to true to have negation
1373 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1374 /// for the comparisons in the current subtree; @p Depth limits the search
1375 /// depth to avoid stack overflow.
1376 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1377     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1378     AArch64CC::CondCode Predicate) {
1379   // We're at a tree leaf, produce a conditional comparison operation.
1380   unsigned Opcode = Val->getOpcode();
1381   if (Opcode == ISD::SETCC) {
1382     SDValue LHS = Val->getOperand(0);
1383     SDValue RHS = Val->getOperand(1);
1384     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1385     bool isInteger = LHS.getValueType().isInteger();
1386     if (Negate)
1387       CC = getSetCCInverse(CC, isInteger);
1388     SDLoc DL(Val);
1389     // Determine OutCC and handle FP special case.
1390     if (isInteger) {
1391       OutCC = changeIntCCToAArch64CC(CC);
1392     } else {
1393       assert(LHS.getValueType().isFloatingPoint());
1394       AArch64CC::CondCode ExtraCC;
1395       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1396       // Some floating point conditions can't be tested with a single condition
1397       // code. Construct an additional comparison in this case.
1398       if (ExtraCC != AArch64CC::AL) {
1399         SDValue ExtraCmp;
1400         if (!CCOp.getNode())
1401           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1402         else
1403           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1404                                                ExtraCC, DL, DAG);
1405         CCOp = ExtraCmp;
1406         Predicate = ExtraCC;
1407       }
1408     }
1409 
1410     // Produce a normal comparison if we are first in the chain
1411     if (!CCOp)
1412       return emitComparison(LHS, RHS, CC, DL, DAG);
1413     // Otherwise produce a ccmp.
1414     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1415                                      DAG);
1416   }
1417   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1418          "Valid conjunction/disjunction tree");
1419 
1420   // Check if both sides can be transformed.
1421   SDValue LHS = Val->getOperand(0);
1422   SDValue RHS = Val->getOperand(1);
1423 
1424   // In case of an OR we need to negate our operands and the result.
1425   // (A v B) <=> not(not(A) ^ not(B))
1426   bool NegateOpsAndResult = Opcode == ISD::OR;
1427   // We can negate the results of all previous operations by inverting the
1428   // predicate flags giving us a free negation for one side. The other side
1429   // must be negatable by itself.
1430   if (NegateOpsAndResult) {
1431     // See which side we can negate.
1432     bool CanNegateL;
1433     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1434     assert(isValidL && "Valid conjunction/disjunction tree");
1435     (void)isValidL;
1436 
1437 #ifndef NDEBUG
1438     bool CanNegateR;
1439     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1440     assert(isValidR && "Valid conjunction/disjunction tree");
1441     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1442 #endif
1443 
1444     // Order the side which we cannot negate to RHS so we can emit it first.
1445     if (!CanNegateL)
1446       std::swap(LHS, RHS);
1447   } else {
1448     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1449     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1450            "Valid conjunction/disjunction tree");
1451     // Order the side where we need to negate the output flags to RHS so it
1452     // gets emitted first.
1453     if (NeedsNegOutL)
1454       std::swap(LHS, RHS);
1455   }
1456 
1457   // Emit RHS. If we want to negate the tree we only need to push a negate
1458   // through if we are already in a PushNegate case, otherwise we can negate
1459   // the "flags to test" afterwards.
1460   AArch64CC::CondCode RHSCC;
1461   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1462                                                    CCOp, Predicate);
1463   if (NegateOpsAndResult && !Negate)
1464     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1465   // Emit LHS. We may need to negate it.
1466   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1467                                                    NegateOpsAndResult, CmpR,
1468                                                    RHSCC);
1469   // If we transformed an OR to and AND then we have to negate the result
1470   // (or absorb the Negate parameter).
1471   if (NegateOpsAndResult && !Negate)
1472     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1473   return CmpL;
1474 }
1475 
1476 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1477 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1478 /// \see emitConjunctionDisjunctionTreeRec().
1479 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1480                                               AArch64CC::CondCode &OutCC) {
1481   bool CanNegate;
1482   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1483     return SDValue();
1484 
1485   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1486                                            AArch64CC::AL);
1487 }
1488 
1489 /// @}
1490 
1491 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1492                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1493   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1494     EVT VT = RHS.getValueType();
1495     uint64_t C = RHSC->getZExtValue();
1496     if (!isLegalArithImmed(C)) {
1497       // Constant does not fit, try adjusting it by one?
1498       switch (CC) {
1499       default:
1500         break;
1501       case ISD::SETLT:
1502       case ISD::SETGE:
1503         if ((VT == MVT::i32 && C != 0x80000000 &&
1504              isLegalArithImmed((uint32_t)(C - 1))) ||
1505             (VT == MVT::i64 && C != 0x80000000ULL &&
1506              isLegalArithImmed(C - 1ULL))) {
1507           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1508           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1509           RHS = DAG.getConstant(C, dl, VT);
1510         }
1511         break;
1512       case ISD::SETULT:
1513       case ISD::SETUGE:
1514         if ((VT == MVT::i32 && C != 0 &&
1515              isLegalArithImmed((uint32_t)(C - 1))) ||
1516             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1517           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1518           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1519           RHS = DAG.getConstant(C, dl, VT);
1520         }
1521         break;
1522       case ISD::SETLE:
1523       case ISD::SETGT:
1524         if ((VT == MVT::i32 && C != INT32_MAX &&
1525              isLegalArithImmed((uint32_t)(C + 1))) ||
1526             (VT == MVT::i64 && C != INT64_MAX &&
1527              isLegalArithImmed(C + 1ULL))) {
1528           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1529           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1530           RHS = DAG.getConstant(C, dl, VT);
1531         }
1532         break;
1533       case ISD::SETULE:
1534       case ISD::SETUGT:
1535         if ((VT == MVT::i32 && C != UINT32_MAX &&
1536              isLegalArithImmed((uint32_t)(C + 1))) ||
1537             (VT == MVT::i64 && C != UINT64_MAX &&
1538              isLegalArithImmed(C + 1ULL))) {
1539           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1540           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1541           RHS = DAG.getConstant(C, dl, VT);
1542         }
1543         break;
1544       }
1545     }
1546   }
1547   SDValue Cmp;
1548   AArch64CC::CondCode AArch64CC;
1549   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1550     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1551 
1552     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1553     // For the i8 operand, the largest immediate is 255, so this can be easily
1554     // encoded in the compare instruction. For the i16 operand, however, the
1555     // largest immediate cannot be encoded in the compare.
1556     // Therefore, use a sign extending load and cmn to avoid materializing the
1557     // -1 constant. For example,
1558     // movz w1, #65535
1559     // ldrh w0, [x0, #0]
1560     // cmp w0, w1
1561     // >
1562     // ldrsh w0, [x0, #0]
1563     // cmn w0, #1
1564     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1565     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1566     // ensure both the LHS and RHS are truly zero extended and to make sure the
1567     // transformation is profitable.
1568     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1569         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1570         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1571         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1572       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1573       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1574         SDValue SExt =
1575             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1576                         DAG.getValueType(MVT::i16));
1577         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1578                                                    RHS.getValueType()),
1579                              CC, dl, DAG);
1580         AArch64CC = changeIntCCToAArch64CC(CC);
1581       }
1582     }
1583 
1584     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1585       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1586         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1587           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1588       }
1589     }
1590   }
1591 
1592   if (!Cmp) {
1593     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1594     AArch64CC = changeIntCCToAArch64CC(CC);
1595   }
1596   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1597   return Cmp;
1598 }
1599 
1600 static std::pair<SDValue, SDValue>
1601 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1602   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1603          "Unsupported value type");
1604   SDValue Value, Overflow;
1605   SDLoc DL(Op);
1606   SDValue LHS = Op.getOperand(0);
1607   SDValue RHS = Op.getOperand(1);
1608   unsigned Opc = 0;
1609   switch (Op.getOpcode()) {
1610   default:
1611     llvm_unreachable("Unknown overflow instruction!");
1612   case ISD::SADDO:
1613     Opc = AArch64ISD::ADDS;
1614     CC = AArch64CC::VS;
1615     break;
1616   case ISD::UADDO:
1617     Opc = AArch64ISD::ADDS;
1618     CC = AArch64CC::HS;
1619     break;
1620   case ISD::SSUBO:
1621     Opc = AArch64ISD::SUBS;
1622     CC = AArch64CC::VS;
1623     break;
1624   case ISD::USUBO:
1625     Opc = AArch64ISD::SUBS;
1626     CC = AArch64CC::LO;
1627     break;
1628   // Multiply needs a little bit extra work.
1629   case ISD::SMULO:
1630   case ISD::UMULO: {
1631     CC = AArch64CC::NE;
1632     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1633     if (Op.getValueType() == MVT::i32) {
1634       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1635       // For a 32 bit multiply with overflow check we want the instruction
1636       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1637       // need to generate the following pattern:
1638       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1639       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1640       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1641       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1642       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1643                                 DAG.getConstant(0, DL, MVT::i64));
1644       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1645       // operation. We need to clear out the upper 32 bits, because we used a
1646       // widening multiply that wrote all 64 bits. In the end this should be a
1647       // noop.
1648       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1649       if (IsSigned) {
1650         // The signed overflow check requires more than just a simple check for
1651         // any bit set in the upper 32 bits of the result. These bits could be
1652         // just the sign bits of a negative number. To perform the overflow
1653         // check we have to arithmetic shift right the 32nd bit of the result by
1654         // 31 bits. Then we compare the result to the upper 32 bits.
1655         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1656                                         DAG.getConstant(32, DL, MVT::i64));
1657         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1658         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1659                                         DAG.getConstant(31, DL, MVT::i64));
1660         // It is important that LowerBits is last, otherwise the arithmetic
1661         // shift will not be folded into the compare (SUBS).
1662         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1663         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1664                        .getValue(1);
1665       } else {
1666         // The overflow check for unsigned multiply is easy. We only need to
1667         // check if any of the upper 32 bits are set. This can be done with a
1668         // CMP (shifted register). For that we need to generate the following
1669         // pattern:
1670         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1671         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1672                                         DAG.getConstant(32, DL, MVT::i64));
1673         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1674         Overflow =
1675             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1676                         DAG.getConstant(0, DL, MVT::i64),
1677                         UpperBits).getValue(1);
1678       }
1679       break;
1680     }
1681     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1682     // For the 64 bit multiply
1683     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1684     if (IsSigned) {
1685       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1686       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1687                                       DAG.getConstant(63, DL, MVT::i64));
1688       // It is important that LowerBits is last, otherwise the arithmetic
1689       // shift will not be folded into the compare (SUBS).
1690       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1691       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1692                      .getValue(1);
1693     } else {
1694       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1695       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1696       Overflow =
1697           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1698                       DAG.getConstant(0, DL, MVT::i64),
1699                       UpperBits).getValue(1);
1700     }
1701     break;
1702   }
1703   } // switch (...)
1704 
1705   if (Opc) {
1706     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1707 
1708     // Emit the AArch64 operation with overflow check.
1709     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1710     Overflow = Value.getValue(1);
1711   }
1712   return std::make_pair(Value, Overflow);
1713 }
1714 
1715 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1716                                              RTLIB::Libcall Call) const {
1717   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1718   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1719 }
1720 
1721 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1722   SDValue Sel = Op.getOperand(0);
1723   SDValue Other = Op.getOperand(1);
1724 
1725   // If neither operand is a SELECT_CC, give up.
1726   if (Sel.getOpcode() != ISD::SELECT_CC)
1727     std::swap(Sel, Other);
1728   if (Sel.getOpcode() != ISD::SELECT_CC)
1729     return Op;
1730 
1731   // The folding we want to perform is:
1732   // (xor x, (select_cc a, b, cc, 0, -1) )
1733   //   -->
1734   // (csel x, (xor x, -1), cc ...)
1735   //
1736   // The latter will get matched to a CSINV instruction.
1737 
1738   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1739   SDValue LHS = Sel.getOperand(0);
1740   SDValue RHS = Sel.getOperand(1);
1741   SDValue TVal = Sel.getOperand(2);
1742   SDValue FVal = Sel.getOperand(3);
1743   SDLoc dl(Sel);
1744 
1745   // FIXME: This could be generalized to non-integer comparisons.
1746   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1747     return Op;
1748 
1749   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1750   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1751 
1752   // The values aren't constants, this isn't the pattern we're looking for.
1753   if (!CFVal || !CTVal)
1754     return Op;
1755 
1756   // We can commute the SELECT_CC by inverting the condition.  This
1757   // might be needed to make this fit into a CSINV pattern.
1758   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1759     std::swap(TVal, FVal);
1760     std::swap(CTVal, CFVal);
1761     CC = ISD::getSetCCInverse(CC, true);
1762   }
1763 
1764   // If the constants line up, perform the transform!
1765   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1766     SDValue CCVal;
1767     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1768 
1769     FVal = Other;
1770     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1771                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1772 
1773     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1774                        CCVal, Cmp);
1775   }
1776 
1777   return Op;
1778 }
1779 
1780 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1781   EVT VT = Op.getValueType();
1782 
1783   // Let legalize expand this if it isn't a legal type yet.
1784   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1785     return SDValue();
1786 
1787   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1788 
1789   unsigned Opc;
1790   bool ExtraOp = false;
1791   switch (Op.getOpcode()) {
1792   default:
1793     llvm_unreachable("Invalid code");
1794   case ISD::ADDC:
1795     Opc = AArch64ISD::ADDS;
1796     break;
1797   case ISD::SUBC:
1798     Opc = AArch64ISD::SUBS;
1799     break;
1800   case ISD::ADDE:
1801     Opc = AArch64ISD::ADCS;
1802     ExtraOp = true;
1803     break;
1804   case ISD::SUBE:
1805     Opc = AArch64ISD::SBCS;
1806     ExtraOp = true;
1807     break;
1808   }
1809 
1810   if (!ExtraOp)
1811     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1812   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1813                      Op.getOperand(2));
1814 }
1815 
1816 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1817   // Let legalize expand this if it isn't a legal type yet.
1818   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1819     return SDValue();
1820 
1821   SDLoc dl(Op);
1822   AArch64CC::CondCode CC;
1823   // The actual operation that sets the overflow or carry flag.
1824   SDValue Value, Overflow;
1825   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1826 
1827   // We use 0 and 1 as false and true values.
1828   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1829   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1830 
1831   // We use an inverted condition, because the conditional select is inverted
1832   // too. This will allow it to be selected to a single instruction:
1833   // CSINC Wd, WZR, WZR, invert(cond).
1834   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1835   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1836                          CCVal, Overflow);
1837 
1838   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1839   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1840 }
1841 
1842 // Prefetch operands are:
1843 // 1: Address to prefetch
1844 // 2: bool isWrite
1845 // 3: int locality (0 = no locality ... 3 = extreme locality)
1846 // 4: bool isDataCache
1847 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1848   SDLoc DL(Op);
1849   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1850   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1851   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1852 
1853   bool IsStream = !Locality;
1854   // When the locality number is set
1855   if (Locality) {
1856     // The front-end should have filtered out the out-of-range values
1857     assert(Locality <= 3 && "Prefetch locality out-of-range");
1858     // The locality degree is the opposite of the cache speed.
1859     // Put the number the other way around.
1860     // The encoding starts at 0 for level 1
1861     Locality = 3 - Locality;
1862   }
1863 
1864   // built the mask value encoding the expected behavior.
1865   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1866                    (!IsData << 3) |     // IsDataCache bit
1867                    (Locality << 1) |    // Cache level bits
1868                    (unsigned)IsStream;  // Stream bit
1869   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1870                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1871 }
1872 
1873 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1874                                               SelectionDAG &DAG) const {
1875   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1876 
1877   RTLIB::Libcall LC;
1878   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1879 
1880   return LowerF128Call(Op, DAG, LC);
1881 }
1882 
1883 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1884                                              SelectionDAG &DAG) const {
1885   if (Op.getOperand(0).getValueType() != MVT::f128) {
1886     // It's legal except when f128 is involved
1887     return Op;
1888   }
1889 
1890   RTLIB::Libcall LC;
1891   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1892 
1893   // FP_ROUND node has a second operand indicating whether it is known to be
1894   // precise. That doesn't take part in the LibCall so we can't directly use
1895   // LowerF128Call.
1896   SDValue SrcVal = Op.getOperand(0);
1897   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1898                      SDLoc(Op)).first;
1899 }
1900 
1901 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1902   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1903   // Any additional optimization in this function should be recorded
1904   // in the cost tables.
1905   EVT InVT = Op.getOperand(0).getValueType();
1906   EVT VT = Op.getValueType();
1907   unsigned NumElts = InVT.getVectorNumElements();
1908 
1909   // f16 vectors are promoted to f32 before a conversion.
1910   if (InVT.getVectorElementType() == MVT::f16) {
1911     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1912     SDLoc dl(Op);
1913     return DAG.getNode(
1914         Op.getOpcode(), dl, Op.getValueType(),
1915         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1916   }
1917 
1918   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1919     SDLoc dl(Op);
1920     SDValue Cv =
1921         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1922                     Op.getOperand(0));
1923     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1924   }
1925 
1926   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1927     SDLoc dl(Op);
1928     MVT ExtVT =
1929         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1930                          VT.getVectorNumElements());
1931     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1932     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1933   }
1934 
1935   // Type changing conversions are illegal.
1936   return Op;
1937 }
1938 
1939 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1940                                               SelectionDAG &DAG) const {
1941   if (Op.getOperand(0).getValueType().isVector())
1942     return LowerVectorFP_TO_INT(Op, DAG);
1943 
1944   // f16 conversions are promoted to f32.
1945   if (Op.getOperand(0).getValueType() == MVT::f16) {
1946     SDLoc dl(Op);
1947     return DAG.getNode(
1948         Op.getOpcode(), dl, Op.getValueType(),
1949         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1950   }
1951 
1952   if (Op.getOperand(0).getValueType() != MVT::f128) {
1953     // It's legal except when f128 is involved
1954     return Op;
1955   }
1956 
1957   RTLIB::Libcall LC;
1958   if (Op.getOpcode() == ISD::FP_TO_SINT)
1959     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1960   else
1961     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1962 
1963   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1964   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1965 }
1966 
1967 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1968   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1969   // Any additional optimization in this function should be recorded
1970   // in the cost tables.
1971   EVT VT = Op.getValueType();
1972   SDLoc dl(Op);
1973   SDValue In = Op.getOperand(0);
1974   EVT InVT = In.getValueType();
1975 
1976   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1977     MVT CastVT =
1978         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1979                          InVT.getVectorNumElements());
1980     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1981     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1982   }
1983 
1984   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1985     unsigned CastOpc =
1986         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1987     EVT CastVT = VT.changeVectorElementTypeToInteger();
1988     In = DAG.getNode(CastOpc, dl, CastVT, In);
1989     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1990   }
1991 
1992   return Op;
1993 }
1994 
1995 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1996                                             SelectionDAG &DAG) const {
1997   if (Op.getValueType().isVector())
1998     return LowerVectorINT_TO_FP(Op, DAG);
1999 
2000   // f16 conversions are promoted to f32.
2001   if (Op.getValueType() == MVT::f16) {
2002     SDLoc dl(Op);
2003     return DAG.getNode(
2004         ISD::FP_ROUND, dl, MVT::f16,
2005         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2006         DAG.getIntPtrConstant(0, dl));
2007   }
2008 
2009   // i128 conversions are libcalls.
2010   if (Op.getOperand(0).getValueType() == MVT::i128)
2011     return SDValue();
2012 
2013   // Other conversions are legal, unless it's to the completely software-based
2014   // fp128.
2015   if (Op.getValueType() != MVT::f128)
2016     return Op;
2017 
2018   RTLIB::Libcall LC;
2019   if (Op.getOpcode() == ISD::SINT_TO_FP)
2020     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2021   else
2022     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2023 
2024   return LowerF128Call(Op, DAG, LC);
2025 }
2026 
2027 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2028                                             SelectionDAG &DAG) const {
2029   // For iOS, we want to call an alternative entry point: __sincos_stret,
2030   // which returns the values in two S / D registers.
2031   SDLoc dl(Op);
2032   SDValue Arg = Op.getOperand(0);
2033   EVT ArgVT = Arg.getValueType();
2034   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2035 
2036   ArgListTy Args;
2037   ArgListEntry Entry;
2038 
2039   Entry.Node = Arg;
2040   Entry.Ty = ArgTy;
2041   Entry.isSExt = false;
2042   Entry.isZExt = false;
2043   Args.push_back(Entry);
2044 
2045   const char *LibcallName =
2046       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2047   SDValue Callee =
2048       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2049 
2050   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2051   TargetLowering::CallLoweringInfo CLI(DAG);
2052   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2053     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
2054 
2055   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2056   return CallResult.first;
2057 }
2058 
2059 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2060   if (Op.getValueType() != MVT::f16)
2061     return SDValue();
2062 
2063   assert(Op.getOperand(0).getValueType() == MVT::i16);
2064   SDLoc DL(Op);
2065 
2066   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2067   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2068   return SDValue(
2069       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2070                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2071       0);
2072 }
2073 
2074 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2075   if (OrigVT.getSizeInBits() >= 64)
2076     return OrigVT;
2077 
2078   assert(OrigVT.isSimple() && "Expecting a simple value type");
2079 
2080   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2081   switch (OrigSimpleTy) {
2082   default: llvm_unreachable("Unexpected Vector Type");
2083   case MVT::v2i8:
2084   case MVT::v2i16:
2085      return MVT::v2i32;
2086   case MVT::v4i8:
2087     return  MVT::v4i16;
2088   }
2089 }
2090 
2091 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2092                                                  const EVT &OrigTy,
2093                                                  const EVT &ExtTy,
2094                                                  unsigned ExtOpcode) {
2095   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2096   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2097   // 64-bits we need to insert a new extension so that it will be 64-bits.
2098   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2099   if (OrigTy.getSizeInBits() >= 64)
2100     return N;
2101 
2102   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2103   EVT NewVT = getExtensionTo64Bits(OrigTy);
2104 
2105   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2106 }
2107 
2108 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2109                                    bool isSigned) {
2110   EVT VT = N->getValueType(0);
2111 
2112   if (N->getOpcode() != ISD::BUILD_VECTOR)
2113     return false;
2114 
2115   for (const SDValue &Elt : N->op_values()) {
2116     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2117       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2118       unsigned HalfSize = EltSize / 2;
2119       if (isSigned) {
2120         if (!isIntN(HalfSize, C->getSExtValue()))
2121           return false;
2122       } else {
2123         if (!isUIntN(HalfSize, C->getZExtValue()))
2124           return false;
2125       }
2126       continue;
2127     }
2128     return false;
2129   }
2130 
2131   return true;
2132 }
2133 
2134 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2135   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2136     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2137                                              N->getOperand(0)->getValueType(0),
2138                                              N->getValueType(0),
2139                                              N->getOpcode());
2140 
2141   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2142   EVT VT = N->getValueType(0);
2143   SDLoc dl(N);
2144   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2145   unsigned NumElts = VT.getVectorNumElements();
2146   MVT TruncVT = MVT::getIntegerVT(EltSize);
2147   SmallVector<SDValue, 8> Ops;
2148   for (unsigned i = 0; i != NumElts; ++i) {
2149     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2150     const APInt &CInt = C->getAPIntValue();
2151     // Element types smaller than 32 bits are not legal, so use i32 elements.
2152     // The values are implicitly truncated so sext vs. zext doesn't matter.
2153     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2154   }
2155   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2156                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2157 }
2158 
2159 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2160   if (N->getOpcode() == ISD::SIGN_EXTEND)
2161     return true;
2162   if (isExtendedBUILD_VECTOR(N, DAG, true))
2163     return true;
2164   return false;
2165 }
2166 
2167 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2168   if (N->getOpcode() == ISD::ZERO_EXTEND)
2169     return true;
2170   if (isExtendedBUILD_VECTOR(N, DAG, false))
2171     return true;
2172   return false;
2173 }
2174 
2175 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2176   unsigned Opcode = N->getOpcode();
2177   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2178     SDNode *N0 = N->getOperand(0).getNode();
2179     SDNode *N1 = N->getOperand(1).getNode();
2180     return N0->hasOneUse() && N1->hasOneUse() &&
2181       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2182   }
2183   return false;
2184 }
2185 
2186 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2187   unsigned Opcode = N->getOpcode();
2188   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2189     SDNode *N0 = N->getOperand(0).getNode();
2190     SDNode *N1 = N->getOperand(1).getNode();
2191     return N0->hasOneUse() && N1->hasOneUse() &&
2192       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2193   }
2194   return false;
2195 }
2196 
2197 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2198   // Multiplications are only custom-lowered for 128-bit vectors so that
2199   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2200   EVT VT = Op.getValueType();
2201   assert(VT.is128BitVector() && VT.isInteger() &&
2202          "unexpected type for custom-lowering ISD::MUL");
2203   SDNode *N0 = Op.getOperand(0).getNode();
2204   SDNode *N1 = Op.getOperand(1).getNode();
2205   unsigned NewOpc = 0;
2206   bool isMLA = false;
2207   bool isN0SExt = isSignExtended(N0, DAG);
2208   bool isN1SExt = isSignExtended(N1, DAG);
2209   if (isN0SExt && isN1SExt)
2210     NewOpc = AArch64ISD::SMULL;
2211   else {
2212     bool isN0ZExt = isZeroExtended(N0, DAG);
2213     bool isN1ZExt = isZeroExtended(N1, DAG);
2214     if (isN0ZExt && isN1ZExt)
2215       NewOpc = AArch64ISD::UMULL;
2216     else if (isN1SExt || isN1ZExt) {
2217       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2218       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2219       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2220         NewOpc = AArch64ISD::SMULL;
2221         isMLA = true;
2222       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2223         NewOpc =  AArch64ISD::UMULL;
2224         isMLA = true;
2225       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2226         std::swap(N0, N1);
2227         NewOpc =  AArch64ISD::UMULL;
2228         isMLA = true;
2229       }
2230     }
2231 
2232     if (!NewOpc) {
2233       if (VT == MVT::v2i64)
2234         // Fall through to expand this.  It is not legal.
2235         return SDValue();
2236       else
2237         // Other vector multiplications are legal.
2238         return Op;
2239     }
2240   }
2241 
2242   // Legalize to a S/UMULL instruction
2243   SDLoc DL(Op);
2244   SDValue Op0;
2245   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2246   if (!isMLA) {
2247     Op0 = skipExtensionForVectorMULL(N0, DAG);
2248     assert(Op0.getValueType().is64BitVector() &&
2249            Op1.getValueType().is64BitVector() &&
2250            "unexpected types for extended operands to VMULL");
2251     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2252   }
2253   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2254   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2255   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2256   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2257   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2258   EVT Op1VT = Op1.getValueType();
2259   return DAG.getNode(N0->getOpcode(), DL, VT,
2260                      DAG.getNode(NewOpc, DL, VT,
2261                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2262                      DAG.getNode(NewOpc, DL, VT,
2263                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2264 }
2265 
2266 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2267                                                      SelectionDAG &DAG) const {
2268   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2269   SDLoc dl(Op);
2270   switch (IntNo) {
2271   default: return SDValue();    // Don't custom lower most intrinsics.
2272   case Intrinsic::aarch64_thread_pointer: {
2273     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2274     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2275   }
2276   case Intrinsic::aarch64_neon_smax:
2277     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2278                        Op.getOperand(1), Op.getOperand(2));
2279   case Intrinsic::aarch64_neon_umax:
2280     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2281                        Op.getOperand(1), Op.getOperand(2));
2282   case Intrinsic::aarch64_neon_smin:
2283     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2284                        Op.getOperand(1), Op.getOperand(2));
2285   case Intrinsic::aarch64_neon_umin:
2286     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2287                        Op.getOperand(1), Op.getOperand(2));
2288   }
2289 }
2290 
2291 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2292                                               SelectionDAG &DAG) const {
2293   switch (Op.getOpcode()) {
2294   default:
2295     llvm_unreachable("unimplemented operand");
2296     return SDValue();
2297   case ISD::BITCAST:
2298     return LowerBITCAST(Op, DAG);
2299   case ISD::GlobalAddress:
2300     return LowerGlobalAddress(Op, DAG);
2301   case ISD::GlobalTLSAddress:
2302     return LowerGlobalTLSAddress(Op, DAG);
2303   case ISD::SETCC:
2304     return LowerSETCC(Op, DAG);
2305   case ISD::BR_CC:
2306     return LowerBR_CC(Op, DAG);
2307   case ISD::SELECT:
2308     return LowerSELECT(Op, DAG);
2309   case ISD::SELECT_CC:
2310     return LowerSELECT_CC(Op, DAG);
2311   case ISD::JumpTable:
2312     return LowerJumpTable(Op, DAG);
2313   case ISD::ConstantPool:
2314     return LowerConstantPool(Op, DAG);
2315   case ISD::BlockAddress:
2316     return LowerBlockAddress(Op, DAG);
2317   case ISD::VASTART:
2318     return LowerVASTART(Op, DAG);
2319   case ISD::VACOPY:
2320     return LowerVACOPY(Op, DAG);
2321   case ISD::VAARG:
2322     return LowerVAARG(Op, DAG);
2323   case ISD::ADDC:
2324   case ISD::ADDE:
2325   case ISD::SUBC:
2326   case ISD::SUBE:
2327     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2328   case ISD::SADDO:
2329   case ISD::UADDO:
2330   case ISD::SSUBO:
2331   case ISD::USUBO:
2332   case ISD::SMULO:
2333   case ISD::UMULO:
2334     return LowerXALUO(Op, DAG);
2335   case ISD::FADD:
2336     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2337   case ISD::FSUB:
2338     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2339   case ISD::FMUL:
2340     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2341   case ISD::FDIV:
2342     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2343   case ISD::FP_ROUND:
2344     return LowerFP_ROUND(Op, DAG);
2345   case ISD::FP_EXTEND:
2346     return LowerFP_EXTEND(Op, DAG);
2347   case ISD::FRAMEADDR:
2348     return LowerFRAMEADDR(Op, DAG);
2349   case ISD::RETURNADDR:
2350     return LowerRETURNADDR(Op, DAG);
2351   case ISD::INSERT_VECTOR_ELT:
2352     return LowerINSERT_VECTOR_ELT(Op, DAG);
2353   case ISD::EXTRACT_VECTOR_ELT:
2354     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2355   case ISD::BUILD_VECTOR:
2356     return LowerBUILD_VECTOR(Op, DAG);
2357   case ISD::VECTOR_SHUFFLE:
2358     return LowerVECTOR_SHUFFLE(Op, DAG);
2359   case ISD::EXTRACT_SUBVECTOR:
2360     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2361   case ISD::SRA:
2362   case ISD::SRL:
2363   case ISD::SHL:
2364     return LowerVectorSRA_SRL_SHL(Op, DAG);
2365   case ISD::SHL_PARTS:
2366     return LowerShiftLeftParts(Op, DAG);
2367   case ISD::SRL_PARTS:
2368   case ISD::SRA_PARTS:
2369     return LowerShiftRightParts(Op, DAG);
2370   case ISD::CTPOP:
2371     return LowerCTPOP(Op, DAG);
2372   case ISD::FCOPYSIGN:
2373     return LowerFCOPYSIGN(Op, DAG);
2374   case ISD::AND:
2375     return LowerVectorAND(Op, DAG);
2376   case ISD::OR:
2377     return LowerVectorOR(Op, DAG);
2378   case ISD::XOR:
2379     return LowerXOR(Op, DAG);
2380   case ISD::PREFETCH:
2381     return LowerPREFETCH(Op, DAG);
2382   case ISD::SINT_TO_FP:
2383   case ISD::UINT_TO_FP:
2384     return LowerINT_TO_FP(Op, DAG);
2385   case ISD::FP_TO_SINT:
2386   case ISD::FP_TO_UINT:
2387     return LowerFP_TO_INT(Op, DAG);
2388   case ISD::FSINCOS:
2389     return LowerFSINCOS(Op, DAG);
2390   case ISD::MUL:
2391     return LowerMUL(Op, DAG);
2392   case ISD::INTRINSIC_WO_CHAIN:
2393     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2394   }
2395 }
2396 
2397 //===----------------------------------------------------------------------===//
2398 //                      Calling Convention Implementation
2399 //===----------------------------------------------------------------------===//
2400 
2401 #include "AArch64GenCallingConv.inc"
2402 
2403 /// Selects the correct CCAssignFn for a given CallingConvention value.
2404 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2405                                                      bool IsVarArg) const {
2406   switch (CC) {
2407   default:
2408     llvm_unreachable("Unsupported calling convention.");
2409   case CallingConv::WebKit_JS:
2410     return CC_AArch64_WebKit_JS;
2411   case CallingConv::GHC:
2412     return CC_AArch64_GHC;
2413   case CallingConv::C:
2414   case CallingConv::Fast:
2415     if (!Subtarget->isTargetDarwin())
2416       return CC_AArch64_AAPCS;
2417     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2418   }
2419 }
2420 
2421 SDValue AArch64TargetLowering::LowerFormalArguments(
2422     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2423     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2424     SmallVectorImpl<SDValue> &InVals) const {
2425   MachineFunction &MF = DAG.getMachineFunction();
2426   MachineFrameInfo *MFI = MF.getFrameInfo();
2427 
2428   // Assign locations to all of the incoming arguments.
2429   SmallVector<CCValAssign, 16> ArgLocs;
2430   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2431                  *DAG.getContext());
2432 
2433   // At this point, Ins[].VT may already be promoted to i32. To correctly
2434   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2435   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2436   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2437   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2438   // LocVT.
2439   unsigned NumArgs = Ins.size();
2440   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2441   unsigned CurArgIdx = 0;
2442   for (unsigned i = 0; i != NumArgs; ++i) {
2443     MVT ValVT = Ins[i].VT;
2444     if (Ins[i].isOrigArg()) {
2445       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2446       CurArgIdx = Ins[i].getOrigArgIndex();
2447 
2448       // Get type of the original argument.
2449       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2450                                   /*AllowUnknown*/ true);
2451       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2452       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2453       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2454         ValVT = MVT::i8;
2455       else if (ActualMVT == MVT::i16)
2456         ValVT = MVT::i16;
2457     }
2458     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2459     bool Res =
2460         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2461     assert(!Res && "Call operand has unhandled type");
2462     (void)Res;
2463   }
2464   assert(ArgLocs.size() == Ins.size());
2465   SmallVector<SDValue, 16> ArgValues;
2466   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2467     CCValAssign &VA = ArgLocs[i];
2468 
2469     if (Ins[i].Flags.isByVal()) {
2470       // Byval is used for HFAs in the PCS, but the system should work in a
2471       // non-compliant manner for larger structs.
2472       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2473       int Size = Ins[i].Flags.getByValSize();
2474       unsigned NumRegs = (Size + 7) / 8;
2475 
2476       // FIXME: This works on big-endian for composite byvals, which are the common
2477       // case. It should also work for fundamental types too.
2478       unsigned FrameIdx =
2479         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2480       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2481       InVals.push_back(FrameIdxN);
2482 
2483       continue;
2484     }
2485 
2486     if (VA.isRegLoc()) {
2487       // Arguments stored in registers.
2488       EVT RegVT = VA.getLocVT();
2489 
2490       SDValue ArgValue;
2491       const TargetRegisterClass *RC;
2492 
2493       if (RegVT == MVT::i32)
2494         RC = &AArch64::GPR32RegClass;
2495       else if (RegVT == MVT::i64)
2496         RC = &AArch64::GPR64RegClass;
2497       else if (RegVT == MVT::f16)
2498         RC = &AArch64::FPR16RegClass;
2499       else if (RegVT == MVT::f32)
2500         RC = &AArch64::FPR32RegClass;
2501       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2502         RC = &AArch64::FPR64RegClass;
2503       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2504         RC = &AArch64::FPR128RegClass;
2505       else
2506         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2507 
2508       // Transform the arguments in physical registers into virtual ones.
2509       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2510       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2511 
2512       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2513       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2514       // truncate to the right size.
2515       switch (VA.getLocInfo()) {
2516       default:
2517         llvm_unreachable("Unknown loc info!");
2518       case CCValAssign::Full:
2519         break;
2520       case CCValAssign::BCvt:
2521         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2522         break;
2523       case CCValAssign::AExt:
2524       case CCValAssign::SExt:
2525       case CCValAssign::ZExt:
2526         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2527         // nodes after our lowering.
2528         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2529         break;
2530       }
2531 
2532       InVals.push_back(ArgValue);
2533 
2534     } else { // VA.isRegLoc()
2535       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2536       unsigned ArgOffset = VA.getLocMemOffset();
2537       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2538 
2539       uint32_t BEAlign = 0;
2540       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2541           !Ins[i].Flags.isInConsecutiveRegs())
2542         BEAlign = 8 - ArgSize;
2543 
2544       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2545 
2546       // Create load nodes to retrieve arguments from the stack.
2547       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2548       SDValue ArgValue;
2549 
2550       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2551       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2552       MVT MemVT = VA.getValVT();
2553 
2554       switch (VA.getLocInfo()) {
2555       default:
2556         break;
2557       case CCValAssign::BCvt:
2558         MemVT = VA.getLocVT();
2559         break;
2560       case CCValAssign::SExt:
2561         ExtType = ISD::SEXTLOAD;
2562         break;
2563       case CCValAssign::ZExt:
2564         ExtType = ISD::ZEXTLOAD;
2565         break;
2566       case CCValAssign::AExt:
2567         ExtType = ISD::EXTLOAD;
2568         break;
2569       }
2570 
2571       ArgValue = DAG.getExtLoad(
2572           ExtType, DL, VA.getLocVT(), Chain, FIN,
2573           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2574           MemVT, false, false, false, 0);
2575 
2576       InVals.push_back(ArgValue);
2577     }
2578   }
2579 
2580   // varargs
2581   if (isVarArg) {
2582     if (!Subtarget->isTargetDarwin()) {
2583       // The AAPCS variadic function ABI is identical to the non-variadic
2584       // one. As a result there may be more arguments in registers and we should
2585       // save them for future reference.
2586       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2587     }
2588 
2589     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2590     // This will point to the next argument passed via stack.
2591     unsigned StackOffset = CCInfo.getNextStackOffset();
2592     // We currently pass all varargs at 8-byte alignment.
2593     StackOffset = ((StackOffset + 7) & ~7);
2594     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2595   }
2596 
2597   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2598   unsigned StackArgSize = CCInfo.getNextStackOffset();
2599   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2600   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2601     // This is a non-standard ABI so by fiat I say we're allowed to make full
2602     // use of the stack area to be popped, which must be aligned to 16 bytes in
2603     // any case:
2604     StackArgSize = alignTo(StackArgSize, 16);
2605 
2606     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2607     // a multiple of 16.
2608     FuncInfo->setArgumentStackToRestore(StackArgSize);
2609 
2610     // This realignment carries over to the available bytes below. Our own
2611     // callers will guarantee the space is free by giving an aligned value to
2612     // CALLSEQ_START.
2613   }
2614   // Even if we're not expected to free up the space, it's useful to know how
2615   // much is there while considering tail calls (because we can reuse it).
2616   FuncInfo->setBytesInStackArgArea(StackArgSize);
2617 
2618   return Chain;
2619 }
2620 
2621 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2622                                                 SelectionDAG &DAG, SDLoc DL,
2623                                                 SDValue &Chain) const {
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   MachineFrameInfo *MFI = MF.getFrameInfo();
2626   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2627   auto PtrVT = getPointerTy(DAG.getDataLayout());
2628 
2629   SmallVector<SDValue, 8> MemOps;
2630 
2631   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2632                                           AArch64::X3, AArch64::X4, AArch64::X5,
2633                                           AArch64::X6, AArch64::X7 };
2634   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2635   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2636 
2637   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2638   int GPRIdx = 0;
2639   if (GPRSaveSize != 0) {
2640     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2641 
2642     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2643 
2644     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2645       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2646       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2647       SDValue Store = DAG.getStore(
2648           Val.getValue(1), DL, Val, FIN,
2649           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2650           false, 0);
2651       MemOps.push_back(Store);
2652       FIN =
2653           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2654     }
2655   }
2656   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2657   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2658 
2659   if (Subtarget->hasFPARMv8()) {
2660     static const MCPhysReg FPRArgRegs[] = {
2661         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2662         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2663     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2664     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2665 
2666     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2667     int FPRIdx = 0;
2668     if (FPRSaveSize != 0) {
2669       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2670 
2671       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2672 
2673       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2674         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2675         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2676 
2677         SDValue Store = DAG.getStore(
2678             Val.getValue(1), DL, Val, FIN,
2679             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2680             false, false, 0);
2681         MemOps.push_back(Store);
2682         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2683                           DAG.getConstant(16, DL, PtrVT));
2684       }
2685     }
2686     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2687     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2688   }
2689 
2690   if (!MemOps.empty()) {
2691     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2692   }
2693 }
2694 
2695 /// LowerCallResult - Lower the result values of a call into the
2696 /// appropriate copies out of appropriate physical registers.
2697 SDValue AArch64TargetLowering::LowerCallResult(
2698     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2699     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2700     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2701     SDValue ThisVal) const {
2702   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2703                           ? RetCC_AArch64_WebKit_JS
2704                           : RetCC_AArch64_AAPCS;
2705   // Assign locations to each value returned by this call.
2706   SmallVector<CCValAssign, 16> RVLocs;
2707   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2708                  *DAG.getContext());
2709   CCInfo.AnalyzeCallResult(Ins, RetCC);
2710 
2711   // Copy all of the result registers out of their specified physreg.
2712   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2713     CCValAssign VA = RVLocs[i];
2714 
2715     // Pass 'this' value directly from the argument to return value, to avoid
2716     // reg unit interference
2717     if (i == 0 && isThisReturn) {
2718       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2719              "unexpected return calling convention register assignment");
2720       InVals.push_back(ThisVal);
2721       continue;
2722     }
2723 
2724     SDValue Val =
2725         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2726     Chain = Val.getValue(1);
2727     InFlag = Val.getValue(2);
2728 
2729     switch (VA.getLocInfo()) {
2730     default:
2731       llvm_unreachable("Unknown loc info!");
2732     case CCValAssign::Full:
2733       break;
2734     case CCValAssign::BCvt:
2735       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2736       break;
2737     }
2738 
2739     InVals.push_back(Val);
2740   }
2741 
2742   return Chain;
2743 }
2744 
2745 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2746     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2747     bool isCalleeStructRet, bool isCallerStructRet,
2748     const SmallVectorImpl<ISD::OutputArg> &Outs,
2749     const SmallVectorImpl<SDValue> &OutVals,
2750     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2751   // For CallingConv::C this function knows whether the ABI needs
2752   // changing. That's not true for other conventions so they will have to opt in
2753   // manually.
2754   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2755     return false;
2756 
2757   const MachineFunction &MF = DAG.getMachineFunction();
2758   const Function *CallerF = MF.getFunction();
2759   CallingConv::ID CallerCC = CallerF->getCallingConv();
2760   bool CCMatch = CallerCC == CalleeCC;
2761 
2762   // Byval parameters hand the function a pointer directly into the stack area
2763   // we want to reuse during a tail call. Working around this *is* possible (see
2764   // X86) but less efficient and uglier in LowerCall.
2765   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2766                                     e = CallerF->arg_end();
2767        i != e; ++i)
2768     if (i->hasByValAttr())
2769       return false;
2770 
2771   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2772     if (IsTailCallConvention(CalleeCC) && CCMatch)
2773       return true;
2774     return false;
2775   }
2776 
2777   // Externally-defined functions with weak linkage should not be
2778   // tail-called on AArch64 when the OS does not support dynamic
2779   // pre-emption of symbols, as the AAELF spec requires normal calls
2780   // to undefined weak functions to be replaced with a NOP or jump to the
2781   // next instruction. The behaviour of branch instructions in this
2782   // situation (as used for tail calls) is implementation-defined, so we
2783   // cannot rely on the linker replacing the tail call with a return.
2784   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2785     const GlobalValue *GV = G->getGlobal();
2786     const Triple &TT = getTargetMachine().getTargetTriple();
2787     if (GV->hasExternalWeakLinkage() &&
2788         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2789       return false;
2790   }
2791 
2792   // Now we search for cases where we can use a tail call without changing the
2793   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2794   // concept.
2795 
2796   // I want anyone implementing a new calling convention to think long and hard
2797   // about this assert.
2798   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2799          "Unexpected variadic calling convention");
2800 
2801   if (isVarArg && !Outs.empty()) {
2802     // At least two cases here: if caller is fastcc then we can't have any
2803     // memory arguments (we'd be expected to clean up the stack afterwards). If
2804     // caller is C then we could potentially use its argument area.
2805 
2806     // FIXME: for now we take the most conservative of these in both cases:
2807     // disallow all variadic memory operands.
2808     SmallVector<CCValAssign, 16> ArgLocs;
2809     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2810                    *DAG.getContext());
2811 
2812     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2813     for (const CCValAssign &ArgLoc : ArgLocs)
2814       if (!ArgLoc.isRegLoc())
2815         return false;
2816   }
2817 
2818   // If the calling conventions do not match, then we'd better make sure the
2819   // results are returned in the same way as what the caller expects.
2820   if (!CCMatch) {
2821     SmallVector<CCValAssign, 16> RVLocs1;
2822     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2823                     *DAG.getContext());
2824     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2825 
2826     SmallVector<CCValAssign, 16> RVLocs2;
2827     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2828                     *DAG.getContext());
2829     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2830 
2831     if (RVLocs1.size() != RVLocs2.size())
2832       return false;
2833     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2834       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2835         return false;
2836       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2837         return false;
2838       if (RVLocs1[i].isRegLoc()) {
2839         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2840           return false;
2841       } else {
2842         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2843           return false;
2844       }
2845     }
2846   }
2847 
2848   // Nothing more to check if the callee is taking no arguments
2849   if (Outs.empty())
2850     return true;
2851 
2852   SmallVector<CCValAssign, 16> ArgLocs;
2853   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2854                  *DAG.getContext());
2855 
2856   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2857 
2858   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2859 
2860   // If the stack arguments for this call would fit into our own save area then
2861   // the call can be made tail.
2862   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2863 }
2864 
2865 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2866                                                    SelectionDAG &DAG,
2867                                                    MachineFrameInfo *MFI,
2868                                                    int ClobberedFI) const {
2869   SmallVector<SDValue, 8> ArgChains;
2870   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2871   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2872 
2873   // Include the original chain at the beginning of the list. When this is
2874   // used by target LowerCall hooks, this helps legalize find the
2875   // CALLSEQ_BEGIN node.
2876   ArgChains.push_back(Chain);
2877 
2878   // Add a chain value for each stack argument corresponding
2879   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2880                             UE = DAG.getEntryNode().getNode()->use_end();
2881        U != UE; ++U)
2882     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2883       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2884         if (FI->getIndex() < 0) {
2885           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2886           int64_t InLastByte = InFirstByte;
2887           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2888 
2889           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2890               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2891             ArgChains.push_back(SDValue(L, 1));
2892         }
2893 
2894   // Build a tokenfactor for all the chains.
2895   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2896 }
2897 
2898 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2899                                                    bool TailCallOpt) const {
2900   return CallCC == CallingConv::Fast && TailCallOpt;
2901 }
2902 
2903 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2904   return CallCC == CallingConv::Fast;
2905 }
2906 
2907 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2908 /// and add input and output parameter nodes.
2909 SDValue
2910 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2911                                  SmallVectorImpl<SDValue> &InVals) const {
2912   SelectionDAG &DAG = CLI.DAG;
2913   SDLoc &DL = CLI.DL;
2914   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2915   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2916   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2917   SDValue Chain = CLI.Chain;
2918   SDValue Callee = CLI.Callee;
2919   bool &IsTailCall = CLI.IsTailCall;
2920   CallingConv::ID CallConv = CLI.CallConv;
2921   bool IsVarArg = CLI.IsVarArg;
2922 
2923   MachineFunction &MF = DAG.getMachineFunction();
2924   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2925   bool IsThisReturn = false;
2926 
2927   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2928   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2929   bool IsSibCall = false;
2930 
2931   if (IsTailCall) {
2932     // Check if it's really possible to do a tail call.
2933     IsTailCall = isEligibleForTailCallOptimization(
2934         Callee, CallConv, IsVarArg, IsStructRet,
2935         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2936     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2937       report_fatal_error("failed to perform tail call elimination on a call "
2938                          "site marked musttail");
2939 
2940     // A sibling call is one where we're under the usual C ABI and not planning
2941     // to change that but can still do a tail call:
2942     if (!TailCallOpt && IsTailCall)
2943       IsSibCall = true;
2944 
2945     if (IsTailCall)
2946       ++NumTailCalls;
2947   }
2948 
2949   // Analyze operands of the call, assigning locations to each operand.
2950   SmallVector<CCValAssign, 16> ArgLocs;
2951   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2952                  *DAG.getContext());
2953 
2954   if (IsVarArg) {
2955     // Handle fixed and variable vector arguments differently.
2956     // Variable vector arguments always go into memory.
2957     unsigned NumArgs = Outs.size();
2958 
2959     for (unsigned i = 0; i != NumArgs; ++i) {
2960       MVT ArgVT = Outs[i].VT;
2961       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2962       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2963                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2964       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2965       assert(!Res && "Call operand has unhandled type");
2966       (void)Res;
2967     }
2968   } else {
2969     // At this point, Outs[].VT may already be promoted to i32. To correctly
2970     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2971     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2972     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2973     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2974     // LocVT.
2975     unsigned NumArgs = Outs.size();
2976     for (unsigned i = 0; i != NumArgs; ++i) {
2977       MVT ValVT = Outs[i].VT;
2978       // Get type of the original argument.
2979       EVT ActualVT = getValueType(DAG.getDataLayout(),
2980                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2981                                   /*AllowUnknown*/ true);
2982       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2983       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2984       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2985       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2986         ValVT = MVT::i8;
2987       else if (ActualMVT == MVT::i16)
2988         ValVT = MVT::i16;
2989 
2990       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2991       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2992       assert(!Res && "Call operand has unhandled type");
2993       (void)Res;
2994     }
2995   }
2996 
2997   // Get a count of how many bytes are to be pushed on the stack.
2998   unsigned NumBytes = CCInfo.getNextStackOffset();
2999 
3000   if (IsSibCall) {
3001     // Since we're not changing the ABI to make this a tail call, the memory
3002     // operands are already available in the caller's incoming argument space.
3003     NumBytes = 0;
3004   }
3005 
3006   // FPDiff is the byte offset of the call's argument area from the callee's.
3007   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3008   // by this amount for a tail call. In a sibling call it must be 0 because the
3009   // caller will deallocate the entire stack and the callee still expects its
3010   // arguments to begin at SP+0. Completely unused for non-tail calls.
3011   int FPDiff = 0;
3012 
3013   if (IsTailCall && !IsSibCall) {
3014     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3015 
3016     // Since callee will pop argument stack as a tail call, we must keep the
3017     // popped size 16-byte aligned.
3018     NumBytes = alignTo(NumBytes, 16);
3019 
3020     // FPDiff will be negative if this tail call requires more space than we
3021     // would automatically have in our incoming argument space. Positive if we
3022     // can actually shrink the stack.
3023     FPDiff = NumReusableBytes - NumBytes;
3024 
3025     // The stack pointer must be 16-byte aligned at all times it's used for a
3026     // memory operation, which in practice means at *all* times and in
3027     // particular across call boundaries. Therefore our own arguments started at
3028     // a 16-byte aligned SP and the delta applied for the tail call should
3029     // satisfy the same constraint.
3030     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3031   }
3032 
3033   // Adjust the stack pointer for the new arguments...
3034   // These operations are automatically eliminated by the prolog/epilog pass
3035   if (!IsSibCall)
3036     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3037                                                               true),
3038                                  DL);
3039 
3040   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3041                                         getPointerTy(DAG.getDataLayout()));
3042 
3043   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3044   SmallVector<SDValue, 8> MemOpChains;
3045   auto PtrVT = getPointerTy(DAG.getDataLayout());
3046 
3047   // Walk the register/memloc assignments, inserting copies/loads.
3048   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3049        ++i, ++realArgIdx) {
3050     CCValAssign &VA = ArgLocs[i];
3051     SDValue Arg = OutVals[realArgIdx];
3052     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3053 
3054     // Promote the value if needed.
3055     switch (VA.getLocInfo()) {
3056     default:
3057       llvm_unreachable("Unknown loc info!");
3058     case CCValAssign::Full:
3059       break;
3060     case CCValAssign::SExt:
3061       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3062       break;
3063     case CCValAssign::ZExt:
3064       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3065       break;
3066     case CCValAssign::AExt:
3067       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3068         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3069         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3070         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3071       }
3072       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3073       break;
3074     case CCValAssign::BCvt:
3075       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3076       break;
3077     case CCValAssign::FPExt:
3078       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3079       break;
3080     }
3081 
3082     if (VA.isRegLoc()) {
3083       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3084         assert(VA.getLocVT() == MVT::i64 &&
3085                "unexpected calling convention register assignment");
3086         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3087                "unexpected use of 'returned'");
3088         IsThisReturn = true;
3089       }
3090       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3091     } else {
3092       assert(VA.isMemLoc());
3093 
3094       SDValue DstAddr;
3095       MachinePointerInfo DstInfo;
3096 
3097       // FIXME: This works on big-endian for composite byvals, which are the
3098       // common case. It should also work for fundamental types too.
3099       uint32_t BEAlign = 0;
3100       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3101                                         : VA.getValVT().getSizeInBits();
3102       OpSize = (OpSize + 7) / 8;
3103       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3104           !Flags.isInConsecutiveRegs()) {
3105         if (OpSize < 8)
3106           BEAlign = 8 - OpSize;
3107       }
3108       unsigned LocMemOffset = VA.getLocMemOffset();
3109       int32_t Offset = LocMemOffset + BEAlign;
3110       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3111       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3112 
3113       if (IsTailCall) {
3114         Offset = Offset + FPDiff;
3115         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3116 
3117         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3118         DstInfo =
3119             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3120 
3121         // Make sure any stack arguments overlapping with where we're storing
3122         // are loaded before this eventual operation. Otherwise they'll be
3123         // clobbered.
3124         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3125       } else {
3126         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3127 
3128         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3129         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3130                                                LocMemOffset);
3131       }
3132 
3133       if (Outs[i].Flags.isByVal()) {
3134         SDValue SizeNode =
3135             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3136         SDValue Cpy = DAG.getMemcpy(
3137             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3138             /*isVol = */ false, /*AlwaysInline = */ false,
3139             /*isTailCall = */ false,
3140             DstInfo, MachinePointerInfo());
3141 
3142         MemOpChains.push_back(Cpy);
3143       } else {
3144         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3145         // promoted to a legal register type i32, we should truncate Arg back to
3146         // i1/i8/i16.
3147         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3148             VA.getValVT() == MVT::i16)
3149           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3150 
3151         SDValue Store =
3152             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3153         MemOpChains.push_back(Store);
3154       }
3155     }
3156   }
3157 
3158   if (!MemOpChains.empty())
3159     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3160 
3161   // Build a sequence of copy-to-reg nodes chained together with token chain
3162   // and flag operands which copy the outgoing args into the appropriate regs.
3163   SDValue InFlag;
3164   for (auto &RegToPass : RegsToPass) {
3165     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3166                              RegToPass.second, InFlag);
3167     InFlag = Chain.getValue(1);
3168   }
3169 
3170   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3171   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3172   // node so that legalize doesn't hack it.
3173   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3174       Subtarget->isTargetMachO()) {
3175     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3176       const GlobalValue *GV = G->getGlobal();
3177       bool InternalLinkage = GV->hasInternalLinkage();
3178       if (InternalLinkage)
3179         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3180       else {
3181         Callee =
3182             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3183         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3184       }
3185     } else if (ExternalSymbolSDNode *S =
3186                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3187       const char *Sym = S->getSymbol();
3188       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3189       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3190     }
3191   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3192     const GlobalValue *GV = G->getGlobal();
3193     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3194   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3195     const char *Sym = S->getSymbol();
3196     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3197   }
3198 
3199   // We don't usually want to end the call-sequence here because we would tidy
3200   // the frame up *after* the call, however in the ABI-changing tail-call case
3201   // we've carefully laid out the parameters so that when sp is reset they'll be
3202   // in the correct location.
3203   if (IsTailCall && !IsSibCall) {
3204     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3205                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3206     InFlag = Chain.getValue(1);
3207   }
3208 
3209   std::vector<SDValue> Ops;
3210   Ops.push_back(Chain);
3211   Ops.push_back(Callee);
3212 
3213   if (IsTailCall) {
3214     // Each tail call may have to adjust the stack by a different amount, so
3215     // this information must travel along with the operation for eventual
3216     // consumption by emitEpilogue.
3217     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3218   }
3219 
3220   // Add argument registers to the end of the list so that they are known live
3221   // into the call.
3222   for (auto &RegToPass : RegsToPass)
3223     Ops.push_back(DAG.getRegister(RegToPass.first,
3224                                   RegToPass.second.getValueType()));
3225 
3226   // Add a register mask operand representing the call-preserved registers.
3227   const uint32_t *Mask;
3228   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3229   if (IsThisReturn) {
3230     // For 'this' returns, use the X0-preserving mask if applicable
3231     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3232     if (!Mask) {
3233       IsThisReturn = false;
3234       Mask = TRI->getCallPreservedMask(MF, CallConv);
3235     }
3236   } else
3237     Mask = TRI->getCallPreservedMask(MF, CallConv);
3238 
3239   assert(Mask && "Missing call preserved mask for calling convention");
3240   Ops.push_back(DAG.getRegisterMask(Mask));
3241 
3242   if (InFlag.getNode())
3243     Ops.push_back(InFlag);
3244 
3245   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3246 
3247   // If we're doing a tall call, use a TC_RETURN here rather than an
3248   // actual call instruction.
3249   if (IsTailCall) {
3250     MF.getFrameInfo()->setHasTailCall();
3251     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3252   }
3253 
3254   // Returns a chain and a flag for retval copy to use.
3255   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3256   InFlag = Chain.getValue(1);
3257 
3258   uint64_t CalleePopBytes =
3259       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3260 
3261   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3262                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3263                              InFlag, DL);
3264   if (!Ins.empty())
3265     InFlag = Chain.getValue(1);
3266 
3267   // Handle result values, copying them out of physregs into vregs that we
3268   // return.
3269   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3270                          InVals, IsThisReturn,
3271                          IsThisReturn ? OutVals[0] : SDValue());
3272 }
3273 
3274 bool AArch64TargetLowering::CanLowerReturn(
3275     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3276     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3277   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3278                           ? RetCC_AArch64_WebKit_JS
3279                           : RetCC_AArch64_AAPCS;
3280   SmallVector<CCValAssign, 16> RVLocs;
3281   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3282   return CCInfo.CheckReturn(Outs, RetCC);
3283 }
3284 
3285 SDValue
3286 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3287                                    bool isVarArg,
3288                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3289                                    const SmallVectorImpl<SDValue> &OutVals,
3290                                    SDLoc DL, SelectionDAG &DAG) const {
3291   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3292                           ? RetCC_AArch64_WebKit_JS
3293                           : RetCC_AArch64_AAPCS;
3294   SmallVector<CCValAssign, 16> RVLocs;
3295   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3296                  *DAG.getContext());
3297   CCInfo.AnalyzeReturn(Outs, RetCC);
3298 
3299   // Copy the result values into the output registers.
3300   SDValue Flag;
3301   SmallVector<SDValue, 4> RetOps(1, Chain);
3302   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3303        ++i, ++realRVLocIdx) {
3304     CCValAssign &VA = RVLocs[i];
3305     assert(VA.isRegLoc() && "Can only return in registers!");
3306     SDValue Arg = OutVals[realRVLocIdx];
3307 
3308     switch (VA.getLocInfo()) {
3309     default:
3310       llvm_unreachable("Unknown loc info!");
3311     case CCValAssign::Full:
3312       if (Outs[i].ArgVT == MVT::i1) {
3313         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3314         // value. This is strictly redundant on Darwin (which uses "zeroext
3315         // i1"), but will be optimised out before ISel.
3316         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3317         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3318       }
3319       break;
3320     case CCValAssign::BCvt:
3321       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3322       break;
3323     }
3324 
3325     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3326     Flag = Chain.getValue(1);
3327     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3328   }
3329   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3330   const MCPhysReg *I =
3331       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3332   if (I) {
3333     for (; *I; ++I) {
3334       if (AArch64::GPR64RegClass.contains(*I))
3335         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3336       else if (AArch64::FPR64RegClass.contains(*I))
3337         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3338       else
3339         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3340     }
3341   }
3342 
3343   RetOps[0] = Chain; // Update chain.
3344 
3345   // Add the flag if we have it.
3346   if (Flag.getNode())
3347     RetOps.push_back(Flag);
3348 
3349   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3350 }
3351 
3352 //===----------------------------------------------------------------------===//
3353 //  Other Lowering Code
3354 //===----------------------------------------------------------------------===//
3355 
3356 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3357                                                   SelectionDAG &DAG) const {
3358   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3359   SDLoc DL(Op);
3360   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3361   const GlobalValue *GV = GN->getGlobal();
3362   unsigned char OpFlags =
3363       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3364 
3365   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3366          "unexpected offset in global node");
3367 
3368   // This also catched the large code model case for Darwin.
3369   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3370     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3371     // FIXME: Once remat is capable of dealing with instructions with register
3372     // operands, expand this into two nodes instead of using a wrapper node.
3373     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3374   }
3375 
3376   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3377     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3378            "use of MO_CONSTPOOL only supported on small model");
3379     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3380     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3381     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3382     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3383     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3384     SDValue GlobalAddr = DAG.getLoad(
3385         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3386         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3387         /*isVolatile=*/false,
3388         /*isNonTemporal=*/true,
3389         /*isInvariant=*/true, 8);
3390     if (GN->getOffset() != 0)
3391       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3392                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3393     return GlobalAddr;
3394   }
3395 
3396   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3397     const unsigned char MO_NC = AArch64II::MO_NC;
3398     return DAG.getNode(
3399         AArch64ISD::WrapperLarge, DL, PtrVT,
3400         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3401         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3402         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3403         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3404   } else {
3405     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3406     // the only correct model on Darwin.
3407     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3408                                             OpFlags | AArch64II::MO_PAGE);
3409     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3410     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3411 
3412     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3413     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3414   }
3415 }
3416 
3417 /// \brief Convert a TLS address reference into the correct sequence of loads
3418 /// and calls to compute the variable's address (for Darwin, currently) and
3419 /// return an SDValue containing the final node.
3420 
3421 /// Darwin only has one TLS scheme which must be capable of dealing with the
3422 /// fully general situation, in the worst case. This means:
3423 ///     + "extern __thread" declaration.
3424 ///     + Defined in a possibly unknown dynamic library.
3425 ///
3426 /// The general system is that each __thread variable has a [3 x i64] descriptor
3427 /// which contains information used by the runtime to calculate the address. The
3428 /// only part of this the compiler needs to know about is the first xword, which
3429 /// contains a function pointer that must be called with the address of the
3430 /// entire descriptor in "x0".
3431 ///
3432 /// Since this descriptor may be in a different unit, in general even the
3433 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3434 /// is:
3435 ///     adrp x0, _var@TLVPPAGE
3436 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3437 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3438 ///                                      ; the function pointer
3439 ///     blr x1                           ; Uses descriptor address in x0
3440 ///     ; Address of _var is now in x0.
3441 ///
3442 /// If the address of _var's descriptor *is* known to the linker, then it can
3443 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3444 /// a slight efficiency gain.
3445 SDValue
3446 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3447                                                    SelectionDAG &DAG) const {
3448   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3449 
3450   SDLoc DL(Op);
3451   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3452   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3453 
3454   SDValue TLVPAddr =
3455       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3456   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3457 
3458   // The first entry in the descriptor is a function pointer that we must call
3459   // to obtain the address of the variable.
3460   SDValue Chain = DAG.getEntryNode();
3461   SDValue FuncTLVGet =
3462       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3463                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3464                   true, true, 8);
3465   Chain = FuncTLVGet.getValue(1);
3466 
3467   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3468   MFI->setAdjustsStack(true);
3469 
3470   // TLS calls preserve all registers except those that absolutely must be
3471   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3472   // silly).
3473   const uint32_t *Mask =
3474       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3475 
3476   // Finally, we can make the call. This is just a degenerate version of a
3477   // normal AArch64 call node: x0 takes the address of the descriptor, and
3478   // returns the address of the variable in this thread.
3479   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3480   Chain =
3481       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3482                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3483                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3484   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3485 }
3486 
3487 /// When accessing thread-local variables under either the general-dynamic or
3488 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3489 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3490 /// is a function pointer to carry out the resolution.
3491 ///
3492 /// The sequence is:
3493 ///    adrp  x0, :tlsdesc:var
3494 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3495 ///    add   x0, x0, #:tlsdesc_lo12:var
3496 ///    .tlsdesccall var
3497 ///    blr   x1
3498 ///    (TPIDR_EL0 offset now in x0)
3499 ///
3500 ///  The above sequence must be produced unscheduled, to enable the linker to
3501 ///  optimize/relax this sequence.
3502 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3503 ///  above sequence, and expanded really late in the compilation flow, to ensure
3504 ///  the sequence is produced as per above.
3505 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3506                                                       SelectionDAG &DAG) const {
3507   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3508 
3509   SDValue Chain = DAG.getEntryNode();
3510   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3511 
3512   SmallVector<SDValue, 2> Ops;
3513   Ops.push_back(Chain);
3514   Ops.push_back(SymAddr);
3515 
3516   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3517   SDValue Glue = Chain.getValue(1);
3518 
3519   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3520 }
3521 
3522 SDValue
3523 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3524                                                 SelectionDAG &DAG) const {
3525   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3526   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3527          "ELF TLS only supported in small memory model");
3528   // Different choices can be made for the maximum size of the TLS area for a
3529   // module. For the small address model, the default TLS size is 16MiB and the
3530   // maximum TLS size is 4GiB.
3531   // FIXME: add -mtls-size command line option and make it control the 16MiB
3532   // vs. 4GiB code sequence generation.
3533   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3534 
3535   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3536 
3537   if (DAG.getTarget().Options.EmulatedTLS)
3538     return LowerToTLSEmulatedModel(GA, DAG);
3539 
3540   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3541     if (Model == TLSModel::LocalDynamic)
3542       Model = TLSModel::GeneralDynamic;
3543   }
3544 
3545   SDValue TPOff;
3546   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3547   SDLoc DL(Op);
3548   const GlobalValue *GV = GA->getGlobal();
3549 
3550   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3551 
3552   if (Model == TLSModel::LocalExec) {
3553     SDValue HiVar = DAG.getTargetGlobalAddress(
3554         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3555     SDValue LoVar = DAG.getTargetGlobalAddress(
3556         GV, DL, PtrVT, 0,
3557         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3558 
3559     SDValue TPWithOff_lo =
3560         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3561                                    HiVar,
3562                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3563                 0);
3564     SDValue TPWithOff =
3565         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3566                                    LoVar,
3567                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3568                 0);
3569     return TPWithOff;
3570   } else if (Model == TLSModel::InitialExec) {
3571     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3572     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3573   } else if (Model == TLSModel::LocalDynamic) {
3574     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3575     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3576     // the beginning of the module's TLS region, followed by a DTPREL offset
3577     // calculation.
3578 
3579     // These accesses will need deduplicating if there's more than one.
3580     AArch64FunctionInfo *MFI =
3581         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3582     MFI->incNumLocalDynamicTLSAccesses();
3583 
3584     // The call needs a relocation too for linker relaxation. It doesn't make
3585     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3586     // the address.
3587     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3588                                                   AArch64II::MO_TLS);
3589 
3590     // Now we can calculate the offset from TPIDR_EL0 to this module's
3591     // thread-local area.
3592     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3593 
3594     // Now use :dtprel_whatever: operations to calculate this variable's offset
3595     // in its thread-storage area.
3596     SDValue HiVar = DAG.getTargetGlobalAddress(
3597         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3598     SDValue LoVar = DAG.getTargetGlobalAddress(
3599         GV, DL, MVT::i64, 0,
3600         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3601 
3602     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3603                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3604                     0);
3605     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3606                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3607                     0);
3608   } else if (Model == TLSModel::GeneralDynamic) {
3609     // The call needs a relocation too for linker relaxation. It doesn't make
3610     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3611     // the address.
3612     SDValue SymAddr =
3613         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3614 
3615     // Finally we can make a call to calculate the offset from tpidr_el0.
3616     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3617   } else
3618     llvm_unreachable("Unsupported ELF TLS access model");
3619 
3620   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3621 }
3622 
3623 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3624                                                      SelectionDAG &DAG) const {
3625   if (Subtarget->isTargetDarwin())
3626     return LowerDarwinGlobalTLSAddress(Op, DAG);
3627   else if (Subtarget->isTargetELF())
3628     return LowerELFGlobalTLSAddress(Op, DAG);
3629 
3630   llvm_unreachable("Unexpected platform trying to use TLS");
3631 }
3632 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3633   SDValue Chain = Op.getOperand(0);
3634   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3635   SDValue LHS = Op.getOperand(2);
3636   SDValue RHS = Op.getOperand(3);
3637   SDValue Dest = Op.getOperand(4);
3638   SDLoc dl(Op);
3639 
3640   // Handle f128 first, since lowering it will result in comparing the return
3641   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3642   // is expecting to deal with.
3643   if (LHS.getValueType() == MVT::f128) {
3644     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3645 
3646     // If softenSetCCOperands returned a scalar, we need to compare the result
3647     // against zero to select between true and false values.
3648     if (!RHS.getNode()) {
3649       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3650       CC = ISD::SETNE;
3651     }
3652   }
3653 
3654   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3655   // instruction.
3656   unsigned Opc = LHS.getOpcode();
3657   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3658       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3659        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3660     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3661            "Unexpected condition code.");
3662     // Only lower legal XALUO ops.
3663     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3664       return SDValue();
3665 
3666     // The actual operation with overflow check.
3667     AArch64CC::CondCode OFCC;
3668     SDValue Value, Overflow;
3669     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3670 
3671     if (CC == ISD::SETNE)
3672       OFCC = getInvertedCondCode(OFCC);
3673     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3674 
3675     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3676                        Overflow);
3677   }
3678 
3679   if (LHS.getValueType().isInteger()) {
3680     assert((LHS.getValueType() == RHS.getValueType()) &&
3681            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3682 
3683     // If the RHS of the comparison is zero, we can potentially fold this
3684     // to a specialized branch.
3685     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3686     if (RHSC && RHSC->getZExtValue() == 0) {
3687       if (CC == ISD::SETEQ) {
3688         // See if we can use a TBZ to fold in an AND as well.
3689         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3690         // out of bounds, a late MI-layer pass rewrites branches.
3691         // 403.gcc is an example that hits this case.
3692         if (LHS.getOpcode() == ISD::AND &&
3693             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3694             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3695           SDValue Test = LHS.getOperand(0);
3696           uint64_t Mask = LHS.getConstantOperandVal(1);
3697           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3698                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3699                              Dest);
3700         }
3701 
3702         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3703       } else if (CC == ISD::SETNE) {
3704         // See if we can use a TBZ to fold in an AND as well.
3705         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3706         // out of bounds, a late MI-layer pass rewrites branches.
3707         // 403.gcc is an example that hits this case.
3708         if (LHS.getOpcode() == ISD::AND &&
3709             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3710             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3711           SDValue Test = LHS.getOperand(0);
3712           uint64_t Mask = LHS.getConstantOperandVal(1);
3713           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3714                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3715                              Dest);
3716         }
3717 
3718         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3719       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3720         // Don't combine AND since emitComparison converts the AND to an ANDS
3721         // (a.k.a. TST) and the test in the test bit and branch instruction
3722         // becomes redundant.  This would also increase register pressure.
3723         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3724         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3725                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3726       }
3727     }
3728     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3729         LHS.getOpcode() != ISD::AND) {
3730       // Don't combine AND since emitComparison converts the AND to an ANDS
3731       // (a.k.a. TST) and the test in the test bit and branch instruction
3732       // becomes redundant.  This would also increase register pressure.
3733       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3734       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3735                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3736     }
3737 
3738     SDValue CCVal;
3739     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3740     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3741                        Cmp);
3742   }
3743 
3744   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3745 
3746   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3747   // clean.  Some of them require two branches to implement.
3748   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3749   AArch64CC::CondCode CC1, CC2;
3750   changeFPCCToAArch64CC(CC, CC1, CC2);
3751   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3752   SDValue BR1 =
3753       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3754   if (CC2 != AArch64CC::AL) {
3755     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3756     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3757                        Cmp);
3758   }
3759 
3760   return BR1;
3761 }
3762 
3763 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3764                                               SelectionDAG &DAG) const {
3765   EVT VT = Op.getValueType();
3766   SDLoc DL(Op);
3767 
3768   SDValue In1 = Op.getOperand(0);
3769   SDValue In2 = Op.getOperand(1);
3770   EVT SrcVT = In2.getValueType();
3771 
3772   if (SrcVT.bitsLT(VT))
3773     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3774   else if (SrcVT.bitsGT(VT))
3775     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3776 
3777   EVT VecVT;
3778   EVT EltVT;
3779   uint64_t EltMask;
3780   SDValue VecVal1, VecVal2;
3781   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3782     EltVT = MVT::i32;
3783     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3784     EltMask = 0x80000000ULL;
3785 
3786     if (!VT.isVector()) {
3787       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3788                                           DAG.getUNDEF(VecVT), In1);
3789       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3790                                           DAG.getUNDEF(VecVT), In2);
3791     } else {
3792       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3793       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3794     }
3795   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3796     EltVT = MVT::i64;
3797     VecVT = MVT::v2i64;
3798 
3799     // We want to materialize a mask with the high bit set, but the AdvSIMD
3800     // immediate moves cannot materialize that in a single instruction for
3801     // 64-bit elements. Instead, materialize zero and then negate it.
3802     EltMask = 0;
3803 
3804     if (!VT.isVector()) {
3805       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3806                                           DAG.getUNDEF(VecVT), In1);
3807       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3808                                           DAG.getUNDEF(VecVT), In2);
3809     } else {
3810       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3811       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3812     }
3813   } else {
3814     llvm_unreachable("Invalid type for copysign!");
3815   }
3816 
3817   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3818 
3819   // If we couldn't materialize the mask above, then the mask vector will be
3820   // the zero vector, and we need to negate it here.
3821   if (VT == MVT::f64 || VT == MVT::v2f64) {
3822     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3823     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3824     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3825   }
3826 
3827   SDValue Sel =
3828       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3829 
3830   if (VT == MVT::f32)
3831     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3832   else if (VT == MVT::f64)
3833     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3834   else
3835     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3836 }
3837 
3838 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3839   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3840           Attribute::NoImplicitFloat))
3841     return SDValue();
3842 
3843   if (!Subtarget->hasNEON())
3844     return SDValue();
3845 
3846   // While there is no integer popcount instruction, it can
3847   // be more efficiently lowered to the following sequence that uses
3848   // AdvSIMD registers/instructions as long as the copies to/from
3849   // the AdvSIMD registers are cheap.
3850   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3851   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3852   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3853   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3854   SDValue Val = Op.getOperand(0);
3855   SDLoc DL(Op);
3856   EVT VT = Op.getValueType();
3857 
3858   if (VT == MVT::i32)
3859     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3860   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3861 
3862   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3863   SDValue UaddLV = DAG.getNode(
3864       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3865       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3866 
3867   if (VT == MVT::i64)
3868     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3869   return UaddLV;
3870 }
3871 
3872 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3873 
3874   if (Op.getValueType().isVector())
3875     return LowerVSETCC(Op, DAG);
3876 
3877   SDValue LHS = Op.getOperand(0);
3878   SDValue RHS = Op.getOperand(1);
3879   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3880   SDLoc dl(Op);
3881 
3882   // We chose ZeroOrOneBooleanContents, so use zero and one.
3883   EVT VT = Op.getValueType();
3884   SDValue TVal = DAG.getConstant(1, dl, VT);
3885   SDValue FVal = DAG.getConstant(0, dl, VT);
3886 
3887   // Handle f128 first, since one possible outcome is a normal integer
3888   // comparison which gets picked up by the next if statement.
3889   if (LHS.getValueType() == MVT::f128) {
3890     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3891 
3892     // If softenSetCCOperands returned a scalar, use it.
3893     if (!RHS.getNode()) {
3894       assert(LHS.getValueType() == Op.getValueType() &&
3895              "Unexpected setcc expansion!");
3896       return LHS;
3897     }
3898   }
3899 
3900   if (LHS.getValueType().isInteger()) {
3901     SDValue CCVal;
3902     SDValue Cmp =
3903         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3904 
3905     // Note that we inverted the condition above, so we reverse the order of
3906     // the true and false operands here.  This will allow the setcc to be
3907     // matched to a single CSINC instruction.
3908     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3909   }
3910 
3911   // Now we know we're dealing with FP values.
3912   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3913 
3914   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3915   // and do the comparison.
3916   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3917 
3918   AArch64CC::CondCode CC1, CC2;
3919   changeFPCCToAArch64CC(CC, CC1, CC2);
3920   if (CC2 == AArch64CC::AL) {
3921     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3922     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3923 
3924     // Note that we inverted the condition above, so we reverse the order of
3925     // the true and false operands here.  This will allow the setcc to be
3926     // matched to a single CSINC instruction.
3927     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3928   } else {
3929     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3930     // totally clean.  Some of them require two CSELs to implement.  As is in
3931     // this case, we emit the first CSEL and then emit a second using the output
3932     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3933 
3934     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3935     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3936     SDValue CS1 =
3937         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3938 
3939     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3940     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3941   }
3942 }
3943 
3944 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3945                                               SDValue RHS, SDValue TVal,
3946                                               SDValue FVal, SDLoc dl,
3947                                               SelectionDAG &DAG) const {
3948   // Handle f128 first, because it will result in a comparison of some RTLIB
3949   // call result against zero.
3950   if (LHS.getValueType() == MVT::f128) {
3951     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3952 
3953     // If softenSetCCOperands returned a scalar, we need to compare the result
3954     // against zero to select between true and false values.
3955     if (!RHS.getNode()) {
3956       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3957       CC = ISD::SETNE;
3958     }
3959   }
3960 
3961   // Also handle f16, for which we need to do a f32 comparison.
3962   if (LHS.getValueType() == MVT::f16) {
3963     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3964     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3965   }
3966 
3967   // Next, handle integers.
3968   if (LHS.getValueType().isInteger()) {
3969     assert((LHS.getValueType() == RHS.getValueType()) &&
3970            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3971 
3972     unsigned Opcode = AArch64ISD::CSEL;
3973 
3974     // If both the TVal and the FVal are constants, see if we can swap them in
3975     // order to for a CSINV or CSINC out of them.
3976     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3977     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3978 
3979     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3980       std::swap(TVal, FVal);
3981       std::swap(CTVal, CFVal);
3982       CC = ISD::getSetCCInverse(CC, true);
3983     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3984       std::swap(TVal, FVal);
3985       std::swap(CTVal, CFVal);
3986       CC = ISD::getSetCCInverse(CC, true);
3987     } else if (TVal.getOpcode() == ISD::XOR) {
3988       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3989       // with a CSINV rather than a CSEL.
3990       if (isAllOnesConstant(TVal.getOperand(1))) {
3991         std::swap(TVal, FVal);
3992         std::swap(CTVal, CFVal);
3993         CC = ISD::getSetCCInverse(CC, true);
3994       }
3995     } else if (TVal.getOpcode() == ISD::SUB) {
3996       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3997       // that we can match with a CSNEG rather than a CSEL.
3998       if (isNullConstant(TVal.getOperand(0))) {
3999         std::swap(TVal, FVal);
4000         std::swap(CTVal, CFVal);
4001         CC = ISD::getSetCCInverse(CC, true);
4002       }
4003     } else if (CTVal && CFVal) {
4004       const int64_t TrueVal = CTVal->getSExtValue();
4005       const int64_t FalseVal = CFVal->getSExtValue();
4006       bool Swap = false;
4007 
4008       // If both TVal and FVal are constants, see if FVal is the
4009       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4010       // instead of a CSEL in that case.
4011       if (TrueVal == ~FalseVal) {
4012         Opcode = AArch64ISD::CSINV;
4013       } else if (TrueVal == -FalseVal) {
4014         Opcode = AArch64ISD::CSNEG;
4015       } else if (TVal.getValueType() == MVT::i32) {
4016         // If our operands are only 32-bit wide, make sure we use 32-bit
4017         // arithmetic for the check whether we can use CSINC. This ensures that
4018         // the addition in the check will wrap around properly in case there is
4019         // an overflow (which would not be the case if we do the check with
4020         // 64-bit arithmetic).
4021         const uint32_t TrueVal32 = CTVal->getZExtValue();
4022         const uint32_t FalseVal32 = CFVal->getZExtValue();
4023 
4024         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4025           Opcode = AArch64ISD::CSINC;
4026 
4027           if (TrueVal32 > FalseVal32) {
4028             Swap = true;
4029           }
4030         }
4031         // 64-bit check whether we can use CSINC.
4032       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4033         Opcode = AArch64ISD::CSINC;
4034 
4035         if (TrueVal > FalseVal) {
4036           Swap = true;
4037         }
4038       }
4039 
4040       // Swap TVal and FVal if necessary.
4041       if (Swap) {
4042         std::swap(TVal, FVal);
4043         std::swap(CTVal, CFVal);
4044         CC = ISD::getSetCCInverse(CC, true);
4045       }
4046 
4047       if (Opcode != AArch64ISD::CSEL) {
4048         // Drop FVal since we can get its value by simply inverting/negating
4049         // TVal.
4050         FVal = TVal;
4051       }
4052     }
4053 
4054     SDValue CCVal;
4055     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4056 
4057     EVT VT = TVal.getValueType();
4058     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4059   }
4060 
4061   // Now we know we're dealing with FP values.
4062   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4063   assert(LHS.getValueType() == RHS.getValueType());
4064   EVT VT = TVal.getValueType();
4065   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4066 
4067   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4068   // clean.  Some of them require two CSELs to implement.
4069   AArch64CC::CondCode CC1, CC2;
4070   changeFPCCToAArch64CC(CC, CC1, CC2);
4071   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4072   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4073 
4074   // If we need a second CSEL, emit it, using the output of the first as the
4075   // RHS.  We're effectively OR'ing the two CC's together.
4076   if (CC2 != AArch64CC::AL) {
4077     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4078     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4079   }
4080 
4081   // Otherwise, return the output of the first CSEL.
4082   return CS1;
4083 }
4084 
4085 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4086                                               SelectionDAG &DAG) const {
4087   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4088   SDValue LHS = Op.getOperand(0);
4089   SDValue RHS = Op.getOperand(1);
4090   SDValue TVal = Op.getOperand(2);
4091   SDValue FVal = Op.getOperand(3);
4092   SDLoc DL(Op);
4093   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4094 }
4095 
4096 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4097                                            SelectionDAG &DAG) const {
4098   SDValue CCVal = Op->getOperand(0);
4099   SDValue TVal = Op->getOperand(1);
4100   SDValue FVal = Op->getOperand(2);
4101   SDLoc DL(Op);
4102 
4103   unsigned Opc = CCVal.getOpcode();
4104   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4105   // instruction.
4106   if (CCVal.getResNo() == 1 &&
4107       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4108        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4109     // Only lower legal XALUO ops.
4110     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4111       return SDValue();
4112 
4113     AArch64CC::CondCode OFCC;
4114     SDValue Value, Overflow;
4115     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4116     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4117 
4118     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4119                        CCVal, Overflow);
4120   }
4121 
4122   // Lower it the same way as we would lower a SELECT_CC node.
4123   ISD::CondCode CC;
4124   SDValue LHS, RHS;
4125   if (CCVal.getOpcode() == ISD::SETCC) {
4126     LHS = CCVal.getOperand(0);
4127     RHS = CCVal.getOperand(1);
4128     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4129   } else {
4130     LHS = CCVal;
4131     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4132     CC = ISD::SETNE;
4133   }
4134   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4135 }
4136 
4137 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4138                                               SelectionDAG &DAG) const {
4139   // Jump table entries as PC relative offsets. No additional tweaking
4140   // is necessary here. Just get the address of the jump table.
4141   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4142   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4143   SDLoc DL(Op);
4144 
4145   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4146       !Subtarget->isTargetMachO()) {
4147     const unsigned char MO_NC = AArch64II::MO_NC;
4148     return DAG.getNode(
4149         AArch64ISD::WrapperLarge, DL, PtrVT,
4150         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4151         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4152         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4153         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4154                                AArch64II::MO_G0 | MO_NC));
4155   }
4156 
4157   SDValue Hi =
4158       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4159   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4160                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4161   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4162   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4163 }
4164 
4165 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4166                                                  SelectionDAG &DAG) const {
4167   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4168   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4169   SDLoc DL(Op);
4170 
4171   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4172     // Use the GOT for the large code model on iOS.
4173     if (Subtarget->isTargetMachO()) {
4174       SDValue GotAddr = DAG.getTargetConstantPool(
4175           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4176           AArch64II::MO_GOT);
4177       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4178     }
4179 
4180     const unsigned char MO_NC = AArch64II::MO_NC;
4181     return DAG.getNode(
4182         AArch64ISD::WrapperLarge, DL, PtrVT,
4183         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4184                                   CP->getOffset(), AArch64II::MO_G3),
4185         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4186                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4187         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4188                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4189         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4190                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4191   } else {
4192     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4193     // ELF, the only valid one on Darwin.
4194     SDValue Hi =
4195         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4196                                   CP->getOffset(), AArch64II::MO_PAGE);
4197     SDValue Lo = DAG.getTargetConstantPool(
4198         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4199         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4200 
4201     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4202     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4203   }
4204 }
4205 
4206 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4207                                                SelectionDAG &DAG) const {
4208   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4209   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4210   SDLoc DL(Op);
4211   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4212       !Subtarget->isTargetMachO()) {
4213     const unsigned char MO_NC = AArch64II::MO_NC;
4214     return DAG.getNode(
4215         AArch64ISD::WrapperLarge, DL, PtrVT,
4216         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4217         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4218         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4219         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4220   } else {
4221     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4222     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4223                                                              AArch64II::MO_NC);
4224     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4225     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4226   }
4227 }
4228 
4229 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4230                                                  SelectionDAG &DAG) const {
4231   AArch64FunctionInfo *FuncInfo =
4232       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4233 
4234   SDLoc DL(Op);
4235   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4236                                  getPointerTy(DAG.getDataLayout()));
4237   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4238   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4239                       MachinePointerInfo(SV), false, false, 0);
4240 }
4241 
4242 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4243                                                 SelectionDAG &DAG) const {
4244   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4245   // Standard, section B.3.
4246   MachineFunction &MF = DAG.getMachineFunction();
4247   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4248   auto PtrVT = getPointerTy(DAG.getDataLayout());
4249   SDLoc DL(Op);
4250 
4251   SDValue Chain = Op.getOperand(0);
4252   SDValue VAList = Op.getOperand(1);
4253   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4254   SmallVector<SDValue, 4> MemOps;
4255 
4256   // void *__stack at offset 0
4257   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4258   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4259                                 MachinePointerInfo(SV), false, false, 8));
4260 
4261   // void *__gr_top at offset 8
4262   int GPRSize = FuncInfo->getVarArgsGPRSize();
4263   if (GPRSize > 0) {
4264     SDValue GRTop, GRTopAddr;
4265 
4266     GRTopAddr =
4267         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4268 
4269     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4270     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4271                         DAG.getConstant(GPRSize, DL, PtrVT));
4272 
4273     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4274                                   MachinePointerInfo(SV, 8), false, false, 8));
4275   }
4276 
4277   // void *__vr_top at offset 16
4278   int FPRSize = FuncInfo->getVarArgsFPRSize();
4279   if (FPRSize > 0) {
4280     SDValue VRTop, VRTopAddr;
4281     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4282                             DAG.getConstant(16, DL, PtrVT));
4283 
4284     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4285     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4286                         DAG.getConstant(FPRSize, DL, PtrVT));
4287 
4288     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4289                                   MachinePointerInfo(SV, 16), false, false, 8));
4290   }
4291 
4292   // int __gr_offs at offset 24
4293   SDValue GROffsAddr =
4294       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4295   MemOps.push_back(DAG.getStore(Chain, DL,
4296                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4297                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4298                                 false, 4));
4299 
4300   // int __vr_offs at offset 28
4301   SDValue VROffsAddr =
4302       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4303   MemOps.push_back(DAG.getStore(Chain, DL,
4304                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4305                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4306                                 false, 4));
4307 
4308   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4309 }
4310 
4311 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4312                                             SelectionDAG &DAG) const {
4313   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4314                                      : LowerAAPCS_VASTART(Op, DAG);
4315 }
4316 
4317 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4318                                            SelectionDAG &DAG) const {
4319   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4320   // pointer.
4321   SDLoc DL(Op);
4322   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4323   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4324   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4325 
4326   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4327                        Op.getOperand(2),
4328                        DAG.getConstant(VaListSize, DL, MVT::i32),
4329                        8, false, false, false, MachinePointerInfo(DestSV),
4330                        MachinePointerInfo(SrcSV));
4331 }
4332 
4333 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4334   assert(Subtarget->isTargetDarwin() &&
4335          "automatic va_arg instruction only works on Darwin");
4336 
4337   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4338   EVT VT = Op.getValueType();
4339   SDLoc DL(Op);
4340   SDValue Chain = Op.getOperand(0);
4341   SDValue Addr = Op.getOperand(1);
4342   unsigned Align = Op.getConstantOperandVal(3);
4343   auto PtrVT = getPointerTy(DAG.getDataLayout());
4344 
4345   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4346                                false, false, false, 0);
4347   Chain = VAList.getValue(1);
4348 
4349   if (Align > 8) {
4350     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4351     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4352                          DAG.getConstant(Align - 1, DL, PtrVT));
4353     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4354                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4355   }
4356 
4357   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4358   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4359 
4360   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4361   // up to 64 bits.  At the very least, we have to increase the striding of the
4362   // vaargs list to match this, and for FP values we need to introduce
4363   // FP_ROUND nodes as well.
4364   if (VT.isInteger() && !VT.isVector())
4365     ArgSize = 8;
4366   bool NeedFPTrunc = false;
4367   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4368     ArgSize = 8;
4369     NeedFPTrunc = true;
4370   }
4371 
4372   // Increment the pointer, VAList, to the next vaarg
4373   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4374                                DAG.getConstant(ArgSize, DL, PtrVT));
4375   // Store the incremented VAList to the legalized pointer
4376   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4377                                  false, false, 0);
4378 
4379   // Load the actual argument out of the pointer VAList
4380   if (NeedFPTrunc) {
4381     // Load the value as an f64.
4382     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4383                                  MachinePointerInfo(), false, false, false, 0);
4384     // Round the value down to an f32.
4385     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4386                                    DAG.getIntPtrConstant(1, DL));
4387     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4388     // Merge the rounded value with the chain output of the load.
4389     return DAG.getMergeValues(Ops, DL);
4390   }
4391 
4392   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4393                      false, false, 0);
4394 }
4395 
4396 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4397                                               SelectionDAG &DAG) const {
4398   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4399   MFI->setFrameAddressIsTaken(true);
4400 
4401   EVT VT = Op.getValueType();
4402   SDLoc DL(Op);
4403   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4404   SDValue FrameAddr =
4405       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4406   while (Depth--)
4407     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4408                             MachinePointerInfo(), false, false, false, 0);
4409   return FrameAddr;
4410 }
4411 
4412 // FIXME? Maybe this could be a TableGen attribute on some registers and
4413 // this table could be generated automatically from RegInfo.
4414 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4415                                                   SelectionDAG &DAG) const {
4416   unsigned Reg = StringSwitch<unsigned>(RegName)
4417                        .Case("sp", AArch64::SP)
4418                        .Default(0);
4419   if (Reg)
4420     return Reg;
4421   report_fatal_error(Twine("Invalid register name \""
4422                               + StringRef(RegName)  + "\"."));
4423 }
4424 
4425 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4426                                                SelectionDAG &DAG) const {
4427   MachineFunction &MF = DAG.getMachineFunction();
4428   MachineFrameInfo *MFI = MF.getFrameInfo();
4429   MFI->setReturnAddressIsTaken(true);
4430 
4431   EVT VT = Op.getValueType();
4432   SDLoc DL(Op);
4433   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4434   if (Depth) {
4435     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4436     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4437     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4438                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4439                        MachinePointerInfo(), false, false, false, 0);
4440   }
4441 
4442   // Return LR, which contains the return address. Mark it an implicit live-in.
4443   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4444   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4445 }
4446 
4447 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4448 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4449 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4450                                                     SelectionDAG &DAG) const {
4451   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4452   EVT VT = Op.getValueType();
4453   unsigned VTBits = VT.getSizeInBits();
4454   SDLoc dl(Op);
4455   SDValue ShOpLo = Op.getOperand(0);
4456   SDValue ShOpHi = Op.getOperand(1);
4457   SDValue ShAmt = Op.getOperand(2);
4458   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4459 
4460   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4461 
4462   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4463                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4464   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4465 
4466   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4467   // is "undef". We wanted 0, so CSEL it directly.
4468   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4469                                ISD::SETEQ, dl, DAG);
4470   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4471   HiBitsForLo =
4472       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4473                   HiBitsForLo, CCVal, Cmp);
4474 
4475   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4476                                    DAG.getConstant(VTBits, dl, MVT::i64));
4477 
4478   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4479   SDValue LoForNormalShift =
4480       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4481 
4482   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4483                        dl, DAG);
4484   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4485   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4486   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4487                            LoForNormalShift, CCVal, Cmp);
4488 
4489   // AArch64 shifts larger than the register width are wrapped rather than
4490   // clamped, so we can't just emit "hi >> x".
4491   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4492   SDValue HiForBigShift =
4493       Opc == ISD::SRA
4494           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4495                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4496           : DAG.getConstant(0, dl, VT);
4497   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4498                            HiForNormalShift, CCVal, Cmp);
4499 
4500   SDValue Ops[2] = { Lo, Hi };
4501   return DAG.getMergeValues(Ops, dl);
4502 }
4503 
4504 
4505 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4506 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4507 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4508                                                    SelectionDAG &DAG) const {
4509   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4510   EVT VT = Op.getValueType();
4511   unsigned VTBits = VT.getSizeInBits();
4512   SDLoc dl(Op);
4513   SDValue ShOpLo = Op.getOperand(0);
4514   SDValue ShOpHi = Op.getOperand(1);
4515   SDValue ShAmt = Op.getOperand(2);
4516 
4517   assert(Op.getOpcode() == ISD::SHL_PARTS);
4518   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4519                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4520   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4521 
4522   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4523   // is "undef". We wanted 0, so CSEL it directly.
4524   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4525                                ISD::SETEQ, dl, DAG);
4526   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4527   LoBitsForHi =
4528       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4529                   LoBitsForHi, CCVal, Cmp);
4530 
4531   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4532                                    DAG.getConstant(VTBits, dl, MVT::i64));
4533   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4534   SDValue HiForNormalShift =
4535       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4536 
4537   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4538 
4539   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4540                        dl, DAG);
4541   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4542   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4543                            HiForNormalShift, CCVal, Cmp);
4544 
4545   // AArch64 shifts of larger than register sizes are wrapped rather than
4546   // clamped, so we can't just emit "lo << a" if a is too big.
4547   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4548   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4549   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4550                            LoForNormalShift, CCVal, Cmp);
4551 
4552   SDValue Ops[2] = { Lo, Hi };
4553   return DAG.getMergeValues(Ops, dl);
4554 }
4555 
4556 bool AArch64TargetLowering::isOffsetFoldingLegal(
4557     const GlobalAddressSDNode *GA) const {
4558   // The AArch64 target doesn't support folding offsets into global addresses.
4559   return false;
4560 }
4561 
4562 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4563   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4564   // FIXME: We should be able to handle f128 as well with a clever lowering.
4565   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4566     return true;
4567 
4568   if (VT == MVT::f64)
4569     return AArch64_AM::getFP64Imm(Imm) != -1;
4570   else if (VT == MVT::f32)
4571     return AArch64_AM::getFP32Imm(Imm) != -1;
4572   return false;
4573 }
4574 
4575 //===----------------------------------------------------------------------===//
4576 //                          AArch64 Optimization Hooks
4577 //===----------------------------------------------------------------------===//
4578 
4579 //===----------------------------------------------------------------------===//
4580 //                          AArch64 Inline Assembly Support
4581 //===----------------------------------------------------------------------===//
4582 
4583 // Table of Constraints
4584 // TODO: This is the current set of constraints supported by ARM for the
4585 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4586 //
4587 // r - A general register
4588 // w - An FP/SIMD register of some size in the range v0-v31
4589 // x - An FP/SIMD register of some size in the range v0-v15
4590 // I - Constant that can be used with an ADD instruction
4591 // J - Constant that can be used with a SUB instruction
4592 // K - Constant that can be used with a 32-bit logical instruction
4593 // L - Constant that can be used with a 64-bit logical instruction
4594 // M - Constant that can be used as a 32-bit MOV immediate
4595 // N - Constant that can be used as a 64-bit MOV immediate
4596 // Q - A memory reference with base register and no offset
4597 // S - A symbolic address
4598 // Y - Floating point constant zero
4599 // Z - Integer constant zero
4600 //
4601 //   Note that general register operands will be output using their 64-bit x
4602 // register name, whatever the size of the variable, unless the asm operand
4603 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4604 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4605 // %q modifier.
4606 
4607 /// getConstraintType - Given a constraint letter, return the type of
4608 /// constraint it is for this target.
4609 AArch64TargetLowering::ConstraintType
4610 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4611   if (Constraint.size() == 1) {
4612     switch (Constraint[0]) {
4613     default:
4614       break;
4615     case 'z':
4616       return C_Other;
4617     case 'x':
4618     case 'w':
4619       return C_RegisterClass;
4620     // An address with a single base register. Due to the way we
4621     // currently handle addresses it is the same as 'r'.
4622     case 'Q':
4623       return C_Memory;
4624     }
4625   }
4626   return TargetLowering::getConstraintType(Constraint);
4627 }
4628 
4629 /// Examine constraint type and operand type and determine a weight value.
4630 /// This object must already have been set up with the operand type
4631 /// and the current alternative constraint selected.
4632 TargetLowering::ConstraintWeight
4633 AArch64TargetLowering::getSingleConstraintMatchWeight(
4634     AsmOperandInfo &info, const char *constraint) const {
4635   ConstraintWeight weight = CW_Invalid;
4636   Value *CallOperandVal = info.CallOperandVal;
4637   // If we don't have a value, we can't do a match,
4638   // but allow it at the lowest weight.
4639   if (!CallOperandVal)
4640     return CW_Default;
4641   Type *type = CallOperandVal->getType();
4642   // Look at the constraint type.
4643   switch (*constraint) {
4644   default:
4645     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4646     break;
4647   case 'x':
4648   case 'w':
4649     if (type->isFloatingPointTy() || type->isVectorTy())
4650       weight = CW_Register;
4651     break;
4652   case 'z':
4653     weight = CW_Constant;
4654     break;
4655   }
4656   return weight;
4657 }
4658 
4659 std::pair<unsigned, const TargetRegisterClass *>
4660 AArch64TargetLowering::getRegForInlineAsmConstraint(
4661     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4662   if (Constraint.size() == 1) {
4663     switch (Constraint[0]) {
4664     case 'r':
4665       if (VT.getSizeInBits() == 64)
4666         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4667       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4668     case 'w':
4669       if (VT == MVT::f32)
4670         return std::make_pair(0U, &AArch64::FPR32RegClass);
4671       if (VT.getSizeInBits() == 64)
4672         return std::make_pair(0U, &AArch64::FPR64RegClass);
4673       if (VT.getSizeInBits() == 128)
4674         return std::make_pair(0U, &AArch64::FPR128RegClass);
4675       break;
4676     // The instructions that this constraint is designed for can
4677     // only take 128-bit registers so just use that regclass.
4678     case 'x':
4679       if (VT.getSizeInBits() == 128)
4680         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4681       break;
4682     }
4683   }
4684   if (StringRef("{cc}").equals_lower(Constraint))
4685     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4686 
4687   // Use the default implementation in TargetLowering to convert the register
4688   // constraint into a member of a register class.
4689   std::pair<unsigned, const TargetRegisterClass *> Res;
4690   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4691 
4692   // Not found as a standard register?
4693   if (!Res.second) {
4694     unsigned Size = Constraint.size();
4695     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4696         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4697       int RegNo;
4698       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4699       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4700         // v0 - v31 are aliases of q0 - q31.
4701         // By default we'll emit v0-v31 for this unless there's a modifier where
4702         // we'll emit the correct register as well.
4703         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4704         Res.second = &AArch64::FPR128RegClass;
4705       }
4706     }
4707   }
4708 
4709   return Res;
4710 }
4711 
4712 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4713 /// vector.  If it is invalid, don't add anything to Ops.
4714 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4715     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4716     SelectionDAG &DAG) const {
4717   SDValue Result;
4718 
4719   // Currently only support length 1 constraints.
4720   if (Constraint.length() != 1)
4721     return;
4722 
4723   char ConstraintLetter = Constraint[0];
4724   switch (ConstraintLetter) {
4725   default:
4726     break;
4727 
4728   // This set of constraints deal with valid constants for various instructions.
4729   // Validate and return a target constant for them if we can.
4730   case 'z': {
4731     // 'z' maps to xzr or wzr so it needs an input of 0.
4732     if (!isNullConstant(Op))
4733       return;
4734 
4735     if (Op.getValueType() == MVT::i64)
4736       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4737     else
4738       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4739     break;
4740   }
4741 
4742   case 'I':
4743   case 'J':
4744   case 'K':
4745   case 'L':
4746   case 'M':
4747   case 'N':
4748     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4749     if (!C)
4750       return;
4751 
4752     // Grab the value and do some validation.
4753     uint64_t CVal = C->getZExtValue();
4754     switch (ConstraintLetter) {
4755     // The I constraint applies only to simple ADD or SUB immediate operands:
4756     // i.e. 0 to 4095 with optional shift by 12
4757     // The J constraint applies only to ADD or SUB immediates that would be
4758     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4759     // instruction [or vice versa], in other words -1 to -4095 with optional
4760     // left shift by 12.
4761     case 'I':
4762       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4763         break;
4764       return;
4765     case 'J': {
4766       uint64_t NVal = -C->getSExtValue();
4767       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4768         CVal = C->getSExtValue();
4769         break;
4770       }
4771       return;
4772     }
4773     // The K and L constraints apply *only* to logical immediates, including
4774     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4775     // been removed and MOV should be used). So these constraints have to
4776     // distinguish between bit patterns that are valid 32-bit or 64-bit
4777     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4778     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4779     // versa.
4780     case 'K':
4781       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4782         break;
4783       return;
4784     case 'L':
4785       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4786         break;
4787       return;
4788     // The M and N constraints are a superset of K and L respectively, for use
4789     // with the MOV (immediate) alias. As well as the logical immediates they
4790     // also match 32 or 64-bit immediates that can be loaded either using a
4791     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4792     // (M) or 64-bit 0x1234000000000000 (N) etc.
4793     // As a note some of this code is liberally stolen from the asm parser.
4794     case 'M': {
4795       if (!isUInt<32>(CVal))
4796         return;
4797       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4798         break;
4799       if ((CVal & 0xFFFF) == CVal)
4800         break;
4801       if ((CVal & 0xFFFF0000ULL) == CVal)
4802         break;
4803       uint64_t NCVal = ~(uint32_t)CVal;
4804       if ((NCVal & 0xFFFFULL) == NCVal)
4805         break;
4806       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4807         break;
4808       return;
4809     }
4810     case 'N': {
4811       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4812         break;
4813       if ((CVal & 0xFFFFULL) == CVal)
4814         break;
4815       if ((CVal & 0xFFFF0000ULL) == CVal)
4816         break;
4817       if ((CVal & 0xFFFF00000000ULL) == CVal)
4818         break;
4819       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4820         break;
4821       uint64_t NCVal = ~CVal;
4822       if ((NCVal & 0xFFFFULL) == NCVal)
4823         break;
4824       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4825         break;
4826       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4827         break;
4828       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4829         break;
4830       return;
4831     }
4832     default:
4833       return;
4834     }
4835 
4836     // All assembler immediates are 64-bit integers.
4837     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4838     break;
4839   }
4840 
4841   if (Result.getNode()) {
4842     Ops.push_back(Result);
4843     return;
4844   }
4845 
4846   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4847 }
4848 
4849 //===----------------------------------------------------------------------===//
4850 //                     AArch64 Advanced SIMD Support
4851 //===----------------------------------------------------------------------===//
4852 
4853 /// WidenVector - Given a value in the V64 register class, produce the
4854 /// equivalent value in the V128 register class.
4855 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4856   EVT VT = V64Reg.getValueType();
4857   unsigned NarrowSize = VT.getVectorNumElements();
4858   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4859   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4860   SDLoc DL(V64Reg);
4861 
4862   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4863                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4864 }
4865 
4866 /// getExtFactor - Determine the adjustment factor for the position when
4867 /// generating an "extract from vector registers" instruction.
4868 static unsigned getExtFactor(SDValue &V) {
4869   EVT EltType = V.getValueType().getVectorElementType();
4870   return EltType.getSizeInBits() / 8;
4871 }
4872 
4873 /// NarrowVector - Given a value in the V128 register class, produce the
4874 /// equivalent value in the V64 register class.
4875 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4876   EVT VT = V128Reg.getValueType();
4877   unsigned WideSize = VT.getVectorNumElements();
4878   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4879   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4880   SDLoc DL(V128Reg);
4881 
4882   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4883 }
4884 
4885 // Gather data to see if the operation can be modelled as a
4886 // shuffle in combination with VEXTs.
4887 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4888                                                   SelectionDAG &DAG) const {
4889   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4890   SDLoc dl(Op);
4891   EVT VT = Op.getValueType();
4892   unsigned NumElts = VT.getVectorNumElements();
4893 
4894   struct ShuffleSourceInfo {
4895     SDValue Vec;
4896     unsigned MinElt;
4897     unsigned MaxElt;
4898 
4899     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4900     // be compatible with the shuffle we intend to construct. As a result
4901     // ShuffleVec will be some sliding window into the original Vec.
4902     SDValue ShuffleVec;
4903 
4904     // Code should guarantee that element i in Vec starts at element "WindowBase
4905     // + i * WindowScale in ShuffleVec".
4906     int WindowBase;
4907     int WindowScale;
4908 
4909     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4910     ShuffleSourceInfo(SDValue Vec)
4911         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4912           WindowScale(1) {}
4913   };
4914 
4915   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4916   // node.
4917   SmallVector<ShuffleSourceInfo, 2> Sources;
4918   for (unsigned i = 0; i < NumElts; ++i) {
4919     SDValue V = Op.getOperand(i);
4920     if (V.getOpcode() == ISD::UNDEF)
4921       continue;
4922     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4923              !isa<ConstantSDNode>(V.getOperand(1))) {
4924       // A shuffle can only come from building a vector from various
4925       // elements of other vectors, provided their indices are constant.
4926       return SDValue();
4927     }
4928 
4929     // Add this element source to the list if it's not already there.
4930     SDValue SourceVec = V.getOperand(0);
4931     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4932     if (Source == Sources.end())
4933       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4934 
4935     // Update the minimum and maximum lane number seen.
4936     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4937     Source->MinElt = std::min(Source->MinElt, EltNo);
4938     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4939   }
4940 
4941   // Currently only do something sane when at most two source vectors
4942   // are involved.
4943   if (Sources.size() > 2)
4944     return SDValue();
4945 
4946   // Find out the smallest element size among result and two sources, and use
4947   // it as element size to build the shuffle_vector.
4948   EVT SmallestEltTy = VT.getVectorElementType();
4949   for (auto &Source : Sources) {
4950     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4951     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4952       SmallestEltTy = SrcEltTy;
4953     }
4954   }
4955   unsigned ResMultiplier =
4956       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4957   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4958   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4959 
4960   // If the source vector is too wide or too narrow, we may nevertheless be able
4961   // to construct a compatible shuffle either by concatenating it with UNDEF or
4962   // extracting a suitable range of elements.
4963   for (auto &Src : Sources) {
4964     EVT SrcVT = Src.ShuffleVec.getValueType();
4965 
4966     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4967       continue;
4968 
4969     // This stage of the search produces a source with the same element type as
4970     // the original, but with a total width matching the BUILD_VECTOR output.
4971     EVT EltVT = SrcVT.getVectorElementType();
4972     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4973     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4974 
4975     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4976       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4977       // We can pad out the smaller vector for free, so if it's part of a
4978       // shuffle...
4979       Src.ShuffleVec =
4980           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4981                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4982       continue;
4983     }
4984 
4985     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4986 
4987     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4988       // Span too large for a VEXT to cope
4989       return SDValue();
4990     }
4991 
4992     if (Src.MinElt >= NumSrcElts) {
4993       // The extraction can just take the second half
4994       Src.ShuffleVec =
4995           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4996                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4997       Src.WindowBase = -NumSrcElts;
4998     } else if (Src.MaxElt < NumSrcElts) {
4999       // The extraction can just take the first half
5000       Src.ShuffleVec =
5001           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5002                       DAG.getConstant(0, dl, MVT::i64));
5003     } else {
5004       // An actual VEXT is needed
5005       SDValue VEXTSrc1 =
5006           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5007                       DAG.getConstant(0, dl, MVT::i64));
5008       SDValue VEXTSrc2 =
5009           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5010                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5011       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5012 
5013       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5014                                    VEXTSrc2,
5015                                    DAG.getConstant(Imm, dl, MVT::i32));
5016       Src.WindowBase = -Src.MinElt;
5017     }
5018   }
5019 
5020   // Another possible incompatibility occurs from the vector element types. We
5021   // can fix this by bitcasting the source vectors to the same type we intend
5022   // for the shuffle.
5023   for (auto &Src : Sources) {
5024     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5025     if (SrcEltTy == SmallestEltTy)
5026       continue;
5027     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5028     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5029     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5030     Src.WindowBase *= Src.WindowScale;
5031   }
5032 
5033   // Final sanity check before we try to actually produce a shuffle.
5034   DEBUG(
5035     for (auto Src : Sources)
5036       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5037   );
5038 
5039   // The stars all align, our next step is to produce the mask for the shuffle.
5040   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5041   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5042   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5043     SDValue Entry = Op.getOperand(i);
5044     if (Entry.getOpcode() == ISD::UNDEF)
5045       continue;
5046 
5047     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5048     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5049 
5050     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5051     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5052     // segment.
5053     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5054     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5055                                VT.getVectorElementType().getSizeInBits());
5056     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5057 
5058     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5059     // starting at the appropriate offset.
5060     int *LaneMask = &Mask[i * ResMultiplier];
5061 
5062     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5063     ExtractBase += NumElts * (Src - Sources.begin());
5064     for (int j = 0; j < LanesDefined; ++j)
5065       LaneMask[j] = ExtractBase + j;
5066   }
5067 
5068   // Final check before we try to produce nonsense...
5069   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5070     return SDValue();
5071 
5072   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5073   for (unsigned i = 0; i < Sources.size(); ++i)
5074     ShuffleOps[i] = Sources[i].ShuffleVec;
5075 
5076   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5077                                          ShuffleOps[1], &Mask[0]);
5078   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5079 }
5080 
5081 // check if an EXT instruction can handle the shuffle mask when the
5082 // vector sources of the shuffle are the same.
5083 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5084   unsigned NumElts = VT.getVectorNumElements();
5085 
5086   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5087   if (M[0] < 0)
5088     return false;
5089 
5090   Imm = M[0];
5091 
5092   // If this is a VEXT shuffle, the immediate value is the index of the first
5093   // element.  The other shuffle indices must be the successive elements after
5094   // the first one.
5095   unsigned ExpectedElt = Imm;
5096   for (unsigned i = 1; i < NumElts; ++i) {
5097     // Increment the expected index.  If it wraps around, just follow it
5098     // back to index zero and keep going.
5099     ++ExpectedElt;
5100     if (ExpectedElt == NumElts)
5101       ExpectedElt = 0;
5102 
5103     if (M[i] < 0)
5104       continue; // ignore UNDEF indices
5105     if (ExpectedElt != static_cast<unsigned>(M[i]))
5106       return false;
5107   }
5108 
5109   return true;
5110 }
5111 
5112 // check if an EXT instruction can handle the shuffle mask when the
5113 // vector sources of the shuffle are different.
5114 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5115                       unsigned &Imm) {
5116   // Look for the first non-undef element.
5117   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5118       [](int Elt) {return Elt >= 0;});
5119 
5120   // Benefit form APInt to handle overflow when calculating expected element.
5121   unsigned NumElts = VT.getVectorNumElements();
5122   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5123   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5124   // The following shuffle indices must be the successive elements after the
5125   // first real element.
5126   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5127       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5128   if (FirstWrongElt != M.end())
5129     return false;
5130 
5131   // The index of an EXT is the first element if it is not UNDEF.
5132   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5133   // value of the first element.  E.g.
5134   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5135   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5136   // ExpectedElt is the last mask index plus 1.
5137   Imm = ExpectedElt.getZExtValue();
5138 
5139   // There are two difference cases requiring to reverse input vectors.
5140   // For example, for vector <4 x i32> we have the following cases,
5141   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5142   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5143   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5144   // to reverse two input vectors.
5145   if (Imm < NumElts)
5146     ReverseEXT = true;
5147   else
5148     Imm -= NumElts;
5149 
5150   return true;
5151 }
5152 
5153 /// isREVMask - Check if a vector shuffle corresponds to a REV
5154 /// instruction with the specified blocksize.  (The order of the elements
5155 /// within each block of the vector is reversed.)
5156 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5157   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5158          "Only possible block sizes for REV are: 16, 32, 64");
5159 
5160   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5161   if (EltSz == 64)
5162     return false;
5163 
5164   unsigned NumElts = VT.getVectorNumElements();
5165   unsigned BlockElts = M[0] + 1;
5166   // If the first shuffle index is UNDEF, be optimistic.
5167   if (M[0] < 0)
5168     BlockElts = BlockSize / EltSz;
5169 
5170   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5171     return false;
5172 
5173   for (unsigned i = 0; i < NumElts; ++i) {
5174     if (M[i] < 0)
5175       continue; // ignore UNDEF indices
5176     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5177       return false;
5178   }
5179 
5180   return true;
5181 }
5182 
5183 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5184   unsigned NumElts = VT.getVectorNumElements();
5185   WhichResult = (M[0] == 0 ? 0 : 1);
5186   unsigned Idx = WhichResult * NumElts / 2;
5187   for (unsigned i = 0; i != NumElts; i += 2) {
5188     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5189         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5190       return false;
5191     Idx += 1;
5192   }
5193 
5194   return true;
5195 }
5196 
5197 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5198   unsigned NumElts = VT.getVectorNumElements();
5199   WhichResult = (M[0] == 0 ? 0 : 1);
5200   for (unsigned i = 0; i != NumElts; ++i) {
5201     if (M[i] < 0)
5202       continue; // ignore UNDEF indices
5203     if ((unsigned)M[i] != 2 * i + WhichResult)
5204       return false;
5205   }
5206 
5207   return true;
5208 }
5209 
5210 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5211   unsigned NumElts = VT.getVectorNumElements();
5212   WhichResult = (M[0] == 0 ? 0 : 1);
5213   for (unsigned i = 0; i < NumElts; i += 2) {
5214     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5215         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5216       return false;
5217   }
5218   return true;
5219 }
5220 
5221 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5222 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5223 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5224 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5225   unsigned NumElts = VT.getVectorNumElements();
5226   WhichResult = (M[0] == 0 ? 0 : 1);
5227   unsigned Idx = WhichResult * NumElts / 2;
5228   for (unsigned i = 0; i != NumElts; i += 2) {
5229     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5230         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5231       return false;
5232     Idx += 1;
5233   }
5234 
5235   return true;
5236 }
5237 
5238 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5239 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5240 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5241 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5242   unsigned Half = VT.getVectorNumElements() / 2;
5243   WhichResult = (M[0] == 0 ? 0 : 1);
5244   for (unsigned j = 0; j != 2; ++j) {
5245     unsigned Idx = WhichResult;
5246     for (unsigned i = 0; i != Half; ++i) {
5247       int MIdx = M[i + j * Half];
5248       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5249         return false;
5250       Idx += 2;
5251     }
5252   }
5253 
5254   return true;
5255 }
5256 
5257 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5258 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5259 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5260 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5261   unsigned NumElts = VT.getVectorNumElements();
5262   WhichResult = (M[0] == 0 ? 0 : 1);
5263   for (unsigned i = 0; i < NumElts; i += 2) {
5264     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5265         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5266       return false;
5267   }
5268   return true;
5269 }
5270 
5271 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5272                       bool &DstIsLeft, int &Anomaly) {
5273   if (M.size() != static_cast<size_t>(NumInputElements))
5274     return false;
5275 
5276   int NumLHSMatch = 0, NumRHSMatch = 0;
5277   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5278 
5279   for (int i = 0; i < NumInputElements; ++i) {
5280     if (M[i] == -1) {
5281       ++NumLHSMatch;
5282       ++NumRHSMatch;
5283       continue;
5284     }
5285 
5286     if (M[i] == i)
5287       ++NumLHSMatch;
5288     else
5289       LastLHSMismatch = i;
5290 
5291     if (M[i] == i + NumInputElements)
5292       ++NumRHSMatch;
5293     else
5294       LastRHSMismatch = i;
5295   }
5296 
5297   if (NumLHSMatch == NumInputElements - 1) {
5298     DstIsLeft = true;
5299     Anomaly = LastLHSMismatch;
5300     return true;
5301   } else if (NumRHSMatch == NumInputElements - 1) {
5302     DstIsLeft = false;
5303     Anomaly = LastRHSMismatch;
5304     return true;
5305   }
5306 
5307   return false;
5308 }
5309 
5310 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5311   if (VT.getSizeInBits() != 128)
5312     return false;
5313 
5314   unsigned NumElts = VT.getVectorNumElements();
5315 
5316   for (int I = 0, E = NumElts / 2; I != E; I++) {
5317     if (Mask[I] != I)
5318       return false;
5319   }
5320 
5321   int Offset = NumElts / 2;
5322   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5323     if (Mask[I] != I + SplitLHS * Offset)
5324       return false;
5325   }
5326 
5327   return true;
5328 }
5329 
5330 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5331   SDLoc DL(Op);
5332   EVT VT = Op.getValueType();
5333   SDValue V0 = Op.getOperand(0);
5334   SDValue V1 = Op.getOperand(1);
5335   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5336 
5337   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5338       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5339     return SDValue();
5340 
5341   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5342 
5343   if (!isConcatMask(Mask, VT, SplitV0))
5344     return SDValue();
5345 
5346   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5347                                 VT.getVectorNumElements() / 2);
5348   if (SplitV0) {
5349     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5350                      DAG.getConstant(0, DL, MVT::i64));
5351   }
5352   if (V1.getValueType().getSizeInBits() == 128) {
5353     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5354                      DAG.getConstant(0, DL, MVT::i64));
5355   }
5356   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5357 }
5358 
5359 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5360 /// the specified operations to build the shuffle.
5361 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5362                                       SDValue RHS, SelectionDAG &DAG,
5363                                       SDLoc dl) {
5364   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5365   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5366   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5367 
5368   enum {
5369     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5370     OP_VREV,
5371     OP_VDUP0,
5372     OP_VDUP1,
5373     OP_VDUP2,
5374     OP_VDUP3,
5375     OP_VEXT1,
5376     OP_VEXT2,
5377     OP_VEXT3,
5378     OP_VUZPL, // VUZP, left result
5379     OP_VUZPR, // VUZP, right result
5380     OP_VZIPL, // VZIP, left result
5381     OP_VZIPR, // VZIP, right result
5382     OP_VTRNL, // VTRN, left result
5383     OP_VTRNR  // VTRN, right result
5384   };
5385 
5386   if (OpNum == OP_COPY) {
5387     if (LHSID == (1 * 9 + 2) * 9 + 3)
5388       return LHS;
5389     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5390     return RHS;
5391   }
5392 
5393   SDValue OpLHS, OpRHS;
5394   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5395   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5396   EVT VT = OpLHS.getValueType();
5397 
5398   switch (OpNum) {
5399   default:
5400     llvm_unreachable("Unknown shuffle opcode!");
5401   case OP_VREV:
5402     // VREV divides the vector in half and swaps within the half.
5403     if (VT.getVectorElementType() == MVT::i32 ||
5404         VT.getVectorElementType() == MVT::f32)
5405       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5406     // vrev <4 x i16> -> REV32
5407     if (VT.getVectorElementType() == MVT::i16 ||
5408         VT.getVectorElementType() == MVT::f16)
5409       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5410     // vrev <4 x i8> -> REV16
5411     assert(VT.getVectorElementType() == MVT::i8);
5412     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5413   case OP_VDUP0:
5414   case OP_VDUP1:
5415   case OP_VDUP2:
5416   case OP_VDUP3: {
5417     EVT EltTy = VT.getVectorElementType();
5418     unsigned Opcode;
5419     if (EltTy == MVT::i8)
5420       Opcode = AArch64ISD::DUPLANE8;
5421     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5422       Opcode = AArch64ISD::DUPLANE16;
5423     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5424       Opcode = AArch64ISD::DUPLANE32;
5425     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5426       Opcode = AArch64ISD::DUPLANE64;
5427     else
5428       llvm_unreachable("Invalid vector element type?");
5429 
5430     if (VT.getSizeInBits() == 64)
5431       OpLHS = WidenVector(OpLHS, DAG);
5432     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5433     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5434   }
5435   case OP_VEXT1:
5436   case OP_VEXT2:
5437   case OP_VEXT3: {
5438     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5439     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5440                        DAG.getConstant(Imm, dl, MVT::i32));
5441   }
5442   case OP_VUZPL:
5443     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5444                        OpRHS);
5445   case OP_VUZPR:
5446     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5447                        OpRHS);
5448   case OP_VZIPL:
5449     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5450                        OpRHS);
5451   case OP_VZIPR:
5452     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5453                        OpRHS);
5454   case OP_VTRNL:
5455     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5456                        OpRHS);
5457   case OP_VTRNR:
5458     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5459                        OpRHS);
5460   }
5461 }
5462 
5463 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5464                            SelectionDAG &DAG) {
5465   // Check to see if we can use the TBL instruction.
5466   SDValue V1 = Op.getOperand(0);
5467   SDValue V2 = Op.getOperand(1);
5468   SDLoc DL(Op);
5469 
5470   EVT EltVT = Op.getValueType().getVectorElementType();
5471   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5472 
5473   SmallVector<SDValue, 8> TBLMask;
5474   for (int Val : ShuffleMask) {
5475     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5476       unsigned Offset = Byte + Val * BytesPerElt;
5477       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5478     }
5479   }
5480 
5481   MVT IndexVT = MVT::v8i8;
5482   unsigned IndexLen = 8;
5483   if (Op.getValueType().getSizeInBits() == 128) {
5484     IndexVT = MVT::v16i8;
5485     IndexLen = 16;
5486   }
5487 
5488   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5489   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5490 
5491   SDValue Shuffle;
5492   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5493     if (IndexLen == 8)
5494       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5495     Shuffle = DAG.getNode(
5496         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5497         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5498         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5499                     makeArrayRef(TBLMask.data(), IndexLen)));
5500   } else {
5501     if (IndexLen == 8) {
5502       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5503       Shuffle = DAG.getNode(
5504           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5505           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5506           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5507                       makeArrayRef(TBLMask.data(), IndexLen)));
5508     } else {
5509       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5510       // cannot currently represent the register constraints on the input
5511       // table registers.
5512       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5513       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5514       //                               &TBLMask[0], IndexLen));
5515       Shuffle = DAG.getNode(
5516           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5517           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5518           V1Cst, V2Cst,
5519           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5520                       makeArrayRef(TBLMask.data(), IndexLen)));
5521     }
5522   }
5523   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5524 }
5525 
5526 static unsigned getDUPLANEOp(EVT EltType) {
5527   if (EltType == MVT::i8)
5528     return AArch64ISD::DUPLANE8;
5529   if (EltType == MVT::i16 || EltType == MVT::f16)
5530     return AArch64ISD::DUPLANE16;
5531   if (EltType == MVT::i32 || EltType == MVT::f32)
5532     return AArch64ISD::DUPLANE32;
5533   if (EltType == MVT::i64 || EltType == MVT::f64)
5534     return AArch64ISD::DUPLANE64;
5535 
5536   llvm_unreachable("Invalid vector element type?");
5537 }
5538 
5539 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5540                                                    SelectionDAG &DAG) const {
5541   SDLoc dl(Op);
5542   EVT VT = Op.getValueType();
5543 
5544   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5545 
5546   // Convert shuffles that are directly supported on NEON to target-specific
5547   // DAG nodes, instead of keeping them as shuffles and matching them again
5548   // during code selection.  This is more efficient and avoids the possibility
5549   // of inconsistencies between legalization and selection.
5550   ArrayRef<int> ShuffleMask = SVN->getMask();
5551 
5552   SDValue V1 = Op.getOperand(0);
5553   SDValue V2 = Op.getOperand(1);
5554 
5555   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5556                                        V1.getValueType().getSimpleVT())) {
5557     int Lane = SVN->getSplatIndex();
5558     // If this is undef splat, generate it via "just" vdup, if possible.
5559     if (Lane == -1)
5560       Lane = 0;
5561 
5562     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5563       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5564                          V1.getOperand(0));
5565     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5566     // constant. If so, we can just reference the lane's definition directly.
5567     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5568         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5569       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5570 
5571     // Otherwise, duplicate from the lane of the input vector.
5572     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5573 
5574     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5575     // to make a vector of the same size as this SHUFFLE. We can ignore the
5576     // extract entirely, and canonicalise the concat using WidenVector.
5577     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5578       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5579       V1 = V1.getOperand(0);
5580     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5581       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5582       Lane -= Idx * VT.getVectorNumElements() / 2;
5583       V1 = WidenVector(V1.getOperand(Idx), DAG);
5584     } else if (VT.getSizeInBits() == 64)
5585       V1 = WidenVector(V1, DAG);
5586 
5587     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5588   }
5589 
5590   if (isREVMask(ShuffleMask, VT, 64))
5591     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5592   if (isREVMask(ShuffleMask, VT, 32))
5593     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5594   if (isREVMask(ShuffleMask, VT, 16))
5595     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5596 
5597   bool ReverseEXT = false;
5598   unsigned Imm;
5599   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5600     if (ReverseEXT)
5601       std::swap(V1, V2);
5602     Imm *= getExtFactor(V1);
5603     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5604                        DAG.getConstant(Imm, dl, MVT::i32));
5605   } else if (V2->getOpcode() == ISD::UNDEF &&
5606              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5607     Imm *= getExtFactor(V1);
5608     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5609                        DAG.getConstant(Imm, dl, MVT::i32));
5610   }
5611 
5612   unsigned WhichResult;
5613   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5614     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5615     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5616   }
5617   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5618     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5619     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5620   }
5621   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5622     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5623     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5624   }
5625 
5626   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5627     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5628     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5629   }
5630   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5631     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5632     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5633   }
5634   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5635     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5636     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5637   }
5638 
5639   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5640   if (Concat.getNode())
5641     return Concat;
5642 
5643   bool DstIsLeft;
5644   int Anomaly;
5645   int NumInputElements = V1.getValueType().getVectorNumElements();
5646   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5647     SDValue DstVec = DstIsLeft ? V1 : V2;
5648     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5649 
5650     SDValue SrcVec = V1;
5651     int SrcLane = ShuffleMask[Anomaly];
5652     if (SrcLane >= NumInputElements) {
5653       SrcVec = V2;
5654       SrcLane -= VT.getVectorNumElements();
5655     }
5656     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5657 
5658     EVT ScalarVT = VT.getVectorElementType();
5659 
5660     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5661       ScalarVT = MVT::i32;
5662 
5663     return DAG.getNode(
5664         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5665         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5666         DstLaneV);
5667   }
5668 
5669   // If the shuffle is not directly supported and it has 4 elements, use
5670   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5671   unsigned NumElts = VT.getVectorNumElements();
5672   if (NumElts == 4) {
5673     unsigned PFIndexes[4];
5674     for (unsigned i = 0; i != 4; ++i) {
5675       if (ShuffleMask[i] < 0)
5676         PFIndexes[i] = 8;
5677       else
5678         PFIndexes[i] = ShuffleMask[i];
5679     }
5680 
5681     // Compute the index in the perfect shuffle table.
5682     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5683                             PFIndexes[2] * 9 + PFIndexes[3];
5684     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5685     unsigned Cost = (PFEntry >> 30);
5686 
5687     if (Cost <= 4)
5688       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5689   }
5690 
5691   return GenerateTBL(Op, ShuffleMask, DAG);
5692 }
5693 
5694 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5695                                APInt &UndefBits) {
5696   EVT VT = BVN->getValueType(0);
5697   APInt SplatBits, SplatUndef;
5698   unsigned SplatBitSize;
5699   bool HasAnyUndefs;
5700   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5701     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5702 
5703     for (unsigned i = 0; i < NumSplats; ++i) {
5704       CnstBits <<= SplatBitSize;
5705       UndefBits <<= SplatBitSize;
5706       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5707       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5708     }
5709 
5710     return true;
5711   }
5712 
5713   return false;
5714 }
5715 
5716 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5717                                               SelectionDAG &DAG) const {
5718   BuildVectorSDNode *BVN =
5719       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5720   SDValue LHS = Op.getOperand(0);
5721   SDLoc dl(Op);
5722   EVT VT = Op.getValueType();
5723 
5724   if (!BVN)
5725     return Op;
5726 
5727   APInt CnstBits(VT.getSizeInBits(), 0);
5728   APInt UndefBits(VT.getSizeInBits(), 0);
5729   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5730     // We only have BIC vector immediate instruction, which is and-not.
5731     CnstBits = ~CnstBits;
5732 
5733     // We make use of a little bit of goto ickiness in order to avoid having to
5734     // duplicate the immediate matching logic for the undef toggled case.
5735     bool SecondTry = false;
5736   AttemptModImm:
5737 
5738     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5739       CnstBits = CnstBits.zextOrTrunc(64);
5740       uint64_t CnstVal = CnstBits.getZExtValue();
5741 
5742       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5743         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5744         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5745         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5746                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5747                                   DAG.getConstant(0, dl, MVT::i32));
5748         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5749       }
5750 
5751       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5752         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5753         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5754         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5755                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5756                                   DAG.getConstant(8, dl, MVT::i32));
5757         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5758       }
5759 
5760       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5761         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5762         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5763         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5764                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5765                                   DAG.getConstant(16, dl, MVT::i32));
5766         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5767       }
5768 
5769       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5770         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5771         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5772         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5773                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5774                                   DAG.getConstant(24, dl, MVT::i32));
5775         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5776       }
5777 
5778       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5779         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5780         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5781         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5782                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5783                                   DAG.getConstant(0, dl, MVT::i32));
5784         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5785       }
5786 
5787       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5788         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5789         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5790         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5791                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5792                                   DAG.getConstant(8, dl, MVT::i32));
5793         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5794       }
5795     }
5796 
5797     if (SecondTry)
5798       goto FailedModImm;
5799     SecondTry = true;
5800     CnstBits = ~UndefBits;
5801     goto AttemptModImm;
5802   }
5803 
5804 // We can always fall back to a non-immediate AND.
5805 FailedModImm:
5806   return Op;
5807 }
5808 
5809 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5810 // consists of only the same constant int value, returned in reference arg
5811 // ConstVal
5812 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5813                                      uint64_t &ConstVal) {
5814   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5815   if (!Bvec)
5816     return false;
5817   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5818   if (!FirstElt)
5819     return false;
5820   EVT VT = Bvec->getValueType(0);
5821   unsigned NumElts = VT.getVectorNumElements();
5822   for (unsigned i = 1; i < NumElts; ++i)
5823     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5824       return false;
5825   ConstVal = FirstElt->getZExtValue();
5826   return true;
5827 }
5828 
5829 static unsigned getIntrinsicID(const SDNode *N) {
5830   unsigned Opcode = N->getOpcode();
5831   switch (Opcode) {
5832   default:
5833     return Intrinsic::not_intrinsic;
5834   case ISD::INTRINSIC_WO_CHAIN: {
5835     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5836     if (IID < Intrinsic::num_intrinsics)
5837       return IID;
5838     return Intrinsic::not_intrinsic;
5839   }
5840   }
5841 }
5842 
5843 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5844 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5845 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5846 // Also, logical shift right -> sri, with the same structure.
5847 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5848   EVT VT = N->getValueType(0);
5849 
5850   if (!VT.isVector())
5851     return SDValue();
5852 
5853   SDLoc DL(N);
5854 
5855   // Is the first op an AND?
5856   const SDValue And = N->getOperand(0);
5857   if (And.getOpcode() != ISD::AND)
5858     return SDValue();
5859 
5860   // Is the second op an shl or lshr?
5861   SDValue Shift = N->getOperand(1);
5862   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5863   // or AArch64ISD::VLSHR vector, #shift
5864   unsigned ShiftOpc = Shift.getOpcode();
5865   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5866     return SDValue();
5867   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5868 
5869   // Is the shift amount constant?
5870   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5871   if (!C2node)
5872     return SDValue();
5873 
5874   // Is the and mask vector all constant?
5875   uint64_t C1;
5876   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5877     return SDValue();
5878 
5879   // Is C1 == ~C2, taking into account how much one can shift elements of a
5880   // particular size?
5881   uint64_t C2 = C2node->getZExtValue();
5882   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5883   if (C2 > ElemSizeInBits)
5884     return SDValue();
5885   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5886   if ((C1 & ElemMask) != (~C2 & ElemMask))
5887     return SDValue();
5888 
5889   SDValue X = And.getOperand(0);
5890   SDValue Y = Shift.getOperand(0);
5891 
5892   unsigned Intrin =
5893       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5894   SDValue ResultSLI =
5895       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5896                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5897                   Shift.getOperand(1));
5898 
5899   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5900   DEBUG(N->dump(&DAG));
5901   DEBUG(dbgs() << "into: \n");
5902   DEBUG(ResultSLI->dump(&DAG));
5903 
5904   ++NumShiftInserts;
5905   return ResultSLI;
5906 }
5907 
5908 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5909                                              SelectionDAG &DAG) const {
5910   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5911   if (EnableAArch64SlrGeneration) {
5912     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5913     if (Res.getNode())
5914       return Res;
5915   }
5916 
5917   BuildVectorSDNode *BVN =
5918       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5919   SDValue LHS = Op.getOperand(1);
5920   SDLoc dl(Op);
5921   EVT VT = Op.getValueType();
5922 
5923   // OR commutes, so try swapping the operands.
5924   if (!BVN) {
5925     LHS = Op.getOperand(0);
5926     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5927   }
5928   if (!BVN)
5929     return Op;
5930 
5931   APInt CnstBits(VT.getSizeInBits(), 0);
5932   APInt UndefBits(VT.getSizeInBits(), 0);
5933   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5934     // We make use of a little bit of goto ickiness in order to avoid having to
5935     // duplicate the immediate matching logic for the undef toggled case.
5936     bool SecondTry = false;
5937   AttemptModImm:
5938 
5939     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5940       CnstBits = CnstBits.zextOrTrunc(64);
5941       uint64_t CnstVal = CnstBits.getZExtValue();
5942 
5943       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5944         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5945         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5946         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5947                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5948                                   DAG.getConstant(0, dl, MVT::i32));
5949         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5950       }
5951 
5952       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5953         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5954         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5955         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5956                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5957                                   DAG.getConstant(8, dl, MVT::i32));
5958         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5959       }
5960 
5961       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5962         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5963         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5964         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5965                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5966                                   DAG.getConstant(16, dl, MVT::i32));
5967         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5968       }
5969 
5970       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5971         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5972         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5973         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5974                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5975                                   DAG.getConstant(24, dl, MVT::i32));
5976         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5977       }
5978 
5979       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5980         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5981         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5982         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5983                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5984                                   DAG.getConstant(0, dl, MVT::i32));
5985         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5986       }
5987 
5988       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5989         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5990         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5991         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5992                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5993                                   DAG.getConstant(8, dl, MVT::i32));
5994         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5995       }
5996     }
5997 
5998     if (SecondTry)
5999       goto FailedModImm;
6000     SecondTry = true;
6001     CnstBits = UndefBits;
6002     goto AttemptModImm;
6003   }
6004 
6005 // We can always fall back to a non-immediate OR.
6006 FailedModImm:
6007   return Op;
6008 }
6009 
6010 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6011 // be truncated to fit element width.
6012 static SDValue NormalizeBuildVector(SDValue Op,
6013                                     SelectionDAG &DAG) {
6014   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6015   SDLoc dl(Op);
6016   EVT VT = Op.getValueType();
6017   EVT EltTy= VT.getVectorElementType();
6018 
6019   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6020     return Op;
6021 
6022   SmallVector<SDValue, 16> Ops;
6023   for (SDValue Lane : Op->ops()) {
6024     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6025       APInt LowBits(EltTy.getSizeInBits(),
6026                     CstLane->getZExtValue());
6027       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6028     }
6029     Ops.push_back(Lane);
6030   }
6031   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6032 }
6033 
6034 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6035                                                  SelectionDAG &DAG) const {
6036   SDLoc dl(Op);
6037   EVT VT = Op.getValueType();
6038   Op = NormalizeBuildVector(Op, DAG);
6039   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6040 
6041   APInt CnstBits(VT.getSizeInBits(), 0);
6042   APInt UndefBits(VT.getSizeInBits(), 0);
6043   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6044     // We make use of a little bit of goto ickiness in order to avoid having to
6045     // duplicate the immediate matching logic for the undef toggled case.
6046     bool SecondTry = false;
6047   AttemptModImm:
6048 
6049     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6050       CnstBits = CnstBits.zextOrTrunc(64);
6051       uint64_t CnstVal = CnstBits.getZExtValue();
6052 
6053       // Certain magic vector constants (used to express things like NOT
6054       // and NEG) are passed through unmodified.  This allows codegen patterns
6055       // for these operations to match.  Special-purpose patterns will lower
6056       // these immediates to MOVIs if it proves necessary.
6057       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6058         return Op;
6059 
6060       // The many faces of MOVI...
6061       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6062         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6063         if (VT.getSizeInBits() == 128) {
6064           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6065                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6066           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6067         }
6068 
6069         // Support the V64 version via subregister insertion.
6070         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6071                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6072         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6073       }
6074 
6075       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6076         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6077         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6078         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6079                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6080                                   DAG.getConstant(0, dl, MVT::i32));
6081         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6082       }
6083 
6084       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6085         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6086         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6087         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6088                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6089                                   DAG.getConstant(8, dl, MVT::i32));
6090         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6091       }
6092 
6093       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6094         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6095         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6096         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6097                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6098                                   DAG.getConstant(16, dl, MVT::i32));
6099         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6100       }
6101 
6102       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6103         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6104         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6105         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6106                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6107                                   DAG.getConstant(24, dl, MVT::i32));
6108         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6109       }
6110 
6111       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6112         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6113         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6114         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6115                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6116                                   DAG.getConstant(0, dl, MVT::i32));
6117         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6118       }
6119 
6120       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6121         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6122         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6123         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6124                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6125                                   DAG.getConstant(8, dl, MVT::i32));
6126         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6127       }
6128 
6129       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6130         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6131         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6132         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6133                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6134                                   DAG.getConstant(264, dl, MVT::i32));
6135         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6136       }
6137 
6138       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6139         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6140         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6141         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6142                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6143                                   DAG.getConstant(272, dl, MVT::i32));
6144         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6145       }
6146 
6147       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6148         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6149         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6150         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6151                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6152         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6153       }
6154 
6155       // The few faces of FMOV...
6156       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6157         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6158         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6159         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6160                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6161         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6162       }
6163 
6164       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6165           VT.getSizeInBits() == 128) {
6166         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6167         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6168                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6169         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6170       }
6171 
6172       // The many faces of MVNI...
6173       CnstVal = ~CnstVal;
6174       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6175         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6176         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6177         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6178                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6179                                   DAG.getConstant(0, dl, MVT::i32));
6180         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6181       }
6182 
6183       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6184         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6185         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6186         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6187                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6188                                   DAG.getConstant(8, dl, MVT::i32));
6189         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6190       }
6191 
6192       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6193         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6194         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6195         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6196                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6197                                   DAG.getConstant(16, dl, MVT::i32));
6198         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6199       }
6200 
6201       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6202         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6203         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6204         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6205                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6206                                   DAG.getConstant(24, dl, MVT::i32));
6207         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6208       }
6209 
6210       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6211         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6212         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6213         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6214                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6215                                   DAG.getConstant(0, dl, MVT::i32));
6216         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6217       }
6218 
6219       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6220         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6221         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6222         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6223                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6224                                   DAG.getConstant(8, dl, MVT::i32));
6225         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6226       }
6227 
6228       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6229         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6230         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6231         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6232                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6233                                   DAG.getConstant(264, dl, MVT::i32));
6234         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6235       }
6236 
6237       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6238         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6239         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6240         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6241                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6242                                   DAG.getConstant(272, dl, MVT::i32));
6243         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6244       }
6245     }
6246 
6247     if (SecondTry)
6248       goto FailedModImm;
6249     SecondTry = true;
6250     CnstBits = UndefBits;
6251     goto AttemptModImm;
6252   }
6253 FailedModImm:
6254 
6255   // Scan through the operands to find some interesting properties we can
6256   // exploit:
6257   //   1) If only one value is used, we can use a DUP, or
6258   //   2) if only the low element is not undef, we can just insert that, or
6259   //   3) if only one constant value is used (w/ some non-constant lanes),
6260   //      we can splat the constant value into the whole vector then fill
6261   //      in the non-constant lanes.
6262   //   4) FIXME: If different constant values are used, but we can intelligently
6263   //             select the values we'll be overwriting for the non-constant
6264   //             lanes such that we can directly materialize the vector
6265   //             some other way (MOVI, e.g.), we can be sneaky.
6266   unsigned NumElts = VT.getVectorNumElements();
6267   bool isOnlyLowElement = true;
6268   bool usesOnlyOneValue = true;
6269   bool usesOnlyOneConstantValue = true;
6270   bool isConstant = true;
6271   unsigned NumConstantLanes = 0;
6272   SDValue Value;
6273   SDValue ConstantValue;
6274   for (unsigned i = 0; i < NumElts; ++i) {
6275     SDValue V = Op.getOperand(i);
6276     if (V.getOpcode() == ISD::UNDEF)
6277       continue;
6278     if (i > 0)
6279       isOnlyLowElement = false;
6280     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6281       isConstant = false;
6282 
6283     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6284       ++NumConstantLanes;
6285       if (!ConstantValue.getNode())
6286         ConstantValue = V;
6287       else if (ConstantValue != V)
6288         usesOnlyOneConstantValue = false;
6289     }
6290 
6291     if (!Value.getNode())
6292       Value = V;
6293     else if (V != Value)
6294       usesOnlyOneValue = false;
6295   }
6296 
6297   if (!Value.getNode())
6298     return DAG.getUNDEF(VT);
6299 
6300   if (isOnlyLowElement)
6301     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6302 
6303   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6304   // i32 and try again.
6305   if (usesOnlyOneValue) {
6306     if (!isConstant) {
6307       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6308           Value.getValueType() != VT)
6309         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6310 
6311       // This is actually a DUPLANExx operation, which keeps everything vectory.
6312 
6313       // DUPLANE works on 128-bit vectors, widen it if necessary.
6314       SDValue Lane = Value.getOperand(1);
6315       Value = Value.getOperand(0);
6316       if (Value.getValueType().getSizeInBits() == 64)
6317         Value = WidenVector(Value, DAG);
6318 
6319       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6320       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6321     }
6322 
6323     if (VT.getVectorElementType().isFloatingPoint()) {
6324       SmallVector<SDValue, 8> Ops;
6325       EVT EltTy = VT.getVectorElementType();
6326       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6327               "Unsupported floating-point vector type");
6328       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6329       for (unsigned i = 0; i < NumElts; ++i)
6330         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6331       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6332       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6333       Val = LowerBUILD_VECTOR(Val, DAG);
6334       if (Val.getNode())
6335         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6336     }
6337   }
6338 
6339   // If there was only one constant value used and for more than one lane,
6340   // start by splatting that value, then replace the non-constant lanes. This
6341   // is better than the default, which will perform a separate initialization
6342   // for each lane.
6343   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6344     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6345     // Now insert the non-constant lanes.
6346     for (unsigned i = 0; i < NumElts; ++i) {
6347       SDValue V = Op.getOperand(i);
6348       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6349       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6350         // Note that type legalization likely mucked about with the VT of the
6351         // source operand, so we may have to convert it here before inserting.
6352         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6353       }
6354     }
6355     return Val;
6356   }
6357 
6358   // If all elements are constants and the case above didn't get hit, fall back
6359   // to the default expansion, which will generate a load from the constant
6360   // pool.
6361   if (isConstant)
6362     return SDValue();
6363 
6364   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6365   if (NumElts >= 4) {
6366     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6367       return shuffle;
6368   }
6369 
6370   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6371   // know the default expansion would otherwise fall back on something even
6372   // worse. For a vector with one or two non-undef values, that's
6373   // scalar_to_vector for the elements followed by a shuffle (provided the
6374   // shuffle is valid for the target) and materialization element by element
6375   // on the stack followed by a load for everything else.
6376   if (!isConstant && !usesOnlyOneValue) {
6377     SDValue Vec = DAG.getUNDEF(VT);
6378     SDValue Op0 = Op.getOperand(0);
6379     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6380     unsigned i = 0;
6381     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6382     // a) Avoid a RMW dependency on the full vector register, and
6383     // b) Allow the register coalescer to fold away the copy if the
6384     //    value is already in an S or D register.
6385     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6386     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6387     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6388         (ElemSize == 32 || ElemSize == 64)) {
6389       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6390       MachineSDNode *N =
6391           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6392                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6393       Vec = SDValue(N, 0);
6394       ++i;
6395     }
6396     for (; i < NumElts; ++i) {
6397       SDValue V = Op.getOperand(i);
6398       if (V.getOpcode() == ISD::UNDEF)
6399         continue;
6400       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6401       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6402     }
6403     return Vec;
6404   }
6405 
6406   // Just use the default expansion. We failed to find a better alternative.
6407   return SDValue();
6408 }
6409 
6410 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6411                                                       SelectionDAG &DAG) const {
6412   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6413 
6414   // Check for non-constant or out of range lane.
6415   EVT VT = Op.getOperand(0).getValueType();
6416   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6417   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6418     return SDValue();
6419 
6420 
6421   // Insertion/extraction are legal for V128 types.
6422   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6423       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6424       VT == MVT::v8f16)
6425     return Op;
6426 
6427   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6428       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6429     return SDValue();
6430 
6431   // For V64 types, we perform insertion by expanding the value
6432   // to a V128 type and perform the insertion on that.
6433   SDLoc DL(Op);
6434   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6435   EVT WideTy = WideVec.getValueType();
6436 
6437   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6438                              Op.getOperand(1), Op.getOperand(2));
6439   // Re-narrow the resultant vector.
6440   return NarrowVector(Node, DAG);
6441 }
6442 
6443 SDValue
6444 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6445                                                SelectionDAG &DAG) const {
6446   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6447 
6448   // Check for non-constant or out of range lane.
6449   EVT VT = Op.getOperand(0).getValueType();
6450   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6451   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6452     return SDValue();
6453 
6454 
6455   // Insertion/extraction are legal for V128 types.
6456   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6457       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6458       VT == MVT::v8f16)
6459     return Op;
6460 
6461   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6462       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6463     return SDValue();
6464 
6465   // For V64 types, we perform extraction by expanding the value
6466   // to a V128 type and perform the extraction on that.
6467   SDLoc DL(Op);
6468   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6469   EVT WideTy = WideVec.getValueType();
6470 
6471   EVT ExtrTy = WideTy.getVectorElementType();
6472   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6473     ExtrTy = MVT::i32;
6474 
6475   // For extractions, we just return the result directly.
6476   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6477                      Op.getOperand(1));
6478 }
6479 
6480 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6481                                                       SelectionDAG &DAG) const {
6482   EVT VT = Op.getOperand(0).getValueType();
6483   SDLoc dl(Op);
6484   // Just in case...
6485   if (!VT.isVector())
6486     return SDValue();
6487 
6488   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6489   if (!Cst)
6490     return SDValue();
6491   unsigned Val = Cst->getZExtValue();
6492 
6493   unsigned Size = Op.getValueType().getSizeInBits();
6494 
6495   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6496   if (Val == 0)
6497     return Op;
6498 
6499   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6500   // that directly.
6501   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6502     return Op;
6503 
6504   return SDValue();
6505 }
6506 
6507 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6508                                                EVT VT) const {
6509   if (VT.getVectorNumElements() == 4 &&
6510       (VT.is128BitVector() || VT.is64BitVector())) {
6511     unsigned PFIndexes[4];
6512     for (unsigned i = 0; i != 4; ++i) {
6513       if (M[i] < 0)
6514         PFIndexes[i] = 8;
6515       else
6516         PFIndexes[i] = M[i];
6517     }
6518 
6519     // Compute the index in the perfect shuffle table.
6520     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6521                             PFIndexes[2] * 9 + PFIndexes[3];
6522     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6523     unsigned Cost = (PFEntry >> 30);
6524 
6525     if (Cost <= 4)
6526       return true;
6527   }
6528 
6529   bool DummyBool;
6530   int DummyInt;
6531   unsigned DummyUnsigned;
6532 
6533   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6534           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6535           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6536           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6537           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6538           isZIPMask(M, VT, DummyUnsigned) ||
6539           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6540           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6541           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6542           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6543           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6544 }
6545 
6546 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6547 /// operand of a vector shift operation, where all the elements of the
6548 /// build_vector must have the same constant integer value.
6549 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6550   // Ignore bit_converts.
6551   while (Op.getOpcode() == ISD::BITCAST)
6552     Op = Op.getOperand(0);
6553   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6554   APInt SplatBits, SplatUndef;
6555   unsigned SplatBitSize;
6556   bool HasAnyUndefs;
6557   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6558                                     HasAnyUndefs, ElementBits) ||
6559       SplatBitSize > ElementBits)
6560     return false;
6561   Cnt = SplatBits.getSExtValue();
6562   return true;
6563 }
6564 
6565 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6566 /// operand of a vector shift left operation.  That value must be in the range:
6567 ///   0 <= Value < ElementBits for a left shift; or
6568 ///   0 <= Value <= ElementBits for a long left shift.
6569 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6570   assert(VT.isVector() && "vector shift count is not a vector type");
6571   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6572   if (!getVShiftImm(Op, ElementBits, Cnt))
6573     return false;
6574   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6575 }
6576 
6577 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6578 /// operand of a vector shift right operation. The value must be in the range:
6579 ///   1 <= Value <= ElementBits for a right shift; or
6580 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6581   assert(VT.isVector() && "vector shift count is not a vector type");
6582   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6583   if (!getVShiftImm(Op, ElementBits, Cnt))
6584     return false;
6585   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6586 }
6587 
6588 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6589                                                       SelectionDAG &DAG) const {
6590   EVT VT = Op.getValueType();
6591   SDLoc DL(Op);
6592   int64_t Cnt;
6593 
6594   if (!Op.getOperand(1).getValueType().isVector())
6595     return Op;
6596   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6597 
6598   switch (Op.getOpcode()) {
6599   default:
6600     llvm_unreachable("unexpected shift opcode");
6601 
6602   case ISD::SHL:
6603     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6604       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6605                          DAG.getConstant(Cnt, DL, MVT::i32));
6606     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6607                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6608                                        MVT::i32),
6609                        Op.getOperand(0), Op.getOperand(1));
6610   case ISD::SRA:
6611   case ISD::SRL:
6612     // Right shift immediate
6613     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6614       unsigned Opc =
6615           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6616       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6617                          DAG.getConstant(Cnt, DL, MVT::i32));
6618     }
6619 
6620     // Right shift register.  Note, there is not a shift right register
6621     // instruction, but the shift left register instruction takes a signed
6622     // value, where negative numbers specify a right shift.
6623     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6624                                                 : Intrinsic::aarch64_neon_ushl;
6625     // negate the shift amount
6626     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6627     SDValue NegShiftLeft =
6628         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6629                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6630                     NegShift);
6631     return NegShiftLeft;
6632   }
6633 
6634   return SDValue();
6635 }
6636 
6637 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6638                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6639                                     SDLoc dl, SelectionDAG &DAG) {
6640   EVT SrcVT = LHS.getValueType();
6641   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6642          "function only supposed to emit natural comparisons");
6643 
6644   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6645   APInt CnstBits(VT.getSizeInBits(), 0);
6646   APInt UndefBits(VT.getSizeInBits(), 0);
6647   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6648   bool IsZero = IsCnst && (CnstBits == 0);
6649 
6650   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6651     switch (CC) {
6652     default:
6653       return SDValue();
6654     case AArch64CC::NE: {
6655       SDValue Fcmeq;
6656       if (IsZero)
6657         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6658       else
6659         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6660       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6661     }
6662     case AArch64CC::EQ:
6663       if (IsZero)
6664         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6665       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6666     case AArch64CC::GE:
6667       if (IsZero)
6668         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6669       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6670     case AArch64CC::GT:
6671       if (IsZero)
6672         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6673       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6674     case AArch64CC::LS:
6675       if (IsZero)
6676         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6677       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6678     case AArch64CC::LT:
6679       if (!NoNans)
6680         return SDValue();
6681     // If we ignore NaNs then we can use to the MI implementation.
6682     // Fallthrough.
6683     case AArch64CC::MI:
6684       if (IsZero)
6685         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6686       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6687     }
6688   }
6689 
6690   switch (CC) {
6691   default:
6692     return SDValue();
6693   case AArch64CC::NE: {
6694     SDValue Cmeq;
6695     if (IsZero)
6696       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6697     else
6698       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6699     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6700   }
6701   case AArch64CC::EQ:
6702     if (IsZero)
6703       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6704     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6705   case AArch64CC::GE:
6706     if (IsZero)
6707       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6708     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6709   case AArch64CC::GT:
6710     if (IsZero)
6711       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6712     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6713   case AArch64CC::LE:
6714     if (IsZero)
6715       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6716     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6717   case AArch64CC::LS:
6718     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6719   case AArch64CC::LO:
6720     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6721   case AArch64CC::LT:
6722     if (IsZero)
6723       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6724     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6725   case AArch64CC::HI:
6726     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6727   case AArch64CC::HS:
6728     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6729   }
6730 }
6731 
6732 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6733                                            SelectionDAG &DAG) const {
6734   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6735   SDValue LHS = Op.getOperand(0);
6736   SDValue RHS = Op.getOperand(1);
6737   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6738   SDLoc dl(Op);
6739 
6740   if (LHS.getValueType().getVectorElementType().isInteger()) {
6741     assert(LHS.getValueType() == RHS.getValueType());
6742     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6743     SDValue Cmp =
6744         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6745     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6746   }
6747 
6748   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6749     return SDValue();
6750 
6751   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6752          LHS.getValueType().getVectorElementType() == MVT::f64);
6753 
6754   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6755   // clean.  Some of them require two branches to implement.
6756   AArch64CC::CondCode CC1, CC2;
6757   bool ShouldInvert;
6758   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6759 
6760   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6761   SDValue Cmp =
6762       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6763   if (!Cmp.getNode())
6764     return SDValue();
6765 
6766   if (CC2 != AArch64CC::AL) {
6767     SDValue Cmp2 =
6768         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6769     if (!Cmp2.getNode())
6770       return SDValue();
6771 
6772     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6773   }
6774 
6775   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6776 
6777   if (ShouldInvert)
6778     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6779 
6780   return Cmp;
6781 }
6782 
6783 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6784 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6785 /// specified in the intrinsic calls.
6786 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6787                                                const CallInst &I,
6788                                                unsigned Intrinsic) const {
6789   auto &DL = I.getModule()->getDataLayout();
6790   switch (Intrinsic) {
6791   case Intrinsic::aarch64_neon_ld2:
6792   case Intrinsic::aarch64_neon_ld3:
6793   case Intrinsic::aarch64_neon_ld4:
6794   case Intrinsic::aarch64_neon_ld1x2:
6795   case Intrinsic::aarch64_neon_ld1x3:
6796   case Intrinsic::aarch64_neon_ld1x4:
6797   case Intrinsic::aarch64_neon_ld2lane:
6798   case Intrinsic::aarch64_neon_ld3lane:
6799   case Intrinsic::aarch64_neon_ld4lane:
6800   case Intrinsic::aarch64_neon_ld2r:
6801   case Intrinsic::aarch64_neon_ld3r:
6802   case Intrinsic::aarch64_neon_ld4r: {
6803     Info.opc = ISD::INTRINSIC_W_CHAIN;
6804     // Conservatively set memVT to the entire set of vectors loaded.
6805     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6806     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6807     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6808     Info.offset = 0;
6809     Info.align = 0;
6810     Info.vol = false; // volatile loads with NEON intrinsics not supported
6811     Info.readMem = true;
6812     Info.writeMem = false;
6813     return true;
6814   }
6815   case Intrinsic::aarch64_neon_st2:
6816   case Intrinsic::aarch64_neon_st3:
6817   case Intrinsic::aarch64_neon_st4:
6818   case Intrinsic::aarch64_neon_st1x2:
6819   case Intrinsic::aarch64_neon_st1x3:
6820   case Intrinsic::aarch64_neon_st1x4:
6821   case Intrinsic::aarch64_neon_st2lane:
6822   case Intrinsic::aarch64_neon_st3lane:
6823   case Intrinsic::aarch64_neon_st4lane: {
6824     Info.opc = ISD::INTRINSIC_VOID;
6825     // Conservatively set memVT to the entire set of vectors stored.
6826     unsigned NumElts = 0;
6827     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6828       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6829       if (!ArgTy->isVectorTy())
6830         break;
6831       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6832     }
6833     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6834     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6835     Info.offset = 0;
6836     Info.align = 0;
6837     Info.vol = false; // volatile stores with NEON intrinsics not supported
6838     Info.readMem = false;
6839     Info.writeMem = true;
6840     return true;
6841   }
6842   case Intrinsic::aarch64_ldaxr:
6843   case Intrinsic::aarch64_ldxr: {
6844     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6845     Info.opc = ISD::INTRINSIC_W_CHAIN;
6846     Info.memVT = MVT::getVT(PtrTy->getElementType());
6847     Info.ptrVal = I.getArgOperand(0);
6848     Info.offset = 0;
6849     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6850     Info.vol = true;
6851     Info.readMem = true;
6852     Info.writeMem = false;
6853     return true;
6854   }
6855   case Intrinsic::aarch64_stlxr:
6856   case Intrinsic::aarch64_stxr: {
6857     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6858     Info.opc = ISD::INTRINSIC_W_CHAIN;
6859     Info.memVT = MVT::getVT(PtrTy->getElementType());
6860     Info.ptrVal = I.getArgOperand(1);
6861     Info.offset = 0;
6862     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6863     Info.vol = true;
6864     Info.readMem = false;
6865     Info.writeMem = true;
6866     return true;
6867   }
6868   case Intrinsic::aarch64_ldaxp:
6869   case Intrinsic::aarch64_ldxp: {
6870     Info.opc = ISD::INTRINSIC_W_CHAIN;
6871     Info.memVT = MVT::i128;
6872     Info.ptrVal = I.getArgOperand(0);
6873     Info.offset = 0;
6874     Info.align = 16;
6875     Info.vol = true;
6876     Info.readMem = true;
6877     Info.writeMem = false;
6878     return true;
6879   }
6880   case Intrinsic::aarch64_stlxp:
6881   case Intrinsic::aarch64_stxp: {
6882     Info.opc = ISD::INTRINSIC_W_CHAIN;
6883     Info.memVT = MVT::i128;
6884     Info.ptrVal = I.getArgOperand(2);
6885     Info.offset = 0;
6886     Info.align = 16;
6887     Info.vol = true;
6888     Info.readMem = false;
6889     Info.writeMem = true;
6890     return true;
6891   }
6892   default:
6893     break;
6894   }
6895 
6896   return false;
6897 }
6898 
6899 // Truncations from 64-bit GPR to 32-bit GPR is free.
6900 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6901   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6902     return false;
6903   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6904   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6905   return NumBits1 > NumBits2;
6906 }
6907 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6908   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6909     return false;
6910   unsigned NumBits1 = VT1.getSizeInBits();
6911   unsigned NumBits2 = VT2.getSizeInBits();
6912   return NumBits1 > NumBits2;
6913 }
6914 
6915 /// Check if it is profitable to hoist instruction in then/else to if.
6916 /// Not profitable if I and it's user can form a FMA instruction
6917 /// because we prefer FMSUB/FMADD.
6918 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6919   if (I->getOpcode() != Instruction::FMul)
6920     return true;
6921 
6922   if (I->getNumUses() != 1)
6923     return true;
6924 
6925   Instruction *User = I->user_back();
6926 
6927   if (User &&
6928       !(User->getOpcode() == Instruction::FSub ||
6929         User->getOpcode() == Instruction::FAdd))
6930     return true;
6931 
6932   const TargetOptions &Options = getTargetMachine().Options;
6933   const DataLayout &DL = I->getModule()->getDataLayout();
6934   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6935 
6936   if (isFMAFasterThanFMulAndFAdd(VT) &&
6937       isOperationLegalOrCustom(ISD::FMA, VT) &&
6938       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6939     return false;
6940 
6941   return true;
6942 }
6943 
6944 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6945 // 64-bit GPR.
6946 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6947   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6948     return false;
6949   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6950   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6951   return NumBits1 == 32 && NumBits2 == 64;
6952 }
6953 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6954   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6955     return false;
6956   unsigned NumBits1 = VT1.getSizeInBits();
6957   unsigned NumBits2 = VT2.getSizeInBits();
6958   return NumBits1 == 32 && NumBits2 == 64;
6959 }
6960 
6961 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6962   EVT VT1 = Val.getValueType();
6963   if (isZExtFree(VT1, VT2)) {
6964     return true;
6965   }
6966 
6967   if (Val.getOpcode() != ISD::LOAD)
6968     return false;
6969 
6970   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6971   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6972           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6973           VT1.getSizeInBits() <= 32);
6974 }
6975 
6976 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6977   if (isa<FPExtInst>(Ext))
6978     return false;
6979 
6980   // Vector types are next free.
6981   if (Ext->getType()->isVectorTy())
6982     return false;
6983 
6984   for (const Use &U : Ext->uses()) {
6985     // The extension is free if we can fold it with a left shift in an
6986     // addressing mode or an arithmetic operation: add, sub, and cmp.
6987 
6988     // Is there a shift?
6989     const Instruction *Instr = cast<Instruction>(U.getUser());
6990 
6991     // Is this a constant shift?
6992     switch (Instr->getOpcode()) {
6993     case Instruction::Shl:
6994       if (!isa<ConstantInt>(Instr->getOperand(1)))
6995         return false;
6996       break;
6997     case Instruction::GetElementPtr: {
6998       gep_type_iterator GTI = gep_type_begin(Instr);
6999       auto &DL = Ext->getModule()->getDataLayout();
7000       std::advance(GTI, U.getOperandNo());
7001       Type *IdxTy = *GTI;
7002       // This extension will end up with a shift because of the scaling factor.
7003       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7004       // Get the shift amount based on the scaling factor:
7005       // log2(sizeof(IdxTy)) - log2(8).
7006       uint64_t ShiftAmt =
7007           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7008       // Is the constant foldable in the shift of the addressing mode?
7009       // I.e., shift amount is between 1 and 4 inclusive.
7010       if (ShiftAmt == 0 || ShiftAmt > 4)
7011         return false;
7012       break;
7013     }
7014     case Instruction::Trunc:
7015       // Check if this is a noop.
7016       // trunc(sext ty1 to ty2) to ty1.
7017       if (Instr->getType() == Ext->getOperand(0)->getType())
7018         continue;
7019     // FALL THROUGH.
7020     default:
7021       return false;
7022     }
7023 
7024     // At this point we can use the bfm family, so this extension is free
7025     // for that use.
7026   }
7027   return true;
7028 }
7029 
7030 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7031                                           unsigned &RequiredAligment) const {
7032   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7033     return false;
7034   // Cyclone supports unaligned accesses.
7035   RequiredAligment = 0;
7036   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7037   return NumBits == 32 || NumBits == 64;
7038 }
7039 
7040 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7041                                           unsigned &RequiredAligment) const {
7042   if (!LoadedType.isSimple() ||
7043       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7044     return false;
7045   // Cyclone supports unaligned accesses.
7046   RequiredAligment = 0;
7047   unsigned NumBits = LoadedType.getSizeInBits();
7048   return NumBits == 32 || NumBits == 64;
7049 }
7050 
7051 /// \brief Lower an interleaved load into a ldN intrinsic.
7052 ///
7053 /// E.g. Lower an interleaved load (Factor = 2):
7054 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7055 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7056 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7057 ///
7058 ///      Into:
7059 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7060 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7061 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7062 bool AArch64TargetLowering::lowerInterleavedLoad(
7063     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7064     ArrayRef<unsigned> Indices, unsigned Factor) const {
7065   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7066          "Invalid interleave factor");
7067   assert(!Shuffles.empty() && "Empty shufflevector input");
7068   assert(Shuffles.size() == Indices.size() &&
7069          "Unmatched number of shufflevectors and indices");
7070 
7071   const DataLayout &DL = LI->getModule()->getDataLayout();
7072 
7073   VectorType *VecTy = Shuffles[0]->getType();
7074   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7075 
7076   // Skip if we do not have NEON and skip illegal vector types.
7077   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7078     return false;
7079 
7080   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7081   // load integer vectors first and then convert to pointer vectors.
7082   Type *EltTy = VecTy->getVectorElementType();
7083   if (EltTy->isPointerTy())
7084     VecTy =
7085         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7086 
7087   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7088   Type *Tys[2] = {VecTy, PtrTy};
7089   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7090                                             Intrinsic::aarch64_neon_ld3,
7091                                             Intrinsic::aarch64_neon_ld4};
7092   Function *LdNFunc =
7093       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7094 
7095   IRBuilder<> Builder(LI);
7096   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7097 
7098   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7099 
7100   // Replace uses of each shufflevector with the corresponding vector loaded
7101   // by ldN.
7102   for (unsigned i = 0; i < Shuffles.size(); i++) {
7103     ShuffleVectorInst *SVI = Shuffles[i];
7104     unsigned Index = Indices[i];
7105 
7106     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7107 
7108     // Convert the integer vector to pointer vector if the element is pointer.
7109     if (EltTy->isPointerTy())
7110       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7111 
7112     SVI->replaceAllUsesWith(SubVec);
7113   }
7114 
7115   return true;
7116 }
7117 
7118 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7119 ///
7120 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7121 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7122                                    unsigned NumElts) {
7123   SmallVector<Constant *, 16> Mask;
7124   for (unsigned i = 0; i < NumElts; i++)
7125     Mask.push_back(Builder.getInt32(Start + i));
7126 
7127   return ConstantVector::get(Mask);
7128 }
7129 
7130 /// \brief Lower an interleaved store into a stN intrinsic.
7131 ///
7132 /// E.g. Lower an interleaved store (Factor = 3):
7133 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7134 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7135 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7136 ///
7137 ///      Into:
7138 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7139 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7140 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7141 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7142 ///
7143 /// Note that the new shufflevectors will be removed and we'll only generate one
7144 /// st3 instruction in CodeGen.
7145 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7146                                                   ShuffleVectorInst *SVI,
7147                                                   unsigned Factor) const {
7148   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7149          "Invalid interleave factor");
7150 
7151   VectorType *VecTy = SVI->getType();
7152   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7153          "Invalid interleaved store");
7154 
7155   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7156   Type *EltTy = VecTy->getVectorElementType();
7157   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7158 
7159   const DataLayout &DL = SI->getModule()->getDataLayout();
7160   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7161 
7162   // Skip if we do not have NEON and skip illegal vector types.
7163   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7164     return false;
7165 
7166   Value *Op0 = SVI->getOperand(0);
7167   Value *Op1 = SVI->getOperand(1);
7168   IRBuilder<> Builder(SI);
7169 
7170   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7171   // vectors to integer vectors.
7172   if (EltTy->isPointerTy()) {
7173     Type *IntTy = DL.getIntPtrType(EltTy);
7174     unsigned NumOpElts =
7175         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7176 
7177     // Convert to the corresponding integer vector.
7178     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7179     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7180     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7181 
7182     SubVecTy = VectorType::get(IntTy, NumSubElts);
7183   }
7184 
7185   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7186   Type *Tys[2] = {SubVecTy, PtrTy};
7187   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7188                                              Intrinsic::aarch64_neon_st3,
7189                                              Intrinsic::aarch64_neon_st4};
7190   Function *StNFunc =
7191       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7192 
7193   SmallVector<Value *, 5> Ops;
7194 
7195   // Split the shufflevector operands into sub vectors for the new stN call.
7196   for (unsigned i = 0; i < Factor; i++)
7197     Ops.push_back(Builder.CreateShuffleVector(
7198         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7199 
7200   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7201   Builder.CreateCall(StNFunc, Ops);
7202   return true;
7203 }
7204 
7205 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7206                        unsigned AlignCheck) {
7207   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7208           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7209 }
7210 
7211 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7212                                                unsigned SrcAlign, bool IsMemset,
7213                                                bool ZeroMemset,
7214                                                bool MemcpyStrSrc,
7215                                                MachineFunction &MF) const {
7216   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7217   // instruction to materialize the v2i64 zero and one store (with restrictive
7218   // addressing mode). Just do two i64 store of zero-registers.
7219   bool Fast;
7220   const Function *F = MF.getFunction();
7221   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7222       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7223       (memOpAlign(SrcAlign, DstAlign, 16) ||
7224        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7225     return MVT::f128;
7226 
7227   if (Size >= 8 &&
7228       (memOpAlign(SrcAlign, DstAlign, 8) ||
7229        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7230     return MVT::i64;
7231 
7232   if (Size >= 4 &&
7233       (memOpAlign(SrcAlign, DstAlign, 4) ||
7234        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7235     return MVT::i32;
7236 
7237   return MVT::Other;
7238 }
7239 
7240 // 12-bit optionally shifted immediates are legal for adds.
7241 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7242   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7243     return true;
7244   return false;
7245 }
7246 
7247 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7248 // immediates is the same as for an add or a sub.
7249 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7250   if (Immed < 0)
7251     Immed *= -1;
7252   return isLegalAddImmediate(Immed);
7253 }
7254 
7255 /// isLegalAddressingMode - Return true if the addressing mode represented
7256 /// by AM is legal for this target, for a load/store of the specified type.
7257 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7258                                                   const AddrMode &AM, Type *Ty,
7259                                                   unsigned AS) const {
7260   // AArch64 has five basic addressing modes:
7261   //  reg
7262   //  reg + 9-bit signed offset
7263   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7264   //  reg1 + reg2
7265   //  reg + SIZE_IN_BYTES * reg
7266 
7267   // No global is ever allowed as a base.
7268   if (AM.BaseGV)
7269     return false;
7270 
7271   // No reg+reg+imm addressing.
7272   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7273     return false;
7274 
7275   // check reg + imm case:
7276   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7277   uint64_t NumBytes = 0;
7278   if (Ty->isSized()) {
7279     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7280     NumBytes = NumBits / 8;
7281     if (!isPowerOf2_64(NumBits))
7282       NumBytes = 0;
7283   }
7284 
7285   if (!AM.Scale) {
7286     int64_t Offset = AM.BaseOffs;
7287 
7288     // 9-bit signed offset
7289     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7290       return true;
7291 
7292     // 12-bit unsigned offset
7293     unsigned shift = Log2_64(NumBytes);
7294     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7295         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7296         (Offset >> shift) << shift == Offset)
7297       return true;
7298     return false;
7299   }
7300 
7301   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7302 
7303   if (!AM.Scale || AM.Scale == 1 ||
7304       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7305     return true;
7306   return false;
7307 }
7308 
7309 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7310                                                 const AddrMode &AM, Type *Ty,
7311                                                 unsigned AS) const {
7312   // Scaling factors are not free at all.
7313   // Operands                     | Rt Latency
7314   // -------------------------------------------
7315   // Rt, [Xn, Xm]                 | 4
7316   // -------------------------------------------
7317   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7318   // Rt, [Xn, Wm, <extend> #imm]  |
7319   if (isLegalAddressingMode(DL, AM, Ty, AS))
7320     // Scale represents reg2 * scale, thus account for 1 if
7321     // it is not equal to 0 or 1.
7322     return AM.Scale != 0 && AM.Scale != 1;
7323   return -1;
7324 }
7325 
7326 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7327   VT = VT.getScalarType();
7328 
7329   if (!VT.isSimple())
7330     return false;
7331 
7332   switch (VT.getSimpleVT().SimpleTy) {
7333   case MVT::f32:
7334   case MVT::f64:
7335     return true;
7336   default:
7337     break;
7338   }
7339 
7340   return false;
7341 }
7342 
7343 const MCPhysReg *
7344 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7345   // LR is a callee-save register, but we must treat it as clobbered by any call
7346   // site. Hence we include LR in the scratch registers, which are in turn added
7347   // as implicit-defs for stackmaps and patchpoints.
7348   static const MCPhysReg ScratchRegs[] = {
7349     AArch64::X16, AArch64::X17, AArch64::LR, 0
7350   };
7351   return ScratchRegs;
7352 }
7353 
7354 bool
7355 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7356   EVT VT = N->getValueType(0);
7357     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7358     // it with shift to let it be lowered to UBFX.
7359   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7360       isa<ConstantSDNode>(N->getOperand(1))) {
7361     uint64_t TruncMask = N->getConstantOperandVal(1);
7362     if (isMask_64(TruncMask) &&
7363       N->getOperand(0).getOpcode() == ISD::SRL &&
7364       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7365       return false;
7366   }
7367   return true;
7368 }
7369 
7370 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7371                                                               Type *Ty) const {
7372   assert(Ty->isIntegerTy());
7373 
7374   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7375   if (BitSize == 0)
7376     return false;
7377 
7378   int64_t Val = Imm.getSExtValue();
7379   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7380     return true;
7381 
7382   if ((int64_t)Val < 0)
7383     Val = ~Val;
7384   if (BitSize == 32)
7385     Val &= (1LL << 32) - 1;
7386 
7387   unsigned LZ = countLeadingZeros((uint64_t)Val);
7388   unsigned Shift = (63 - LZ) / 16;
7389   // MOVZ is free so return true for one or fewer MOVK.
7390   return Shift < 3;
7391 }
7392 
7393 // Generate SUBS and CSEL for integer abs.
7394 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7395   EVT VT = N->getValueType(0);
7396 
7397   SDValue N0 = N->getOperand(0);
7398   SDValue N1 = N->getOperand(1);
7399   SDLoc DL(N);
7400 
7401   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7402   // and change it to SUB and CSEL.
7403   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7404       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7405       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7406     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7407       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7408         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7409                                   N0.getOperand(0));
7410         // Generate SUBS & CSEL.
7411         SDValue Cmp =
7412             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7413                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7414         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7415                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7416                            SDValue(Cmp.getNode(), 1));
7417       }
7418   return SDValue();
7419 }
7420 
7421 // performXorCombine - Attempts to handle integer ABS.
7422 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7423                                  TargetLowering::DAGCombinerInfo &DCI,
7424                                  const AArch64Subtarget *Subtarget) {
7425   if (DCI.isBeforeLegalizeOps())
7426     return SDValue();
7427 
7428   return performIntegerAbsCombine(N, DAG);
7429 }
7430 
7431 SDValue
7432 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7433                                      SelectionDAG &DAG,
7434                                      std::vector<SDNode *> *Created) const {
7435   // fold (sdiv X, pow2)
7436   EVT VT = N->getValueType(0);
7437   if ((VT != MVT::i32 && VT != MVT::i64) ||
7438       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7439     return SDValue();
7440 
7441   SDLoc DL(N);
7442   SDValue N0 = N->getOperand(0);
7443   unsigned Lg2 = Divisor.countTrailingZeros();
7444   SDValue Zero = DAG.getConstant(0, DL, VT);
7445   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7446 
7447   // Add (N0 < 0) ? Pow2 - 1 : 0;
7448   SDValue CCVal;
7449   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7450   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7451   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7452 
7453   if (Created) {
7454     Created->push_back(Cmp.getNode());
7455     Created->push_back(Add.getNode());
7456     Created->push_back(CSel.getNode());
7457   }
7458 
7459   // Divide by pow2.
7460   SDValue SRA =
7461       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7462 
7463   // If we're dividing by a positive value, we're done.  Otherwise, we must
7464   // negate the result.
7465   if (Divisor.isNonNegative())
7466     return SRA;
7467 
7468   if (Created)
7469     Created->push_back(SRA.getNode());
7470   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7471 }
7472 
7473 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7474                                  TargetLowering::DAGCombinerInfo &DCI,
7475                                  const AArch64Subtarget *Subtarget) {
7476   if (DCI.isBeforeLegalizeOps())
7477     return SDValue();
7478 
7479   // Multiplication of a power of two plus/minus one can be done more
7480   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7481   // future CPUs have a cheaper MADD instruction, this may need to be
7482   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7483   // 64-bit is 5 cycles, so this is always a win.
7484   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7485     APInt Value = C->getAPIntValue();
7486     EVT VT = N->getValueType(0);
7487     SDLoc DL(N);
7488     if (Value.isNonNegative()) {
7489       // (mul x, 2^N + 1) => (add (shl x, N), x)
7490       APInt VM1 = Value - 1;
7491       if (VM1.isPowerOf2()) {
7492         SDValue ShiftedVal =
7493             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7494                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7495         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7496                            N->getOperand(0));
7497       }
7498       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7499       APInt VP1 = Value + 1;
7500       if (VP1.isPowerOf2()) {
7501         SDValue ShiftedVal =
7502             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7503                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7504         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7505                            N->getOperand(0));
7506       }
7507     } else {
7508       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7509       APInt VNP1 = -Value + 1;
7510       if (VNP1.isPowerOf2()) {
7511         SDValue ShiftedVal =
7512             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7513                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7514         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7515                            ShiftedVal);
7516       }
7517       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7518       APInt VNM1 = -Value - 1;
7519       if (VNM1.isPowerOf2()) {
7520         SDValue ShiftedVal =
7521             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7522                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7523         SDValue Add =
7524             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7525         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7526       }
7527     }
7528   }
7529   return SDValue();
7530 }
7531 
7532 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7533                                                          SelectionDAG &DAG) {
7534   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7535   // optimize away operation when it's from a constant.
7536   //
7537   // The general transformation is:
7538   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7539   //       AND(VECTOR_CMP(x,y), constant2)
7540   //    constant2 = UNARYOP(constant)
7541 
7542   // Early exit if this isn't a vector operation, the operand of the
7543   // unary operation isn't a bitwise AND, or if the sizes of the operations
7544   // aren't the same.
7545   EVT VT = N->getValueType(0);
7546   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7547       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7548       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7549     return SDValue();
7550 
7551   // Now check that the other operand of the AND is a constant. We could
7552   // make the transformation for non-constant splats as well, but it's unclear
7553   // that would be a benefit as it would not eliminate any operations, just
7554   // perform one more step in scalar code before moving to the vector unit.
7555   if (BuildVectorSDNode *BV =
7556           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7557     // Bail out if the vector isn't a constant.
7558     if (!BV->isConstant())
7559       return SDValue();
7560 
7561     // Everything checks out. Build up the new and improved node.
7562     SDLoc DL(N);
7563     EVT IntVT = BV->getValueType(0);
7564     // Create a new constant of the appropriate type for the transformed
7565     // DAG.
7566     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7567     // The AND node needs bitcasts to/from an integer vector type around it.
7568     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7569     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7570                                  N->getOperand(0)->getOperand(0), MaskConst);
7571     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7572     return Res;
7573   }
7574 
7575   return SDValue();
7576 }
7577 
7578 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7579                                      const AArch64Subtarget *Subtarget) {
7580   // First try to optimize away the conversion when it's conditionally from
7581   // a constant. Vectors only.
7582   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7583     return Res;
7584 
7585   EVT VT = N->getValueType(0);
7586   if (VT != MVT::f32 && VT != MVT::f64)
7587     return SDValue();
7588 
7589   // Only optimize when the source and destination types have the same width.
7590   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7591     return SDValue();
7592 
7593   // If the result of an integer load is only used by an integer-to-float
7594   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7595   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7596   SDValue N0 = N->getOperand(0);
7597   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7598       // Do not change the width of a volatile load.
7599       !cast<LoadSDNode>(N0)->isVolatile()) {
7600     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7601     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7602                                LN0->getPointerInfo(), LN0->isVolatile(),
7603                                LN0->isNonTemporal(), LN0->isInvariant(),
7604                                LN0->getAlignment());
7605 
7606     // Make sure successors of the original load stay after it by updating them
7607     // to use the new Chain.
7608     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7609 
7610     unsigned Opcode =
7611         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7612     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7613   }
7614 
7615   return SDValue();
7616 }
7617 
7618 /// Fold a floating-point multiply by power of two into floating-point to
7619 /// fixed-point conversion.
7620 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7621                                      const AArch64Subtarget *Subtarget) {
7622   if (!Subtarget->hasNEON())
7623     return SDValue();
7624 
7625   SDValue Op = N->getOperand(0);
7626   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7627     return SDValue();
7628 
7629   SDValue ConstVec = Op->getOperand(1);
7630   if (!isa<BuildVectorSDNode>(ConstVec))
7631     return SDValue();
7632 
7633   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7634   uint32_t FloatBits = FloatTy.getSizeInBits();
7635   if (FloatBits != 32 && FloatBits != 64)
7636     return SDValue();
7637 
7638   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7639   uint32_t IntBits = IntTy.getSizeInBits();
7640   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7641     return SDValue();
7642 
7643   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7644   if (IntBits > FloatBits)
7645     return SDValue();
7646 
7647   BitVector UndefElements;
7648   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7649   int32_t Bits = IntBits == 64 ? 64 : 32;
7650   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7651   if (C == -1 || C == 0 || C > Bits)
7652     return SDValue();
7653 
7654   MVT ResTy;
7655   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7656   switch (NumLanes) {
7657   default:
7658     return SDValue();
7659   case 2:
7660     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7661     break;
7662   case 4:
7663     ResTy = MVT::v4i32;
7664     break;
7665   }
7666 
7667   SDLoc DL(N);
7668   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7669   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7670                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7671   SDValue FixConv =
7672       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7673                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7674                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7675   // We can handle smaller integers by generating an extra trunc.
7676   if (IntBits < FloatBits)
7677     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7678 
7679   return FixConv;
7680 }
7681 
7682 /// Fold a floating-point divide by power of two into fixed-point to
7683 /// floating-point conversion.
7684 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7685                                   const AArch64Subtarget *Subtarget) {
7686   if (!Subtarget->hasNEON())
7687     return SDValue();
7688 
7689   SDValue Op = N->getOperand(0);
7690   unsigned Opc = Op->getOpcode();
7691   if (!Op.getValueType().isVector() ||
7692       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7693     return SDValue();
7694 
7695   SDValue ConstVec = N->getOperand(1);
7696   if (!isa<BuildVectorSDNode>(ConstVec))
7697     return SDValue();
7698 
7699   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7700   int32_t IntBits = IntTy.getSizeInBits();
7701   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7702     return SDValue();
7703 
7704   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7705   int32_t FloatBits = FloatTy.getSizeInBits();
7706   if (FloatBits != 32 && FloatBits != 64)
7707     return SDValue();
7708 
7709   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7710   if (IntBits > FloatBits)
7711     return SDValue();
7712 
7713   BitVector UndefElements;
7714   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7715   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7716   if (C == -1 || C == 0 || C > FloatBits)
7717     return SDValue();
7718 
7719   MVT ResTy;
7720   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7721   switch (NumLanes) {
7722   default:
7723     return SDValue();
7724   case 2:
7725     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7726     break;
7727   case 4:
7728     ResTy = MVT::v4i32;
7729     break;
7730   }
7731 
7732   SDLoc DL(N);
7733   SDValue ConvInput = Op.getOperand(0);
7734   bool IsSigned = Opc == ISD::SINT_TO_FP;
7735   if (IntBits < FloatBits)
7736     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7737                             ResTy, ConvInput);
7738 
7739   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7740                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7741   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7742                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7743                      DAG.getConstant(C, DL, MVT::i32));
7744 }
7745 
7746 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7747 /// searches for and classifies those shifts.
7748 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7749                          bool &FromHi) {
7750   if (N.getOpcode() == ISD::SHL)
7751     FromHi = false;
7752   else if (N.getOpcode() == ISD::SRL)
7753     FromHi = true;
7754   else
7755     return false;
7756 
7757   if (!isa<ConstantSDNode>(N.getOperand(1)))
7758     return false;
7759 
7760   ShiftAmount = N->getConstantOperandVal(1);
7761   Src = N->getOperand(0);
7762   return true;
7763 }
7764 
7765 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7766 /// registers viewed as a high/low pair. This function looks for the pattern:
7767 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7768 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7769 /// independent.
7770 static SDValue tryCombineToEXTR(SDNode *N,
7771                                 TargetLowering::DAGCombinerInfo &DCI) {
7772   SelectionDAG &DAG = DCI.DAG;
7773   SDLoc DL(N);
7774   EVT VT = N->getValueType(0);
7775 
7776   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7777 
7778   if (VT != MVT::i32 && VT != MVT::i64)
7779     return SDValue();
7780 
7781   SDValue LHS;
7782   uint32_t ShiftLHS = 0;
7783   bool LHSFromHi = 0;
7784   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7785     return SDValue();
7786 
7787   SDValue RHS;
7788   uint32_t ShiftRHS = 0;
7789   bool RHSFromHi = 0;
7790   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7791     return SDValue();
7792 
7793   // If they're both trying to come from the high part of the register, they're
7794   // not really an EXTR.
7795   if (LHSFromHi == RHSFromHi)
7796     return SDValue();
7797 
7798   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7799     return SDValue();
7800 
7801   if (LHSFromHi) {
7802     std::swap(LHS, RHS);
7803     std::swap(ShiftLHS, ShiftRHS);
7804   }
7805 
7806   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7807                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7808 }
7809 
7810 static SDValue tryCombineToBSL(SDNode *N,
7811                                 TargetLowering::DAGCombinerInfo &DCI) {
7812   EVT VT = N->getValueType(0);
7813   SelectionDAG &DAG = DCI.DAG;
7814   SDLoc DL(N);
7815 
7816   if (!VT.isVector())
7817     return SDValue();
7818 
7819   SDValue N0 = N->getOperand(0);
7820   if (N0.getOpcode() != ISD::AND)
7821     return SDValue();
7822 
7823   SDValue N1 = N->getOperand(1);
7824   if (N1.getOpcode() != ISD::AND)
7825     return SDValue();
7826 
7827   // We only have to look for constant vectors here since the general, variable
7828   // case can be handled in TableGen.
7829   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7830   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7831   for (int i = 1; i >= 0; --i)
7832     for (int j = 1; j >= 0; --j) {
7833       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7834       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7835       if (!BVN0 || !BVN1)
7836         continue;
7837 
7838       bool FoundMatch = true;
7839       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7840         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7841         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7842         if (!CN0 || !CN1 ||
7843             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7844           FoundMatch = false;
7845           break;
7846         }
7847       }
7848 
7849       if (FoundMatch)
7850         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7851                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7852     }
7853 
7854   return SDValue();
7855 }
7856 
7857 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7858                                 const AArch64Subtarget *Subtarget) {
7859   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7860   if (!EnableAArch64ExtrGeneration)
7861     return SDValue();
7862   SelectionDAG &DAG = DCI.DAG;
7863   EVT VT = N->getValueType(0);
7864 
7865   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7866     return SDValue();
7867 
7868   SDValue Res = tryCombineToEXTR(N, DCI);
7869   if (Res.getNode())
7870     return Res;
7871 
7872   Res = tryCombineToBSL(N, DCI);
7873   if (Res.getNode())
7874     return Res;
7875 
7876   return SDValue();
7877 }
7878 
7879 static SDValue performBitcastCombine(SDNode *N,
7880                                      TargetLowering::DAGCombinerInfo &DCI,
7881                                      SelectionDAG &DAG) {
7882   // Wait 'til after everything is legalized to try this. That way we have
7883   // legal vector types and such.
7884   if (DCI.isBeforeLegalizeOps())
7885     return SDValue();
7886 
7887   // Remove extraneous bitcasts around an extract_subvector.
7888   // For example,
7889   //    (v4i16 (bitconvert
7890   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7891   //  becomes
7892   //    (extract_subvector ((v8i16 ...), (i64 4)))
7893 
7894   // Only interested in 64-bit vectors as the ultimate result.
7895   EVT VT = N->getValueType(0);
7896   if (!VT.isVector())
7897     return SDValue();
7898   if (VT.getSimpleVT().getSizeInBits() != 64)
7899     return SDValue();
7900   // Is the operand an extract_subvector starting at the beginning or halfway
7901   // point of the vector? A low half may also come through as an
7902   // EXTRACT_SUBREG, so look for that, too.
7903   SDValue Op0 = N->getOperand(0);
7904   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7905       !(Op0->isMachineOpcode() &&
7906         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7907     return SDValue();
7908   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7909   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7910     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7911       return SDValue();
7912   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7913     if (idx != AArch64::dsub)
7914       return SDValue();
7915     // The dsub reference is equivalent to a lane zero subvector reference.
7916     idx = 0;
7917   }
7918   // Look through the bitcast of the input to the extract.
7919   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7920     return SDValue();
7921   SDValue Source = Op0->getOperand(0)->getOperand(0);
7922   // If the source type has twice the number of elements as our destination
7923   // type, we know this is an extract of the high or low half of the vector.
7924   EVT SVT = Source->getValueType(0);
7925   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7926     return SDValue();
7927 
7928   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7929 
7930   // Create the simplified form to just extract the low or high half of the
7931   // vector directly rather than bothering with the bitcasts.
7932   SDLoc dl(N);
7933   unsigned NumElements = VT.getVectorNumElements();
7934   if (idx) {
7935     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7936     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7937   } else {
7938     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7939     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7940                                       Source, SubReg),
7941                    0);
7942   }
7943 }
7944 
7945 static SDValue performConcatVectorsCombine(SDNode *N,
7946                                            TargetLowering::DAGCombinerInfo &DCI,
7947                                            SelectionDAG &DAG) {
7948   SDLoc dl(N);
7949   EVT VT = N->getValueType(0);
7950   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7951 
7952   // Optimize concat_vectors of truncated vectors, where the intermediate
7953   // type is illegal, to avoid said illegality,  e.g.,
7954   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7955   //                          (v2i16 (truncate (v2i64)))))
7956   // ->
7957   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7958   //                                    (v4i32 (bitcast (v2i64))),
7959   //                                    <0, 2, 4, 6>)))
7960   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7961   // on both input and result type, so we might generate worse code.
7962   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7963   if (N->getNumOperands() == 2 &&
7964       N0->getOpcode() == ISD::TRUNCATE &&
7965       N1->getOpcode() == ISD::TRUNCATE) {
7966     SDValue N00 = N0->getOperand(0);
7967     SDValue N10 = N1->getOperand(0);
7968     EVT N00VT = N00.getValueType();
7969 
7970     if (N00VT == N10.getValueType() &&
7971         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7972         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7973       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7974       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7975       for (size_t i = 0; i < Mask.size(); ++i)
7976         Mask[i] = i * 2;
7977       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7978                          DAG.getVectorShuffle(
7979                              MidVT, dl,
7980                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7981                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7982     }
7983   }
7984 
7985   // Wait 'til after everything is legalized to try this. That way we have
7986   // legal vector types and such.
7987   if (DCI.isBeforeLegalizeOps())
7988     return SDValue();
7989 
7990   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7991   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7992   // canonicalise to that.
7993   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7994     assert(VT.getVectorElementType().getSizeInBits() == 64);
7995     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7996                        DAG.getConstant(0, dl, MVT::i64));
7997   }
7998 
7999   // Canonicalise concat_vectors so that the right-hand vector has as few
8000   // bit-casts as possible before its real operation. The primary matching
8001   // destination for these operations will be the narrowing "2" instructions,
8002   // which depend on the operation being performed on this right-hand vector.
8003   // For example,
8004   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8005   // becomes
8006   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8007 
8008   if (N1->getOpcode() != ISD::BITCAST)
8009     return SDValue();
8010   SDValue RHS = N1->getOperand(0);
8011   MVT RHSTy = RHS.getValueType().getSimpleVT();
8012   // If the RHS is not a vector, this is not the pattern we're looking for.
8013   if (!RHSTy.isVector())
8014     return SDValue();
8015 
8016   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8017 
8018   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8019                                   RHSTy.getVectorNumElements() * 2);
8020   return DAG.getNode(ISD::BITCAST, dl, VT,
8021                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8022                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8023                                  RHS));
8024 }
8025 
8026 static SDValue tryCombineFixedPointConvert(SDNode *N,
8027                                            TargetLowering::DAGCombinerInfo &DCI,
8028                                            SelectionDAG &DAG) {
8029   // Wait 'til after everything is legalized to try this. That way we have
8030   // legal vector types and such.
8031   if (DCI.isBeforeLegalizeOps())
8032     return SDValue();
8033   // Transform a scalar conversion of a value from a lane extract into a
8034   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8035   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8036   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8037   //
8038   // The second form interacts better with instruction selection and the
8039   // register allocator to avoid cross-class register copies that aren't
8040   // coalescable due to a lane reference.
8041 
8042   // Check the operand and see if it originates from a lane extract.
8043   SDValue Op1 = N->getOperand(1);
8044   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8045     // Yep, no additional predication needed. Perform the transform.
8046     SDValue IID = N->getOperand(0);
8047     SDValue Shift = N->getOperand(2);
8048     SDValue Vec = Op1.getOperand(0);
8049     SDValue Lane = Op1.getOperand(1);
8050     EVT ResTy = N->getValueType(0);
8051     EVT VecResTy;
8052     SDLoc DL(N);
8053 
8054     // The vector width should be 128 bits by the time we get here, even
8055     // if it started as 64 bits (the extract_vector handling will have
8056     // done so).
8057     assert(Vec.getValueType().getSizeInBits() == 128 &&
8058            "unexpected vector size on extract_vector_elt!");
8059     if (Vec.getValueType() == MVT::v4i32)
8060       VecResTy = MVT::v4f32;
8061     else if (Vec.getValueType() == MVT::v2i64)
8062       VecResTy = MVT::v2f64;
8063     else
8064       llvm_unreachable("unexpected vector type!");
8065 
8066     SDValue Convert =
8067         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8068     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8069   }
8070   return SDValue();
8071 }
8072 
8073 // AArch64 high-vector "long" operations are formed by performing the non-high
8074 // version on an extract_subvector of each operand which gets the high half:
8075 //
8076 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8077 //
8078 // However, there are cases which don't have an extract_high explicitly, but
8079 // have another operation that can be made compatible with one for free. For
8080 // example:
8081 //
8082 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8083 //
8084 // This routine does the actual conversion of such DUPs, once outer routines
8085 // have determined that everything else is in order.
8086 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8087 // similarly here.
8088 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8089   switch (N.getOpcode()) {
8090   case AArch64ISD::DUP:
8091   case AArch64ISD::DUPLANE8:
8092   case AArch64ISD::DUPLANE16:
8093   case AArch64ISD::DUPLANE32:
8094   case AArch64ISD::DUPLANE64:
8095   case AArch64ISD::MOVI:
8096   case AArch64ISD::MOVIshift:
8097   case AArch64ISD::MOVIedit:
8098   case AArch64ISD::MOVImsl:
8099   case AArch64ISD::MVNIshift:
8100   case AArch64ISD::MVNImsl:
8101     break;
8102   default:
8103     // FMOV could be supported, but isn't very useful, as it would only occur
8104     // if you passed a bitcast' floating point immediate to an eligible long
8105     // integer op (addl, smull, ...).
8106     return SDValue();
8107   }
8108 
8109   MVT NarrowTy = N.getSimpleValueType();
8110   if (!NarrowTy.is64BitVector())
8111     return SDValue();
8112 
8113   MVT ElementTy = NarrowTy.getVectorElementType();
8114   unsigned NumElems = NarrowTy.getVectorNumElements();
8115   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8116 
8117   SDLoc dl(N);
8118   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8119                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8120                      DAG.getConstant(NumElems, dl, MVT::i64));
8121 }
8122 
8123 static bool isEssentiallyExtractSubvector(SDValue N) {
8124   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8125     return true;
8126 
8127   return N.getOpcode() == ISD::BITCAST &&
8128          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8129 }
8130 
8131 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8132 struct GenericSetCCInfo {
8133   const SDValue *Opnd0;
8134   const SDValue *Opnd1;
8135   ISD::CondCode CC;
8136 };
8137 
8138 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8139 struct AArch64SetCCInfo {
8140   const SDValue *Cmp;
8141   AArch64CC::CondCode CC;
8142 };
8143 
8144 /// \brief Helper structure to keep track of SetCC information.
8145 union SetCCInfo {
8146   GenericSetCCInfo Generic;
8147   AArch64SetCCInfo AArch64;
8148 };
8149 
8150 /// \brief Helper structure to be able to read SetCC information.  If set to
8151 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8152 /// GenericSetCCInfo.
8153 struct SetCCInfoAndKind {
8154   SetCCInfo Info;
8155   bool IsAArch64;
8156 };
8157 
8158 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8159 /// an
8160 /// AArch64 lowered one.
8161 /// \p SetCCInfo is filled accordingly.
8162 /// \post SetCCInfo is meanginfull only when this function returns true.
8163 /// \return True when Op is a kind of SET_CC operation.
8164 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8165   // If this is a setcc, this is straight forward.
8166   if (Op.getOpcode() == ISD::SETCC) {
8167     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8168     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8169     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8170     SetCCInfo.IsAArch64 = false;
8171     return true;
8172   }
8173   // Otherwise, check if this is a matching csel instruction.
8174   // In other words:
8175   // - csel 1, 0, cc
8176   // - csel 0, 1, !cc
8177   if (Op.getOpcode() != AArch64ISD::CSEL)
8178     return false;
8179   // Set the information about the operands.
8180   // TODO: we want the operands of the Cmp not the csel
8181   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8182   SetCCInfo.IsAArch64 = true;
8183   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8184       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8185 
8186   // Check that the operands matches the constraints:
8187   // (1) Both operands must be constants.
8188   // (2) One must be 1 and the other must be 0.
8189   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8190   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8191 
8192   // Check (1).
8193   if (!TValue || !FValue)
8194     return false;
8195 
8196   // Check (2).
8197   if (!TValue->isOne()) {
8198     // Update the comparison when we are interested in !cc.
8199     std::swap(TValue, FValue);
8200     SetCCInfo.Info.AArch64.CC =
8201         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8202   }
8203   return TValue->isOne() && FValue->isNullValue();
8204 }
8205 
8206 // Returns true if Op is setcc or zext of setcc.
8207 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8208   if (isSetCC(Op, Info))
8209     return true;
8210   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8211     isSetCC(Op->getOperand(0), Info));
8212 }
8213 
8214 // The folding we want to perform is:
8215 // (add x, [zext] (setcc cc ...) )
8216 //   -->
8217 // (csel x, (add x, 1), !cc ...)
8218 //
8219 // The latter will get matched to a CSINC instruction.
8220 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8221   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8222   SDValue LHS = Op->getOperand(0);
8223   SDValue RHS = Op->getOperand(1);
8224   SetCCInfoAndKind InfoAndKind;
8225 
8226   // If neither operand is a SET_CC, give up.
8227   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8228     std::swap(LHS, RHS);
8229     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8230       return SDValue();
8231   }
8232 
8233   // FIXME: This could be generatized to work for FP comparisons.
8234   EVT CmpVT = InfoAndKind.IsAArch64
8235                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8236                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8237   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8238     return SDValue();
8239 
8240   SDValue CCVal;
8241   SDValue Cmp;
8242   SDLoc dl(Op);
8243   if (InfoAndKind.IsAArch64) {
8244     CCVal = DAG.getConstant(
8245         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8246         MVT::i32);
8247     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8248   } else
8249     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8250                       *InfoAndKind.Info.Generic.Opnd1,
8251                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8252                       CCVal, DAG, dl);
8253 
8254   EVT VT = Op->getValueType(0);
8255   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8256   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8257 }
8258 
8259 // The basic add/sub long vector instructions have variants with "2" on the end
8260 // which act on the high-half of their inputs. They are normally matched by
8261 // patterns like:
8262 //
8263 // (add (zeroext (extract_high LHS)),
8264 //      (zeroext (extract_high RHS)))
8265 // -> uaddl2 vD, vN, vM
8266 //
8267 // However, if one of the extracts is something like a duplicate, this
8268 // instruction can still be used profitably. This function puts the DAG into a
8269 // more appropriate form for those patterns to trigger.
8270 static SDValue performAddSubLongCombine(SDNode *N,
8271                                         TargetLowering::DAGCombinerInfo &DCI,
8272                                         SelectionDAG &DAG) {
8273   if (DCI.isBeforeLegalizeOps())
8274     return SDValue();
8275 
8276   MVT VT = N->getSimpleValueType(0);
8277   if (!VT.is128BitVector()) {
8278     if (N->getOpcode() == ISD::ADD)
8279       return performSetccAddFolding(N, DAG);
8280     return SDValue();
8281   }
8282 
8283   // Make sure both branches are extended in the same way.
8284   SDValue LHS = N->getOperand(0);
8285   SDValue RHS = N->getOperand(1);
8286   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8287        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8288       LHS.getOpcode() != RHS.getOpcode())
8289     return SDValue();
8290 
8291   unsigned ExtType = LHS.getOpcode();
8292 
8293   // It's not worth doing if at least one of the inputs isn't already an
8294   // extract, but we don't know which it'll be so we have to try both.
8295   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8296     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8297     if (!RHS.getNode())
8298       return SDValue();
8299 
8300     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8301   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8302     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8303     if (!LHS.getNode())
8304       return SDValue();
8305 
8306     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8307   }
8308 
8309   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8310 }
8311 
8312 // Massage DAGs which we can use the high-half "long" operations on into
8313 // something isel will recognize better. E.g.
8314 //
8315 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8316 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8317 //                     (extract_high (v2i64 (dup128 scalar)))))
8318 //
8319 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8320                                        TargetLowering::DAGCombinerInfo &DCI,
8321                                        SelectionDAG &DAG) {
8322   if (DCI.isBeforeLegalizeOps())
8323     return SDValue();
8324 
8325   SDValue LHS = N->getOperand(1);
8326   SDValue RHS = N->getOperand(2);
8327   assert(LHS.getValueType().is64BitVector() &&
8328          RHS.getValueType().is64BitVector() &&
8329          "unexpected shape for long operation");
8330 
8331   // Either node could be a DUP, but it's not worth doing both of them (you'd
8332   // just as well use the non-high version) so look for a corresponding extract
8333   // operation on the other "wing".
8334   if (isEssentiallyExtractSubvector(LHS)) {
8335     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8336     if (!RHS.getNode())
8337       return SDValue();
8338   } else if (isEssentiallyExtractSubvector(RHS)) {
8339     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8340     if (!LHS.getNode())
8341       return SDValue();
8342   }
8343 
8344   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8345                      N->getOperand(0), LHS, RHS);
8346 }
8347 
8348 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8349   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8350   unsigned ElemBits = ElemTy.getSizeInBits();
8351 
8352   int64_t ShiftAmount;
8353   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8354     APInt SplatValue, SplatUndef;
8355     unsigned SplatBitSize;
8356     bool HasAnyUndefs;
8357     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8358                               HasAnyUndefs, ElemBits) ||
8359         SplatBitSize != ElemBits)
8360       return SDValue();
8361 
8362     ShiftAmount = SplatValue.getSExtValue();
8363   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8364     ShiftAmount = CVN->getSExtValue();
8365   } else
8366     return SDValue();
8367 
8368   unsigned Opcode;
8369   bool IsRightShift;
8370   switch (IID) {
8371   default:
8372     llvm_unreachable("Unknown shift intrinsic");
8373   case Intrinsic::aarch64_neon_sqshl:
8374     Opcode = AArch64ISD::SQSHL_I;
8375     IsRightShift = false;
8376     break;
8377   case Intrinsic::aarch64_neon_uqshl:
8378     Opcode = AArch64ISD::UQSHL_I;
8379     IsRightShift = false;
8380     break;
8381   case Intrinsic::aarch64_neon_srshl:
8382     Opcode = AArch64ISD::SRSHR_I;
8383     IsRightShift = true;
8384     break;
8385   case Intrinsic::aarch64_neon_urshl:
8386     Opcode = AArch64ISD::URSHR_I;
8387     IsRightShift = true;
8388     break;
8389   case Intrinsic::aarch64_neon_sqshlu:
8390     Opcode = AArch64ISD::SQSHLU_I;
8391     IsRightShift = false;
8392     break;
8393   }
8394 
8395   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8396     SDLoc dl(N);
8397     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8398                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8399   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8400     SDLoc dl(N);
8401     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8402                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8403   }
8404 
8405   return SDValue();
8406 }
8407 
8408 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8409 // the intrinsics must be legal and take an i32, this means there's almost
8410 // certainly going to be a zext in the DAG which we can eliminate.
8411 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8412   SDValue AndN = N->getOperand(2);
8413   if (AndN.getOpcode() != ISD::AND)
8414     return SDValue();
8415 
8416   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8417   if (!CMask || CMask->getZExtValue() != Mask)
8418     return SDValue();
8419 
8420   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8421                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8422 }
8423 
8424 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8425                                            SelectionDAG &DAG) {
8426   SDLoc dl(N);
8427   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8428                      DAG.getNode(Opc, dl,
8429                                  N->getOperand(1).getSimpleValueType(),
8430                                  N->getOperand(1)),
8431                      DAG.getConstant(0, dl, MVT::i64));
8432 }
8433 
8434 static SDValue performIntrinsicCombine(SDNode *N,
8435                                        TargetLowering::DAGCombinerInfo &DCI,
8436                                        const AArch64Subtarget *Subtarget) {
8437   SelectionDAG &DAG = DCI.DAG;
8438   unsigned IID = getIntrinsicID(N);
8439   switch (IID) {
8440   default:
8441     break;
8442   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8443   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8444     return tryCombineFixedPointConvert(N, DCI, DAG);
8445   case Intrinsic::aarch64_neon_saddv:
8446     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8447   case Intrinsic::aarch64_neon_uaddv:
8448     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8449   case Intrinsic::aarch64_neon_sminv:
8450     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8451   case Intrinsic::aarch64_neon_uminv:
8452     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8453   case Intrinsic::aarch64_neon_smaxv:
8454     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8455   case Intrinsic::aarch64_neon_umaxv:
8456     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8457   case Intrinsic::aarch64_neon_fmax:
8458     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8459                        N->getOperand(1), N->getOperand(2));
8460   case Intrinsic::aarch64_neon_fmin:
8461     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8462                        N->getOperand(1), N->getOperand(2));
8463   case Intrinsic::aarch64_neon_fmaxnm:
8464     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8465                        N->getOperand(1), N->getOperand(2));
8466   case Intrinsic::aarch64_neon_fminnm:
8467     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8468                        N->getOperand(1), N->getOperand(2));
8469   case Intrinsic::aarch64_neon_smull:
8470   case Intrinsic::aarch64_neon_umull:
8471   case Intrinsic::aarch64_neon_pmull:
8472   case Intrinsic::aarch64_neon_sqdmull:
8473     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8474   case Intrinsic::aarch64_neon_sqshl:
8475   case Intrinsic::aarch64_neon_uqshl:
8476   case Intrinsic::aarch64_neon_sqshlu:
8477   case Intrinsic::aarch64_neon_srshl:
8478   case Intrinsic::aarch64_neon_urshl:
8479     return tryCombineShiftImm(IID, N, DAG);
8480   case Intrinsic::aarch64_crc32b:
8481   case Intrinsic::aarch64_crc32cb:
8482     return tryCombineCRC32(0xff, N, DAG);
8483   case Intrinsic::aarch64_crc32h:
8484   case Intrinsic::aarch64_crc32ch:
8485     return tryCombineCRC32(0xffff, N, DAG);
8486   }
8487   return SDValue();
8488 }
8489 
8490 static SDValue performExtendCombine(SDNode *N,
8491                                     TargetLowering::DAGCombinerInfo &DCI,
8492                                     SelectionDAG &DAG) {
8493   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8494   // we can convert that DUP into another extract_high (of a bigger DUP), which
8495   // helps the backend to decide that an sabdl2 would be useful, saving a real
8496   // extract_high operation.
8497   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8498       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8499     SDNode *ABDNode = N->getOperand(0).getNode();
8500     unsigned IID = getIntrinsicID(ABDNode);
8501     if (IID == Intrinsic::aarch64_neon_sabd ||
8502         IID == Intrinsic::aarch64_neon_uabd) {
8503       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8504       if (!NewABD.getNode())
8505         return SDValue();
8506 
8507       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8508                          NewABD);
8509     }
8510   }
8511 
8512   // This is effectively a custom type legalization for AArch64.
8513   //
8514   // Type legalization will split an extend of a small, legal, type to a larger
8515   // illegal type by first splitting the destination type, often creating
8516   // illegal source types, which then get legalized in isel-confusing ways,
8517   // leading to really terrible codegen. E.g.,
8518   //   %result = v8i32 sext v8i8 %value
8519   // becomes
8520   //   %losrc = extract_subreg %value, ...
8521   //   %hisrc = extract_subreg %value, ...
8522   //   %lo = v4i32 sext v4i8 %losrc
8523   //   %hi = v4i32 sext v4i8 %hisrc
8524   // Things go rapidly downhill from there.
8525   //
8526   // For AArch64, the [sz]ext vector instructions can only go up one element
8527   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8528   // take two instructions.
8529   //
8530   // This implies that the most efficient way to do the extend from v8i8
8531   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8532   // the normal splitting to happen for the v8i16->v8i32.
8533 
8534   // This is pre-legalization to catch some cases where the default
8535   // type legalization will create ill-tempered code.
8536   if (!DCI.isBeforeLegalizeOps())
8537     return SDValue();
8538 
8539   // We're only interested in cleaning things up for non-legal vector types
8540   // here. If both the source and destination are legal, things will just
8541   // work naturally without any fiddling.
8542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8543   EVT ResVT = N->getValueType(0);
8544   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8545     return SDValue();
8546   // If the vector type isn't a simple VT, it's beyond the scope of what
8547   // we're  worried about here. Let legalization do its thing and hope for
8548   // the best.
8549   SDValue Src = N->getOperand(0);
8550   EVT SrcVT = Src->getValueType(0);
8551   if (!ResVT.isSimple() || !SrcVT.isSimple())
8552     return SDValue();
8553 
8554   // If the source VT is a 64-bit vector, we can play games and get the
8555   // better results we want.
8556   if (SrcVT.getSizeInBits() != 64)
8557     return SDValue();
8558 
8559   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8560   unsigned ElementCount = SrcVT.getVectorNumElements();
8561   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8562   SDLoc DL(N);
8563   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8564 
8565   // Now split the rest of the operation into two halves, each with a 64
8566   // bit source.
8567   EVT LoVT, HiVT;
8568   SDValue Lo, Hi;
8569   unsigned NumElements = ResVT.getVectorNumElements();
8570   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8571   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8572                                  ResVT.getVectorElementType(), NumElements / 2);
8573 
8574   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8575                                LoVT.getVectorNumElements());
8576   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8577                    DAG.getConstant(0, DL, MVT::i64));
8578   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8579                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8580   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8581   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8582 
8583   // Now combine the parts back together so we still have a single result
8584   // like the combiner expects.
8585   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8586 }
8587 
8588 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8589 /// value. The load store optimizer pass will merge them to store pair stores.
8590 /// This has better performance than a splat of the scalar followed by a split
8591 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8592 /// followed by an ext.b and two stores.
8593 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8594   SDValue StVal = St->getValue();
8595   EVT VT = StVal.getValueType();
8596 
8597   // Don't replace floating point stores, they possibly won't be transformed to
8598   // stp because of the store pair suppress pass.
8599   if (VT.isFloatingPoint())
8600     return SDValue();
8601 
8602   // Check for insert vector elements.
8603   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8604     return SDValue();
8605 
8606   // We can express a splat as store pair(s) for 2 or 4 elements.
8607   unsigned NumVecElts = VT.getVectorNumElements();
8608   if (NumVecElts != 4 && NumVecElts != 2)
8609     return SDValue();
8610   SDValue SplatVal = StVal.getOperand(1);
8611   unsigned RemainInsertElts = NumVecElts - 1;
8612 
8613   // Check that this is a splat.
8614   while (--RemainInsertElts) {
8615     SDValue NextInsertElt = StVal.getOperand(0);
8616     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8617       return SDValue();
8618     if (NextInsertElt.getOperand(1) != SplatVal)
8619       return SDValue();
8620     StVal = NextInsertElt;
8621   }
8622   unsigned OrigAlignment = St->getAlignment();
8623   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8624   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8625 
8626   // Create scalar stores. This is at least as good as the code sequence for a
8627   // split unaligned store which is a dup.s, ext.b, and two stores.
8628   // Most of the time the three stores should be replaced by store pair
8629   // instructions (stp).
8630   SDLoc DL(St);
8631   SDValue BasePtr = St->getBasePtr();
8632   SDValue NewST1 =
8633       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8634                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8635 
8636   unsigned Offset = EltOffset;
8637   while (--NumVecElts) {
8638     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8639                                     DAG.getConstant(Offset, DL, MVT::i64));
8640     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8641                           St->getPointerInfo(), St->isVolatile(),
8642                           St->isNonTemporal(), Alignment);
8643     Offset += EltOffset;
8644   }
8645   return NewST1;
8646 }
8647 
8648 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8649                               SelectionDAG &DAG,
8650                               const AArch64Subtarget *Subtarget) {
8651   if (!DCI.isBeforeLegalize())
8652     return SDValue();
8653 
8654   StoreSDNode *S = cast<StoreSDNode>(N);
8655   if (S->isVolatile())
8656     return SDValue();
8657 
8658   // FIXME: The logic for deciding if an unaligned store should be split should
8659   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8660   // a call to that function here.
8661 
8662   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8663   // page boundaries. We want to split such stores.
8664   if (!Subtarget->isCyclone())
8665     return SDValue();
8666 
8667   // Don't split at -Oz.
8668   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8669     return SDValue();
8670 
8671   SDValue StVal = S->getValue();
8672   EVT VT = StVal.getValueType();
8673 
8674   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8675   // those up regresses performance on micro-benchmarks and olden/bh.
8676   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8677     return SDValue();
8678 
8679   // Split unaligned 16B stores. They are terrible for performance.
8680   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8681   // extensions can use this to mark that it does not want splitting to happen
8682   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8683   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8684   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8685       S->getAlignment() <= 2)
8686     return SDValue();
8687 
8688   // If we get a splat of a scalar convert this vector store to a store of
8689   // scalars. They will be merged into store pairs thereby removing two
8690   // instructions.
8691   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8692     return ReplacedSplat;
8693 
8694   SDLoc DL(S);
8695   unsigned NumElts = VT.getVectorNumElements() / 2;
8696   // Split VT into two.
8697   EVT HalfVT =
8698       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8699   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8700                                    DAG.getConstant(0, DL, MVT::i64));
8701   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8702                                    DAG.getConstant(NumElts, DL, MVT::i64));
8703   SDValue BasePtr = S->getBasePtr();
8704   SDValue NewST1 =
8705       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8706                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8707   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8708                                   DAG.getConstant(8, DL, MVT::i64));
8709   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8710                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8711                       S->getAlignment());
8712 }
8713 
8714 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8715 /// post-increment LD1R.
8716 static SDValue performPostLD1Combine(SDNode *N,
8717                                      TargetLowering::DAGCombinerInfo &DCI,
8718                                      bool IsLaneOp) {
8719   if (DCI.isBeforeLegalizeOps())
8720     return SDValue();
8721 
8722   SelectionDAG &DAG = DCI.DAG;
8723   EVT VT = N->getValueType(0);
8724 
8725   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8726   SDNode *LD = N->getOperand(LoadIdx).getNode();
8727   // If it is not LOAD, can not do such combine.
8728   if (LD->getOpcode() != ISD::LOAD)
8729     return SDValue();
8730 
8731   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8732   EVT MemVT = LoadSDN->getMemoryVT();
8733   // Check if memory operand is the same type as the vector element.
8734   if (MemVT != VT.getVectorElementType())
8735     return SDValue();
8736 
8737   // Check if there are other uses. If so, do not combine as it will introduce
8738   // an extra load.
8739   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8740        ++UI) {
8741     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8742       continue;
8743     if (*UI != N)
8744       return SDValue();
8745   }
8746 
8747   SDValue Addr = LD->getOperand(1);
8748   SDValue Vector = N->getOperand(0);
8749   // Search for a use of the address operand that is an increment.
8750   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8751        Addr.getNode()->use_end(); UI != UE; ++UI) {
8752     SDNode *User = *UI;
8753     if (User->getOpcode() != ISD::ADD
8754         || UI.getUse().getResNo() != Addr.getResNo())
8755       continue;
8756 
8757     // Check that the add is independent of the load.  Otherwise, folding it
8758     // would create a cycle.
8759     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8760       continue;
8761     // Also check that add is not used in the vector operand.  This would also
8762     // create a cycle.
8763     if (User->isPredecessorOf(Vector.getNode()))
8764       continue;
8765 
8766     // If the increment is a constant, it must match the memory ref size.
8767     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8768     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8769       uint32_t IncVal = CInc->getZExtValue();
8770       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8771       if (IncVal != NumBytes)
8772         continue;
8773       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8774     }
8775 
8776     // Finally, check that the vector doesn't depend on the load.
8777     // Again, this would create a cycle.
8778     // The load depending on the vector is fine, as that's the case for the
8779     // LD1*post we'll eventually generate anyway.
8780     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8781       continue;
8782 
8783     SmallVector<SDValue, 8> Ops;
8784     Ops.push_back(LD->getOperand(0));  // Chain
8785     if (IsLaneOp) {
8786       Ops.push_back(Vector);           // The vector to be inserted
8787       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8788     }
8789     Ops.push_back(Addr);
8790     Ops.push_back(Inc);
8791 
8792     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8793     SDVTList SDTys = DAG.getVTList(Tys);
8794     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8795     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8796                                            MemVT,
8797                                            LoadSDN->getMemOperand());
8798 
8799     // Update the uses.
8800     SmallVector<SDValue, 2> NewResults;
8801     NewResults.push_back(SDValue(LD, 0));             // The result of load
8802     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8803     DCI.CombineTo(LD, NewResults);
8804     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8805     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8806 
8807     break;
8808   }
8809   return SDValue();
8810 }
8811 
8812 /// Simplify \Addr given that the top byte of it is ignored by HW during
8813 /// address translation.
8814 static bool performTBISimplification(SDValue Addr,
8815                                      TargetLowering::DAGCombinerInfo &DCI,
8816                                      SelectionDAG &DAG) {
8817   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8818   APInt KnownZero, KnownOne;
8819   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8820                                         DCI.isBeforeLegalizeOps());
8821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8822   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8823     DCI.CommitTargetLoweringOpt(TLO);
8824     return true;
8825   }
8826   return false;
8827 }
8828 
8829 static SDValue performSTORECombine(SDNode *N,
8830                                    TargetLowering::DAGCombinerInfo &DCI,
8831                                    SelectionDAG &DAG,
8832                                    const AArch64Subtarget *Subtarget) {
8833   SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8834   if (Split.getNode())
8835     return Split;
8836 
8837   if (Subtarget->supportsAddressTopByteIgnored() &&
8838       performTBISimplification(N->getOperand(2), DCI, DAG))
8839     return SDValue(N, 0);
8840 
8841   return SDValue();
8842 }
8843 
8844   /// This function handles the log2-shuffle pattern produced by the
8845 /// LoopVectorizer for the across vector reduction. It consists of
8846 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8847 /// are reduced, where s is an induction variable from 0 to
8848 /// log2(NumVectorElements).
8849 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8850                                                      unsigned Op,
8851                                                      SelectionDAG &DAG) {
8852   EVT VTy = OpV->getOperand(0).getValueType();
8853   if (!VTy.isVector())
8854     return SDValue();
8855 
8856   int NumVecElts = VTy.getVectorNumElements();
8857   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8858     if (NumVecElts != 4)
8859       return SDValue();
8860   } else {
8861     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8862       return SDValue();
8863   }
8864 
8865   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8866   SDValue PreOp = OpV;
8867   // Iterate over each step of the across vector reduction.
8868   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8869     SDValue CurOp = PreOp.getOperand(0);
8870     SDValue Shuffle = PreOp.getOperand(1);
8871     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8872       // Try to swap the 1st and 2nd operand as add and min/max instructions
8873       // are commutative.
8874       CurOp = PreOp.getOperand(1);
8875       Shuffle = PreOp.getOperand(0);
8876       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8877         return SDValue();
8878     }
8879 
8880     // Check if the input vector is fed by the operator we want to handle,
8881     // except the last step; the very first input vector is not necessarily
8882     // the same operator we are handling.
8883     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8884       return SDValue();
8885 
8886     // Check if it forms one step of the across vector reduction.
8887     // E.g.,
8888     //   %cur = add %1, %0
8889     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8890     //   %pre = add %cur, %shuffle
8891     if (Shuffle.getOperand(0) != CurOp)
8892       return SDValue();
8893 
8894     int NumMaskElts = 1 << CurStep;
8895     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8896     // Check mask values in each step.
8897     // We expect the shuffle mask in each step follows a specific pattern
8898     // denoted here by the <M, U> form, where M is a sequence of integers
8899     // starting from NumMaskElts, increasing by 1, and the number integers
8900     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8901     // of undef in U should be NumVecElts - NumMaskElts.
8902     // E.g., for <8 x i16>, mask values in each step should be :
8903     //   step 0 : <1,u,u,u,u,u,u,u>
8904     //   step 1 : <2,3,u,u,u,u,u,u>
8905     //   step 2 : <4,5,6,7,u,u,u,u>
8906     for (int i = 0; i < NumVecElts; ++i)
8907       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8908           (i >= NumMaskElts && !(Mask[i] < 0)))
8909         return SDValue();
8910 
8911     PreOp = CurOp;
8912   }
8913   unsigned Opcode;
8914   bool IsIntrinsic = false;
8915 
8916   switch (Op) {
8917   default:
8918     llvm_unreachable("Unexpected operator for across vector reduction");
8919   case ISD::ADD:
8920     Opcode = AArch64ISD::UADDV;
8921     break;
8922   case ISD::SMAX:
8923     Opcode = AArch64ISD::SMAXV;
8924     break;
8925   case ISD::UMAX:
8926     Opcode = AArch64ISD::UMAXV;
8927     break;
8928   case ISD::SMIN:
8929     Opcode = AArch64ISD::SMINV;
8930     break;
8931   case ISD::UMIN:
8932     Opcode = AArch64ISD::UMINV;
8933     break;
8934   case ISD::FMAXNUM:
8935     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8936     IsIntrinsic = true;
8937     break;
8938   case ISD::FMINNUM:
8939     Opcode = Intrinsic::aarch64_neon_fminnmv;
8940     IsIntrinsic = true;
8941     break;
8942   }
8943   SDLoc DL(N);
8944 
8945   return IsIntrinsic
8946              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8947                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8948              : DAG.getNode(
8949                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8950                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8951                    DAG.getConstant(0, DL, MVT::i64));
8952 }
8953 
8954 /// Target-specific DAG combine for the across vector min/max reductions.
8955 /// This function specifically handles the final clean-up step of the vector
8956 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8957 /// pattern, which narrows down and finds the final min/max value from all
8958 /// elements of the vector.
8959 /// For example, for a <16 x i8> vector :
8960 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8961 ///   %smax0 = smax %arr, svn0
8962 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8963 ///   %smax1 = smax %smax0, %svn1
8964 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8965 ///   %smax2 = smax %smax1, svn2
8966 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8967 ///   %sc = setcc %smax2, %svn3, gt
8968 ///   %n0 = extract_vector_elt %sc, #0
8969 ///   %n1 = extract_vector_elt %smax2, #0
8970 ///   %n2 = extract_vector_elt $smax2, #1
8971 ///   %result = select %n0, %n1, n2
8972 ///     becomes :
8973 ///   %1 = smaxv %0
8974 ///   %result = extract_vector_elt %1, 0
8975 static SDValue
8976 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8977                                         const AArch64Subtarget *Subtarget) {
8978   if (!Subtarget->hasNEON())
8979     return SDValue();
8980 
8981   SDValue N0 = N->getOperand(0);
8982   SDValue IfTrue = N->getOperand(1);
8983   SDValue IfFalse = N->getOperand(2);
8984 
8985   // Check if the SELECT merges up the final result of the min/max
8986   // from a vector.
8987   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8988       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8989       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8990     return SDValue();
8991 
8992   // Expect N0 is fed by SETCC.
8993   SDValue SetCC = N0.getOperand(0);
8994   EVT SetCCVT = SetCC.getValueType();
8995   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8996       SetCCVT.getVectorElementType() != MVT::i1)
8997     return SDValue();
8998 
8999   SDValue VectorOp = SetCC.getOperand(0);
9000   unsigned Op = VectorOp->getOpcode();
9001   // Check if the input vector is fed by the operator we want to handle.
9002   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9003       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9004     return SDValue();
9005 
9006   EVT VTy = VectorOp.getValueType();
9007   if (!VTy.isVector())
9008     return SDValue();
9009 
9010   if (VTy.getSizeInBits() < 64)
9011     return SDValue();
9012 
9013   EVT EltTy = VTy.getVectorElementType();
9014   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9015     if (EltTy != MVT::f32)
9016       return SDValue();
9017   } else {
9018     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9019       return SDValue();
9020   }
9021 
9022   // Check if extracting from the same vector.
9023   // For example,
9024   //   %sc = setcc %vector, %svn1, gt
9025   //   %n0 = extract_vector_elt %sc, #0
9026   //   %n1 = extract_vector_elt %vector, #0
9027   //   %n2 = extract_vector_elt $vector, #1
9028   if (!(VectorOp == IfTrue->getOperand(0) &&
9029         VectorOp == IfFalse->getOperand(0)))
9030     return SDValue();
9031 
9032   // Check if the condition code is matched with the operator type.
9033   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9034   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9035       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9036       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9037       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9038       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9039        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9040        CC != ISD::SETGE) ||
9041       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9042        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9043        CC != ISD::SETLE))
9044     return SDValue();
9045 
9046   // Expect to check only lane 0 from the vector SETCC.
9047   if (!isNullConstant(N0.getOperand(1)))
9048     return SDValue();
9049 
9050   // Expect to extract the true value from lane 0.
9051   if (!isNullConstant(IfTrue.getOperand(1)))
9052     return SDValue();
9053 
9054   // Expect to extract the false value from lane 1.
9055   if (!isOneConstant(IfFalse.getOperand(1)))
9056     return SDValue();
9057 
9058   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9059 }
9060 
9061 /// Target-specific DAG combine for the across vector add reduction.
9062 /// This function specifically handles the final clean-up step of the vector
9063 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9064 /// pattern, which adds all elements of a vector together.
9065 /// For example, for a <4 x i32> vector :
9066 ///   %1 = vector_shuffle %0, <2,3,u,u>
9067 ///   %2 = add %0, %1
9068 ///   %3 = vector_shuffle %2, <1,u,u,u>
9069 ///   %4 = add %2, %3
9070 ///   %result = extract_vector_elt %4, 0
9071 /// becomes :
9072 ///   %0 = uaddv %0
9073 ///   %result = extract_vector_elt %0, 0
9074 static SDValue
9075 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9076                                      const AArch64Subtarget *Subtarget) {
9077   if (!Subtarget->hasNEON())
9078     return SDValue();
9079   SDValue N0 = N->getOperand(0);
9080   SDValue N1 = N->getOperand(1);
9081 
9082   // Check if the input vector is fed by the ADD.
9083   if (N0->getOpcode() != ISD::ADD)
9084     return SDValue();
9085 
9086   // The vector extract idx must constant zero because we only expect the final
9087   // result of the reduction is placed in lane 0.
9088   if (!isNullConstant(N1))
9089     return SDValue();
9090 
9091   EVT VTy = N0.getValueType();
9092   if (!VTy.isVector())
9093     return SDValue();
9094 
9095   EVT EltTy = VTy.getVectorElementType();
9096   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9097     return SDValue();
9098 
9099   if (VTy.getSizeInBits() < 64)
9100     return SDValue();
9101 
9102   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9103 }
9104 
9105 /// Target-specific DAG combine function for NEON load/store intrinsics
9106 /// to merge base address updates.
9107 static SDValue performNEONPostLDSTCombine(SDNode *N,
9108                                           TargetLowering::DAGCombinerInfo &DCI,
9109                                           SelectionDAG &DAG) {
9110   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9111     return SDValue();
9112 
9113   unsigned AddrOpIdx = N->getNumOperands() - 1;
9114   SDValue Addr = N->getOperand(AddrOpIdx);
9115 
9116   // Search for a use of the address operand that is an increment.
9117   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9118        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9119     SDNode *User = *UI;
9120     if (User->getOpcode() != ISD::ADD ||
9121         UI.getUse().getResNo() != Addr.getResNo())
9122       continue;
9123 
9124     // Check that the add is independent of the load/store.  Otherwise, folding
9125     // it would create a cycle.
9126     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9127       continue;
9128 
9129     // Find the new opcode for the updating load/store.
9130     bool IsStore = false;
9131     bool IsLaneOp = false;
9132     bool IsDupOp = false;
9133     unsigned NewOpc = 0;
9134     unsigned NumVecs = 0;
9135     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9136     switch (IntNo) {
9137     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9138     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9139       NumVecs = 2; break;
9140     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9141       NumVecs = 3; break;
9142     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9143       NumVecs = 4; break;
9144     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9145       NumVecs = 2; IsStore = true; break;
9146     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9147       NumVecs = 3; IsStore = true; break;
9148     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9149       NumVecs = 4; IsStore = true; break;
9150     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9151       NumVecs = 2; break;
9152     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9153       NumVecs = 3; break;
9154     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9155       NumVecs = 4; break;
9156     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9157       NumVecs = 2; IsStore = true; break;
9158     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9159       NumVecs = 3; IsStore = true; break;
9160     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9161       NumVecs = 4; IsStore = true; break;
9162     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9163       NumVecs = 2; IsDupOp = true; break;
9164     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9165       NumVecs = 3; IsDupOp = true; break;
9166     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9167       NumVecs = 4; IsDupOp = true; break;
9168     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9169       NumVecs = 2; IsLaneOp = true; break;
9170     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9171       NumVecs = 3; IsLaneOp = true; break;
9172     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9173       NumVecs = 4; IsLaneOp = true; break;
9174     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9175       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9176     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9177       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9178     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9179       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9180     }
9181 
9182     EVT VecTy;
9183     if (IsStore)
9184       VecTy = N->getOperand(2).getValueType();
9185     else
9186       VecTy = N->getValueType(0);
9187 
9188     // If the increment is a constant, it must match the memory ref size.
9189     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9190     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9191       uint32_t IncVal = CInc->getZExtValue();
9192       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9193       if (IsLaneOp || IsDupOp)
9194         NumBytes /= VecTy.getVectorNumElements();
9195       if (IncVal != NumBytes)
9196         continue;
9197       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9198     }
9199     SmallVector<SDValue, 8> Ops;
9200     Ops.push_back(N->getOperand(0)); // Incoming chain
9201     // Load lane and store have vector list as input.
9202     if (IsLaneOp || IsStore)
9203       for (unsigned i = 2; i < AddrOpIdx; ++i)
9204         Ops.push_back(N->getOperand(i));
9205     Ops.push_back(Addr); // Base register
9206     Ops.push_back(Inc);
9207 
9208     // Return Types.
9209     EVT Tys[6];
9210     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9211     unsigned n;
9212     for (n = 0; n < NumResultVecs; ++n)
9213       Tys[n] = VecTy;
9214     Tys[n++] = MVT::i64;  // Type of write back register
9215     Tys[n] = MVT::Other;  // Type of the chain
9216     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9217 
9218     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9219     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9220                                            MemInt->getMemoryVT(),
9221                                            MemInt->getMemOperand());
9222 
9223     // Update the uses.
9224     std::vector<SDValue> NewResults;
9225     for (unsigned i = 0; i < NumResultVecs; ++i) {
9226       NewResults.push_back(SDValue(UpdN.getNode(), i));
9227     }
9228     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9229     DCI.CombineTo(N, NewResults);
9230     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9231 
9232     break;
9233   }
9234   return SDValue();
9235 }
9236 
9237 // Checks to see if the value is the prescribed width and returns information
9238 // about its extension mode.
9239 static
9240 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9241   ExtType = ISD::NON_EXTLOAD;
9242   switch(V.getNode()->getOpcode()) {
9243   default:
9244     return false;
9245   case ISD::LOAD: {
9246     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9247     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9248        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9249       ExtType = LoadNode->getExtensionType();
9250       return true;
9251     }
9252     return false;
9253   }
9254   case ISD::AssertSext: {
9255     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9256     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9257        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9258       ExtType = ISD::SEXTLOAD;
9259       return true;
9260     }
9261     return false;
9262   }
9263   case ISD::AssertZext: {
9264     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9265     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9266        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9267       ExtType = ISD::ZEXTLOAD;
9268       return true;
9269     }
9270     return false;
9271   }
9272   case ISD::Constant:
9273   case ISD::TargetConstant: {
9274     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9275         1LL << (width - 1))
9276       return true;
9277     return false;
9278   }
9279   }
9280 
9281   return true;
9282 }
9283 
9284 // This function does a whole lot of voodoo to determine if the tests are
9285 // equivalent without and with a mask. Essentially what happens is that given a
9286 // DAG resembling:
9287 //
9288 //  +-------------+ +-------------+ +-------------+ +-------------+
9289 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9290 //  +-------------+ +-------------+ +-------------+ +-------------+
9291 //           |           |           |               |
9292 //           V           V           |    +----------+
9293 //          +-------------+  +----+  |    |
9294 //          |     ADD     |  |0xff|  |    |
9295 //          +-------------+  +----+  |    |
9296 //                  |           |    |    |
9297 //                  V           V    |    |
9298 //                 +-------------+   |    |
9299 //                 |     AND     |   |    |
9300 //                 +-------------+   |    |
9301 //                      |            |    |
9302 //                      +-----+      |    |
9303 //                            |      |    |
9304 //                            V      V    V
9305 //                           +-------------+
9306 //                           |     CMP     |
9307 //                           +-------------+
9308 //
9309 // The AND node may be safely removed for some combinations of inputs. In
9310 // particular we need to take into account the extension type of the Input,
9311 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9312 // width of the input (this can work for any width inputs, the above graph is
9313 // specific to 8 bits.
9314 //
9315 // The specific equations were worked out by generating output tables for each
9316 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9317 // problem was simplified by working with 4 bit inputs, which means we only
9318 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9319 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9320 // patterns present in both extensions (0,7). For every distinct set of
9321 // AddConstant and CompConstants bit patterns we can consider the masked and
9322 // unmasked versions to be equivalent if the result of this function is true for
9323 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9324 //
9325 //   sub      w8, w0, w1
9326 //   and      w10, w8, #0x0f
9327 //   cmp      w8, w2
9328 //   cset     w9, AArch64CC
9329 //   cmp      w10, w2
9330 //   cset     w11, AArch64CC
9331 //   cmp      w9, w11
9332 //   cset     w0, eq
9333 //   ret
9334 //
9335 // Since the above function shows when the outputs are equivalent it defines
9336 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9337 // would be expensive to run during compiles. The equations below were written
9338 // in a test harness that confirmed they gave equivalent outputs to the above
9339 // for all inputs function, so they can be used determine if the removal is
9340 // legal instead.
9341 //
9342 // isEquivalentMaskless() is the code for testing if the AND can be removed
9343 // factored out of the DAG recognition as the DAG can take several forms.
9344 
9345 static
9346 bool isEquivalentMaskless(unsigned CC, unsigned width,
9347                           ISD::LoadExtType ExtType, signed AddConstant,
9348                           signed CompConstant) {
9349   // By being careful about our equations and only writing the in term
9350   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9351   // make them generally applicable to all bit widths.
9352   signed MaxUInt = (1 << width);
9353 
9354   // For the purposes of these comparisons sign extending the type is
9355   // equivalent to zero extending the add and displacing it by half the integer
9356   // width. Provided we are careful and make sure our equations are valid over
9357   // the whole range we can just adjust the input and avoid writing equations
9358   // for sign extended inputs.
9359   if (ExtType == ISD::SEXTLOAD)
9360     AddConstant -= (1 << (width-1));
9361 
9362   switch(CC) {
9363   case AArch64CC::LE:
9364   case AArch64CC::GT: {
9365     if ((AddConstant == 0) ||
9366         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9367         (AddConstant >= 0 && CompConstant < 0) ||
9368         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9369       return true;
9370   } break;
9371   case AArch64CC::LT:
9372   case AArch64CC::GE: {
9373     if ((AddConstant == 0) ||
9374         (AddConstant >= 0 && CompConstant <= 0) ||
9375         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9376       return true;
9377   } break;
9378   case AArch64CC::HI:
9379   case AArch64CC::LS: {
9380     if ((AddConstant >= 0 && CompConstant < 0) ||
9381        (AddConstant <= 0 && CompConstant >= -1 &&
9382         CompConstant < AddConstant + MaxUInt))
9383       return true;
9384   } break;
9385   case AArch64CC::PL:
9386   case AArch64CC::MI: {
9387     if ((AddConstant == 0) ||
9388         (AddConstant > 0 && CompConstant <= 0) ||
9389         (AddConstant < 0 && CompConstant <= AddConstant))
9390       return true;
9391   } break;
9392   case AArch64CC::LO:
9393   case AArch64CC::HS: {
9394     if ((AddConstant >= 0 && CompConstant <= 0) ||
9395         (AddConstant <= 0 && CompConstant >= 0 &&
9396          CompConstant <= AddConstant + MaxUInt))
9397       return true;
9398   } break;
9399   case AArch64CC::EQ:
9400   case AArch64CC::NE: {
9401     if ((AddConstant > 0 && CompConstant < 0) ||
9402         (AddConstant < 0 && CompConstant >= 0 &&
9403          CompConstant < AddConstant + MaxUInt) ||
9404         (AddConstant >= 0 && CompConstant >= 0 &&
9405          CompConstant >= AddConstant) ||
9406         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9407 
9408       return true;
9409   } break;
9410   case AArch64CC::VS:
9411   case AArch64CC::VC:
9412   case AArch64CC::AL:
9413   case AArch64CC::NV:
9414     return true;
9415   case AArch64CC::Invalid:
9416     break;
9417   }
9418 
9419   return false;
9420 }
9421 
9422 static
9423 SDValue performCONDCombine(SDNode *N,
9424                            TargetLowering::DAGCombinerInfo &DCI,
9425                            SelectionDAG &DAG, unsigned CCIndex,
9426                            unsigned CmpIndex) {
9427   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9428   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9429   unsigned CondOpcode = SubsNode->getOpcode();
9430 
9431   if (CondOpcode != AArch64ISD::SUBS)
9432     return SDValue();
9433 
9434   // There is a SUBS feeding this condition. Is it fed by a mask we can
9435   // use?
9436 
9437   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9438   unsigned MaskBits = 0;
9439 
9440   if (AndNode->getOpcode() != ISD::AND)
9441     return SDValue();
9442 
9443   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9444     uint32_t CNV = CN->getZExtValue();
9445     if (CNV == 255)
9446       MaskBits = 8;
9447     else if (CNV == 65535)
9448       MaskBits = 16;
9449   }
9450 
9451   if (!MaskBits)
9452     return SDValue();
9453 
9454   SDValue AddValue = AndNode->getOperand(0);
9455 
9456   if (AddValue.getOpcode() != ISD::ADD)
9457     return SDValue();
9458 
9459   // The basic dag structure is correct, grab the inputs and validate them.
9460 
9461   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9462   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9463   SDValue SubsInputValue = SubsNode->getOperand(1);
9464 
9465   // The mask is present and the provenance of all the values is a smaller type,
9466   // lets see if the mask is superfluous.
9467 
9468   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9469       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9470     return SDValue();
9471 
9472   ISD::LoadExtType ExtType;
9473 
9474   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9475       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9476       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9477     return SDValue();
9478 
9479   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9480                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9481                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9482     return SDValue();
9483 
9484   // The AND is not necessary, remove it.
9485 
9486   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9487                                SubsNode->getValueType(1));
9488   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9489 
9490   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9491   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9492 
9493   return SDValue(N, 0);
9494 }
9495 
9496 // Optimize compare with zero and branch.
9497 static SDValue performBRCONDCombine(SDNode *N,
9498                                     TargetLowering::DAGCombinerInfo &DCI,
9499                                     SelectionDAG &DAG) {
9500   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9501   if (NV.getNode())
9502     N = NV.getNode();
9503   SDValue Chain = N->getOperand(0);
9504   SDValue Dest = N->getOperand(1);
9505   SDValue CCVal = N->getOperand(2);
9506   SDValue Cmp = N->getOperand(3);
9507 
9508   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9509   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9510   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9511     return SDValue();
9512 
9513   unsigned CmpOpc = Cmp.getOpcode();
9514   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9515     return SDValue();
9516 
9517   // Only attempt folding if there is only one use of the flag and no use of the
9518   // value.
9519   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9520     return SDValue();
9521 
9522   SDValue LHS = Cmp.getOperand(0);
9523   SDValue RHS = Cmp.getOperand(1);
9524 
9525   assert(LHS.getValueType() == RHS.getValueType() &&
9526          "Expected the value type to be the same for both operands!");
9527   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9528     return SDValue();
9529 
9530   if (isNullConstant(LHS))
9531     std::swap(LHS, RHS);
9532 
9533   if (!isNullConstant(RHS))
9534     return SDValue();
9535 
9536   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9537       LHS.getOpcode() == ISD::SRL)
9538     return SDValue();
9539 
9540   // Fold the compare into the branch instruction.
9541   SDValue BR;
9542   if (CC == AArch64CC::EQ)
9543     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9544   else
9545     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9546 
9547   // Do not add new nodes to DAG combiner worklist.
9548   DCI.CombineTo(N, BR, false);
9549 
9550   return SDValue();
9551 }
9552 
9553 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9554 // as well as whether the test should be inverted.  This code is required to
9555 // catch these cases (as opposed to standard dag combines) because
9556 // AArch64ISD::TBZ is matched during legalization.
9557 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9558                                  SelectionDAG &DAG) {
9559 
9560   if (!Op->hasOneUse())
9561     return Op;
9562 
9563   // We don't handle undef/constant-fold cases below, as they should have
9564   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9565   // etc.)
9566 
9567   // (tbz (trunc x), b) -> (tbz x, b)
9568   // This case is just here to enable more of the below cases to be caught.
9569   if (Op->getOpcode() == ISD::TRUNCATE &&
9570       Bit < Op->getValueType(0).getSizeInBits()) {
9571     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9572   }
9573 
9574   if (Op->getNumOperands() != 2)
9575     return Op;
9576 
9577   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9578   if (!C)
9579     return Op;
9580 
9581   switch (Op->getOpcode()) {
9582   default:
9583     return Op;
9584 
9585   // (tbz (and x, m), b) -> (tbz x, b)
9586   case ISD::AND:
9587     if ((C->getZExtValue() >> Bit) & 1)
9588       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9589     return Op;
9590 
9591   // (tbz (shl x, c), b) -> (tbz x, b-c)
9592   case ISD::SHL:
9593     if (C->getZExtValue() <= Bit &&
9594         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9595       Bit = Bit - C->getZExtValue();
9596       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9597     }
9598     return Op;
9599 
9600   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9601   case ISD::SRA:
9602     Bit = Bit + C->getZExtValue();
9603     if (Bit >= Op->getValueType(0).getSizeInBits())
9604       Bit = Op->getValueType(0).getSizeInBits() - 1;
9605     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9606 
9607   // (tbz (srl x, c), b) -> (tbz x, b+c)
9608   case ISD::SRL:
9609     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9610       Bit = Bit + C->getZExtValue();
9611       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9612     }
9613     return Op;
9614 
9615   // (tbz (xor x, -1), b) -> (tbnz x, b)
9616   case ISD::XOR:
9617     if ((C->getZExtValue() >> Bit) & 1)
9618       Invert = !Invert;
9619     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9620   }
9621 }
9622 
9623 // Optimize test single bit zero/non-zero and branch.
9624 static SDValue performTBZCombine(SDNode *N,
9625                                  TargetLowering::DAGCombinerInfo &DCI,
9626                                  SelectionDAG &DAG) {
9627   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9628   bool Invert = false;
9629   SDValue TestSrc = N->getOperand(1);
9630   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9631 
9632   if (TestSrc == NewTestSrc)
9633     return SDValue();
9634 
9635   unsigned NewOpc = N->getOpcode();
9636   if (Invert) {
9637     if (NewOpc == AArch64ISD::TBZ)
9638       NewOpc = AArch64ISD::TBNZ;
9639     else {
9640       assert(NewOpc == AArch64ISD::TBNZ);
9641       NewOpc = AArch64ISD::TBZ;
9642     }
9643   }
9644 
9645   SDLoc DL(N);
9646   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9647                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9648 }
9649 
9650 // vselect (v1i1 setcc) ->
9651 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9652 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9653 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9654 // such VSELECT.
9655 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9656   SDValue N0 = N->getOperand(0);
9657   EVT CCVT = N0.getValueType();
9658 
9659   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9660       CCVT.getVectorElementType() != MVT::i1)
9661     return SDValue();
9662 
9663   EVT ResVT = N->getValueType(0);
9664   EVT CmpVT = N0.getOperand(0).getValueType();
9665   // Only combine when the result type is of the same size as the compared
9666   // operands.
9667   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9668     return SDValue();
9669 
9670   SDValue IfTrue = N->getOperand(1);
9671   SDValue IfFalse = N->getOperand(2);
9672   SDValue SetCC =
9673       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9674                    N0.getOperand(0), N0.getOperand(1),
9675                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9676   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9677                      IfTrue, IfFalse);
9678 }
9679 
9680 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9681 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9682 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9683 /// with a vector one followed by a DUP shuffle on the result.
9684 static SDValue performSelectCombine(SDNode *N,
9685                                     TargetLowering::DAGCombinerInfo &DCI) {
9686   SelectionDAG &DAG = DCI.DAG;
9687   SDValue N0 = N->getOperand(0);
9688   EVT ResVT = N->getValueType(0);
9689 
9690   if (N0.getOpcode() != ISD::SETCC)
9691     return SDValue();
9692 
9693   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9694   // scalar SetCCResultType. We also don't expect vectors, because we assume
9695   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9696   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9697          "Scalar-SETCC feeding SELECT has unexpected result type!");
9698 
9699   // If NumMaskElts == 0, the comparison is larger than select result. The
9700   // largest real NEON comparison is 64-bits per lane, which means the result is
9701   // at most 32-bits and an illegal vector. Just bail out for now.
9702   EVT SrcVT = N0.getOperand(0).getValueType();
9703 
9704   // Don't try to do this optimization when the setcc itself has i1 operands.
9705   // There are no legal vectors of i1, so this would be pointless.
9706   if (SrcVT == MVT::i1)
9707     return SDValue();
9708 
9709   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9710   if (!ResVT.isVector() || NumMaskElts == 0)
9711     return SDValue();
9712 
9713   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9714   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9715 
9716   // Also bail out if the vector CCVT isn't the same size as ResVT.
9717   // This can happen if the SETCC operand size doesn't divide the ResVT size
9718   // (e.g., f64 vs v3f32).
9719   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9720     return SDValue();
9721 
9722   // Make sure we didn't create illegal types, if we're not supposed to.
9723   assert(DCI.isBeforeLegalize() ||
9724          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9725 
9726   // First perform a vector comparison, where lane 0 is the one we're interested
9727   // in.
9728   SDLoc DL(N0);
9729   SDValue LHS =
9730       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9731   SDValue RHS =
9732       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9733   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9734 
9735   // Now duplicate the comparison mask we want across all other lanes.
9736   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9737   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9738   Mask = DAG.getNode(ISD::BITCAST, DL,
9739                      ResVT.changeVectorElementTypeToInteger(), Mask);
9740 
9741   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9742 }
9743 
9744 /// Get rid of unnecessary NVCASTs (that don't change the type).
9745 static SDValue performNVCASTCombine(SDNode *N) {
9746   if (N->getValueType(0) == N->getOperand(0).getValueType())
9747     return N->getOperand(0);
9748 
9749   return SDValue();
9750 }
9751 
9752 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9753                                                  DAGCombinerInfo &DCI) const {
9754   SelectionDAG &DAG = DCI.DAG;
9755   switch (N->getOpcode()) {
9756   default:
9757     break;
9758   case ISD::ADD:
9759   case ISD::SUB:
9760     return performAddSubLongCombine(N, DCI, DAG);
9761   case ISD::XOR:
9762     return performXorCombine(N, DAG, DCI, Subtarget);
9763   case ISD::MUL:
9764     return performMulCombine(N, DAG, DCI, Subtarget);
9765   case ISD::SINT_TO_FP:
9766   case ISD::UINT_TO_FP:
9767     return performIntToFpCombine(N, DAG, Subtarget);
9768   case ISD::FP_TO_SINT:
9769   case ISD::FP_TO_UINT:
9770     return performFpToIntCombine(N, DAG, Subtarget);
9771   case ISD::FDIV:
9772     return performFDivCombine(N, DAG, Subtarget);
9773   case ISD::OR:
9774     return performORCombine(N, DCI, Subtarget);
9775   case ISD::INTRINSIC_WO_CHAIN:
9776     return performIntrinsicCombine(N, DCI, Subtarget);
9777   case ISD::ANY_EXTEND:
9778   case ISD::ZERO_EXTEND:
9779   case ISD::SIGN_EXTEND:
9780     return performExtendCombine(N, DCI, DAG);
9781   case ISD::BITCAST:
9782     return performBitcastCombine(N, DCI, DAG);
9783   case ISD::CONCAT_VECTORS:
9784     return performConcatVectorsCombine(N, DCI, DAG);
9785   case ISD::SELECT: {
9786     SDValue RV = performSelectCombine(N, DCI);
9787     if (!RV.getNode())
9788       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9789     return RV;
9790   }
9791   case ISD::VSELECT:
9792     return performVSelectCombine(N, DCI.DAG);
9793   case ISD::LOAD:
9794     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9795       return SDValue(N, 0);
9796     break;
9797   case ISD::STORE:
9798     return performSTORECombine(N, DCI, DAG, Subtarget);
9799   case AArch64ISD::BRCOND:
9800     return performBRCONDCombine(N, DCI, DAG);
9801   case AArch64ISD::TBNZ:
9802   case AArch64ISD::TBZ:
9803     return performTBZCombine(N, DCI, DAG);
9804   case AArch64ISD::CSEL:
9805     return performCONDCombine(N, DCI, DAG, 2, 3);
9806   case AArch64ISD::DUP:
9807     return performPostLD1Combine(N, DCI, false);
9808   case AArch64ISD::NVCAST:
9809     return performNVCASTCombine(N);
9810   case ISD::INSERT_VECTOR_ELT:
9811     return performPostLD1Combine(N, DCI, true);
9812   case ISD::EXTRACT_VECTOR_ELT:
9813     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9814   case ISD::INTRINSIC_VOID:
9815   case ISD::INTRINSIC_W_CHAIN:
9816     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9817     case Intrinsic::aarch64_neon_ld2:
9818     case Intrinsic::aarch64_neon_ld3:
9819     case Intrinsic::aarch64_neon_ld4:
9820     case Intrinsic::aarch64_neon_ld1x2:
9821     case Intrinsic::aarch64_neon_ld1x3:
9822     case Intrinsic::aarch64_neon_ld1x4:
9823     case Intrinsic::aarch64_neon_ld2lane:
9824     case Intrinsic::aarch64_neon_ld3lane:
9825     case Intrinsic::aarch64_neon_ld4lane:
9826     case Intrinsic::aarch64_neon_ld2r:
9827     case Intrinsic::aarch64_neon_ld3r:
9828     case Intrinsic::aarch64_neon_ld4r:
9829     case Intrinsic::aarch64_neon_st2:
9830     case Intrinsic::aarch64_neon_st3:
9831     case Intrinsic::aarch64_neon_st4:
9832     case Intrinsic::aarch64_neon_st1x2:
9833     case Intrinsic::aarch64_neon_st1x3:
9834     case Intrinsic::aarch64_neon_st1x4:
9835     case Intrinsic::aarch64_neon_st2lane:
9836     case Intrinsic::aarch64_neon_st3lane:
9837     case Intrinsic::aarch64_neon_st4lane:
9838       return performNEONPostLDSTCombine(N, DCI, DAG);
9839     default:
9840       break;
9841     }
9842   }
9843   return SDValue();
9844 }
9845 
9846 // Check if the return value is used as only a return value, as otherwise
9847 // we can't perform a tail-call. In particular, we need to check for
9848 // target ISD nodes that are returns and any other "odd" constructs
9849 // that the generic analysis code won't necessarily catch.
9850 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9851                                                SDValue &Chain) const {
9852   if (N->getNumValues() != 1)
9853     return false;
9854   if (!N->hasNUsesOfValue(1, 0))
9855     return false;
9856 
9857   SDValue TCChain = Chain;
9858   SDNode *Copy = *N->use_begin();
9859   if (Copy->getOpcode() == ISD::CopyToReg) {
9860     // If the copy has a glue operand, we conservatively assume it isn't safe to
9861     // perform a tail call.
9862     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9863         MVT::Glue)
9864       return false;
9865     TCChain = Copy->getOperand(0);
9866   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9867     return false;
9868 
9869   bool HasRet = false;
9870   for (SDNode *Node : Copy->uses()) {
9871     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9872       return false;
9873     HasRet = true;
9874   }
9875 
9876   if (!HasRet)
9877     return false;
9878 
9879   Chain = TCChain;
9880   return true;
9881 }
9882 
9883 // Return whether the an instruction can potentially be optimized to a tail
9884 // call. This will cause the optimizers to attempt to move, or duplicate,
9885 // return instructions to help enable tail call optimizations for this
9886 // instruction.
9887 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9888   if (!CI->isTailCall())
9889     return false;
9890 
9891   return true;
9892 }
9893 
9894 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9895                                                    SDValue &Offset,
9896                                                    ISD::MemIndexedMode &AM,
9897                                                    bool &IsInc,
9898                                                    SelectionDAG &DAG) const {
9899   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9900     return false;
9901 
9902   Base = Op->getOperand(0);
9903   // All of the indexed addressing mode instructions take a signed
9904   // 9 bit immediate offset.
9905   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9906     int64_t RHSC = (int64_t)RHS->getZExtValue();
9907     if (RHSC >= 256 || RHSC <= -256)
9908       return false;
9909     IsInc = (Op->getOpcode() == ISD::ADD);
9910     Offset = Op->getOperand(1);
9911     return true;
9912   }
9913   return false;
9914 }
9915 
9916 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9917                                                       SDValue &Offset,
9918                                                       ISD::MemIndexedMode &AM,
9919                                                       SelectionDAG &DAG) const {
9920   EVT VT;
9921   SDValue Ptr;
9922   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9923     VT = LD->getMemoryVT();
9924     Ptr = LD->getBasePtr();
9925   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9926     VT = ST->getMemoryVT();
9927     Ptr = ST->getBasePtr();
9928   } else
9929     return false;
9930 
9931   bool IsInc;
9932   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9933     return false;
9934   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9935   return true;
9936 }
9937 
9938 bool AArch64TargetLowering::getPostIndexedAddressParts(
9939     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9940     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9941   EVT VT;
9942   SDValue Ptr;
9943   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9944     VT = LD->getMemoryVT();
9945     Ptr = LD->getBasePtr();
9946   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9947     VT = ST->getMemoryVT();
9948     Ptr = ST->getBasePtr();
9949   } else
9950     return false;
9951 
9952   bool IsInc;
9953   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9954     return false;
9955   // Post-indexing updates the base, so it's not a valid transform
9956   // if that's not the same as the load's pointer.
9957   if (Ptr != Base)
9958     return false;
9959   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9960   return true;
9961 }
9962 
9963 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9964                                   SelectionDAG &DAG) {
9965   SDLoc DL(N);
9966   SDValue Op = N->getOperand(0);
9967 
9968   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9969     return;
9970 
9971   Op = SDValue(
9972       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9973                          DAG.getUNDEF(MVT::i32), Op,
9974                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9975       0);
9976   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9977   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9978 }
9979 
9980 static void ReplaceReductionResults(SDNode *N,
9981                                     SmallVectorImpl<SDValue> &Results,
9982                                     SelectionDAG &DAG, unsigned InterOp,
9983                                     unsigned AcrossOp) {
9984   EVT LoVT, HiVT;
9985   SDValue Lo, Hi;
9986   SDLoc dl(N);
9987   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9988   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9989   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9990   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9991   Results.push_back(SplitVal);
9992 }
9993 
9994 void AArch64TargetLowering::ReplaceNodeResults(
9995     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9996   switch (N->getOpcode()) {
9997   default:
9998     llvm_unreachable("Don't know how to custom expand this");
9999   case ISD::BITCAST:
10000     ReplaceBITCASTResults(N, Results, DAG);
10001     return;
10002   case AArch64ISD::SADDV:
10003     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10004     return;
10005   case AArch64ISD::UADDV:
10006     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10007     return;
10008   case AArch64ISD::SMINV:
10009     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10010     return;
10011   case AArch64ISD::UMINV:
10012     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10013     return;
10014   case AArch64ISD::SMAXV:
10015     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10016     return;
10017   case AArch64ISD::UMAXV:
10018     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10019     return;
10020   case ISD::FP_TO_UINT:
10021   case ISD::FP_TO_SINT:
10022     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10023     // Let normal code take care of it by not adding anything to Results.
10024     return;
10025   }
10026 }
10027 
10028 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10029   return true;
10030 }
10031 
10032 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10033   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10034   // reciprocal if there are three or more FDIVs.
10035   return 3;
10036 }
10037 
10038 TargetLoweringBase::LegalizeTypeAction
10039 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10040   MVT SVT = VT.getSimpleVT();
10041   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10042   // v4i16, v2i32 instead of to promote.
10043   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10044       || SVT == MVT::v1f32)
10045     return TypeWidenVector;
10046 
10047   return TargetLoweringBase::getPreferredVectorAction(VT);
10048 }
10049 
10050 // Loads and stores less than 128-bits are already atomic; ones above that
10051 // are doomed anyway, so defer to the default libcall and blame the OS when
10052 // things go wrong.
10053 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10054   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10055   return Size == 128;
10056 }
10057 
10058 // Loads and stores less than 128-bits are already atomic; ones above that
10059 // are doomed anyway, so defer to the default libcall and blame the OS when
10060 // things go wrong.
10061 TargetLowering::AtomicExpansionKind
10062 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10063   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10064   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10065 }
10066 
10067 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10068 TargetLowering::AtomicExpansionKind
10069 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10070   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10071   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10072 }
10073 
10074 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10075     AtomicCmpXchgInst *AI) const {
10076   return true;
10077 }
10078 
10079 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10080                                              AtomicOrdering Ord) const {
10081   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10082   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10083   bool IsAcquire = isAtLeastAcquire(Ord);
10084 
10085   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10086   // intrinsic must return {i64, i64} and we have to recombine them into a
10087   // single i128 here.
10088   if (ValTy->getPrimitiveSizeInBits() == 128) {
10089     Intrinsic::ID Int =
10090         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10091     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10092 
10093     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10094     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10095 
10096     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10097     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10098     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10099     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10100     return Builder.CreateOr(
10101         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10102   }
10103 
10104   Type *Tys[] = { Addr->getType() };
10105   Intrinsic::ID Int =
10106       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10107   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10108 
10109   return Builder.CreateTruncOrBitCast(
10110       Builder.CreateCall(Ldxr, Addr),
10111       cast<PointerType>(Addr->getType())->getElementType());
10112 }
10113 
10114 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10115     IRBuilder<> &Builder) const {
10116   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10117   Builder.CreateCall(
10118       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10119 }
10120 
10121 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10122                                                    Value *Val, Value *Addr,
10123                                                    AtomicOrdering Ord) const {
10124   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10125   bool IsRelease = isAtLeastRelease(Ord);
10126 
10127   // Since the intrinsics must have legal type, the i128 intrinsics take two
10128   // parameters: "i64, i64". We must marshal Val into the appropriate form
10129   // before the call.
10130   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10131     Intrinsic::ID Int =
10132         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10133     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10134     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10135 
10136     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10137     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10138     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10139     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10140   }
10141 
10142   Intrinsic::ID Int =
10143       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10144   Type *Tys[] = { Addr->getType() };
10145   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10146 
10147   return Builder.CreateCall(Stxr,
10148                             {Builder.CreateZExtOrBitCast(
10149                                  Val, Stxr->getFunctionType()->getParamType(0)),
10150                              Addr});
10151 }
10152 
10153 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10154     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10155   return Ty->isArrayTy();
10156 }
10157 
10158 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10159                                                             EVT) const {
10160   return false;
10161 }
10162 
10163 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10164   if (!Subtarget->isTargetAndroid())
10165     return TargetLowering::getSafeStackPointerLocation(IRB);
10166 
10167   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10168   // definition of TLS_SLOT_SAFESTACK in
10169   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10170   const unsigned TlsOffset = 0x48;
10171   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10172   Function *ThreadPointerFunc =
10173       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10174   return IRB.CreatePointerCast(
10175       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10176       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10177 }
10178 
10179 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10180   // Update IsSplitCSR in AArch64unctionInfo.
10181   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10182   AFI->setIsSplitCSR(true);
10183 }
10184 
10185 void AArch64TargetLowering::insertCopiesSplitCSR(
10186     MachineBasicBlock *Entry,
10187     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10188   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10189   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10190   if (!IStart)
10191     return;
10192 
10193   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10194   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10195   MachineBasicBlock::iterator MBBI = Entry->begin();
10196   for (const MCPhysReg *I = IStart; *I; ++I) {
10197     const TargetRegisterClass *RC = nullptr;
10198     if (AArch64::GPR64RegClass.contains(*I))
10199       RC = &AArch64::GPR64RegClass;
10200     else if (AArch64::FPR64RegClass.contains(*I))
10201       RC = &AArch64::FPR64RegClass;
10202     else
10203       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10204 
10205     unsigned NewVR = MRI->createVirtualRegister(RC);
10206     // Create copy from CSR to a virtual register.
10207     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10208     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10209     // nounwind. If we want to generalize this later, we may need to emit
10210     // CFI pseudo-instructions.
10211     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10212                Attribute::NoUnwind) &&
10213            "Function should be nounwind in insertCopiesSplitCSR!");
10214     Entry->addLiveIn(*I);
10215     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10216         .addReg(*I);
10217 
10218     // Insert the copy-back instructions right before the terminator.
10219     for (auto *Exit : Exits)
10220       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10221               TII->get(TargetOpcode::COPY), *I)
10222           .addReg(NewVR);
10223   }
10224 }
10225