]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Merge ACPICA 20161117.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / AArch64 / AArch64ISelLowering.cpp
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 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1139 /// CC usable with the vector instructions. Fewer operations are available
1140 /// without a real NZCV register, so we have to use less efficient combinations
1141 /// to get the same effect.
1142 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1143                                         AArch64CC::CondCode &CondCode,
1144                                         AArch64CC::CondCode &CondCode2,
1145                                         bool &Invert) {
1146   Invert = false;
1147   switch (CC) {
1148   default:
1149     // Mostly the scalar mappings work fine.
1150     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1151     break;
1152   case ISD::SETUO:
1153     Invert = true; // Fallthrough
1154   case ISD::SETO:
1155     CondCode = AArch64CC::MI;
1156     CondCode2 = AArch64CC::GE;
1157     break;
1158   case ISD::SETUEQ:
1159   case ISD::SETULT:
1160   case ISD::SETULE:
1161   case ISD::SETUGT:
1162   case ISD::SETUGE:
1163     // All of the compare-mask comparisons are ordered, but we can switch
1164     // between the two by a double inversion. E.g. ULE == !OGT.
1165     Invert = true;
1166     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1167     break;
1168   }
1169 }
1170
1171 static bool isLegalArithImmed(uint64_t C) {
1172   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1173   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1174 }
1175
1176 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1177                               SDLoc dl, SelectionDAG &DAG) {
1178   EVT VT = LHS.getValueType();
1179
1180   if (VT.isFloatingPoint()) {
1181     assert(VT != MVT::f128);
1182     if (VT == MVT::f16) {
1183       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1184       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1185     }
1186     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1187   }
1188
1189   // The CMP instruction is just an alias for SUBS, and representing it as
1190   // SUBS means that it's possible to get CSE with subtract operations.
1191   // A later phase can perform the optimization of setting the destination
1192   // register to WZR/XZR if it ends up being unused.
1193   unsigned Opcode = AArch64ISD::SUBS;
1194
1195   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1196       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1197     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1198     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1199     // can be set differently by this operation. It comes down to whether
1200     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1201     // everything is fine. If not then the optimization is wrong. Thus general
1202     // comparisons are only valid if op2 != 0.
1203
1204     // So, finally, the only LLVM-native comparisons that don't mention C and V
1205     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1206     // the absence of information about op2.
1207     Opcode = AArch64ISD::ADDS;
1208     RHS = RHS.getOperand(1);
1209   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1210              !isUnsignedIntSetCC(CC)) {
1211     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1212     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1213     // of the signed comparisons.
1214     Opcode = AArch64ISD::ANDS;
1215     RHS = LHS.getOperand(1);
1216     LHS = LHS.getOperand(0);
1217   }
1218
1219   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1220       .getValue(1);
1221 }
1222
1223 /// \defgroup AArch64CCMP CMP;CCMP matching
1224 ///
1225 /// These functions deal with the formation of CMP;CCMP;... sequences.
1226 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1227 /// a comparison. They set the NZCV flags to a predefined value if their
1228 /// predicate is false. This allows to express arbitrary conjunctions, for
1229 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1230 /// expressed as:
1231 ///   cmp A
1232 ///   ccmp B, inv(CB), CA
1233 ///   check for CB flags
1234 ///
1235 /// In general we can create code for arbitrary "... (and (and A B) C)"
1236 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1237 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1238 /// negation operations:
1239 /// We can negate the results of a single comparison by inverting the flags
1240 /// used when the predicate fails and inverting the flags tested in the next
1241 /// instruction; We can also negate the results of the whole previous
1242 /// conditional compare sequence by inverting the flags tested in the next
1243 /// instruction. However there is no way to negate the result of a partial
1244 /// sequence.
1245 ///
1246 /// Therefore on encountering an "or" expression we can negate the subtree on
1247 /// one side and have to be able to push the negate to the leafs of the subtree
1248 /// on the other side (see also the comments in code). As complete example:
1249 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1250 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1251 /// is transformed to
1252 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1253 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1254 /// and implemented as:
1255 ///   cmp C
1256 ///   ccmp D, inv(CD), CC
1257 ///   ccmp A, CA, inv(CD)
1258 ///   ccmp B, CB, inv(CA)
1259 ///   check for CB flags
1260 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1261 /// by conditional compare sequences.
1262 /// @{
1263
1264 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1265 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1266                                          ISD::CondCode CC, SDValue CCOp,
1267                                          SDValue Condition, unsigned NZCV,
1268                                          SDLoc DL, SelectionDAG &DAG) {
1269   unsigned Opcode = 0;
1270   if (LHS.getValueType().isFloatingPoint()) {
1271     assert(LHS.getValueType() != MVT::f128);
1272     if (LHS.getValueType() == MVT::f16) {
1273       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1274       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1275     }
1276     Opcode = AArch64ISD::FCCMP;
1277   } else if (RHS.getOpcode() == ISD::SUB) {
1278     SDValue SubOp0 = RHS.getOperand(0);
1279     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1280         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1281         Opcode = AArch64ISD::CCMN;
1282         RHS = RHS.getOperand(1);
1283       }
1284   }
1285   if (Opcode == 0)
1286     Opcode = AArch64ISD::CCMP;
1287
1288   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1289   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1290 }
1291
1292 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1293 /// CanPushNegate is set to true if we can push a negate operation through
1294 /// the tree in a was that we are left with AND operations and negate operations
1295 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1296 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1297 /// brought into such a form.
1298 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1299                                          unsigned Depth = 0) {
1300   if (!Val.hasOneUse())
1301     return false;
1302   unsigned Opcode = Val->getOpcode();
1303   if (Opcode == ISD::SETCC) {
1304     if (Val->getOperand(0).getValueType() == MVT::f128)
1305       return false;
1306     CanPushNegate = true;
1307     return true;
1308   }
1309   // Protect against stack overflow.
1310   if (Depth > 15)
1311     return false;
1312   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1313     SDValue O0 = Val->getOperand(0);
1314     SDValue O1 = Val->getOperand(1);
1315     bool CanPushNegateL;
1316     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1317       return false;
1318     bool CanPushNegateR;
1319     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1320       return false;
1321     // We cannot push a negate through an AND operation (it would become an OR),
1322     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1323     // push the negate through the x/y subtrees.
1324     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1325     return true;
1326   }
1327   return false;
1328 }
1329
1330 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1331 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1332 /// Tries to transform the given i1 producing node @p Val to a series compare
1333 /// and conditional compare operations. @returns an NZCV flags producing node
1334 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1335 /// transformation was not possible.
1336 /// On recursive invocations @p PushNegate may be set to true to have negation
1337 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1338 /// for the comparisons in the current subtree; @p Depth limits the search
1339 /// depth to avoid stack overflow.
1340 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1341     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1342     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1343     unsigned Depth = 0) {
1344   // We're at a tree leaf, produce a conditional comparison operation.
1345   unsigned Opcode = Val->getOpcode();
1346   if (Opcode == ISD::SETCC) {
1347     SDValue LHS = Val->getOperand(0);
1348     SDValue RHS = Val->getOperand(1);
1349     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1350     bool isInteger = LHS.getValueType().isInteger();
1351     if (PushNegate)
1352       CC = getSetCCInverse(CC, isInteger);
1353     SDLoc DL(Val);
1354     // Determine OutCC and handle FP special case.
1355     if (isInteger) {
1356       OutCC = changeIntCCToAArch64CC(CC);
1357     } else {
1358       assert(LHS.getValueType().isFloatingPoint());
1359       AArch64CC::CondCode ExtraCC;
1360       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1361       // Surpisingly some floating point conditions can't be tested with a
1362       // single condition code. Construct an additional comparison in this case.
1363       // See comment below on how we deal with OR conditions.
1364       if (ExtraCC != AArch64CC::AL) {
1365         SDValue ExtraCmp;
1366         if (!CCOp.getNode())
1367           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1368         else {
1369           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1370           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1371           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1372           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1373                                                NZCV, DL, DAG);
1374         }
1375         CCOp = ExtraCmp;
1376         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1377         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1378       }
1379     }
1380
1381     // Produce a normal comparison if we are first in the chain
1382     if (!CCOp.getNode())
1383       return emitComparison(LHS, RHS, CC, DL, DAG);
1384     // Otherwise produce a ccmp.
1385     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1386     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1387     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1388     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1389                                      DAG);
1390   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1391     return SDValue();
1392
1393   assert((Opcode == ISD::OR || !PushNegate)
1394          && "Can only push negate through OR operation");
1395
1396   // Check if both sides can be transformed.
1397   SDValue LHS = Val->getOperand(0);
1398   SDValue RHS = Val->getOperand(1);
1399   bool CanPushNegateL;
1400   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1401     return SDValue();
1402   bool CanPushNegateR;
1403   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1404     return SDValue();
1405
1406   // Do we need to negate our operands?
1407   bool NegateOperands = Opcode == ISD::OR;
1408   // We can negate the results of all previous operations by inverting the
1409   // predicate flags giving us a free negation for one side. For the other side
1410   // we need to be able to push the negation to the leafs of the tree.
1411   if (NegateOperands) {
1412     if (!CanPushNegateL && !CanPushNegateR)
1413       return SDValue();
1414     // Order the side where we can push the negate through to LHS.
1415     if (!CanPushNegateL && CanPushNegateR)
1416       std::swap(LHS, RHS);
1417   } else {
1418     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1419     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1420     if (NeedsNegOutL && NeedsNegOutR)
1421       return SDValue();
1422     // Order the side where we need to negate the output flags to RHS so it
1423     // gets emitted first.
1424     if (NeedsNegOutL)
1425       std::swap(LHS, RHS);
1426   }
1427
1428   // Emit RHS. If we want to negate the tree we only need to push a negate
1429   // through if we are already in a PushNegate case, otherwise we can negate
1430   // the "flags to test" afterwards.
1431   AArch64CC::CondCode RHSCC;
1432   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1433                                                 CCOp, Predicate, Depth+1);
1434   if (NegateOperands && !PushNegate)
1435     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1436   // Emit LHS. We must push the negate through if we need to negate it.
1437   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1438                                                 CmpR, RHSCC, Depth+1);
1439   // If we transformed an OR to and AND then we have to negate the result
1440   // (or absorb a PushNegate resulting in a double negation).
1441   if (Opcode == ISD::OR && !PushNegate)
1442     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1443   return CmpL;
1444 }
1445
1446 /// @}
1447
1448 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1449                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1450   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1451     EVT VT = RHS.getValueType();
1452     uint64_t C = RHSC->getZExtValue();
1453     if (!isLegalArithImmed(C)) {
1454       // Constant does not fit, try adjusting it by one?
1455       switch (CC) {
1456       default:
1457         break;
1458       case ISD::SETLT:
1459       case ISD::SETGE:
1460         if ((VT == MVT::i32 && C != 0x80000000 &&
1461              isLegalArithImmed((uint32_t)(C - 1))) ||
1462             (VT == MVT::i64 && C != 0x80000000ULL &&
1463              isLegalArithImmed(C - 1ULL))) {
1464           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1465           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1466           RHS = DAG.getConstant(C, dl, VT);
1467         }
1468         break;
1469       case ISD::SETULT:
1470       case ISD::SETUGE:
1471         if ((VT == MVT::i32 && C != 0 &&
1472              isLegalArithImmed((uint32_t)(C - 1))) ||
1473             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1474           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1475           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1476           RHS = DAG.getConstant(C, dl, VT);
1477         }
1478         break;
1479       case ISD::SETLE:
1480       case ISD::SETGT:
1481         if ((VT == MVT::i32 && C != INT32_MAX &&
1482              isLegalArithImmed((uint32_t)(C + 1))) ||
1483             (VT == MVT::i64 && C != INT64_MAX &&
1484              isLegalArithImmed(C + 1ULL))) {
1485           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1486           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1487           RHS = DAG.getConstant(C, dl, VT);
1488         }
1489         break;
1490       case ISD::SETULE:
1491       case ISD::SETUGT:
1492         if ((VT == MVT::i32 && C != UINT32_MAX &&
1493              isLegalArithImmed((uint32_t)(C + 1))) ||
1494             (VT == MVT::i64 && C != UINT64_MAX &&
1495              isLegalArithImmed(C + 1ULL))) {
1496           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1497           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1498           RHS = DAG.getConstant(C, dl, VT);
1499         }
1500         break;
1501       }
1502     }
1503   }
1504   SDValue Cmp;
1505   AArch64CC::CondCode AArch64CC;
1506   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1507     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1508
1509     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1510     // For the i8 operand, the largest immediate is 255, so this can be easily
1511     // encoded in the compare instruction. For the i16 operand, however, the
1512     // largest immediate cannot be encoded in the compare.
1513     // Therefore, use a sign extending load and cmn to avoid materializing the
1514     // -1 constant. For example,
1515     // movz w1, #65535
1516     // ldrh w0, [x0, #0]
1517     // cmp w0, w1
1518     // >
1519     // ldrsh w0, [x0, #0]
1520     // cmn w0, #1
1521     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1522     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1523     // ensure both the LHS and RHS are truly zero extended and to make sure the
1524     // transformation is profitable.
1525     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1526         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1527         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1528         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1529       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1530       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1531         SDValue SExt =
1532             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1533                         DAG.getValueType(MVT::i16));
1534         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1535                                                    RHS.getValueType()),
1536                              CC, dl, DAG);
1537         AArch64CC = changeIntCCToAArch64CC(CC);
1538       }
1539     }
1540
1541     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1542       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1543         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1544           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1545       }
1546     }
1547   }
1548
1549   if (!Cmp) {
1550     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1551     AArch64CC = changeIntCCToAArch64CC(CC);
1552   }
1553   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1554   return Cmp;
1555 }
1556
1557 static std::pair<SDValue, SDValue>
1558 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1559   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1560          "Unsupported value type");
1561   SDValue Value, Overflow;
1562   SDLoc DL(Op);
1563   SDValue LHS = Op.getOperand(0);
1564   SDValue RHS = Op.getOperand(1);
1565   unsigned Opc = 0;
1566   switch (Op.getOpcode()) {
1567   default:
1568     llvm_unreachable("Unknown overflow instruction!");
1569   case ISD::SADDO:
1570     Opc = AArch64ISD::ADDS;
1571     CC = AArch64CC::VS;
1572     break;
1573   case ISD::UADDO:
1574     Opc = AArch64ISD::ADDS;
1575     CC = AArch64CC::HS;
1576     break;
1577   case ISD::SSUBO:
1578     Opc = AArch64ISD::SUBS;
1579     CC = AArch64CC::VS;
1580     break;
1581   case ISD::USUBO:
1582     Opc = AArch64ISD::SUBS;
1583     CC = AArch64CC::LO;
1584     break;
1585   // Multiply needs a little bit extra work.
1586   case ISD::SMULO:
1587   case ISD::UMULO: {
1588     CC = AArch64CC::NE;
1589     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1590     if (Op.getValueType() == MVT::i32) {
1591       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1592       // For a 32 bit multiply with overflow check we want the instruction
1593       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1594       // need to generate the following pattern:
1595       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1596       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1597       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1598       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1599       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1600                                 DAG.getConstant(0, DL, MVT::i64));
1601       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1602       // operation. We need to clear out the upper 32 bits, because we used a
1603       // widening multiply that wrote all 64 bits. In the end this should be a
1604       // noop.
1605       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1606       if (IsSigned) {
1607         // The signed overflow check requires more than just a simple check for
1608         // any bit set in the upper 32 bits of the result. These bits could be
1609         // just the sign bits of a negative number. To perform the overflow
1610         // check we have to arithmetic shift right the 32nd bit of the result by
1611         // 31 bits. Then we compare the result to the upper 32 bits.
1612         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1613                                         DAG.getConstant(32, DL, MVT::i64));
1614         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1615         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1616                                         DAG.getConstant(31, DL, MVT::i64));
1617         // It is important that LowerBits is last, otherwise the arithmetic
1618         // shift will not be folded into the compare (SUBS).
1619         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1620         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1621                        .getValue(1);
1622       } else {
1623         // The overflow check for unsigned multiply is easy. We only need to
1624         // check if any of the upper 32 bits are set. This can be done with a
1625         // CMP (shifted register). For that we need to generate the following
1626         // pattern:
1627         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1628         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1629                                         DAG.getConstant(32, DL, MVT::i64));
1630         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1631         Overflow =
1632             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1633                         DAG.getConstant(0, DL, MVT::i64),
1634                         UpperBits).getValue(1);
1635       }
1636       break;
1637     }
1638     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1639     // For the 64 bit multiply
1640     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1641     if (IsSigned) {
1642       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1643       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1644                                       DAG.getConstant(63, DL, MVT::i64));
1645       // It is important that LowerBits is last, otherwise the arithmetic
1646       // shift will not be folded into the compare (SUBS).
1647       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1648       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1649                      .getValue(1);
1650     } else {
1651       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1652       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1653       Overflow =
1654           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1655                       DAG.getConstant(0, DL, MVT::i64),
1656                       UpperBits).getValue(1);
1657     }
1658     break;
1659   }
1660   } // switch (...)
1661
1662   if (Opc) {
1663     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1664
1665     // Emit the AArch64 operation with overflow check.
1666     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1667     Overflow = Value.getValue(1);
1668   }
1669   return std::make_pair(Value, Overflow);
1670 }
1671
1672 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1673                                              RTLIB::Libcall Call) const {
1674   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1675   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1676 }
1677
1678 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1679   SDValue Sel = Op.getOperand(0);
1680   SDValue Other = Op.getOperand(1);
1681
1682   // If neither operand is a SELECT_CC, give up.
1683   if (Sel.getOpcode() != ISD::SELECT_CC)
1684     std::swap(Sel, Other);
1685   if (Sel.getOpcode() != ISD::SELECT_CC)
1686     return Op;
1687
1688   // The folding we want to perform is:
1689   // (xor x, (select_cc a, b, cc, 0, -1) )
1690   //   -->
1691   // (csel x, (xor x, -1), cc ...)
1692   //
1693   // The latter will get matched to a CSINV instruction.
1694
1695   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1696   SDValue LHS = Sel.getOperand(0);
1697   SDValue RHS = Sel.getOperand(1);
1698   SDValue TVal = Sel.getOperand(2);
1699   SDValue FVal = Sel.getOperand(3);
1700   SDLoc dl(Sel);
1701
1702   // FIXME: This could be generalized to non-integer comparisons.
1703   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1704     return Op;
1705
1706   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1707   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1708
1709   // The values aren't constants, this isn't the pattern we're looking for.
1710   if (!CFVal || !CTVal)
1711     return Op;
1712
1713   // We can commute the SELECT_CC by inverting the condition.  This
1714   // might be needed to make this fit into a CSINV pattern.
1715   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1716     std::swap(TVal, FVal);
1717     std::swap(CTVal, CFVal);
1718     CC = ISD::getSetCCInverse(CC, true);
1719   }
1720
1721   // If the constants line up, perform the transform!
1722   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1723     SDValue CCVal;
1724     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1725
1726     FVal = Other;
1727     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1728                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1729
1730     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1731                        CCVal, Cmp);
1732   }
1733
1734   return Op;
1735 }
1736
1737 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1738   EVT VT = Op.getValueType();
1739
1740   // Let legalize expand this if it isn't a legal type yet.
1741   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1742     return SDValue();
1743
1744   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1745
1746   unsigned Opc;
1747   bool ExtraOp = false;
1748   switch (Op.getOpcode()) {
1749   default:
1750     llvm_unreachable("Invalid code");
1751   case ISD::ADDC:
1752     Opc = AArch64ISD::ADDS;
1753     break;
1754   case ISD::SUBC:
1755     Opc = AArch64ISD::SUBS;
1756     break;
1757   case ISD::ADDE:
1758     Opc = AArch64ISD::ADCS;
1759     ExtraOp = true;
1760     break;
1761   case ISD::SUBE:
1762     Opc = AArch64ISD::SBCS;
1763     ExtraOp = true;
1764     break;
1765   }
1766
1767   if (!ExtraOp)
1768     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1769   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1770                      Op.getOperand(2));
1771 }
1772
1773 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1774   // Let legalize expand this if it isn't a legal type yet.
1775   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1776     return SDValue();
1777
1778   SDLoc dl(Op);
1779   AArch64CC::CondCode CC;
1780   // The actual operation that sets the overflow or carry flag.
1781   SDValue Value, Overflow;
1782   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1783
1784   // We use 0 and 1 as false and true values.
1785   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1786   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1787
1788   // We use an inverted condition, because the conditional select is inverted
1789   // too. This will allow it to be selected to a single instruction:
1790   // CSINC Wd, WZR, WZR, invert(cond).
1791   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1792   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1793                          CCVal, Overflow);
1794
1795   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1796   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1797 }
1798
1799 // Prefetch operands are:
1800 // 1: Address to prefetch
1801 // 2: bool isWrite
1802 // 3: int locality (0 = no locality ... 3 = extreme locality)
1803 // 4: bool isDataCache
1804 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1805   SDLoc DL(Op);
1806   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1807   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1808   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1809
1810   bool IsStream = !Locality;
1811   // When the locality number is set
1812   if (Locality) {
1813     // The front-end should have filtered out the out-of-range values
1814     assert(Locality <= 3 && "Prefetch locality out-of-range");
1815     // The locality degree is the opposite of the cache speed.
1816     // Put the number the other way around.
1817     // The encoding starts at 0 for level 1
1818     Locality = 3 - Locality;
1819   }
1820
1821   // built the mask value encoding the expected behavior.
1822   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1823                    (!IsData << 3) |     // IsDataCache bit
1824                    (Locality << 1) |    // Cache level bits
1825                    (unsigned)IsStream;  // Stream bit
1826   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1827                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1828 }
1829
1830 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1831                                               SelectionDAG &DAG) const {
1832   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1833
1834   RTLIB::Libcall LC;
1835   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1836
1837   return LowerF128Call(Op, DAG, LC);
1838 }
1839
1840 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1841                                              SelectionDAG &DAG) const {
1842   if (Op.getOperand(0).getValueType() != MVT::f128) {
1843     // It's legal except when f128 is involved
1844     return Op;
1845   }
1846
1847   RTLIB::Libcall LC;
1848   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1849
1850   // FP_ROUND node has a second operand indicating whether it is known to be
1851   // precise. That doesn't take part in the LibCall so we can't directly use
1852   // LowerF128Call.
1853   SDValue SrcVal = Op.getOperand(0);
1854   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1855                      SDLoc(Op)).first;
1856 }
1857
1858 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1859   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1860   // Any additional optimization in this function should be recorded
1861   // in the cost tables.
1862   EVT InVT = Op.getOperand(0).getValueType();
1863   EVT VT = Op.getValueType();
1864   unsigned NumElts = InVT.getVectorNumElements();
1865
1866   // f16 vectors are promoted to f32 before a conversion.
1867   if (InVT.getVectorElementType() == MVT::f16) {
1868     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1869     SDLoc dl(Op);
1870     return DAG.getNode(
1871         Op.getOpcode(), dl, Op.getValueType(),
1872         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1873   }
1874
1875   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1876     SDLoc dl(Op);
1877     SDValue Cv =
1878         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1879                     Op.getOperand(0));
1880     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1881   }
1882
1883   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1884     SDLoc dl(Op);
1885     MVT ExtVT =
1886         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1887                          VT.getVectorNumElements());
1888     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1889     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1890   }
1891
1892   // Type changing conversions are illegal.
1893   return Op;
1894 }
1895
1896 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1897                                               SelectionDAG &DAG) const {
1898   if (Op.getOperand(0).getValueType().isVector())
1899     return LowerVectorFP_TO_INT(Op, DAG);
1900
1901   // f16 conversions are promoted to f32.
1902   if (Op.getOperand(0).getValueType() == MVT::f16) {
1903     SDLoc dl(Op);
1904     return DAG.getNode(
1905         Op.getOpcode(), dl, Op.getValueType(),
1906         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1907   }
1908
1909   if (Op.getOperand(0).getValueType() != MVT::f128) {
1910     // It's legal except when f128 is involved
1911     return Op;
1912   }
1913
1914   RTLIB::Libcall LC;
1915   if (Op.getOpcode() == ISD::FP_TO_SINT)
1916     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1917   else
1918     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1919
1920   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1921   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1922 }
1923
1924 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1925   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1926   // Any additional optimization in this function should be recorded
1927   // in the cost tables.
1928   EVT VT = Op.getValueType();
1929   SDLoc dl(Op);
1930   SDValue In = Op.getOperand(0);
1931   EVT InVT = In.getValueType();
1932
1933   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1934     MVT CastVT =
1935         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1936                          InVT.getVectorNumElements());
1937     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1938     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1939   }
1940
1941   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1942     unsigned CastOpc =
1943         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1944     EVT CastVT = VT.changeVectorElementTypeToInteger();
1945     In = DAG.getNode(CastOpc, dl, CastVT, In);
1946     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1947   }
1948
1949   return Op;
1950 }
1951
1952 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1953                                             SelectionDAG &DAG) const {
1954   if (Op.getValueType().isVector())
1955     return LowerVectorINT_TO_FP(Op, DAG);
1956
1957   // f16 conversions are promoted to f32.
1958   if (Op.getValueType() == MVT::f16) {
1959     SDLoc dl(Op);
1960     return DAG.getNode(
1961         ISD::FP_ROUND, dl, MVT::f16,
1962         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1963         DAG.getIntPtrConstant(0, dl));
1964   }
1965
1966   // i128 conversions are libcalls.
1967   if (Op.getOperand(0).getValueType() == MVT::i128)
1968     return SDValue();
1969
1970   // Other conversions are legal, unless it's to the completely software-based
1971   // fp128.
1972   if (Op.getValueType() != MVT::f128)
1973     return Op;
1974
1975   RTLIB::Libcall LC;
1976   if (Op.getOpcode() == ISD::SINT_TO_FP)
1977     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1978   else
1979     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1980
1981   return LowerF128Call(Op, DAG, LC);
1982 }
1983
1984 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1985                                             SelectionDAG &DAG) const {
1986   // For iOS, we want to call an alternative entry point: __sincos_stret,
1987   // which returns the values in two S / D registers.
1988   SDLoc dl(Op);
1989   SDValue Arg = Op.getOperand(0);
1990   EVT ArgVT = Arg.getValueType();
1991   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1992
1993   ArgListTy Args;
1994   ArgListEntry Entry;
1995
1996   Entry.Node = Arg;
1997   Entry.Ty = ArgTy;
1998   Entry.isSExt = false;
1999   Entry.isZExt = false;
2000   Args.push_back(Entry);
2001
2002   const char *LibcallName =
2003       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2004   SDValue Callee =
2005       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2006
2007   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2008   TargetLowering::CallLoweringInfo CLI(DAG);
2009   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2010     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
2011
2012   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2013   return CallResult.first;
2014 }
2015
2016 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2017   if (Op.getValueType() != MVT::f16)
2018     return SDValue();
2019
2020   assert(Op.getOperand(0).getValueType() == MVT::i16);
2021   SDLoc DL(Op);
2022
2023   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2024   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2025   return SDValue(
2026       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2027                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2028       0);
2029 }
2030
2031 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2032   if (OrigVT.getSizeInBits() >= 64)
2033     return OrigVT;
2034
2035   assert(OrigVT.isSimple() && "Expecting a simple value type");
2036
2037   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2038   switch (OrigSimpleTy) {
2039   default: llvm_unreachable("Unexpected Vector Type");
2040   case MVT::v2i8:
2041   case MVT::v2i16:
2042      return MVT::v2i32;
2043   case MVT::v4i8:
2044     return  MVT::v4i16;
2045   }
2046 }
2047
2048 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2049                                                  const EVT &OrigTy,
2050                                                  const EVT &ExtTy,
2051                                                  unsigned ExtOpcode) {
2052   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2053   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2054   // 64-bits we need to insert a new extension so that it will be 64-bits.
2055   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2056   if (OrigTy.getSizeInBits() >= 64)
2057     return N;
2058
2059   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2060   EVT NewVT = getExtensionTo64Bits(OrigTy);
2061
2062   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2063 }
2064
2065 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2066                                    bool isSigned) {
2067   EVT VT = N->getValueType(0);
2068
2069   if (N->getOpcode() != ISD::BUILD_VECTOR)
2070     return false;
2071
2072   for (const SDValue &Elt : N->op_values()) {
2073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2074       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2075       unsigned HalfSize = EltSize / 2;
2076       if (isSigned) {
2077         if (!isIntN(HalfSize, C->getSExtValue()))
2078           return false;
2079       } else {
2080         if (!isUIntN(HalfSize, C->getZExtValue()))
2081           return false;
2082       }
2083       continue;
2084     }
2085     return false;
2086   }
2087
2088   return true;
2089 }
2090
2091 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2092   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2093     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2094                                              N->getOperand(0)->getValueType(0),
2095                                              N->getValueType(0),
2096                                              N->getOpcode());
2097
2098   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2099   EVT VT = N->getValueType(0);
2100   SDLoc dl(N);
2101   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2102   unsigned NumElts = VT.getVectorNumElements();
2103   MVT TruncVT = MVT::getIntegerVT(EltSize);
2104   SmallVector<SDValue, 8> Ops;
2105   for (unsigned i = 0; i != NumElts; ++i) {
2106     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2107     const APInt &CInt = C->getAPIntValue();
2108     // Element types smaller than 32 bits are not legal, so use i32 elements.
2109     // The values are implicitly truncated so sext vs. zext doesn't matter.
2110     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2111   }
2112   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2113                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2114 }
2115
2116 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2117   if (N->getOpcode() == ISD::SIGN_EXTEND)
2118     return true;
2119   if (isExtendedBUILD_VECTOR(N, DAG, true))
2120     return true;
2121   return false;
2122 }
2123
2124 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2125   if (N->getOpcode() == ISD::ZERO_EXTEND)
2126     return true;
2127   if (isExtendedBUILD_VECTOR(N, DAG, false))
2128     return true;
2129   return false;
2130 }
2131
2132 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2133   unsigned Opcode = N->getOpcode();
2134   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2135     SDNode *N0 = N->getOperand(0).getNode();
2136     SDNode *N1 = N->getOperand(1).getNode();
2137     return N0->hasOneUse() && N1->hasOneUse() &&
2138       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2139   }
2140   return false;
2141 }
2142
2143 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2144   unsigned Opcode = N->getOpcode();
2145   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2146     SDNode *N0 = N->getOperand(0).getNode();
2147     SDNode *N1 = N->getOperand(1).getNode();
2148     return N0->hasOneUse() && N1->hasOneUse() &&
2149       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2150   }
2151   return false;
2152 }
2153
2154 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2155   // Multiplications are only custom-lowered for 128-bit vectors so that
2156   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2157   EVT VT = Op.getValueType();
2158   assert(VT.is128BitVector() && VT.isInteger() &&
2159          "unexpected type for custom-lowering ISD::MUL");
2160   SDNode *N0 = Op.getOperand(0).getNode();
2161   SDNode *N1 = Op.getOperand(1).getNode();
2162   unsigned NewOpc = 0;
2163   bool isMLA = false;
2164   bool isN0SExt = isSignExtended(N0, DAG);
2165   bool isN1SExt = isSignExtended(N1, DAG);
2166   if (isN0SExt && isN1SExt)
2167     NewOpc = AArch64ISD::SMULL;
2168   else {
2169     bool isN0ZExt = isZeroExtended(N0, DAG);
2170     bool isN1ZExt = isZeroExtended(N1, DAG);
2171     if (isN0ZExt && isN1ZExt)
2172       NewOpc = AArch64ISD::UMULL;
2173     else if (isN1SExt || isN1ZExt) {
2174       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2175       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2176       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2177         NewOpc = AArch64ISD::SMULL;
2178         isMLA = true;
2179       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2180         NewOpc =  AArch64ISD::UMULL;
2181         isMLA = true;
2182       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2183         std::swap(N0, N1);
2184         NewOpc =  AArch64ISD::UMULL;
2185         isMLA = true;
2186       }
2187     }
2188
2189     if (!NewOpc) {
2190       if (VT == MVT::v2i64)
2191         // Fall through to expand this.  It is not legal.
2192         return SDValue();
2193       else
2194         // Other vector multiplications are legal.
2195         return Op;
2196     }
2197   }
2198
2199   // Legalize to a S/UMULL instruction
2200   SDLoc DL(Op);
2201   SDValue Op0;
2202   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2203   if (!isMLA) {
2204     Op0 = skipExtensionForVectorMULL(N0, DAG);
2205     assert(Op0.getValueType().is64BitVector() &&
2206            Op1.getValueType().is64BitVector() &&
2207            "unexpected types for extended operands to VMULL");
2208     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2209   }
2210   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2211   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2212   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2213   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2214   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2215   EVT Op1VT = Op1.getValueType();
2216   return DAG.getNode(N0->getOpcode(), DL, VT,
2217                      DAG.getNode(NewOpc, DL, VT,
2218                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2219                      DAG.getNode(NewOpc, DL, VT,
2220                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2221 }
2222
2223 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2224                                                      SelectionDAG &DAG) const {
2225   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2226   SDLoc dl(Op);
2227   switch (IntNo) {
2228   default: return SDValue();    // Don't custom lower most intrinsics.
2229   case Intrinsic::aarch64_thread_pointer: {
2230     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2231     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2232   }
2233   case Intrinsic::aarch64_neon_smax:
2234     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2235                        Op.getOperand(1), Op.getOperand(2));
2236   case Intrinsic::aarch64_neon_umax:
2237     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2238                        Op.getOperand(1), Op.getOperand(2));
2239   case Intrinsic::aarch64_neon_smin:
2240     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2241                        Op.getOperand(1), Op.getOperand(2));
2242   case Intrinsic::aarch64_neon_umin:
2243     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2244                        Op.getOperand(1), Op.getOperand(2));
2245   }
2246 }
2247
2248 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2249                                               SelectionDAG &DAG) const {
2250   switch (Op.getOpcode()) {
2251   default:
2252     llvm_unreachable("unimplemented operand");
2253     return SDValue();
2254   case ISD::BITCAST:
2255     return LowerBITCAST(Op, DAG);
2256   case ISD::GlobalAddress:
2257     return LowerGlobalAddress(Op, DAG);
2258   case ISD::GlobalTLSAddress:
2259     return LowerGlobalTLSAddress(Op, DAG);
2260   case ISD::SETCC:
2261     return LowerSETCC(Op, DAG);
2262   case ISD::BR_CC:
2263     return LowerBR_CC(Op, DAG);
2264   case ISD::SELECT:
2265     return LowerSELECT(Op, DAG);
2266   case ISD::SELECT_CC:
2267     return LowerSELECT_CC(Op, DAG);
2268   case ISD::JumpTable:
2269     return LowerJumpTable(Op, DAG);
2270   case ISD::ConstantPool:
2271     return LowerConstantPool(Op, DAG);
2272   case ISD::BlockAddress:
2273     return LowerBlockAddress(Op, DAG);
2274   case ISD::VASTART:
2275     return LowerVASTART(Op, DAG);
2276   case ISD::VACOPY:
2277     return LowerVACOPY(Op, DAG);
2278   case ISD::VAARG:
2279     return LowerVAARG(Op, DAG);
2280   case ISD::ADDC:
2281   case ISD::ADDE:
2282   case ISD::SUBC:
2283   case ISD::SUBE:
2284     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2285   case ISD::SADDO:
2286   case ISD::UADDO:
2287   case ISD::SSUBO:
2288   case ISD::USUBO:
2289   case ISD::SMULO:
2290   case ISD::UMULO:
2291     return LowerXALUO(Op, DAG);
2292   case ISD::FADD:
2293     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2294   case ISD::FSUB:
2295     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2296   case ISD::FMUL:
2297     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2298   case ISD::FDIV:
2299     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2300   case ISD::FP_ROUND:
2301     return LowerFP_ROUND(Op, DAG);
2302   case ISD::FP_EXTEND:
2303     return LowerFP_EXTEND(Op, DAG);
2304   case ISD::FRAMEADDR:
2305     return LowerFRAMEADDR(Op, DAG);
2306   case ISD::RETURNADDR:
2307     return LowerRETURNADDR(Op, DAG);
2308   case ISD::INSERT_VECTOR_ELT:
2309     return LowerINSERT_VECTOR_ELT(Op, DAG);
2310   case ISD::EXTRACT_VECTOR_ELT:
2311     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2312   case ISD::BUILD_VECTOR:
2313     return LowerBUILD_VECTOR(Op, DAG);
2314   case ISD::VECTOR_SHUFFLE:
2315     return LowerVECTOR_SHUFFLE(Op, DAG);
2316   case ISD::EXTRACT_SUBVECTOR:
2317     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2318   case ISD::SRA:
2319   case ISD::SRL:
2320   case ISD::SHL:
2321     return LowerVectorSRA_SRL_SHL(Op, DAG);
2322   case ISD::SHL_PARTS:
2323     return LowerShiftLeftParts(Op, DAG);
2324   case ISD::SRL_PARTS:
2325   case ISD::SRA_PARTS:
2326     return LowerShiftRightParts(Op, DAG);
2327   case ISD::CTPOP:
2328     return LowerCTPOP(Op, DAG);
2329   case ISD::FCOPYSIGN:
2330     return LowerFCOPYSIGN(Op, DAG);
2331   case ISD::AND:
2332     return LowerVectorAND(Op, DAG);
2333   case ISD::OR:
2334     return LowerVectorOR(Op, DAG);
2335   case ISD::XOR:
2336     return LowerXOR(Op, DAG);
2337   case ISD::PREFETCH:
2338     return LowerPREFETCH(Op, DAG);
2339   case ISD::SINT_TO_FP:
2340   case ISD::UINT_TO_FP:
2341     return LowerINT_TO_FP(Op, DAG);
2342   case ISD::FP_TO_SINT:
2343   case ISD::FP_TO_UINT:
2344     return LowerFP_TO_INT(Op, DAG);
2345   case ISD::FSINCOS:
2346     return LowerFSINCOS(Op, DAG);
2347   case ISD::MUL:
2348     return LowerMUL(Op, DAG);
2349   case ISD::INTRINSIC_WO_CHAIN:
2350     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2351   }
2352 }
2353
2354 //===----------------------------------------------------------------------===//
2355 //                      Calling Convention Implementation
2356 //===----------------------------------------------------------------------===//
2357
2358 #include "AArch64GenCallingConv.inc"
2359
2360 /// Selects the correct CCAssignFn for a given CallingConvention value.
2361 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2362                                                      bool IsVarArg) const {
2363   switch (CC) {
2364   default:
2365     llvm_unreachable("Unsupported calling convention.");
2366   case CallingConv::WebKit_JS:
2367     return CC_AArch64_WebKit_JS;
2368   case CallingConv::GHC:
2369     return CC_AArch64_GHC;
2370   case CallingConv::C:
2371   case CallingConv::Fast:
2372     if (!Subtarget->isTargetDarwin())
2373       return CC_AArch64_AAPCS;
2374     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2375   }
2376 }
2377
2378 SDValue AArch64TargetLowering::LowerFormalArguments(
2379     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2380     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2381     SmallVectorImpl<SDValue> &InVals) const {
2382   MachineFunction &MF = DAG.getMachineFunction();
2383   MachineFrameInfo *MFI = MF.getFrameInfo();
2384
2385   // Assign locations to all of the incoming arguments.
2386   SmallVector<CCValAssign, 16> ArgLocs;
2387   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2388                  *DAG.getContext());
2389
2390   // At this point, Ins[].VT may already be promoted to i32. To correctly
2391   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2392   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2393   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2394   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2395   // LocVT.
2396   unsigned NumArgs = Ins.size();
2397   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2398   unsigned CurArgIdx = 0;
2399   for (unsigned i = 0; i != NumArgs; ++i) {
2400     MVT ValVT = Ins[i].VT;
2401     if (Ins[i].isOrigArg()) {
2402       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2403       CurArgIdx = Ins[i].getOrigArgIndex();
2404
2405       // Get type of the original argument.
2406       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2407                                   /*AllowUnknown*/ true);
2408       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2409       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2410       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2411         ValVT = MVT::i8;
2412       else if (ActualMVT == MVT::i16)
2413         ValVT = MVT::i16;
2414     }
2415     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2416     bool Res =
2417         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2418     assert(!Res && "Call operand has unhandled type");
2419     (void)Res;
2420   }
2421   assert(ArgLocs.size() == Ins.size());
2422   SmallVector<SDValue, 16> ArgValues;
2423   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2424     CCValAssign &VA = ArgLocs[i];
2425
2426     if (Ins[i].Flags.isByVal()) {
2427       // Byval is used for HFAs in the PCS, but the system should work in a
2428       // non-compliant manner for larger structs.
2429       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2430       int Size = Ins[i].Flags.getByValSize();
2431       unsigned NumRegs = (Size + 7) / 8;
2432
2433       // FIXME: This works on big-endian for composite byvals, which are the common
2434       // case. It should also work for fundamental types too.
2435       unsigned FrameIdx =
2436         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2437       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2438       InVals.push_back(FrameIdxN);
2439
2440       continue;
2441     }
2442
2443     if (VA.isRegLoc()) {
2444       // Arguments stored in registers.
2445       EVT RegVT = VA.getLocVT();
2446
2447       SDValue ArgValue;
2448       const TargetRegisterClass *RC;
2449
2450       if (RegVT == MVT::i32)
2451         RC = &AArch64::GPR32RegClass;
2452       else if (RegVT == MVT::i64)
2453         RC = &AArch64::GPR64RegClass;
2454       else if (RegVT == MVT::f16)
2455         RC = &AArch64::FPR16RegClass;
2456       else if (RegVT == MVT::f32)
2457         RC = &AArch64::FPR32RegClass;
2458       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2459         RC = &AArch64::FPR64RegClass;
2460       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2461         RC = &AArch64::FPR128RegClass;
2462       else
2463         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2464
2465       // Transform the arguments in physical registers into virtual ones.
2466       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2467       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2468
2469       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2470       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2471       // truncate to the right size.
2472       switch (VA.getLocInfo()) {
2473       default:
2474         llvm_unreachable("Unknown loc info!");
2475       case CCValAssign::Full:
2476         break;
2477       case CCValAssign::BCvt:
2478         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2479         break;
2480       case CCValAssign::AExt:
2481       case CCValAssign::SExt:
2482       case CCValAssign::ZExt:
2483         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2484         // nodes after our lowering.
2485         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2486         break;
2487       }
2488
2489       InVals.push_back(ArgValue);
2490
2491     } else { // VA.isRegLoc()
2492       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2493       unsigned ArgOffset = VA.getLocMemOffset();
2494       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2495
2496       uint32_t BEAlign = 0;
2497       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2498           !Ins[i].Flags.isInConsecutiveRegs())
2499         BEAlign = 8 - ArgSize;
2500
2501       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2502
2503       // Create load nodes to retrieve arguments from the stack.
2504       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2505       SDValue ArgValue;
2506
2507       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2508       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2509       MVT MemVT = VA.getValVT();
2510
2511       switch (VA.getLocInfo()) {
2512       default:
2513         break;
2514       case CCValAssign::BCvt:
2515         MemVT = VA.getLocVT();
2516         break;
2517       case CCValAssign::SExt:
2518         ExtType = ISD::SEXTLOAD;
2519         break;
2520       case CCValAssign::ZExt:
2521         ExtType = ISD::ZEXTLOAD;
2522         break;
2523       case CCValAssign::AExt:
2524         ExtType = ISD::EXTLOAD;
2525         break;
2526       }
2527
2528       ArgValue = DAG.getExtLoad(
2529           ExtType, DL, VA.getLocVT(), Chain, FIN,
2530           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2531           MemVT, false, false, false, 0);
2532
2533       InVals.push_back(ArgValue);
2534     }
2535   }
2536
2537   // varargs
2538   if (isVarArg) {
2539     if (!Subtarget->isTargetDarwin()) {
2540       // The AAPCS variadic function ABI is identical to the non-variadic
2541       // one. As a result there may be more arguments in registers and we should
2542       // save them for future reference.
2543       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2544     }
2545
2546     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2547     // This will point to the next argument passed via stack.
2548     unsigned StackOffset = CCInfo.getNextStackOffset();
2549     // We currently pass all varargs at 8-byte alignment.
2550     StackOffset = ((StackOffset + 7) & ~7);
2551     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2552   }
2553
2554   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2555   unsigned StackArgSize = CCInfo.getNextStackOffset();
2556   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2557   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2558     // This is a non-standard ABI so by fiat I say we're allowed to make full
2559     // use of the stack area to be popped, which must be aligned to 16 bytes in
2560     // any case:
2561     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2562
2563     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2564     // a multiple of 16.
2565     FuncInfo->setArgumentStackToRestore(StackArgSize);
2566
2567     // This realignment carries over to the available bytes below. Our own
2568     // callers will guarantee the space is free by giving an aligned value to
2569     // CALLSEQ_START.
2570   }
2571   // Even if we're not expected to free up the space, it's useful to know how
2572   // much is there while considering tail calls (because we can reuse it).
2573   FuncInfo->setBytesInStackArgArea(StackArgSize);
2574
2575   return Chain;
2576 }
2577
2578 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2579                                                 SelectionDAG &DAG, SDLoc DL,
2580                                                 SDValue &Chain) const {
2581   MachineFunction &MF = DAG.getMachineFunction();
2582   MachineFrameInfo *MFI = MF.getFrameInfo();
2583   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2584   auto PtrVT = getPointerTy(DAG.getDataLayout());
2585
2586   SmallVector<SDValue, 8> MemOps;
2587
2588   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2589                                           AArch64::X3, AArch64::X4, AArch64::X5,
2590                                           AArch64::X6, AArch64::X7 };
2591   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2592   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2593
2594   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2595   int GPRIdx = 0;
2596   if (GPRSaveSize != 0) {
2597     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2598
2599     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2600
2601     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2602       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2603       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2604       SDValue Store = DAG.getStore(
2605           Val.getValue(1), DL, Val, FIN,
2606           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2607           false, 0);
2608       MemOps.push_back(Store);
2609       FIN =
2610           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2611     }
2612   }
2613   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2614   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2615
2616   if (Subtarget->hasFPARMv8()) {
2617     static const MCPhysReg FPRArgRegs[] = {
2618         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2619         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2620     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2621     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2622
2623     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2624     int FPRIdx = 0;
2625     if (FPRSaveSize != 0) {
2626       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2627
2628       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2629
2630       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2631         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2632         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2633
2634         SDValue Store = DAG.getStore(
2635             Val.getValue(1), DL, Val, FIN,
2636             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2637             false, false, 0);
2638         MemOps.push_back(Store);
2639         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2640                           DAG.getConstant(16, DL, PtrVT));
2641       }
2642     }
2643     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2644     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2645   }
2646
2647   if (!MemOps.empty()) {
2648     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2649   }
2650 }
2651
2652 /// LowerCallResult - Lower the result values of a call into the
2653 /// appropriate copies out of appropriate physical registers.
2654 SDValue AArch64TargetLowering::LowerCallResult(
2655     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2656     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2657     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2658     SDValue ThisVal) const {
2659   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2660                           ? RetCC_AArch64_WebKit_JS
2661                           : RetCC_AArch64_AAPCS;
2662   // Assign locations to each value returned by this call.
2663   SmallVector<CCValAssign, 16> RVLocs;
2664   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2665                  *DAG.getContext());
2666   CCInfo.AnalyzeCallResult(Ins, RetCC);
2667
2668   // Copy all of the result registers out of their specified physreg.
2669   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2670     CCValAssign VA = RVLocs[i];
2671
2672     // Pass 'this' value directly from the argument to return value, to avoid
2673     // reg unit interference
2674     if (i == 0 && isThisReturn) {
2675       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2676              "unexpected return calling convention register assignment");
2677       InVals.push_back(ThisVal);
2678       continue;
2679     }
2680
2681     SDValue Val =
2682         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2683     Chain = Val.getValue(1);
2684     InFlag = Val.getValue(2);
2685
2686     switch (VA.getLocInfo()) {
2687     default:
2688       llvm_unreachable("Unknown loc info!");
2689     case CCValAssign::Full:
2690       break;
2691     case CCValAssign::BCvt:
2692       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2693       break;
2694     }
2695
2696     InVals.push_back(Val);
2697   }
2698
2699   return Chain;
2700 }
2701
2702 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2703     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2704     bool isCalleeStructRet, bool isCallerStructRet,
2705     const SmallVectorImpl<ISD::OutputArg> &Outs,
2706     const SmallVectorImpl<SDValue> &OutVals,
2707     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2708   // For CallingConv::C this function knows whether the ABI needs
2709   // changing. That's not true for other conventions so they will have to opt in
2710   // manually.
2711   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2712     return false;
2713
2714   const MachineFunction &MF = DAG.getMachineFunction();
2715   const Function *CallerF = MF.getFunction();
2716   CallingConv::ID CallerCC = CallerF->getCallingConv();
2717   bool CCMatch = CallerCC == CalleeCC;
2718
2719   // Byval parameters hand the function a pointer directly into the stack area
2720   // we want to reuse during a tail call. Working around this *is* possible (see
2721   // X86) but less efficient and uglier in LowerCall.
2722   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2723                                     e = CallerF->arg_end();
2724        i != e; ++i)
2725     if (i->hasByValAttr())
2726       return false;
2727
2728   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2729     if (IsTailCallConvention(CalleeCC) && CCMatch)
2730       return true;
2731     return false;
2732   }
2733
2734   // Externally-defined functions with weak linkage should not be
2735   // tail-called on AArch64 when the OS does not support dynamic
2736   // pre-emption of symbols, as the AAELF spec requires normal calls
2737   // to undefined weak functions to be replaced with a NOP or jump to the
2738   // next instruction. The behaviour of branch instructions in this
2739   // situation (as used for tail calls) is implementation-defined, so we
2740   // cannot rely on the linker replacing the tail call with a return.
2741   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2742     const GlobalValue *GV = G->getGlobal();
2743     const Triple &TT = getTargetMachine().getTargetTriple();
2744     if (GV->hasExternalWeakLinkage() &&
2745         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2746       return false;
2747   }
2748
2749   // Now we search for cases where we can use a tail call without changing the
2750   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2751   // concept.
2752
2753   // I want anyone implementing a new calling convention to think long and hard
2754   // about this assert.
2755   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2756          "Unexpected variadic calling convention");
2757
2758   if (isVarArg && !Outs.empty()) {
2759     // At least two cases here: if caller is fastcc then we can't have any
2760     // memory arguments (we'd be expected to clean up the stack afterwards). If
2761     // caller is C then we could potentially use its argument area.
2762
2763     // FIXME: for now we take the most conservative of these in both cases:
2764     // disallow all variadic memory operands.
2765     SmallVector<CCValAssign, 16> ArgLocs;
2766     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2767                    *DAG.getContext());
2768
2769     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2770     for (const CCValAssign &ArgLoc : ArgLocs)
2771       if (!ArgLoc.isRegLoc())
2772         return false;
2773   }
2774
2775   // If the calling conventions do not match, then we'd better make sure the
2776   // results are returned in the same way as what the caller expects.
2777   if (!CCMatch) {
2778     SmallVector<CCValAssign, 16> RVLocs1;
2779     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2780                     *DAG.getContext());
2781     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2782
2783     SmallVector<CCValAssign, 16> RVLocs2;
2784     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2785                     *DAG.getContext());
2786     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2787
2788     if (RVLocs1.size() != RVLocs2.size())
2789       return false;
2790     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2791       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2792         return false;
2793       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2794         return false;
2795       if (RVLocs1[i].isRegLoc()) {
2796         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2797           return false;
2798       } else {
2799         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2800           return false;
2801       }
2802     }
2803   }
2804
2805   // Nothing more to check if the callee is taking no arguments
2806   if (Outs.empty())
2807     return true;
2808
2809   SmallVector<CCValAssign, 16> ArgLocs;
2810   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2811                  *DAG.getContext());
2812
2813   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2814
2815   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2816
2817   // If the stack arguments for this call would fit into our own save area then
2818   // the call can be made tail.
2819   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2820 }
2821
2822 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2823                                                    SelectionDAG &DAG,
2824                                                    MachineFrameInfo *MFI,
2825                                                    int ClobberedFI) const {
2826   SmallVector<SDValue, 8> ArgChains;
2827   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2828   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2829
2830   // Include the original chain at the beginning of the list. When this is
2831   // used by target LowerCall hooks, this helps legalize find the
2832   // CALLSEQ_BEGIN node.
2833   ArgChains.push_back(Chain);
2834
2835   // Add a chain value for each stack argument corresponding
2836   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2837                             UE = DAG.getEntryNode().getNode()->use_end();
2838        U != UE; ++U)
2839     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2840       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2841         if (FI->getIndex() < 0) {
2842           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2843           int64_t InLastByte = InFirstByte;
2844           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2845
2846           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2847               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2848             ArgChains.push_back(SDValue(L, 1));
2849         }
2850
2851   // Build a tokenfactor for all the chains.
2852   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2853 }
2854
2855 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2856                                                    bool TailCallOpt) const {
2857   return CallCC == CallingConv::Fast && TailCallOpt;
2858 }
2859
2860 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2861   return CallCC == CallingConv::Fast;
2862 }
2863
2864 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2865 /// and add input and output parameter nodes.
2866 SDValue
2867 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2868                                  SmallVectorImpl<SDValue> &InVals) const {
2869   SelectionDAG &DAG = CLI.DAG;
2870   SDLoc &DL = CLI.DL;
2871   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2872   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2873   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2874   SDValue Chain = CLI.Chain;
2875   SDValue Callee = CLI.Callee;
2876   bool &IsTailCall = CLI.IsTailCall;
2877   CallingConv::ID CallConv = CLI.CallConv;
2878   bool IsVarArg = CLI.IsVarArg;
2879
2880   MachineFunction &MF = DAG.getMachineFunction();
2881   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2882   bool IsThisReturn = false;
2883
2884   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2885   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2886   bool IsSibCall = false;
2887
2888   if (IsTailCall) {
2889     // Check if it's really possible to do a tail call.
2890     IsTailCall = isEligibleForTailCallOptimization(
2891         Callee, CallConv, IsVarArg, IsStructRet,
2892         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2893     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2894       report_fatal_error("failed to perform tail call elimination on a call "
2895                          "site marked musttail");
2896
2897     // A sibling call is one where we're under the usual C ABI and not planning
2898     // to change that but can still do a tail call:
2899     if (!TailCallOpt && IsTailCall)
2900       IsSibCall = true;
2901
2902     if (IsTailCall)
2903       ++NumTailCalls;
2904   }
2905
2906   // Analyze operands of the call, assigning locations to each operand.
2907   SmallVector<CCValAssign, 16> ArgLocs;
2908   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2909                  *DAG.getContext());
2910
2911   if (IsVarArg) {
2912     // Handle fixed and variable vector arguments differently.
2913     // Variable vector arguments always go into memory.
2914     unsigned NumArgs = Outs.size();
2915
2916     for (unsigned i = 0; i != NumArgs; ++i) {
2917       MVT ArgVT = Outs[i].VT;
2918       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2919       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2920                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2921       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2922       assert(!Res && "Call operand has unhandled type");
2923       (void)Res;
2924     }
2925   } else {
2926     // At this point, Outs[].VT may already be promoted to i32. To correctly
2927     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2928     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2929     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2930     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2931     // LocVT.
2932     unsigned NumArgs = Outs.size();
2933     for (unsigned i = 0; i != NumArgs; ++i) {
2934       MVT ValVT = Outs[i].VT;
2935       // Get type of the original argument.
2936       EVT ActualVT = getValueType(DAG.getDataLayout(),
2937                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2938                                   /*AllowUnknown*/ true);
2939       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2940       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2941       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2942       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2943         ValVT = MVT::i8;
2944       else if (ActualMVT == MVT::i16)
2945         ValVT = MVT::i16;
2946
2947       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2948       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2949       assert(!Res && "Call operand has unhandled type");
2950       (void)Res;
2951     }
2952   }
2953
2954   // Get a count of how many bytes are to be pushed on the stack.
2955   unsigned NumBytes = CCInfo.getNextStackOffset();
2956
2957   if (IsSibCall) {
2958     // Since we're not changing the ABI to make this a tail call, the memory
2959     // operands are already available in the caller's incoming argument space.
2960     NumBytes = 0;
2961   }
2962
2963   // FPDiff is the byte offset of the call's argument area from the callee's.
2964   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2965   // by this amount for a tail call. In a sibling call it must be 0 because the
2966   // caller will deallocate the entire stack and the callee still expects its
2967   // arguments to begin at SP+0. Completely unused for non-tail calls.
2968   int FPDiff = 0;
2969
2970   if (IsTailCall && !IsSibCall) {
2971     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2972
2973     // Since callee will pop argument stack as a tail call, we must keep the
2974     // popped size 16-byte aligned.
2975     NumBytes = RoundUpToAlignment(NumBytes, 16);
2976
2977     // FPDiff will be negative if this tail call requires more space than we
2978     // would automatically have in our incoming argument space. Positive if we
2979     // can actually shrink the stack.
2980     FPDiff = NumReusableBytes - NumBytes;
2981
2982     // The stack pointer must be 16-byte aligned at all times it's used for a
2983     // memory operation, which in practice means at *all* times and in
2984     // particular across call boundaries. Therefore our own arguments started at
2985     // a 16-byte aligned SP and the delta applied for the tail call should
2986     // satisfy the same constraint.
2987     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2988   }
2989
2990   // Adjust the stack pointer for the new arguments...
2991   // These operations are automatically eliminated by the prolog/epilog pass
2992   if (!IsSibCall)
2993     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2994                                                               true),
2995                                  DL);
2996
2997   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2998                                         getPointerTy(DAG.getDataLayout()));
2999
3000   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3001   SmallVector<SDValue, 8> MemOpChains;
3002   auto PtrVT = getPointerTy(DAG.getDataLayout());
3003
3004   // Walk the register/memloc assignments, inserting copies/loads.
3005   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3006        ++i, ++realArgIdx) {
3007     CCValAssign &VA = ArgLocs[i];
3008     SDValue Arg = OutVals[realArgIdx];
3009     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3010
3011     // Promote the value if needed.
3012     switch (VA.getLocInfo()) {
3013     default:
3014       llvm_unreachable("Unknown loc info!");
3015     case CCValAssign::Full:
3016       break;
3017     case CCValAssign::SExt:
3018       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3019       break;
3020     case CCValAssign::ZExt:
3021       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3022       break;
3023     case CCValAssign::AExt:
3024       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3025         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3026         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3027         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3028       }
3029       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3030       break;
3031     case CCValAssign::BCvt:
3032       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3033       break;
3034     case CCValAssign::FPExt:
3035       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3036       break;
3037     }
3038
3039     if (VA.isRegLoc()) {
3040       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3041         assert(VA.getLocVT() == MVT::i64 &&
3042                "unexpected calling convention register assignment");
3043         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3044                "unexpected use of 'returned'");
3045         IsThisReturn = true;
3046       }
3047       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3048     } else {
3049       assert(VA.isMemLoc());
3050
3051       SDValue DstAddr;
3052       MachinePointerInfo DstInfo;
3053
3054       // FIXME: This works on big-endian for composite byvals, which are the
3055       // common case. It should also work for fundamental types too.
3056       uint32_t BEAlign = 0;
3057       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3058                                         : VA.getValVT().getSizeInBits();
3059       OpSize = (OpSize + 7) / 8;
3060       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3061           !Flags.isInConsecutiveRegs()) {
3062         if (OpSize < 8)
3063           BEAlign = 8 - OpSize;
3064       }
3065       unsigned LocMemOffset = VA.getLocMemOffset();
3066       int32_t Offset = LocMemOffset + BEAlign;
3067       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3068       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3069
3070       if (IsTailCall) {
3071         Offset = Offset + FPDiff;
3072         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3073
3074         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3075         DstInfo =
3076             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3077
3078         // Make sure any stack arguments overlapping with where we're storing
3079         // are loaded before this eventual operation. Otherwise they'll be
3080         // clobbered.
3081         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3082       } else {
3083         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3084
3085         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3086         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3087                                                LocMemOffset);
3088       }
3089
3090       if (Outs[i].Flags.isByVal()) {
3091         SDValue SizeNode =
3092             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3093         SDValue Cpy = DAG.getMemcpy(
3094             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3095             /*isVol = */ false, /*AlwaysInline = */ false,
3096             /*isTailCall = */ false,
3097             DstInfo, MachinePointerInfo());
3098
3099         MemOpChains.push_back(Cpy);
3100       } else {
3101         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3102         // promoted to a legal register type i32, we should truncate Arg back to
3103         // i1/i8/i16.
3104         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3105             VA.getValVT() == MVT::i16)
3106           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3107
3108         SDValue Store =
3109             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3110         MemOpChains.push_back(Store);
3111       }
3112     }
3113   }
3114
3115   if (!MemOpChains.empty())
3116     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3117
3118   // Build a sequence of copy-to-reg nodes chained together with token chain
3119   // and flag operands which copy the outgoing args into the appropriate regs.
3120   SDValue InFlag;
3121   for (auto &RegToPass : RegsToPass) {
3122     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3123                              RegToPass.second, InFlag);
3124     InFlag = Chain.getValue(1);
3125   }
3126
3127   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3128   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3129   // node so that legalize doesn't hack it.
3130   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3131       Subtarget->isTargetMachO()) {
3132     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3133       const GlobalValue *GV = G->getGlobal();
3134       bool InternalLinkage = GV->hasInternalLinkage();
3135       if (InternalLinkage)
3136         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3137       else {
3138         Callee =
3139             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3140         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3141       }
3142     } else if (ExternalSymbolSDNode *S =
3143                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3144       const char *Sym = S->getSymbol();
3145       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3146       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3147     }
3148   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3149     const GlobalValue *GV = G->getGlobal();
3150     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3151   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3152     const char *Sym = S->getSymbol();
3153     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3154   }
3155
3156   // We don't usually want to end the call-sequence here because we would tidy
3157   // the frame up *after* the call, however in the ABI-changing tail-call case
3158   // we've carefully laid out the parameters so that when sp is reset they'll be
3159   // in the correct location.
3160   if (IsTailCall && !IsSibCall) {
3161     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3162                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3163     InFlag = Chain.getValue(1);
3164   }
3165
3166   std::vector<SDValue> Ops;
3167   Ops.push_back(Chain);
3168   Ops.push_back(Callee);
3169
3170   if (IsTailCall) {
3171     // Each tail call may have to adjust the stack by a different amount, so
3172     // this information must travel along with the operation for eventual
3173     // consumption by emitEpilogue.
3174     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3175   }
3176
3177   // Add argument registers to the end of the list so that they are known live
3178   // into the call.
3179   for (auto &RegToPass : RegsToPass)
3180     Ops.push_back(DAG.getRegister(RegToPass.first,
3181                                   RegToPass.second.getValueType()));
3182
3183   // Add a register mask operand representing the call-preserved registers.
3184   const uint32_t *Mask;
3185   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3186   if (IsThisReturn) {
3187     // For 'this' returns, use the X0-preserving mask if applicable
3188     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3189     if (!Mask) {
3190       IsThisReturn = false;
3191       Mask = TRI->getCallPreservedMask(MF, CallConv);
3192     }
3193   } else
3194     Mask = TRI->getCallPreservedMask(MF, CallConv);
3195
3196   assert(Mask && "Missing call preserved mask for calling convention");
3197   Ops.push_back(DAG.getRegisterMask(Mask));
3198
3199   if (InFlag.getNode())
3200     Ops.push_back(InFlag);
3201
3202   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3203
3204   // If we're doing a tall call, use a TC_RETURN here rather than an
3205   // actual call instruction.
3206   if (IsTailCall) {
3207     MF.getFrameInfo()->setHasTailCall();
3208     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3209   }
3210
3211   // Returns a chain and a flag for retval copy to use.
3212   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3213   InFlag = Chain.getValue(1);
3214
3215   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3216                                 ? RoundUpToAlignment(NumBytes, 16)
3217                                 : 0;
3218
3219   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3220                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3221                              InFlag, DL);
3222   if (!Ins.empty())
3223     InFlag = Chain.getValue(1);
3224
3225   // Handle result values, copying them out of physregs into vregs that we
3226   // return.
3227   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3228                          InVals, IsThisReturn,
3229                          IsThisReturn ? OutVals[0] : SDValue());
3230 }
3231
3232 bool AArch64TargetLowering::CanLowerReturn(
3233     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3234     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3235   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3236                           ? RetCC_AArch64_WebKit_JS
3237                           : RetCC_AArch64_AAPCS;
3238   SmallVector<CCValAssign, 16> RVLocs;
3239   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3240   return CCInfo.CheckReturn(Outs, RetCC);
3241 }
3242
3243 SDValue
3244 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3245                                    bool isVarArg,
3246                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3247                                    const SmallVectorImpl<SDValue> &OutVals,
3248                                    SDLoc DL, SelectionDAG &DAG) const {
3249   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3250                           ? RetCC_AArch64_WebKit_JS
3251                           : RetCC_AArch64_AAPCS;
3252   SmallVector<CCValAssign, 16> RVLocs;
3253   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3254                  *DAG.getContext());
3255   CCInfo.AnalyzeReturn(Outs, RetCC);
3256
3257   // Copy the result values into the output registers.
3258   SDValue Flag;
3259   SmallVector<SDValue, 4> RetOps(1, Chain);
3260   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3261        ++i, ++realRVLocIdx) {
3262     CCValAssign &VA = RVLocs[i];
3263     assert(VA.isRegLoc() && "Can only return in registers!");
3264     SDValue Arg = OutVals[realRVLocIdx];
3265
3266     switch (VA.getLocInfo()) {
3267     default:
3268       llvm_unreachable("Unknown loc info!");
3269     case CCValAssign::Full:
3270       if (Outs[i].ArgVT == MVT::i1) {
3271         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3272         // value. This is strictly redundant on Darwin (which uses "zeroext
3273         // i1"), but will be optimised out before ISel.
3274         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3275         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3276       }
3277       break;
3278     case CCValAssign::BCvt:
3279       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3280       break;
3281     }
3282
3283     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3284     Flag = Chain.getValue(1);
3285     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3286   }
3287   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3288   const MCPhysReg *I =
3289       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3290   if (I) {
3291     for (; *I; ++I) {
3292       if (AArch64::GPR64RegClass.contains(*I))
3293         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3294       else if (AArch64::FPR64RegClass.contains(*I))
3295         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3296       else
3297         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3298     }
3299   }
3300
3301   RetOps[0] = Chain; // Update chain.
3302
3303   // Add the flag if we have it.
3304   if (Flag.getNode())
3305     RetOps.push_back(Flag);
3306
3307   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3308 }
3309
3310 //===----------------------------------------------------------------------===//
3311 //  Other Lowering Code
3312 //===----------------------------------------------------------------------===//
3313
3314 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3315                                                   SelectionDAG &DAG) const {
3316   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3317   SDLoc DL(Op);
3318   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3319   const GlobalValue *GV = GN->getGlobal();
3320   unsigned char OpFlags =
3321       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3322
3323   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3324          "unexpected offset in global node");
3325
3326   // This also catched the large code model case for Darwin.
3327   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3328     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3329     // FIXME: Once remat is capable of dealing with instructions with register
3330     // operands, expand this into two nodes instead of using a wrapper node.
3331     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3332   }
3333
3334   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3335     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3336            "use of MO_CONSTPOOL only supported on small model");
3337     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3338     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3339     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3340     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3341     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3342     SDValue GlobalAddr = DAG.getLoad(
3343         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3344         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3345         /*isVolatile=*/false,
3346         /*isNonTemporal=*/true,
3347         /*isInvariant=*/true, 8);
3348     if (GN->getOffset() != 0)
3349       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3350                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3351     return GlobalAddr;
3352   }
3353
3354   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3355     const unsigned char MO_NC = AArch64II::MO_NC;
3356     return DAG.getNode(
3357         AArch64ISD::WrapperLarge, DL, PtrVT,
3358         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3359         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3360         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3361         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3362   } else {
3363     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3364     // the only correct model on Darwin.
3365     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3366                                             OpFlags | AArch64II::MO_PAGE);
3367     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3368     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3369
3370     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3371     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3372   }
3373 }
3374
3375 /// \brief Convert a TLS address reference into the correct sequence of loads
3376 /// and calls to compute the variable's address (for Darwin, currently) and
3377 /// return an SDValue containing the final node.
3378
3379 /// Darwin only has one TLS scheme which must be capable of dealing with the
3380 /// fully general situation, in the worst case. This means:
3381 ///     + "extern __thread" declaration.
3382 ///     + Defined in a possibly unknown dynamic library.
3383 ///
3384 /// The general system is that each __thread variable has a [3 x i64] descriptor
3385 /// which contains information used by the runtime to calculate the address. The
3386 /// only part of this the compiler needs to know about is the first xword, which
3387 /// contains a function pointer that must be called with the address of the
3388 /// entire descriptor in "x0".
3389 ///
3390 /// Since this descriptor may be in a different unit, in general even the
3391 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3392 /// is:
3393 ///     adrp x0, _var@TLVPPAGE
3394 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3395 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3396 ///                                      ; the function pointer
3397 ///     blr x1                           ; Uses descriptor address in x0
3398 ///     ; Address of _var is now in x0.
3399 ///
3400 /// If the address of _var's descriptor *is* known to the linker, then it can
3401 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3402 /// a slight efficiency gain.
3403 SDValue
3404 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3405                                                    SelectionDAG &DAG) const {
3406   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3407
3408   SDLoc DL(Op);
3409   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3410   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3411
3412   SDValue TLVPAddr =
3413       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3414   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3415
3416   // The first entry in the descriptor is a function pointer that we must call
3417   // to obtain the address of the variable.
3418   SDValue Chain = DAG.getEntryNode();
3419   SDValue FuncTLVGet =
3420       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3421                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3422                   true, true, 8);
3423   Chain = FuncTLVGet.getValue(1);
3424
3425   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3426   MFI->setAdjustsStack(true);
3427
3428   // TLS calls preserve all registers except those that absolutely must be
3429   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3430   // silly).
3431   const uint32_t *Mask =
3432       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3433
3434   // Finally, we can make the call. This is just a degenerate version of a
3435   // normal AArch64 call node: x0 takes the address of the descriptor, and
3436   // returns the address of the variable in this thread.
3437   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3438   Chain =
3439       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3440                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3441                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3442   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3443 }
3444
3445 /// When accessing thread-local variables under either the general-dynamic or
3446 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3447 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3448 /// is a function pointer to carry out the resolution.
3449 ///
3450 /// The sequence is:
3451 ///    adrp  x0, :tlsdesc:var
3452 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3453 ///    add   x0, x0, #:tlsdesc_lo12:var
3454 ///    .tlsdesccall var
3455 ///    blr   x1
3456 ///    (TPIDR_EL0 offset now in x0)
3457 ///
3458 ///  The above sequence must be produced unscheduled, to enable the linker to
3459 ///  optimize/relax this sequence.
3460 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3461 ///  above sequence, and expanded really late in the compilation flow, to ensure
3462 ///  the sequence is produced as per above.
3463 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3464                                                       SelectionDAG &DAG) const {
3465   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3466
3467   SDValue Chain = DAG.getEntryNode();
3468   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3469
3470   SmallVector<SDValue, 2> Ops;
3471   Ops.push_back(Chain);
3472   Ops.push_back(SymAddr);
3473
3474   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3475   SDValue Glue = Chain.getValue(1);
3476
3477   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3478 }
3479
3480 SDValue
3481 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3482                                                 SelectionDAG &DAG) const {
3483   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3484   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3485          "ELF TLS only supported in small memory model");
3486   // Different choices can be made for the maximum size of the TLS area for a
3487   // module. For the small address model, the default TLS size is 16MiB and the
3488   // maximum TLS size is 4GiB.
3489   // FIXME: add -mtls-size command line option and make it control the 16MiB
3490   // vs. 4GiB code sequence generation.
3491   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3492
3493   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3494
3495   if (DAG.getTarget().Options.EmulatedTLS)
3496     return LowerToTLSEmulatedModel(GA, DAG);
3497
3498   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3499     if (Model == TLSModel::LocalDynamic)
3500       Model = TLSModel::GeneralDynamic;
3501   }
3502
3503   SDValue TPOff;
3504   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3505   SDLoc DL(Op);
3506   const GlobalValue *GV = GA->getGlobal();
3507
3508   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3509
3510   if (Model == TLSModel::LocalExec) {
3511     SDValue HiVar = DAG.getTargetGlobalAddress(
3512         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3513     SDValue LoVar = DAG.getTargetGlobalAddress(
3514         GV, DL, PtrVT, 0,
3515         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3516
3517     SDValue TPWithOff_lo =
3518         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3519                                    HiVar,
3520                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3521                 0);
3522     SDValue TPWithOff =
3523         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3524                                    LoVar,
3525                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3526                 0);
3527     return TPWithOff;
3528   } else if (Model == TLSModel::InitialExec) {
3529     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3530     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3531   } else if (Model == TLSModel::LocalDynamic) {
3532     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3533     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3534     // the beginning of the module's TLS region, followed by a DTPREL offset
3535     // calculation.
3536
3537     // These accesses will need deduplicating if there's more than one.
3538     AArch64FunctionInfo *MFI =
3539         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3540     MFI->incNumLocalDynamicTLSAccesses();
3541
3542     // The call needs a relocation too for linker relaxation. It doesn't make
3543     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3544     // the address.
3545     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3546                                                   AArch64II::MO_TLS);
3547
3548     // Now we can calculate the offset from TPIDR_EL0 to this module's
3549     // thread-local area.
3550     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3551
3552     // Now use :dtprel_whatever: operations to calculate this variable's offset
3553     // in its thread-storage area.
3554     SDValue HiVar = DAG.getTargetGlobalAddress(
3555         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3556     SDValue LoVar = DAG.getTargetGlobalAddress(
3557         GV, DL, MVT::i64, 0,
3558         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3559
3560     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3561                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3562                     0);
3563     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3564                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3565                     0);
3566   } else if (Model == TLSModel::GeneralDynamic) {
3567     // The call needs a relocation too for linker relaxation. It doesn't make
3568     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3569     // the address.
3570     SDValue SymAddr =
3571         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3572
3573     // Finally we can make a call to calculate the offset from tpidr_el0.
3574     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3575   } else
3576     llvm_unreachable("Unsupported ELF TLS access model");
3577
3578   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3579 }
3580
3581 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3582                                                      SelectionDAG &DAG) const {
3583   if (Subtarget->isTargetDarwin())
3584     return LowerDarwinGlobalTLSAddress(Op, DAG);
3585   else if (Subtarget->isTargetELF())
3586     return LowerELFGlobalTLSAddress(Op, DAG);
3587
3588   llvm_unreachable("Unexpected platform trying to use TLS");
3589 }
3590 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3591   SDValue Chain = Op.getOperand(0);
3592   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3593   SDValue LHS = Op.getOperand(2);
3594   SDValue RHS = Op.getOperand(3);
3595   SDValue Dest = Op.getOperand(4);
3596   SDLoc dl(Op);
3597
3598   // Handle f128 first, since lowering it will result in comparing the return
3599   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3600   // is expecting to deal with.
3601   if (LHS.getValueType() == MVT::f128) {
3602     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3603
3604     // If softenSetCCOperands returned a scalar, we need to compare the result
3605     // against zero to select between true and false values.
3606     if (!RHS.getNode()) {
3607       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3608       CC = ISD::SETNE;
3609     }
3610   }
3611
3612   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3613   // instruction.
3614   unsigned Opc = LHS.getOpcode();
3615   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3616       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3617        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3618     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3619            "Unexpected condition code.");
3620     // Only lower legal XALUO ops.
3621     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3622       return SDValue();
3623
3624     // The actual operation with overflow check.
3625     AArch64CC::CondCode OFCC;
3626     SDValue Value, Overflow;
3627     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3628
3629     if (CC == ISD::SETNE)
3630       OFCC = getInvertedCondCode(OFCC);
3631     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3632
3633     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3634                        Overflow);
3635   }
3636
3637   if (LHS.getValueType().isInteger()) {
3638     assert((LHS.getValueType() == RHS.getValueType()) &&
3639            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3640
3641     // If the RHS of the comparison is zero, we can potentially fold this
3642     // to a specialized branch.
3643     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3644     if (RHSC && RHSC->getZExtValue() == 0) {
3645       if (CC == ISD::SETEQ) {
3646         // See if we can use a TBZ to fold in an AND as well.
3647         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3648         // out of bounds, a late MI-layer pass rewrites branches.
3649         // 403.gcc is an example that hits this case.
3650         if (LHS.getOpcode() == ISD::AND &&
3651             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3652             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3653           SDValue Test = LHS.getOperand(0);
3654           uint64_t Mask = LHS.getConstantOperandVal(1);
3655           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3656                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3657                              Dest);
3658         }
3659
3660         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3661       } else if (CC == ISD::SETNE) {
3662         // See if we can use a TBZ to fold in an AND as well.
3663         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3664         // out of bounds, a late MI-layer pass rewrites branches.
3665         // 403.gcc is an example that hits this case.
3666         if (LHS.getOpcode() == ISD::AND &&
3667             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3668             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3669           SDValue Test = LHS.getOperand(0);
3670           uint64_t Mask = LHS.getConstantOperandVal(1);
3671           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3672                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3673                              Dest);
3674         }
3675
3676         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3677       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3678         // Don't combine AND since emitComparison converts the AND to an ANDS
3679         // (a.k.a. TST) and the test in the test bit and branch instruction
3680         // becomes redundant.  This would also increase register pressure.
3681         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3682         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3683                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3684       }
3685     }
3686     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3687         LHS.getOpcode() != ISD::AND) {
3688       // Don't combine AND since emitComparison converts the AND to an ANDS
3689       // (a.k.a. TST) and the test in the test bit and branch instruction
3690       // becomes redundant.  This would also increase register pressure.
3691       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3692       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3693                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3694     }
3695
3696     SDValue CCVal;
3697     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3698     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3699                        Cmp);
3700   }
3701
3702   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3703
3704   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3705   // clean.  Some of them require two branches to implement.
3706   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3707   AArch64CC::CondCode CC1, CC2;
3708   changeFPCCToAArch64CC(CC, CC1, CC2);
3709   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3710   SDValue BR1 =
3711       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3712   if (CC2 != AArch64CC::AL) {
3713     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3714     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3715                        Cmp);
3716   }
3717
3718   return BR1;
3719 }
3720
3721 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3722                                               SelectionDAG &DAG) const {
3723   EVT VT = Op.getValueType();
3724   SDLoc DL(Op);
3725
3726   SDValue In1 = Op.getOperand(0);
3727   SDValue In2 = Op.getOperand(1);
3728   EVT SrcVT = In2.getValueType();
3729
3730   if (SrcVT.bitsLT(VT))
3731     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3732   else if (SrcVT.bitsGT(VT))
3733     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3734
3735   EVT VecVT;
3736   EVT EltVT;
3737   uint64_t EltMask;
3738   SDValue VecVal1, VecVal2;
3739   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3740     EltVT = MVT::i32;
3741     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3742     EltMask = 0x80000000ULL;
3743
3744     if (!VT.isVector()) {
3745       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3746                                           DAG.getUNDEF(VecVT), In1);
3747       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3748                                           DAG.getUNDEF(VecVT), In2);
3749     } else {
3750       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3751       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3752     }
3753   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3754     EltVT = MVT::i64;
3755     VecVT = MVT::v2i64;
3756
3757     // We want to materialize a mask with the high bit set, but the AdvSIMD
3758     // immediate moves cannot materialize that in a single instruction for
3759     // 64-bit elements. Instead, materialize zero and then negate it.
3760     EltMask = 0;
3761
3762     if (!VT.isVector()) {
3763       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3764                                           DAG.getUNDEF(VecVT), In1);
3765       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3766                                           DAG.getUNDEF(VecVT), In2);
3767     } else {
3768       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3769       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3770     }
3771   } else {
3772     llvm_unreachable("Invalid type for copysign!");
3773   }
3774
3775   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3776
3777   // If we couldn't materialize the mask above, then the mask vector will be
3778   // the zero vector, and we need to negate it here.
3779   if (VT == MVT::f64 || VT == MVT::v2f64) {
3780     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3781     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3782     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3783   }
3784
3785   SDValue Sel =
3786       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3787
3788   if (VT == MVT::f32)
3789     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3790   else if (VT == MVT::f64)
3791     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3792   else
3793     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3794 }
3795
3796 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3797   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3798           Attribute::NoImplicitFloat))
3799     return SDValue();
3800
3801   if (!Subtarget->hasNEON())
3802     return SDValue();
3803
3804   // While there is no integer popcount instruction, it can
3805   // be more efficiently lowered to the following sequence that uses
3806   // AdvSIMD registers/instructions as long as the copies to/from
3807   // the AdvSIMD registers are cheap.
3808   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3809   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3810   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3811   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3812   SDValue Val = Op.getOperand(0);
3813   SDLoc DL(Op);
3814   EVT VT = Op.getValueType();
3815
3816   if (VT == MVT::i32)
3817     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3818   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3819
3820   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3821   SDValue UaddLV = DAG.getNode(
3822       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3823       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3824
3825   if (VT == MVT::i64)
3826     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3827   return UaddLV;
3828 }
3829
3830 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3831
3832   if (Op.getValueType().isVector())
3833     return LowerVSETCC(Op, DAG);
3834
3835   SDValue LHS = Op.getOperand(0);
3836   SDValue RHS = Op.getOperand(1);
3837   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3838   SDLoc dl(Op);
3839
3840   // We chose ZeroOrOneBooleanContents, so use zero and one.
3841   EVT VT = Op.getValueType();
3842   SDValue TVal = DAG.getConstant(1, dl, VT);
3843   SDValue FVal = DAG.getConstant(0, dl, VT);
3844
3845   // Handle f128 first, since one possible outcome is a normal integer
3846   // comparison which gets picked up by the next if statement.
3847   if (LHS.getValueType() == MVT::f128) {
3848     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3849
3850     // If softenSetCCOperands returned a scalar, use it.
3851     if (!RHS.getNode()) {
3852       assert(LHS.getValueType() == Op.getValueType() &&
3853              "Unexpected setcc expansion!");
3854       return LHS;
3855     }
3856   }
3857
3858   if (LHS.getValueType().isInteger()) {
3859     SDValue CCVal;
3860     SDValue Cmp =
3861         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3862
3863     // Note that we inverted the condition above, so we reverse the order of
3864     // the true and false operands here.  This will allow the setcc to be
3865     // matched to a single CSINC instruction.
3866     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3867   }
3868
3869   // Now we know we're dealing with FP values.
3870   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3871
3872   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3873   // and do the comparison.
3874   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3875
3876   AArch64CC::CondCode CC1, CC2;
3877   changeFPCCToAArch64CC(CC, CC1, CC2);
3878   if (CC2 == AArch64CC::AL) {
3879     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3880     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3881
3882     // Note that we inverted the condition above, so we reverse the order of
3883     // the true and false operands here.  This will allow the setcc to be
3884     // matched to a single CSINC instruction.
3885     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3886   } else {
3887     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3888     // totally clean.  Some of them require two CSELs to implement.  As is in
3889     // this case, we emit the first CSEL and then emit a second using the output
3890     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3891
3892     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3893     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3894     SDValue CS1 =
3895         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3896
3897     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3898     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3899   }
3900 }
3901
3902 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3903                                               SDValue RHS, SDValue TVal,
3904                                               SDValue FVal, SDLoc dl,
3905                                               SelectionDAG &DAG) const {
3906   // Handle f128 first, because it will result in a comparison of some RTLIB
3907   // call result against zero.
3908   if (LHS.getValueType() == MVT::f128) {
3909     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3910
3911     // If softenSetCCOperands returned a scalar, we need to compare the result
3912     // against zero to select between true and false values.
3913     if (!RHS.getNode()) {
3914       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3915       CC = ISD::SETNE;
3916     }
3917   }
3918
3919   // Also handle f16, for which we need to do a f32 comparison.
3920   if (LHS.getValueType() == MVT::f16) {
3921     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3922     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3923   }
3924
3925   // Next, handle integers.
3926   if (LHS.getValueType().isInteger()) {
3927     assert((LHS.getValueType() == RHS.getValueType()) &&
3928            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3929
3930     unsigned Opcode = AArch64ISD::CSEL;
3931
3932     // If both the TVal and the FVal are constants, see if we can swap them in
3933     // order to for a CSINV or CSINC out of them.
3934     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3935     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3936
3937     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3938       std::swap(TVal, FVal);
3939       std::swap(CTVal, CFVal);
3940       CC = ISD::getSetCCInverse(CC, true);
3941     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3942       std::swap(TVal, FVal);
3943       std::swap(CTVal, CFVal);
3944       CC = ISD::getSetCCInverse(CC, true);
3945     } else if (TVal.getOpcode() == ISD::XOR) {
3946       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3947       // with a CSINV rather than a CSEL.
3948       if (isAllOnesConstant(TVal.getOperand(1))) {
3949         std::swap(TVal, FVal);
3950         std::swap(CTVal, CFVal);
3951         CC = ISD::getSetCCInverse(CC, true);
3952       }
3953     } else if (TVal.getOpcode() == ISD::SUB) {
3954       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3955       // that we can match with a CSNEG rather than a CSEL.
3956       if (isNullConstant(TVal.getOperand(0))) {
3957         std::swap(TVal, FVal);
3958         std::swap(CTVal, CFVal);
3959         CC = ISD::getSetCCInverse(CC, true);
3960       }
3961     } else if (CTVal && CFVal) {
3962       const int64_t TrueVal = CTVal->getSExtValue();
3963       const int64_t FalseVal = CFVal->getSExtValue();
3964       bool Swap = false;
3965
3966       // If both TVal and FVal are constants, see if FVal is the
3967       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3968       // instead of a CSEL in that case.
3969       if (TrueVal == ~FalseVal) {
3970         Opcode = AArch64ISD::CSINV;
3971       } else if (TrueVal == -FalseVal) {
3972         Opcode = AArch64ISD::CSNEG;
3973       } else if (TVal.getValueType() == MVT::i32) {
3974         // If our operands are only 32-bit wide, make sure we use 32-bit
3975         // arithmetic for the check whether we can use CSINC. This ensures that
3976         // the addition in the check will wrap around properly in case there is
3977         // an overflow (which would not be the case if we do the check with
3978         // 64-bit arithmetic).
3979         const uint32_t TrueVal32 = CTVal->getZExtValue();
3980         const uint32_t FalseVal32 = CFVal->getZExtValue();
3981
3982         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3983           Opcode = AArch64ISD::CSINC;
3984
3985           if (TrueVal32 > FalseVal32) {
3986             Swap = true;
3987           }
3988         }
3989         // 64-bit check whether we can use CSINC.
3990       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3991         Opcode = AArch64ISD::CSINC;
3992
3993         if (TrueVal > FalseVal) {
3994           Swap = true;
3995         }
3996       }
3997
3998       // Swap TVal and FVal if necessary.
3999       if (Swap) {
4000         std::swap(TVal, FVal);
4001         std::swap(CTVal, CFVal);
4002         CC = ISD::getSetCCInverse(CC, true);
4003       }
4004
4005       if (Opcode != AArch64ISD::CSEL) {
4006         // Drop FVal since we can get its value by simply inverting/negating
4007         // TVal.
4008         FVal = TVal;
4009       }
4010     }
4011
4012     SDValue CCVal;
4013     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4014
4015     EVT VT = TVal.getValueType();
4016     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4017   }
4018
4019   // Now we know we're dealing with FP values.
4020   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4021   assert(LHS.getValueType() == RHS.getValueType());
4022   EVT VT = TVal.getValueType();
4023   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4024
4025   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4026   // clean.  Some of them require two CSELs to implement.
4027   AArch64CC::CondCode CC1, CC2;
4028   changeFPCCToAArch64CC(CC, CC1, CC2);
4029   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4030   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4031
4032   // If we need a second CSEL, emit it, using the output of the first as the
4033   // RHS.  We're effectively OR'ing the two CC's together.
4034   if (CC2 != AArch64CC::AL) {
4035     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4036     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4037   }
4038
4039   // Otherwise, return the output of the first CSEL.
4040   return CS1;
4041 }
4042
4043 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4044                                               SelectionDAG &DAG) const {
4045   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4046   SDValue LHS = Op.getOperand(0);
4047   SDValue RHS = Op.getOperand(1);
4048   SDValue TVal = Op.getOperand(2);
4049   SDValue FVal = Op.getOperand(3);
4050   SDLoc DL(Op);
4051   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4052 }
4053
4054 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4055                                            SelectionDAG &DAG) const {
4056   SDValue CCVal = Op->getOperand(0);
4057   SDValue TVal = Op->getOperand(1);
4058   SDValue FVal = Op->getOperand(2);
4059   SDLoc DL(Op);
4060
4061   unsigned Opc = CCVal.getOpcode();
4062   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4063   // instruction.
4064   if (CCVal.getResNo() == 1 &&
4065       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4066        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4067     // Only lower legal XALUO ops.
4068     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4069       return SDValue();
4070
4071     AArch64CC::CondCode OFCC;
4072     SDValue Value, Overflow;
4073     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4074     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4075
4076     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4077                        CCVal, Overflow);
4078   }
4079
4080   // Lower it the same way as we would lower a SELECT_CC node.
4081   ISD::CondCode CC;
4082   SDValue LHS, RHS;
4083   if (CCVal.getOpcode() == ISD::SETCC) {
4084     LHS = CCVal.getOperand(0);
4085     RHS = CCVal.getOperand(1);
4086     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4087   } else {
4088     LHS = CCVal;
4089     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4090     CC = ISD::SETNE;
4091   }
4092   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4093 }
4094
4095 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4096                                               SelectionDAG &DAG) const {
4097   // Jump table entries as PC relative offsets. No additional tweaking
4098   // is necessary here. Just get the address of the jump table.
4099   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4100   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4101   SDLoc DL(Op);
4102
4103   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4104       !Subtarget->isTargetMachO()) {
4105     const unsigned char MO_NC = AArch64II::MO_NC;
4106     return DAG.getNode(
4107         AArch64ISD::WrapperLarge, DL, PtrVT,
4108         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4109         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4110         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4111         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4112                                AArch64II::MO_G0 | MO_NC));
4113   }
4114
4115   SDValue Hi =
4116       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4117   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4118                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4119   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4120   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4121 }
4122
4123 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4124                                                  SelectionDAG &DAG) const {
4125   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4126   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4127   SDLoc DL(Op);
4128
4129   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4130     // Use the GOT for the large code model on iOS.
4131     if (Subtarget->isTargetMachO()) {
4132       SDValue GotAddr = DAG.getTargetConstantPool(
4133           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4134           AArch64II::MO_GOT);
4135       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4136     }
4137
4138     const unsigned char MO_NC = AArch64II::MO_NC;
4139     return DAG.getNode(
4140         AArch64ISD::WrapperLarge, DL, PtrVT,
4141         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4142                                   CP->getOffset(), AArch64II::MO_G3),
4143         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4144                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4145         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4146                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4147         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4148                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4149   } else {
4150     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4151     // ELF, the only valid one on Darwin.
4152     SDValue Hi =
4153         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4154                                   CP->getOffset(), AArch64II::MO_PAGE);
4155     SDValue Lo = DAG.getTargetConstantPool(
4156         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4157         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4158
4159     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4160     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4161   }
4162 }
4163
4164 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4165                                                SelectionDAG &DAG) const {
4166   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4167   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4168   SDLoc DL(Op);
4169   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4170       !Subtarget->isTargetMachO()) {
4171     const unsigned char MO_NC = AArch64II::MO_NC;
4172     return DAG.getNode(
4173         AArch64ISD::WrapperLarge, DL, PtrVT,
4174         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4175         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4176         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4177         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4178   } else {
4179     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4180     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4181                                                              AArch64II::MO_NC);
4182     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4183     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4184   }
4185 }
4186
4187 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4188                                                  SelectionDAG &DAG) const {
4189   AArch64FunctionInfo *FuncInfo =
4190       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4191
4192   SDLoc DL(Op);
4193   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4194                                  getPointerTy(DAG.getDataLayout()));
4195   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4196   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4197                       MachinePointerInfo(SV), false, false, 0);
4198 }
4199
4200 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4201                                                 SelectionDAG &DAG) const {
4202   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4203   // Standard, section B.3.
4204   MachineFunction &MF = DAG.getMachineFunction();
4205   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4206   auto PtrVT = getPointerTy(DAG.getDataLayout());
4207   SDLoc DL(Op);
4208
4209   SDValue Chain = Op.getOperand(0);
4210   SDValue VAList = Op.getOperand(1);
4211   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4212   SmallVector<SDValue, 4> MemOps;
4213
4214   // void *__stack at offset 0
4215   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4216   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4217                                 MachinePointerInfo(SV), false, false, 8));
4218
4219   // void *__gr_top at offset 8
4220   int GPRSize = FuncInfo->getVarArgsGPRSize();
4221   if (GPRSize > 0) {
4222     SDValue GRTop, GRTopAddr;
4223
4224     GRTopAddr =
4225         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4226
4227     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4228     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4229                         DAG.getConstant(GPRSize, DL, PtrVT));
4230
4231     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4232                                   MachinePointerInfo(SV, 8), false, false, 8));
4233   }
4234
4235   // void *__vr_top at offset 16
4236   int FPRSize = FuncInfo->getVarArgsFPRSize();
4237   if (FPRSize > 0) {
4238     SDValue VRTop, VRTopAddr;
4239     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4240                             DAG.getConstant(16, DL, PtrVT));
4241
4242     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4243     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4244                         DAG.getConstant(FPRSize, DL, PtrVT));
4245
4246     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4247                                   MachinePointerInfo(SV, 16), false, false, 8));
4248   }
4249
4250   // int __gr_offs at offset 24
4251   SDValue GROffsAddr =
4252       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4253   MemOps.push_back(DAG.getStore(Chain, DL,
4254                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4255                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4256                                 false, 4));
4257
4258   // int __vr_offs at offset 28
4259   SDValue VROffsAddr =
4260       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4261   MemOps.push_back(DAG.getStore(Chain, DL,
4262                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4263                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4264                                 false, 4));
4265
4266   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4267 }
4268
4269 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4270                                             SelectionDAG &DAG) const {
4271   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4272                                      : LowerAAPCS_VASTART(Op, DAG);
4273 }
4274
4275 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4276                                            SelectionDAG &DAG) const {
4277   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4278   // pointer.
4279   SDLoc DL(Op);
4280   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4281   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4282   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4283
4284   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4285                        Op.getOperand(2),
4286                        DAG.getConstant(VaListSize, DL, MVT::i32),
4287                        8, false, false, false, MachinePointerInfo(DestSV),
4288                        MachinePointerInfo(SrcSV));
4289 }
4290
4291 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4292   assert(Subtarget->isTargetDarwin() &&
4293          "automatic va_arg instruction only works on Darwin");
4294
4295   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4296   EVT VT = Op.getValueType();
4297   SDLoc DL(Op);
4298   SDValue Chain = Op.getOperand(0);
4299   SDValue Addr = Op.getOperand(1);
4300   unsigned Align = Op.getConstantOperandVal(3);
4301   auto PtrVT = getPointerTy(DAG.getDataLayout());
4302
4303   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4304                                false, false, false, 0);
4305   Chain = VAList.getValue(1);
4306
4307   if (Align > 8) {
4308     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4309     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4310                          DAG.getConstant(Align - 1, DL, PtrVT));
4311     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4312                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4313   }
4314
4315   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4316   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4317
4318   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4319   // up to 64 bits.  At the very least, we have to increase the striding of the
4320   // vaargs list to match this, and for FP values we need to introduce
4321   // FP_ROUND nodes as well.
4322   if (VT.isInteger() && !VT.isVector())
4323     ArgSize = 8;
4324   bool NeedFPTrunc = false;
4325   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4326     ArgSize = 8;
4327     NeedFPTrunc = true;
4328   }
4329
4330   // Increment the pointer, VAList, to the next vaarg
4331   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4332                                DAG.getConstant(ArgSize, DL, PtrVT));
4333   // Store the incremented VAList to the legalized pointer
4334   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4335                                  false, false, 0);
4336
4337   // Load the actual argument out of the pointer VAList
4338   if (NeedFPTrunc) {
4339     // Load the value as an f64.
4340     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4341                                  MachinePointerInfo(), false, false, false, 0);
4342     // Round the value down to an f32.
4343     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4344                                    DAG.getIntPtrConstant(1, DL));
4345     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4346     // Merge the rounded value with the chain output of the load.
4347     return DAG.getMergeValues(Ops, DL);
4348   }
4349
4350   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4351                      false, false, 0);
4352 }
4353
4354 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4355                                               SelectionDAG &DAG) const {
4356   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4357   MFI->setFrameAddressIsTaken(true);
4358
4359   EVT VT = Op.getValueType();
4360   SDLoc DL(Op);
4361   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4362   SDValue FrameAddr =
4363       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4364   while (Depth--)
4365     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4366                             MachinePointerInfo(), false, false, false, 0);
4367   return FrameAddr;
4368 }
4369
4370 // FIXME? Maybe this could be a TableGen attribute on some registers and
4371 // this table could be generated automatically from RegInfo.
4372 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4373                                                   SelectionDAG &DAG) const {
4374   unsigned Reg = StringSwitch<unsigned>(RegName)
4375                        .Case("sp", AArch64::SP)
4376                        .Default(0);
4377   if (Reg)
4378     return Reg;
4379   report_fatal_error(Twine("Invalid register name \""
4380                               + StringRef(RegName)  + "\"."));
4381 }
4382
4383 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4384                                                SelectionDAG &DAG) const {
4385   MachineFunction &MF = DAG.getMachineFunction();
4386   MachineFrameInfo *MFI = MF.getFrameInfo();
4387   MFI->setReturnAddressIsTaken(true);
4388
4389   EVT VT = Op.getValueType();
4390   SDLoc DL(Op);
4391   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4392   if (Depth) {
4393     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4394     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4395     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4396                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4397                        MachinePointerInfo(), false, false, false, 0);
4398   }
4399
4400   // Return LR, which contains the return address. Mark it an implicit live-in.
4401   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4402   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4403 }
4404
4405 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4406 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4407 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4408                                                     SelectionDAG &DAG) const {
4409   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4410   EVT VT = Op.getValueType();
4411   unsigned VTBits = VT.getSizeInBits();
4412   SDLoc dl(Op);
4413   SDValue ShOpLo = Op.getOperand(0);
4414   SDValue ShOpHi = Op.getOperand(1);
4415   SDValue ShAmt = Op.getOperand(2);
4416   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4417
4418   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4419
4420   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4421                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4422   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4423
4424   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4425   // is "undef". We wanted 0, so CSEL it directly.
4426   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4427                                ISD::SETEQ, dl, DAG);
4428   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4429   HiBitsForLo =
4430       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4431                   HiBitsForLo, CCVal, Cmp);
4432
4433   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4434                                    DAG.getConstant(VTBits, dl, MVT::i64));
4435
4436   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4437   SDValue LoForNormalShift =
4438       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4439
4440   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4441                        dl, DAG);
4442   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4443   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4444   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4445                            LoForNormalShift, CCVal, Cmp);
4446
4447   // AArch64 shifts larger than the register width are wrapped rather than
4448   // clamped, so we can't just emit "hi >> x".
4449   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4450   SDValue HiForBigShift =
4451       Opc == ISD::SRA
4452           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4453                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4454           : DAG.getConstant(0, dl, VT);
4455   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4456                            HiForNormalShift, CCVal, Cmp);
4457
4458   SDValue Ops[2] = { Lo, Hi };
4459   return DAG.getMergeValues(Ops, dl);
4460 }
4461
4462
4463 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4464 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4465 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4466                                                    SelectionDAG &DAG) const {
4467   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4468   EVT VT = Op.getValueType();
4469   unsigned VTBits = VT.getSizeInBits();
4470   SDLoc dl(Op);
4471   SDValue ShOpLo = Op.getOperand(0);
4472   SDValue ShOpHi = Op.getOperand(1);
4473   SDValue ShAmt = Op.getOperand(2);
4474
4475   assert(Op.getOpcode() == ISD::SHL_PARTS);
4476   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4477                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4478   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4479
4480   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4481   // is "undef". We wanted 0, so CSEL it directly.
4482   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4483                                ISD::SETEQ, dl, DAG);
4484   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4485   LoBitsForHi =
4486       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4487                   LoBitsForHi, CCVal, Cmp);
4488
4489   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4490                                    DAG.getConstant(VTBits, dl, MVT::i64));
4491   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4492   SDValue HiForNormalShift =
4493       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4494
4495   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4496
4497   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4498                        dl, DAG);
4499   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4500   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4501                            HiForNormalShift, CCVal, Cmp);
4502
4503   // AArch64 shifts of larger than register sizes are wrapped rather than
4504   // clamped, so we can't just emit "lo << a" if a is too big.
4505   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4506   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4507   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4508                            LoForNormalShift, CCVal, Cmp);
4509
4510   SDValue Ops[2] = { Lo, Hi };
4511   return DAG.getMergeValues(Ops, dl);
4512 }
4513
4514 bool AArch64TargetLowering::isOffsetFoldingLegal(
4515     const GlobalAddressSDNode *GA) const {
4516   // The AArch64 target doesn't support folding offsets into global addresses.
4517   return false;
4518 }
4519
4520 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4521   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4522   // FIXME: We should be able to handle f128 as well with a clever lowering.
4523   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4524     return true;
4525
4526   if (VT == MVT::f64)
4527     return AArch64_AM::getFP64Imm(Imm) != -1;
4528   else if (VT == MVT::f32)
4529     return AArch64_AM::getFP32Imm(Imm) != -1;
4530   return false;
4531 }
4532
4533 //===----------------------------------------------------------------------===//
4534 //                          AArch64 Optimization Hooks
4535 //===----------------------------------------------------------------------===//
4536
4537 //===----------------------------------------------------------------------===//
4538 //                          AArch64 Inline Assembly Support
4539 //===----------------------------------------------------------------------===//
4540
4541 // Table of Constraints
4542 // TODO: This is the current set of constraints supported by ARM for the
4543 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4544 //
4545 // r - A general register
4546 // w - An FP/SIMD register of some size in the range v0-v31
4547 // x - An FP/SIMD register of some size in the range v0-v15
4548 // I - Constant that can be used with an ADD instruction
4549 // J - Constant that can be used with a SUB instruction
4550 // K - Constant that can be used with a 32-bit logical instruction
4551 // L - Constant that can be used with a 64-bit logical instruction
4552 // M - Constant that can be used as a 32-bit MOV immediate
4553 // N - Constant that can be used as a 64-bit MOV immediate
4554 // Q - A memory reference with base register and no offset
4555 // S - A symbolic address
4556 // Y - Floating point constant zero
4557 // Z - Integer constant zero
4558 //
4559 //   Note that general register operands will be output using their 64-bit x
4560 // register name, whatever the size of the variable, unless the asm operand
4561 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4562 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4563 // %q modifier.
4564
4565 /// getConstraintType - Given a constraint letter, return the type of
4566 /// constraint it is for this target.
4567 AArch64TargetLowering::ConstraintType
4568 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4569   if (Constraint.size() == 1) {
4570     switch (Constraint[0]) {
4571     default:
4572       break;
4573     case 'z':
4574       return C_Other;
4575     case 'x':
4576     case 'w':
4577       return C_RegisterClass;
4578     // An address with a single base register. Due to the way we
4579     // currently handle addresses it is the same as 'r'.
4580     case 'Q':
4581       return C_Memory;
4582     }
4583   }
4584   return TargetLowering::getConstraintType(Constraint);
4585 }
4586
4587 /// Examine constraint type and operand type and determine a weight value.
4588 /// This object must already have been set up with the operand type
4589 /// and the current alternative constraint selected.
4590 TargetLowering::ConstraintWeight
4591 AArch64TargetLowering::getSingleConstraintMatchWeight(
4592     AsmOperandInfo &info, const char *constraint) const {
4593   ConstraintWeight weight = CW_Invalid;
4594   Value *CallOperandVal = info.CallOperandVal;
4595   // If we don't have a value, we can't do a match,
4596   // but allow it at the lowest weight.
4597   if (!CallOperandVal)
4598     return CW_Default;
4599   Type *type = CallOperandVal->getType();
4600   // Look at the constraint type.
4601   switch (*constraint) {
4602   default:
4603     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4604     break;
4605   case 'x':
4606   case 'w':
4607     if (type->isFloatingPointTy() || type->isVectorTy())
4608       weight = CW_Register;
4609     break;
4610   case 'z':
4611     weight = CW_Constant;
4612     break;
4613   }
4614   return weight;
4615 }
4616
4617 std::pair<unsigned, const TargetRegisterClass *>
4618 AArch64TargetLowering::getRegForInlineAsmConstraint(
4619     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4620   if (Constraint.size() == 1) {
4621     switch (Constraint[0]) {
4622     case 'r':
4623       if (VT.getSizeInBits() == 64)
4624         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4625       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4626     case 'w':
4627       if (VT == MVT::f32)
4628         return std::make_pair(0U, &AArch64::FPR32RegClass);
4629       if (VT.getSizeInBits() == 64)
4630         return std::make_pair(0U, &AArch64::FPR64RegClass);
4631       if (VT.getSizeInBits() == 128)
4632         return std::make_pair(0U, &AArch64::FPR128RegClass);
4633       break;
4634     // The instructions that this constraint is designed for can
4635     // only take 128-bit registers so just use that regclass.
4636     case 'x':
4637       if (VT.getSizeInBits() == 128)
4638         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4639       break;
4640     }
4641   }
4642   if (StringRef("{cc}").equals_lower(Constraint))
4643     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4644
4645   // Use the default implementation in TargetLowering to convert the register
4646   // constraint into a member of a register class.
4647   std::pair<unsigned, const TargetRegisterClass *> Res;
4648   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4649
4650   // Not found as a standard register?
4651   if (!Res.second) {
4652     unsigned Size = Constraint.size();
4653     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4654         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4655       int RegNo;
4656       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4657       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4658         // v0 - v31 are aliases of q0 - q31.
4659         // By default we'll emit v0-v31 for this unless there's a modifier where
4660         // we'll emit the correct register as well.
4661         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4662         Res.second = &AArch64::FPR128RegClass;
4663       }
4664     }
4665   }
4666
4667   return Res;
4668 }
4669
4670 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4671 /// vector.  If it is invalid, don't add anything to Ops.
4672 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4673     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4674     SelectionDAG &DAG) const {
4675   SDValue Result;
4676
4677   // Currently only support length 1 constraints.
4678   if (Constraint.length() != 1)
4679     return;
4680
4681   char ConstraintLetter = Constraint[0];
4682   switch (ConstraintLetter) {
4683   default:
4684     break;
4685
4686   // This set of constraints deal with valid constants for various instructions.
4687   // Validate and return a target constant for them if we can.
4688   case 'z': {
4689     // 'z' maps to xzr or wzr so it needs an input of 0.
4690     if (!isNullConstant(Op))
4691       return;
4692
4693     if (Op.getValueType() == MVT::i64)
4694       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4695     else
4696       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4697     break;
4698   }
4699
4700   case 'I':
4701   case 'J':
4702   case 'K':
4703   case 'L':
4704   case 'M':
4705   case 'N':
4706     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4707     if (!C)
4708       return;
4709
4710     // Grab the value and do some validation.
4711     uint64_t CVal = C->getZExtValue();
4712     switch (ConstraintLetter) {
4713     // The I constraint applies only to simple ADD or SUB immediate operands:
4714     // i.e. 0 to 4095 with optional shift by 12
4715     // The J constraint applies only to ADD or SUB immediates that would be
4716     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4717     // instruction [or vice versa], in other words -1 to -4095 with optional
4718     // left shift by 12.
4719     case 'I':
4720       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4721         break;
4722       return;
4723     case 'J': {
4724       uint64_t NVal = -C->getSExtValue();
4725       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4726         CVal = C->getSExtValue();
4727         break;
4728       }
4729       return;
4730     }
4731     // The K and L constraints apply *only* to logical immediates, including
4732     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4733     // been removed and MOV should be used). So these constraints have to
4734     // distinguish between bit patterns that are valid 32-bit or 64-bit
4735     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4736     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4737     // versa.
4738     case 'K':
4739       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4740         break;
4741       return;
4742     case 'L':
4743       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4744         break;
4745       return;
4746     // The M and N constraints are a superset of K and L respectively, for use
4747     // with the MOV (immediate) alias. As well as the logical immediates they
4748     // also match 32 or 64-bit immediates that can be loaded either using a
4749     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4750     // (M) or 64-bit 0x1234000000000000 (N) etc.
4751     // As a note some of this code is liberally stolen from the asm parser.
4752     case 'M': {
4753       if (!isUInt<32>(CVal))
4754         return;
4755       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4756         break;
4757       if ((CVal & 0xFFFF) == CVal)
4758         break;
4759       if ((CVal & 0xFFFF0000ULL) == CVal)
4760         break;
4761       uint64_t NCVal = ~(uint32_t)CVal;
4762       if ((NCVal & 0xFFFFULL) == NCVal)
4763         break;
4764       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4765         break;
4766       return;
4767     }
4768     case 'N': {
4769       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4770         break;
4771       if ((CVal & 0xFFFFULL) == CVal)
4772         break;
4773       if ((CVal & 0xFFFF0000ULL) == CVal)
4774         break;
4775       if ((CVal & 0xFFFF00000000ULL) == CVal)
4776         break;
4777       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4778         break;
4779       uint64_t NCVal = ~CVal;
4780       if ((NCVal & 0xFFFFULL) == NCVal)
4781         break;
4782       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4783         break;
4784       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4785         break;
4786       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4787         break;
4788       return;
4789     }
4790     default:
4791       return;
4792     }
4793
4794     // All assembler immediates are 64-bit integers.
4795     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4796     break;
4797   }
4798
4799   if (Result.getNode()) {
4800     Ops.push_back(Result);
4801     return;
4802   }
4803
4804   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4805 }
4806
4807 //===----------------------------------------------------------------------===//
4808 //                     AArch64 Advanced SIMD Support
4809 //===----------------------------------------------------------------------===//
4810
4811 /// WidenVector - Given a value in the V64 register class, produce the
4812 /// equivalent value in the V128 register class.
4813 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4814   EVT VT = V64Reg.getValueType();
4815   unsigned NarrowSize = VT.getVectorNumElements();
4816   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4817   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4818   SDLoc DL(V64Reg);
4819
4820   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4821                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4822 }
4823
4824 /// getExtFactor - Determine the adjustment factor for the position when
4825 /// generating an "extract from vector registers" instruction.
4826 static unsigned getExtFactor(SDValue &V) {
4827   EVT EltType = V.getValueType().getVectorElementType();
4828   return EltType.getSizeInBits() / 8;
4829 }
4830
4831 /// NarrowVector - Given a value in the V128 register class, produce the
4832 /// equivalent value in the V64 register class.
4833 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4834   EVT VT = V128Reg.getValueType();
4835   unsigned WideSize = VT.getVectorNumElements();
4836   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4837   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4838   SDLoc DL(V128Reg);
4839
4840   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4841 }
4842
4843 // Gather data to see if the operation can be modelled as a
4844 // shuffle in combination with VEXTs.
4845 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4846                                                   SelectionDAG &DAG) const {
4847   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4848   SDLoc dl(Op);
4849   EVT VT = Op.getValueType();
4850   unsigned NumElts = VT.getVectorNumElements();
4851
4852   struct ShuffleSourceInfo {
4853     SDValue Vec;
4854     unsigned MinElt;
4855     unsigned MaxElt;
4856
4857     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4858     // be compatible with the shuffle we intend to construct. As a result
4859     // ShuffleVec will be some sliding window into the original Vec.
4860     SDValue ShuffleVec;
4861
4862     // Code should guarantee that element i in Vec starts at element "WindowBase
4863     // + i * WindowScale in ShuffleVec".
4864     int WindowBase;
4865     int WindowScale;
4866
4867     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4868     ShuffleSourceInfo(SDValue Vec)
4869         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4870           WindowScale(1) {}
4871   };
4872
4873   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4874   // node.
4875   SmallVector<ShuffleSourceInfo, 2> Sources;
4876   for (unsigned i = 0; i < NumElts; ++i) {
4877     SDValue V = Op.getOperand(i);
4878     if (V.getOpcode() == ISD::UNDEF)
4879       continue;
4880     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4881       // A shuffle can only come from building a vector from various
4882       // elements of other vectors.
4883       return SDValue();
4884     }
4885
4886     // Add this element source to the list if it's not already there.
4887     SDValue SourceVec = V.getOperand(0);
4888     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4889     if (Source == Sources.end())
4890       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4891
4892     // Update the minimum and maximum lane number seen.
4893     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4894     Source->MinElt = std::min(Source->MinElt, EltNo);
4895     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4896   }
4897
4898   // Currently only do something sane when at most two source vectors
4899   // are involved.
4900   if (Sources.size() > 2)
4901     return SDValue();
4902
4903   // Find out the smallest element size among result and two sources, and use
4904   // it as element size to build the shuffle_vector.
4905   EVT SmallestEltTy = VT.getVectorElementType();
4906   for (auto &Source : Sources) {
4907     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4908     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4909       SmallestEltTy = SrcEltTy;
4910     }
4911   }
4912   unsigned ResMultiplier =
4913       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4914   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4915   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4916
4917   // If the source vector is too wide or too narrow, we may nevertheless be able
4918   // to construct a compatible shuffle either by concatenating it with UNDEF or
4919   // extracting a suitable range of elements.
4920   for (auto &Src : Sources) {
4921     EVT SrcVT = Src.ShuffleVec.getValueType();
4922
4923     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4924       continue;
4925
4926     // This stage of the search produces a source with the same element type as
4927     // the original, but with a total width matching the BUILD_VECTOR output.
4928     EVT EltVT = SrcVT.getVectorElementType();
4929     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4930     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4931
4932     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4933       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4934       // We can pad out the smaller vector for free, so if it's part of a
4935       // shuffle...
4936       Src.ShuffleVec =
4937           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4938                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4939       continue;
4940     }
4941
4942     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4943
4944     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4945       // Span too large for a VEXT to cope
4946       return SDValue();
4947     }
4948
4949     if (Src.MinElt >= NumSrcElts) {
4950       // The extraction can just take the second half
4951       Src.ShuffleVec =
4952           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4953                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4954       Src.WindowBase = -NumSrcElts;
4955     } else if (Src.MaxElt < NumSrcElts) {
4956       // The extraction can just take the first half
4957       Src.ShuffleVec =
4958           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4959                       DAG.getConstant(0, dl, MVT::i64));
4960     } else {
4961       // An actual VEXT is needed
4962       SDValue VEXTSrc1 =
4963           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4964                       DAG.getConstant(0, dl, MVT::i64));
4965       SDValue VEXTSrc2 =
4966           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4967                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4968       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4969
4970       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4971                                    VEXTSrc2,
4972                                    DAG.getConstant(Imm, dl, MVT::i32));
4973       Src.WindowBase = -Src.MinElt;
4974     }
4975   }
4976
4977   // Another possible incompatibility occurs from the vector element types. We
4978   // can fix this by bitcasting the source vectors to the same type we intend
4979   // for the shuffle.
4980   for (auto &Src : Sources) {
4981     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4982     if (SrcEltTy == SmallestEltTy)
4983       continue;
4984     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4985     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4986     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4987     Src.WindowBase *= Src.WindowScale;
4988   }
4989
4990   // Final sanity check before we try to actually produce a shuffle.
4991   DEBUG(
4992     for (auto Src : Sources)
4993       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4994   );
4995
4996   // The stars all align, our next step is to produce the mask for the shuffle.
4997   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4998   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4999   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5000     SDValue Entry = Op.getOperand(i);
5001     if (Entry.getOpcode() == ISD::UNDEF)
5002       continue;
5003
5004     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5005     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5006
5007     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5008     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5009     // segment.
5010     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5011     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5012                                VT.getVectorElementType().getSizeInBits());
5013     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5014
5015     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5016     // starting at the appropriate offset.
5017     int *LaneMask = &Mask[i * ResMultiplier];
5018
5019     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5020     ExtractBase += NumElts * (Src - Sources.begin());
5021     for (int j = 0; j < LanesDefined; ++j)
5022       LaneMask[j] = ExtractBase + j;
5023   }
5024
5025   // Final check before we try to produce nonsense...
5026   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5027     return SDValue();
5028
5029   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5030   for (unsigned i = 0; i < Sources.size(); ++i)
5031     ShuffleOps[i] = Sources[i].ShuffleVec;
5032
5033   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5034                                          ShuffleOps[1], &Mask[0]);
5035   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5036 }
5037
5038 // check if an EXT instruction can handle the shuffle mask when the
5039 // vector sources of the shuffle are the same.
5040 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5041   unsigned NumElts = VT.getVectorNumElements();
5042
5043   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5044   if (M[0] < 0)
5045     return false;
5046
5047   Imm = M[0];
5048
5049   // If this is a VEXT shuffle, the immediate value is the index of the first
5050   // element.  The other shuffle indices must be the successive elements after
5051   // the first one.
5052   unsigned ExpectedElt = Imm;
5053   for (unsigned i = 1; i < NumElts; ++i) {
5054     // Increment the expected index.  If it wraps around, just follow it
5055     // back to index zero and keep going.
5056     ++ExpectedElt;
5057     if (ExpectedElt == NumElts)
5058       ExpectedElt = 0;
5059
5060     if (M[i] < 0)
5061       continue; // ignore UNDEF indices
5062     if (ExpectedElt != static_cast<unsigned>(M[i]))
5063       return false;
5064   }
5065
5066   return true;
5067 }
5068
5069 // check if an EXT instruction can handle the shuffle mask when the
5070 // vector sources of the shuffle are different.
5071 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5072                       unsigned &Imm) {
5073   // Look for the first non-undef element.
5074   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5075       [](int Elt) {return Elt >= 0;});
5076
5077   // Benefit form APInt to handle overflow when calculating expected element.
5078   unsigned NumElts = VT.getVectorNumElements();
5079   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5080   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5081   // The following shuffle indices must be the successive elements after the
5082   // first real element.
5083   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5084       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5085   if (FirstWrongElt != M.end())
5086     return false;
5087
5088   // The index of an EXT is the first element if it is not UNDEF.
5089   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5090   // value of the first element.  E.g.
5091   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5092   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5093   // ExpectedElt is the last mask index plus 1.
5094   Imm = ExpectedElt.getZExtValue();
5095
5096   // There are two difference cases requiring to reverse input vectors.
5097   // For example, for vector <4 x i32> we have the following cases,
5098   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5099   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5100   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5101   // to reverse two input vectors.
5102   if (Imm < NumElts)
5103     ReverseEXT = true;
5104   else
5105     Imm -= NumElts;
5106
5107   return true;
5108 }
5109
5110 /// isREVMask - Check if a vector shuffle corresponds to a REV
5111 /// instruction with the specified blocksize.  (The order of the elements
5112 /// within each block of the vector is reversed.)
5113 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5114   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5115          "Only possible block sizes for REV are: 16, 32, 64");
5116
5117   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5118   if (EltSz == 64)
5119     return false;
5120
5121   unsigned NumElts = VT.getVectorNumElements();
5122   unsigned BlockElts = M[0] + 1;
5123   // If the first shuffle index is UNDEF, be optimistic.
5124   if (M[0] < 0)
5125     BlockElts = BlockSize / EltSz;
5126
5127   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5128     return false;
5129
5130   for (unsigned i = 0; i < NumElts; ++i) {
5131     if (M[i] < 0)
5132       continue; // ignore UNDEF indices
5133     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5134       return false;
5135   }
5136
5137   return true;
5138 }
5139
5140 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5141   unsigned NumElts = VT.getVectorNumElements();
5142   WhichResult = (M[0] == 0 ? 0 : 1);
5143   unsigned Idx = WhichResult * NumElts / 2;
5144   for (unsigned i = 0; i != NumElts; i += 2) {
5145     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5146         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5147       return false;
5148     Idx += 1;
5149   }
5150
5151   return true;
5152 }
5153
5154 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5155   unsigned NumElts = VT.getVectorNumElements();
5156   WhichResult = (M[0] == 0 ? 0 : 1);
5157   for (unsigned i = 0; i != NumElts; ++i) {
5158     if (M[i] < 0)
5159       continue; // ignore UNDEF indices
5160     if ((unsigned)M[i] != 2 * i + WhichResult)
5161       return false;
5162   }
5163
5164   return true;
5165 }
5166
5167 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5168   unsigned NumElts = VT.getVectorNumElements();
5169   WhichResult = (M[0] == 0 ? 0 : 1);
5170   for (unsigned i = 0; i < NumElts; i += 2) {
5171     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5172         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5173       return false;
5174   }
5175   return true;
5176 }
5177
5178 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5179 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5180 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5181 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5182   unsigned NumElts = VT.getVectorNumElements();
5183   WhichResult = (M[0] == 0 ? 0 : 1);
5184   unsigned Idx = WhichResult * NumElts / 2;
5185   for (unsigned i = 0; i != NumElts; i += 2) {
5186     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5187         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5188       return false;
5189     Idx += 1;
5190   }
5191
5192   return true;
5193 }
5194
5195 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5196 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5197 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5198 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5199   unsigned Half = VT.getVectorNumElements() / 2;
5200   WhichResult = (M[0] == 0 ? 0 : 1);
5201   for (unsigned j = 0; j != 2; ++j) {
5202     unsigned Idx = WhichResult;
5203     for (unsigned i = 0; i != Half; ++i) {
5204       int MIdx = M[i + j * Half];
5205       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5206         return false;
5207       Idx += 2;
5208     }
5209   }
5210
5211   return true;
5212 }
5213
5214 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5215 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5216 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5217 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5218   unsigned NumElts = VT.getVectorNumElements();
5219   WhichResult = (M[0] == 0 ? 0 : 1);
5220   for (unsigned i = 0; i < NumElts; i += 2) {
5221     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5222         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5223       return false;
5224   }
5225   return true;
5226 }
5227
5228 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5229                       bool &DstIsLeft, int &Anomaly) {
5230   if (M.size() != static_cast<size_t>(NumInputElements))
5231     return false;
5232
5233   int NumLHSMatch = 0, NumRHSMatch = 0;
5234   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5235
5236   for (int i = 0; i < NumInputElements; ++i) {
5237     if (M[i] == -1) {
5238       ++NumLHSMatch;
5239       ++NumRHSMatch;
5240       continue;
5241     }
5242
5243     if (M[i] == i)
5244       ++NumLHSMatch;
5245     else
5246       LastLHSMismatch = i;
5247
5248     if (M[i] == i + NumInputElements)
5249       ++NumRHSMatch;
5250     else
5251       LastRHSMismatch = i;
5252   }
5253
5254   if (NumLHSMatch == NumInputElements - 1) {
5255     DstIsLeft = true;
5256     Anomaly = LastLHSMismatch;
5257     return true;
5258   } else if (NumRHSMatch == NumInputElements - 1) {
5259     DstIsLeft = false;
5260     Anomaly = LastRHSMismatch;
5261     return true;
5262   }
5263
5264   return false;
5265 }
5266
5267 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5268   if (VT.getSizeInBits() != 128)
5269     return false;
5270
5271   unsigned NumElts = VT.getVectorNumElements();
5272
5273   for (int I = 0, E = NumElts / 2; I != E; I++) {
5274     if (Mask[I] != I)
5275       return false;
5276   }
5277
5278   int Offset = NumElts / 2;
5279   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5280     if (Mask[I] != I + SplitLHS * Offset)
5281       return false;
5282   }
5283
5284   return true;
5285 }
5286
5287 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5288   SDLoc DL(Op);
5289   EVT VT = Op.getValueType();
5290   SDValue V0 = Op.getOperand(0);
5291   SDValue V1 = Op.getOperand(1);
5292   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5293
5294   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5295       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5296     return SDValue();
5297
5298   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5299
5300   if (!isConcatMask(Mask, VT, SplitV0))
5301     return SDValue();
5302
5303   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5304                                 VT.getVectorNumElements() / 2);
5305   if (SplitV0) {
5306     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5307                      DAG.getConstant(0, DL, MVT::i64));
5308   }
5309   if (V1.getValueType().getSizeInBits() == 128) {
5310     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5311                      DAG.getConstant(0, DL, MVT::i64));
5312   }
5313   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5314 }
5315
5316 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5317 /// the specified operations to build the shuffle.
5318 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5319                                       SDValue RHS, SelectionDAG &DAG,
5320                                       SDLoc dl) {
5321   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5322   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5323   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5324
5325   enum {
5326     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5327     OP_VREV,
5328     OP_VDUP0,
5329     OP_VDUP1,
5330     OP_VDUP2,
5331     OP_VDUP3,
5332     OP_VEXT1,
5333     OP_VEXT2,
5334     OP_VEXT3,
5335     OP_VUZPL, // VUZP, left result
5336     OP_VUZPR, // VUZP, right result
5337     OP_VZIPL, // VZIP, left result
5338     OP_VZIPR, // VZIP, right result
5339     OP_VTRNL, // VTRN, left result
5340     OP_VTRNR  // VTRN, right result
5341   };
5342
5343   if (OpNum == OP_COPY) {
5344     if (LHSID == (1 * 9 + 2) * 9 + 3)
5345       return LHS;
5346     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5347     return RHS;
5348   }
5349
5350   SDValue OpLHS, OpRHS;
5351   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5352   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5353   EVT VT = OpLHS.getValueType();
5354
5355   switch (OpNum) {
5356   default:
5357     llvm_unreachable("Unknown shuffle opcode!");
5358   case OP_VREV:
5359     // VREV divides the vector in half and swaps within the half.
5360     if (VT.getVectorElementType() == MVT::i32 ||
5361         VT.getVectorElementType() == MVT::f32)
5362       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5363     // vrev <4 x i16> -> REV32
5364     if (VT.getVectorElementType() == MVT::i16 ||
5365         VT.getVectorElementType() == MVT::f16)
5366       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5367     // vrev <4 x i8> -> REV16
5368     assert(VT.getVectorElementType() == MVT::i8);
5369     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5370   case OP_VDUP0:
5371   case OP_VDUP1:
5372   case OP_VDUP2:
5373   case OP_VDUP3: {
5374     EVT EltTy = VT.getVectorElementType();
5375     unsigned Opcode;
5376     if (EltTy == MVT::i8)
5377       Opcode = AArch64ISD::DUPLANE8;
5378     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5379       Opcode = AArch64ISD::DUPLANE16;
5380     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5381       Opcode = AArch64ISD::DUPLANE32;
5382     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5383       Opcode = AArch64ISD::DUPLANE64;
5384     else
5385       llvm_unreachable("Invalid vector element type?");
5386
5387     if (VT.getSizeInBits() == 64)
5388       OpLHS = WidenVector(OpLHS, DAG);
5389     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5390     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5391   }
5392   case OP_VEXT1:
5393   case OP_VEXT2:
5394   case OP_VEXT3: {
5395     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5396     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5397                        DAG.getConstant(Imm, dl, MVT::i32));
5398   }
5399   case OP_VUZPL:
5400     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5401                        OpRHS);
5402   case OP_VUZPR:
5403     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5404                        OpRHS);
5405   case OP_VZIPL:
5406     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5407                        OpRHS);
5408   case OP_VZIPR:
5409     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5410                        OpRHS);
5411   case OP_VTRNL:
5412     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5413                        OpRHS);
5414   case OP_VTRNR:
5415     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5416                        OpRHS);
5417   }
5418 }
5419
5420 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5421                            SelectionDAG &DAG) {
5422   // Check to see if we can use the TBL instruction.
5423   SDValue V1 = Op.getOperand(0);
5424   SDValue V2 = Op.getOperand(1);
5425   SDLoc DL(Op);
5426
5427   EVT EltVT = Op.getValueType().getVectorElementType();
5428   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5429
5430   SmallVector<SDValue, 8> TBLMask;
5431   for (int Val : ShuffleMask) {
5432     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5433       unsigned Offset = Byte + Val * BytesPerElt;
5434       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5435     }
5436   }
5437
5438   MVT IndexVT = MVT::v8i8;
5439   unsigned IndexLen = 8;
5440   if (Op.getValueType().getSizeInBits() == 128) {
5441     IndexVT = MVT::v16i8;
5442     IndexLen = 16;
5443   }
5444
5445   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5446   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5447
5448   SDValue Shuffle;
5449   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5450     if (IndexLen == 8)
5451       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5452     Shuffle = DAG.getNode(
5453         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5454         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5455         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5456                     makeArrayRef(TBLMask.data(), IndexLen)));
5457   } else {
5458     if (IndexLen == 8) {
5459       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5460       Shuffle = DAG.getNode(
5461           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5462           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5463           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5464                       makeArrayRef(TBLMask.data(), IndexLen)));
5465     } else {
5466       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5467       // cannot currently represent the register constraints on the input
5468       // table registers.
5469       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5470       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5471       //                               &TBLMask[0], IndexLen));
5472       Shuffle = DAG.getNode(
5473           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5474           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5475           V1Cst, V2Cst,
5476           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5477                       makeArrayRef(TBLMask.data(), IndexLen)));
5478     }
5479   }
5480   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5481 }
5482
5483 static unsigned getDUPLANEOp(EVT EltType) {
5484   if (EltType == MVT::i8)
5485     return AArch64ISD::DUPLANE8;
5486   if (EltType == MVT::i16 || EltType == MVT::f16)
5487     return AArch64ISD::DUPLANE16;
5488   if (EltType == MVT::i32 || EltType == MVT::f32)
5489     return AArch64ISD::DUPLANE32;
5490   if (EltType == MVT::i64 || EltType == MVT::f64)
5491     return AArch64ISD::DUPLANE64;
5492
5493   llvm_unreachable("Invalid vector element type?");
5494 }
5495
5496 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5497                                                    SelectionDAG &DAG) const {
5498   SDLoc dl(Op);
5499   EVT VT = Op.getValueType();
5500
5501   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5502
5503   // Convert shuffles that are directly supported on NEON to target-specific
5504   // DAG nodes, instead of keeping them as shuffles and matching them again
5505   // during code selection.  This is more efficient and avoids the possibility
5506   // of inconsistencies between legalization and selection.
5507   ArrayRef<int> ShuffleMask = SVN->getMask();
5508
5509   SDValue V1 = Op.getOperand(0);
5510   SDValue V2 = Op.getOperand(1);
5511
5512   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5513                                        V1.getValueType().getSimpleVT())) {
5514     int Lane = SVN->getSplatIndex();
5515     // If this is undef splat, generate it via "just" vdup, if possible.
5516     if (Lane == -1)
5517       Lane = 0;
5518
5519     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5520       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5521                          V1.getOperand(0));
5522     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5523     // constant. If so, we can just reference the lane's definition directly.
5524     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5525         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5526       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5527
5528     // Otherwise, duplicate from the lane of the input vector.
5529     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5530
5531     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5532     // to make a vector of the same size as this SHUFFLE. We can ignore the
5533     // extract entirely, and canonicalise the concat using WidenVector.
5534     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5535       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5536       V1 = V1.getOperand(0);
5537     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5538       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5539       Lane -= Idx * VT.getVectorNumElements() / 2;
5540       V1 = WidenVector(V1.getOperand(Idx), DAG);
5541     } else if (VT.getSizeInBits() == 64)
5542       V1 = WidenVector(V1, DAG);
5543
5544     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5545   }
5546
5547   if (isREVMask(ShuffleMask, VT, 64))
5548     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5549   if (isREVMask(ShuffleMask, VT, 32))
5550     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5551   if (isREVMask(ShuffleMask, VT, 16))
5552     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5553
5554   bool ReverseEXT = false;
5555   unsigned Imm;
5556   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5557     if (ReverseEXT)
5558       std::swap(V1, V2);
5559     Imm *= getExtFactor(V1);
5560     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5561                        DAG.getConstant(Imm, dl, MVT::i32));
5562   } else if (V2->getOpcode() == ISD::UNDEF &&
5563              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5564     Imm *= getExtFactor(V1);
5565     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5566                        DAG.getConstant(Imm, dl, MVT::i32));
5567   }
5568
5569   unsigned WhichResult;
5570   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5571     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5572     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5573   }
5574   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5575     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5576     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5577   }
5578   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5579     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5580     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5581   }
5582
5583   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5584     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5585     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5586   }
5587   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5588     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5589     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5590   }
5591   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5592     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5593     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5594   }
5595
5596   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5597   if (Concat.getNode())
5598     return Concat;
5599
5600   bool DstIsLeft;
5601   int Anomaly;
5602   int NumInputElements = V1.getValueType().getVectorNumElements();
5603   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5604     SDValue DstVec = DstIsLeft ? V1 : V2;
5605     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5606
5607     SDValue SrcVec = V1;
5608     int SrcLane = ShuffleMask[Anomaly];
5609     if (SrcLane >= NumInputElements) {
5610       SrcVec = V2;
5611       SrcLane -= VT.getVectorNumElements();
5612     }
5613     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5614
5615     EVT ScalarVT = VT.getVectorElementType();
5616
5617     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5618       ScalarVT = MVT::i32;
5619
5620     return DAG.getNode(
5621         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5622         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5623         DstLaneV);
5624   }
5625
5626   // If the shuffle is not directly supported and it has 4 elements, use
5627   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5628   unsigned NumElts = VT.getVectorNumElements();
5629   if (NumElts == 4) {
5630     unsigned PFIndexes[4];
5631     for (unsigned i = 0; i != 4; ++i) {
5632       if (ShuffleMask[i] < 0)
5633         PFIndexes[i] = 8;
5634       else
5635         PFIndexes[i] = ShuffleMask[i];
5636     }
5637
5638     // Compute the index in the perfect shuffle table.
5639     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5640                             PFIndexes[2] * 9 + PFIndexes[3];
5641     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5642     unsigned Cost = (PFEntry >> 30);
5643
5644     if (Cost <= 4)
5645       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5646   }
5647
5648   return GenerateTBL(Op, ShuffleMask, DAG);
5649 }
5650
5651 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5652                                APInt &UndefBits) {
5653   EVT VT = BVN->getValueType(0);
5654   APInt SplatBits, SplatUndef;
5655   unsigned SplatBitSize;
5656   bool HasAnyUndefs;
5657   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5658     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5659
5660     for (unsigned i = 0; i < NumSplats; ++i) {
5661       CnstBits <<= SplatBitSize;
5662       UndefBits <<= SplatBitSize;
5663       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5664       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5665     }
5666
5667     return true;
5668   }
5669
5670   return false;
5671 }
5672
5673 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5674                                               SelectionDAG &DAG) const {
5675   BuildVectorSDNode *BVN =
5676       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5677   SDValue LHS = Op.getOperand(0);
5678   SDLoc dl(Op);
5679   EVT VT = Op.getValueType();
5680
5681   if (!BVN)
5682     return Op;
5683
5684   APInt CnstBits(VT.getSizeInBits(), 0);
5685   APInt UndefBits(VT.getSizeInBits(), 0);
5686   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5687     // We only have BIC vector immediate instruction, which is and-not.
5688     CnstBits = ~CnstBits;
5689
5690     // We make use of a little bit of goto ickiness in order to avoid having to
5691     // duplicate the immediate matching logic for the undef toggled case.
5692     bool SecondTry = false;
5693   AttemptModImm:
5694
5695     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5696       CnstBits = CnstBits.zextOrTrunc(64);
5697       uint64_t CnstVal = CnstBits.getZExtValue();
5698
5699       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5700         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5701         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5702         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5703                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5704                                   DAG.getConstant(0, dl, MVT::i32));
5705         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5706       }
5707
5708       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5709         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5710         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5711         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5712                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5713                                   DAG.getConstant(8, dl, MVT::i32));
5714         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5715       }
5716
5717       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5718         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5719         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5720         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5721                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5722                                   DAG.getConstant(16, dl, MVT::i32));
5723         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5724       }
5725
5726       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5727         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5728         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5729         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5730                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5731                                   DAG.getConstant(24, dl, MVT::i32));
5732         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5733       }
5734
5735       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5736         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5737         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5738         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5739                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5740                                   DAG.getConstant(0, dl, MVT::i32));
5741         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5742       }
5743
5744       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5745         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5746         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5747         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5748                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5749                                   DAG.getConstant(8, dl, MVT::i32));
5750         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5751       }
5752     }
5753
5754     if (SecondTry)
5755       goto FailedModImm;
5756     SecondTry = true;
5757     CnstBits = ~UndefBits;
5758     goto AttemptModImm;
5759   }
5760
5761 // We can always fall back to a non-immediate AND.
5762 FailedModImm:
5763   return Op;
5764 }
5765
5766 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5767 // consists of only the same constant int value, returned in reference arg
5768 // ConstVal
5769 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5770                                      uint64_t &ConstVal) {
5771   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5772   if (!Bvec)
5773     return false;
5774   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5775   if (!FirstElt)
5776     return false;
5777   EVT VT = Bvec->getValueType(0);
5778   unsigned NumElts = VT.getVectorNumElements();
5779   for (unsigned i = 1; i < NumElts; ++i)
5780     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5781       return false;
5782   ConstVal = FirstElt->getZExtValue();
5783   return true;
5784 }
5785
5786 static unsigned getIntrinsicID(const SDNode *N) {
5787   unsigned Opcode = N->getOpcode();
5788   switch (Opcode) {
5789   default:
5790     return Intrinsic::not_intrinsic;
5791   case ISD::INTRINSIC_WO_CHAIN: {
5792     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5793     if (IID < Intrinsic::num_intrinsics)
5794       return IID;
5795     return Intrinsic::not_intrinsic;
5796   }
5797   }
5798 }
5799
5800 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5801 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5802 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5803 // Also, logical shift right -> sri, with the same structure.
5804 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5805   EVT VT = N->getValueType(0);
5806
5807   if (!VT.isVector())
5808     return SDValue();
5809
5810   SDLoc DL(N);
5811
5812   // Is the first op an AND?
5813   const SDValue And = N->getOperand(0);
5814   if (And.getOpcode() != ISD::AND)
5815     return SDValue();
5816
5817   // Is the second op an shl or lshr?
5818   SDValue Shift = N->getOperand(1);
5819   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5820   // or AArch64ISD::VLSHR vector, #shift
5821   unsigned ShiftOpc = Shift.getOpcode();
5822   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5823     return SDValue();
5824   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5825
5826   // Is the shift amount constant?
5827   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5828   if (!C2node)
5829     return SDValue();
5830
5831   // Is the and mask vector all constant?
5832   uint64_t C1;
5833   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5834     return SDValue();
5835
5836   // Is C1 == ~C2, taking into account how much one can shift elements of a
5837   // particular size?
5838   uint64_t C2 = C2node->getZExtValue();
5839   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5840   if (C2 > ElemSizeInBits)
5841     return SDValue();
5842   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5843   if ((C1 & ElemMask) != (~C2 & ElemMask))
5844     return SDValue();
5845
5846   SDValue X = And.getOperand(0);
5847   SDValue Y = Shift.getOperand(0);
5848
5849   unsigned Intrin =
5850       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5851   SDValue ResultSLI =
5852       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5853                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5854                   Shift.getOperand(1));
5855
5856   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5857   DEBUG(N->dump(&DAG));
5858   DEBUG(dbgs() << "into: \n");
5859   DEBUG(ResultSLI->dump(&DAG));
5860
5861   ++NumShiftInserts;
5862   return ResultSLI;
5863 }
5864
5865 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5866                                              SelectionDAG &DAG) const {
5867   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5868   if (EnableAArch64SlrGeneration) {
5869     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5870     if (Res.getNode())
5871       return Res;
5872   }
5873
5874   BuildVectorSDNode *BVN =
5875       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5876   SDValue LHS = Op.getOperand(1);
5877   SDLoc dl(Op);
5878   EVT VT = Op.getValueType();
5879
5880   // OR commutes, so try swapping the operands.
5881   if (!BVN) {
5882     LHS = Op.getOperand(0);
5883     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5884   }
5885   if (!BVN)
5886     return Op;
5887
5888   APInt CnstBits(VT.getSizeInBits(), 0);
5889   APInt UndefBits(VT.getSizeInBits(), 0);
5890   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5891     // We make use of a little bit of goto ickiness in order to avoid having to
5892     // duplicate the immediate matching logic for the undef toggled case.
5893     bool SecondTry = false;
5894   AttemptModImm:
5895
5896     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5897       CnstBits = CnstBits.zextOrTrunc(64);
5898       uint64_t CnstVal = CnstBits.getZExtValue();
5899
5900       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5901         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5902         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5903         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5904                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5905                                   DAG.getConstant(0, dl, MVT::i32));
5906         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5907       }
5908
5909       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5910         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5911         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5912         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5913                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5914                                   DAG.getConstant(8, dl, MVT::i32));
5915         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5916       }
5917
5918       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5919         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5920         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5921         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5922                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5923                                   DAG.getConstant(16, dl, MVT::i32));
5924         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5925       }
5926
5927       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5928         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5929         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5930         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5931                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5932                                   DAG.getConstant(24, dl, MVT::i32));
5933         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5934       }
5935
5936       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5937         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5938         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5939         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5940                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5941                                   DAG.getConstant(0, dl, MVT::i32));
5942         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5943       }
5944
5945       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5946         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5947         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5948         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5949                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5950                                   DAG.getConstant(8, dl, MVT::i32));
5951         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5952       }
5953     }
5954
5955     if (SecondTry)
5956       goto FailedModImm;
5957     SecondTry = true;
5958     CnstBits = UndefBits;
5959     goto AttemptModImm;
5960   }
5961
5962 // We can always fall back to a non-immediate OR.
5963 FailedModImm:
5964   return Op;
5965 }
5966
5967 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5968 // be truncated to fit element width.
5969 static SDValue NormalizeBuildVector(SDValue Op,
5970                                     SelectionDAG &DAG) {
5971   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5972   SDLoc dl(Op);
5973   EVT VT = Op.getValueType();
5974   EVT EltTy= VT.getVectorElementType();
5975
5976   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5977     return Op;
5978
5979   SmallVector<SDValue, 16> Ops;
5980   for (SDValue Lane : Op->ops()) {
5981     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5982       APInt LowBits(EltTy.getSizeInBits(),
5983                     CstLane->getZExtValue());
5984       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5985     }
5986     Ops.push_back(Lane);
5987   }
5988   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5989 }
5990
5991 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5992                                                  SelectionDAG &DAG) const {
5993   SDLoc dl(Op);
5994   EVT VT = Op.getValueType();
5995   Op = NormalizeBuildVector(Op, DAG);
5996   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5997
5998   APInt CnstBits(VT.getSizeInBits(), 0);
5999   APInt UndefBits(VT.getSizeInBits(), 0);
6000   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6001     // We make use of a little bit of goto ickiness in order to avoid having to
6002     // duplicate the immediate matching logic for the undef toggled case.
6003     bool SecondTry = false;
6004   AttemptModImm:
6005
6006     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6007       CnstBits = CnstBits.zextOrTrunc(64);
6008       uint64_t CnstVal = CnstBits.getZExtValue();
6009
6010       // Certain magic vector constants (used to express things like NOT
6011       // and NEG) are passed through unmodified.  This allows codegen patterns
6012       // for these operations to match.  Special-purpose patterns will lower
6013       // these immediates to MOVIs if it proves necessary.
6014       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6015         return Op;
6016
6017       // The many faces of MOVI...
6018       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6019         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6020         if (VT.getSizeInBits() == 128) {
6021           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6022                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6023           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6024         }
6025
6026         // Support the V64 version via subregister insertion.
6027         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6028                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6029         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6030       }
6031
6032       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6033         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6034         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6035         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6036                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6037                                   DAG.getConstant(0, dl, MVT::i32));
6038         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6039       }
6040
6041       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6042         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6043         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6044         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6045                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6046                                   DAG.getConstant(8, dl, MVT::i32));
6047         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6048       }
6049
6050       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6051         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6052         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6053         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6054                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6055                                   DAG.getConstant(16, dl, MVT::i32));
6056         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6057       }
6058
6059       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6060         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6061         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6062         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6063                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6064                                   DAG.getConstant(24, dl, MVT::i32));
6065         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6066       }
6067
6068       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6069         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6070         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6071         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6072                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6073                                   DAG.getConstant(0, dl, MVT::i32));
6074         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6075       }
6076
6077       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6078         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6079         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6080         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6081                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6082                                   DAG.getConstant(8, dl, MVT::i32));
6083         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6084       }
6085
6086       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6087         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6088         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6089         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6090                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6091                                   DAG.getConstant(264, dl, MVT::i32));
6092         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6093       }
6094
6095       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6096         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6097         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6098         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6099                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6100                                   DAG.getConstant(272, dl, MVT::i32));
6101         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6102       }
6103
6104       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6105         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6106         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6107         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6108                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6109         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6110       }
6111
6112       // The few faces of FMOV...
6113       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6114         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6115         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6116         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6117                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6118         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6119       }
6120
6121       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6122           VT.getSizeInBits() == 128) {
6123         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6124         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6125                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6126         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6127       }
6128
6129       // The many faces of MVNI...
6130       CnstVal = ~CnstVal;
6131       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6132         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6133         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6134         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6135                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6136                                   DAG.getConstant(0, dl, MVT::i32));
6137         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6138       }
6139
6140       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6141         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6142         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6143         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6144                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6145                                   DAG.getConstant(8, dl, MVT::i32));
6146         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6147       }
6148
6149       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6150         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6151         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6152         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6153                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6154                                   DAG.getConstant(16, dl, MVT::i32));
6155         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6156       }
6157
6158       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6159         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6160         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6161         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6162                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6163                                   DAG.getConstant(24, dl, MVT::i32));
6164         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6165       }
6166
6167       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6168         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6169         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6170         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6171                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6172                                   DAG.getConstant(0, dl, MVT::i32));
6173         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6174       }
6175
6176       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6177         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6178         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6179         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6180                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6181                                   DAG.getConstant(8, dl, MVT::i32));
6182         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6183       }
6184
6185       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6186         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6187         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6188         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6189                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6190                                   DAG.getConstant(264, dl, MVT::i32));
6191         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6192       }
6193
6194       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6195         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6196         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6197         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6198                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6199                                   DAG.getConstant(272, dl, MVT::i32));
6200         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6201       }
6202     }
6203
6204     if (SecondTry)
6205       goto FailedModImm;
6206     SecondTry = true;
6207     CnstBits = UndefBits;
6208     goto AttemptModImm;
6209   }
6210 FailedModImm:
6211
6212   // Scan through the operands to find some interesting properties we can
6213   // exploit:
6214   //   1) If only one value is used, we can use a DUP, or
6215   //   2) if only the low element is not undef, we can just insert that, or
6216   //   3) if only one constant value is used (w/ some non-constant lanes),
6217   //      we can splat the constant value into the whole vector then fill
6218   //      in the non-constant lanes.
6219   //   4) FIXME: If different constant values are used, but we can intelligently
6220   //             select the values we'll be overwriting for the non-constant
6221   //             lanes such that we can directly materialize the vector
6222   //             some other way (MOVI, e.g.), we can be sneaky.
6223   unsigned NumElts = VT.getVectorNumElements();
6224   bool isOnlyLowElement = true;
6225   bool usesOnlyOneValue = true;
6226   bool usesOnlyOneConstantValue = true;
6227   bool isConstant = true;
6228   unsigned NumConstantLanes = 0;
6229   SDValue Value;
6230   SDValue ConstantValue;
6231   for (unsigned i = 0; i < NumElts; ++i) {
6232     SDValue V = Op.getOperand(i);
6233     if (V.getOpcode() == ISD::UNDEF)
6234       continue;
6235     if (i > 0)
6236       isOnlyLowElement = false;
6237     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6238       isConstant = false;
6239
6240     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6241       ++NumConstantLanes;
6242       if (!ConstantValue.getNode())
6243         ConstantValue = V;
6244       else if (ConstantValue != V)
6245         usesOnlyOneConstantValue = false;
6246     }
6247
6248     if (!Value.getNode())
6249       Value = V;
6250     else if (V != Value)
6251       usesOnlyOneValue = false;
6252   }
6253
6254   if (!Value.getNode())
6255     return DAG.getUNDEF(VT);
6256
6257   if (isOnlyLowElement)
6258     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6259
6260   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6261   // i32 and try again.
6262   if (usesOnlyOneValue) {
6263     if (!isConstant) {
6264       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6265           Value.getValueType() != VT)
6266         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6267
6268       // This is actually a DUPLANExx operation, which keeps everything vectory.
6269
6270       // DUPLANE works on 128-bit vectors, widen it if necessary.
6271       SDValue Lane = Value.getOperand(1);
6272       Value = Value.getOperand(0);
6273       if (Value.getValueType().getSizeInBits() == 64)
6274         Value = WidenVector(Value, DAG);
6275
6276       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6277       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6278     }
6279
6280     if (VT.getVectorElementType().isFloatingPoint()) {
6281       SmallVector<SDValue, 8> Ops;
6282       EVT EltTy = VT.getVectorElementType();
6283       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6284               "Unsupported floating-point vector type");
6285       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6286       for (unsigned i = 0; i < NumElts; ++i)
6287         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6288       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6289       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6290       Val = LowerBUILD_VECTOR(Val, DAG);
6291       if (Val.getNode())
6292         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6293     }
6294   }
6295
6296   // If there was only one constant value used and for more than one lane,
6297   // start by splatting that value, then replace the non-constant lanes. This
6298   // is better than the default, which will perform a separate initialization
6299   // for each lane.
6300   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6301     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6302     // Now insert the non-constant lanes.
6303     for (unsigned i = 0; i < NumElts; ++i) {
6304       SDValue V = Op.getOperand(i);
6305       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6306       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6307         // Note that type legalization likely mucked about with the VT of the
6308         // source operand, so we may have to convert it here before inserting.
6309         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6310       }
6311     }
6312     return Val;
6313   }
6314
6315   // If all elements are constants and the case above didn't get hit, fall back
6316   // to the default expansion, which will generate a load from the constant
6317   // pool.
6318   if (isConstant)
6319     return SDValue();
6320
6321   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6322   if (NumElts >= 4) {
6323     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6324       return shuffle;
6325   }
6326
6327   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6328   // know the default expansion would otherwise fall back on something even
6329   // worse. For a vector with one or two non-undef values, that's
6330   // scalar_to_vector for the elements followed by a shuffle (provided the
6331   // shuffle is valid for the target) and materialization element by element
6332   // on the stack followed by a load for everything else.
6333   if (!isConstant && !usesOnlyOneValue) {
6334     SDValue Vec = DAG.getUNDEF(VT);
6335     SDValue Op0 = Op.getOperand(0);
6336     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6337     unsigned i = 0;
6338     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6339     // a) Avoid a RMW dependency on the full vector register, and
6340     // b) Allow the register coalescer to fold away the copy if the
6341     //    value is already in an S or D register.
6342     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6343     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6344     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6345         (ElemSize == 32 || ElemSize == 64)) {
6346       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6347       MachineSDNode *N =
6348           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6349                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6350       Vec = SDValue(N, 0);
6351       ++i;
6352     }
6353     for (; i < NumElts; ++i) {
6354       SDValue V = Op.getOperand(i);
6355       if (V.getOpcode() == ISD::UNDEF)
6356         continue;
6357       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6358       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6359     }
6360     return Vec;
6361   }
6362
6363   // Just use the default expansion. We failed to find a better alternative.
6364   return SDValue();
6365 }
6366
6367 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6368                                                       SelectionDAG &DAG) const {
6369   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6370
6371   // Check for non-constant or out of range lane.
6372   EVT VT = Op.getOperand(0).getValueType();
6373   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6374   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6375     return SDValue();
6376
6377
6378   // Insertion/extraction are legal for V128 types.
6379   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6380       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6381       VT == MVT::v8f16)
6382     return Op;
6383
6384   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6385       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6386     return SDValue();
6387
6388   // For V64 types, we perform insertion by expanding the value
6389   // to a V128 type and perform the insertion on that.
6390   SDLoc DL(Op);
6391   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6392   EVT WideTy = WideVec.getValueType();
6393
6394   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6395                              Op.getOperand(1), Op.getOperand(2));
6396   // Re-narrow the resultant vector.
6397   return NarrowVector(Node, DAG);
6398 }
6399
6400 SDValue
6401 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6402                                                SelectionDAG &DAG) const {
6403   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6404
6405   // Check for non-constant or out of range lane.
6406   EVT VT = Op.getOperand(0).getValueType();
6407   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6408   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6409     return SDValue();
6410
6411
6412   // Insertion/extraction are legal for V128 types.
6413   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6414       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6415       VT == MVT::v8f16)
6416     return Op;
6417
6418   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6419       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6420     return SDValue();
6421
6422   // For V64 types, we perform extraction by expanding the value
6423   // to a V128 type and perform the extraction on that.
6424   SDLoc DL(Op);
6425   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6426   EVT WideTy = WideVec.getValueType();
6427
6428   EVT ExtrTy = WideTy.getVectorElementType();
6429   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6430     ExtrTy = MVT::i32;
6431
6432   // For extractions, we just return the result directly.
6433   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6434                      Op.getOperand(1));
6435 }
6436
6437 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6438                                                       SelectionDAG &DAG) const {
6439   EVT VT = Op.getOperand(0).getValueType();
6440   SDLoc dl(Op);
6441   // Just in case...
6442   if (!VT.isVector())
6443     return SDValue();
6444
6445   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6446   if (!Cst)
6447     return SDValue();
6448   unsigned Val = Cst->getZExtValue();
6449
6450   unsigned Size = Op.getValueType().getSizeInBits();
6451
6452   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6453   if (Val == 0)
6454     return Op;
6455
6456   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6457   // that directly.
6458   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6459     return Op;
6460
6461   return SDValue();
6462 }
6463
6464 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6465                                                EVT VT) const {
6466   if (VT.getVectorNumElements() == 4 &&
6467       (VT.is128BitVector() || VT.is64BitVector())) {
6468     unsigned PFIndexes[4];
6469     for (unsigned i = 0; i != 4; ++i) {
6470       if (M[i] < 0)
6471         PFIndexes[i] = 8;
6472       else
6473         PFIndexes[i] = M[i];
6474     }
6475
6476     // Compute the index in the perfect shuffle table.
6477     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6478                             PFIndexes[2] * 9 + PFIndexes[3];
6479     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6480     unsigned Cost = (PFEntry >> 30);
6481
6482     if (Cost <= 4)
6483       return true;
6484   }
6485
6486   bool DummyBool;
6487   int DummyInt;
6488   unsigned DummyUnsigned;
6489
6490   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6491           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6492           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6493           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6494           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6495           isZIPMask(M, VT, DummyUnsigned) ||
6496           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6497           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6498           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6499           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6500           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6501 }
6502
6503 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6504 /// operand of a vector shift operation, where all the elements of the
6505 /// build_vector must have the same constant integer value.
6506 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6507   // Ignore bit_converts.
6508   while (Op.getOpcode() == ISD::BITCAST)
6509     Op = Op.getOperand(0);
6510   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6511   APInt SplatBits, SplatUndef;
6512   unsigned SplatBitSize;
6513   bool HasAnyUndefs;
6514   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6515                                     HasAnyUndefs, ElementBits) ||
6516       SplatBitSize > ElementBits)
6517     return false;
6518   Cnt = SplatBits.getSExtValue();
6519   return true;
6520 }
6521
6522 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6523 /// operand of a vector shift left operation.  That value must be in the range:
6524 ///   0 <= Value < ElementBits for a left shift; or
6525 ///   0 <= Value <= ElementBits for a long left shift.
6526 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6527   assert(VT.isVector() && "vector shift count is not a vector type");
6528   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6529   if (!getVShiftImm(Op, ElementBits, Cnt))
6530     return false;
6531   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6532 }
6533
6534 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6535 /// operand of a vector shift right operation. The value must be in the range:
6536 ///   1 <= Value <= ElementBits for a right shift; or
6537 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6538   assert(VT.isVector() && "vector shift count is not a vector type");
6539   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6540   if (!getVShiftImm(Op, ElementBits, Cnt))
6541     return false;
6542   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6543 }
6544
6545 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6546                                                       SelectionDAG &DAG) const {
6547   EVT VT = Op.getValueType();
6548   SDLoc DL(Op);
6549   int64_t Cnt;
6550
6551   if (!Op.getOperand(1).getValueType().isVector())
6552     return Op;
6553   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6554
6555   switch (Op.getOpcode()) {
6556   default:
6557     llvm_unreachable("unexpected shift opcode");
6558
6559   case ISD::SHL:
6560     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6561       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6562                          DAG.getConstant(Cnt, DL, MVT::i32));
6563     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6564                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6565                                        MVT::i32),
6566                        Op.getOperand(0), Op.getOperand(1));
6567   case ISD::SRA:
6568   case ISD::SRL:
6569     // Right shift immediate
6570     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6571       unsigned Opc =
6572           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6573       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6574                          DAG.getConstant(Cnt, DL, MVT::i32));
6575     }
6576
6577     // Right shift register.  Note, there is not a shift right register
6578     // instruction, but the shift left register instruction takes a signed
6579     // value, where negative numbers specify a right shift.
6580     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6581                                                 : Intrinsic::aarch64_neon_ushl;
6582     // negate the shift amount
6583     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6584     SDValue NegShiftLeft =
6585         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6586                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6587                     NegShift);
6588     return NegShiftLeft;
6589   }
6590
6591   return SDValue();
6592 }
6593
6594 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6595                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6596                                     SDLoc dl, SelectionDAG &DAG) {
6597   EVT SrcVT = LHS.getValueType();
6598   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6599          "function only supposed to emit natural comparisons");
6600
6601   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6602   APInt CnstBits(VT.getSizeInBits(), 0);
6603   APInt UndefBits(VT.getSizeInBits(), 0);
6604   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6605   bool IsZero = IsCnst && (CnstBits == 0);
6606
6607   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6608     switch (CC) {
6609     default:
6610       return SDValue();
6611     case AArch64CC::NE: {
6612       SDValue Fcmeq;
6613       if (IsZero)
6614         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6615       else
6616         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6617       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6618     }
6619     case AArch64CC::EQ:
6620       if (IsZero)
6621         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6622       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6623     case AArch64CC::GE:
6624       if (IsZero)
6625         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6626       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6627     case AArch64CC::GT:
6628       if (IsZero)
6629         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6630       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6631     case AArch64CC::LS:
6632       if (IsZero)
6633         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6634       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6635     case AArch64CC::LT:
6636       if (!NoNans)
6637         return SDValue();
6638     // If we ignore NaNs then we can use to the MI implementation.
6639     // Fallthrough.
6640     case AArch64CC::MI:
6641       if (IsZero)
6642         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6643       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6644     }
6645   }
6646
6647   switch (CC) {
6648   default:
6649     return SDValue();
6650   case AArch64CC::NE: {
6651     SDValue Cmeq;
6652     if (IsZero)
6653       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6654     else
6655       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6656     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6657   }
6658   case AArch64CC::EQ:
6659     if (IsZero)
6660       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6661     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6662   case AArch64CC::GE:
6663     if (IsZero)
6664       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6665     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6666   case AArch64CC::GT:
6667     if (IsZero)
6668       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6669     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6670   case AArch64CC::LE:
6671     if (IsZero)
6672       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6673     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6674   case AArch64CC::LS:
6675     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6676   case AArch64CC::LO:
6677     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6678   case AArch64CC::LT:
6679     if (IsZero)
6680       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6681     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6682   case AArch64CC::HI:
6683     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6684   case AArch64CC::HS:
6685     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6686   }
6687 }
6688
6689 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6690                                            SelectionDAG &DAG) const {
6691   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6692   SDValue LHS = Op.getOperand(0);
6693   SDValue RHS = Op.getOperand(1);
6694   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6695   SDLoc dl(Op);
6696
6697   if (LHS.getValueType().getVectorElementType().isInteger()) {
6698     assert(LHS.getValueType() == RHS.getValueType());
6699     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6700     SDValue Cmp =
6701         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6702     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6703   }
6704
6705   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6706     return SDValue();
6707
6708   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6709          LHS.getValueType().getVectorElementType() == MVT::f64);
6710
6711   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6712   // clean.  Some of them require two branches to implement.
6713   AArch64CC::CondCode CC1, CC2;
6714   bool ShouldInvert;
6715   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6716
6717   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6718   SDValue Cmp =
6719       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6720   if (!Cmp.getNode())
6721     return SDValue();
6722
6723   if (CC2 != AArch64CC::AL) {
6724     SDValue Cmp2 =
6725         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6726     if (!Cmp2.getNode())
6727       return SDValue();
6728
6729     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6730   }
6731
6732   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6733
6734   if (ShouldInvert)
6735     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6736
6737   return Cmp;
6738 }
6739
6740 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6741 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6742 /// specified in the intrinsic calls.
6743 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6744                                                const CallInst &I,
6745                                                unsigned Intrinsic) const {
6746   auto &DL = I.getModule()->getDataLayout();
6747   switch (Intrinsic) {
6748   case Intrinsic::aarch64_neon_ld2:
6749   case Intrinsic::aarch64_neon_ld3:
6750   case Intrinsic::aarch64_neon_ld4:
6751   case Intrinsic::aarch64_neon_ld1x2:
6752   case Intrinsic::aarch64_neon_ld1x3:
6753   case Intrinsic::aarch64_neon_ld1x4:
6754   case Intrinsic::aarch64_neon_ld2lane:
6755   case Intrinsic::aarch64_neon_ld3lane:
6756   case Intrinsic::aarch64_neon_ld4lane:
6757   case Intrinsic::aarch64_neon_ld2r:
6758   case Intrinsic::aarch64_neon_ld3r:
6759   case Intrinsic::aarch64_neon_ld4r: {
6760     Info.opc = ISD::INTRINSIC_W_CHAIN;
6761     // Conservatively set memVT to the entire set of vectors loaded.
6762     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6763     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6764     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6765     Info.offset = 0;
6766     Info.align = 0;
6767     Info.vol = false; // volatile loads with NEON intrinsics not supported
6768     Info.readMem = true;
6769     Info.writeMem = false;
6770     return true;
6771   }
6772   case Intrinsic::aarch64_neon_st2:
6773   case Intrinsic::aarch64_neon_st3:
6774   case Intrinsic::aarch64_neon_st4:
6775   case Intrinsic::aarch64_neon_st1x2:
6776   case Intrinsic::aarch64_neon_st1x3:
6777   case Intrinsic::aarch64_neon_st1x4:
6778   case Intrinsic::aarch64_neon_st2lane:
6779   case Intrinsic::aarch64_neon_st3lane:
6780   case Intrinsic::aarch64_neon_st4lane: {
6781     Info.opc = ISD::INTRINSIC_VOID;
6782     // Conservatively set memVT to the entire set of vectors stored.
6783     unsigned NumElts = 0;
6784     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6785       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6786       if (!ArgTy->isVectorTy())
6787         break;
6788       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6789     }
6790     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6791     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6792     Info.offset = 0;
6793     Info.align = 0;
6794     Info.vol = false; // volatile stores with NEON intrinsics not supported
6795     Info.readMem = false;
6796     Info.writeMem = true;
6797     return true;
6798   }
6799   case Intrinsic::aarch64_ldaxr:
6800   case Intrinsic::aarch64_ldxr: {
6801     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6802     Info.opc = ISD::INTRINSIC_W_CHAIN;
6803     Info.memVT = MVT::getVT(PtrTy->getElementType());
6804     Info.ptrVal = I.getArgOperand(0);
6805     Info.offset = 0;
6806     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6807     Info.vol = true;
6808     Info.readMem = true;
6809     Info.writeMem = false;
6810     return true;
6811   }
6812   case Intrinsic::aarch64_stlxr:
6813   case Intrinsic::aarch64_stxr: {
6814     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6815     Info.opc = ISD::INTRINSIC_W_CHAIN;
6816     Info.memVT = MVT::getVT(PtrTy->getElementType());
6817     Info.ptrVal = I.getArgOperand(1);
6818     Info.offset = 0;
6819     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6820     Info.vol = true;
6821     Info.readMem = false;
6822     Info.writeMem = true;
6823     return true;
6824   }
6825   case Intrinsic::aarch64_ldaxp:
6826   case Intrinsic::aarch64_ldxp: {
6827     Info.opc = ISD::INTRINSIC_W_CHAIN;
6828     Info.memVT = MVT::i128;
6829     Info.ptrVal = I.getArgOperand(0);
6830     Info.offset = 0;
6831     Info.align = 16;
6832     Info.vol = true;
6833     Info.readMem = true;
6834     Info.writeMem = false;
6835     return true;
6836   }
6837   case Intrinsic::aarch64_stlxp:
6838   case Intrinsic::aarch64_stxp: {
6839     Info.opc = ISD::INTRINSIC_W_CHAIN;
6840     Info.memVT = MVT::i128;
6841     Info.ptrVal = I.getArgOperand(2);
6842     Info.offset = 0;
6843     Info.align = 16;
6844     Info.vol = true;
6845     Info.readMem = false;
6846     Info.writeMem = true;
6847     return true;
6848   }
6849   default:
6850     break;
6851   }
6852
6853   return false;
6854 }
6855
6856 // Truncations from 64-bit GPR to 32-bit GPR is free.
6857 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6858   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6859     return false;
6860   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6861   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6862   return NumBits1 > NumBits2;
6863 }
6864 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6865   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6866     return false;
6867   unsigned NumBits1 = VT1.getSizeInBits();
6868   unsigned NumBits2 = VT2.getSizeInBits();
6869   return NumBits1 > NumBits2;
6870 }
6871
6872 /// Check if it is profitable to hoist instruction in then/else to if.
6873 /// Not profitable if I and it's user can form a FMA instruction
6874 /// because we prefer FMSUB/FMADD.
6875 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6876   if (I->getOpcode() != Instruction::FMul)
6877     return true;
6878
6879   if (I->getNumUses() != 1)
6880     return true;
6881
6882   Instruction *User = I->user_back();
6883
6884   if (User &&
6885       !(User->getOpcode() == Instruction::FSub ||
6886         User->getOpcode() == Instruction::FAdd))
6887     return true;
6888
6889   const TargetOptions &Options = getTargetMachine().Options;
6890   const DataLayout &DL = I->getModule()->getDataLayout();
6891   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6892
6893   if (isFMAFasterThanFMulAndFAdd(VT) &&
6894       isOperationLegalOrCustom(ISD::FMA, VT) &&
6895       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6896     return false;
6897
6898   return true;
6899 }
6900
6901 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6902 // 64-bit GPR.
6903 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6904   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6905     return false;
6906   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6907   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6908   return NumBits1 == 32 && NumBits2 == 64;
6909 }
6910 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6911   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6912     return false;
6913   unsigned NumBits1 = VT1.getSizeInBits();
6914   unsigned NumBits2 = VT2.getSizeInBits();
6915   return NumBits1 == 32 && NumBits2 == 64;
6916 }
6917
6918 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6919   EVT VT1 = Val.getValueType();
6920   if (isZExtFree(VT1, VT2)) {
6921     return true;
6922   }
6923
6924   if (Val.getOpcode() != ISD::LOAD)
6925     return false;
6926
6927   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6928   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6929           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6930           VT1.getSizeInBits() <= 32);
6931 }
6932
6933 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6934   if (isa<FPExtInst>(Ext))
6935     return false;
6936
6937   // Vector types are next free.
6938   if (Ext->getType()->isVectorTy())
6939     return false;
6940
6941   for (const Use &U : Ext->uses()) {
6942     // The extension is free if we can fold it with a left shift in an
6943     // addressing mode or an arithmetic operation: add, sub, and cmp.
6944
6945     // Is there a shift?
6946     const Instruction *Instr = cast<Instruction>(U.getUser());
6947
6948     // Is this a constant shift?
6949     switch (Instr->getOpcode()) {
6950     case Instruction::Shl:
6951       if (!isa<ConstantInt>(Instr->getOperand(1)))
6952         return false;
6953       break;
6954     case Instruction::GetElementPtr: {
6955       gep_type_iterator GTI = gep_type_begin(Instr);
6956       auto &DL = Ext->getModule()->getDataLayout();
6957       std::advance(GTI, U.getOperandNo());
6958       Type *IdxTy = *GTI;
6959       // This extension will end up with a shift because of the scaling factor.
6960       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6961       // Get the shift amount based on the scaling factor:
6962       // log2(sizeof(IdxTy)) - log2(8).
6963       uint64_t ShiftAmt =
6964           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6965       // Is the constant foldable in the shift of the addressing mode?
6966       // I.e., shift amount is between 1 and 4 inclusive.
6967       if (ShiftAmt == 0 || ShiftAmt > 4)
6968         return false;
6969       break;
6970     }
6971     case Instruction::Trunc:
6972       // Check if this is a noop.
6973       // trunc(sext ty1 to ty2) to ty1.
6974       if (Instr->getType() == Ext->getOperand(0)->getType())
6975         continue;
6976     // FALL THROUGH.
6977     default:
6978       return false;
6979     }
6980
6981     // At this point we can use the bfm family, so this extension is free
6982     // for that use.
6983   }
6984   return true;
6985 }
6986
6987 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6988                                           unsigned &RequiredAligment) const {
6989   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6990     return false;
6991   // Cyclone supports unaligned accesses.
6992   RequiredAligment = 0;
6993   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6994   return NumBits == 32 || NumBits == 64;
6995 }
6996
6997 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6998                                           unsigned &RequiredAligment) const {
6999   if (!LoadedType.isSimple() ||
7000       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7001     return false;
7002   // Cyclone supports unaligned accesses.
7003   RequiredAligment = 0;
7004   unsigned NumBits = LoadedType.getSizeInBits();
7005   return NumBits == 32 || NumBits == 64;
7006 }
7007
7008 /// \brief Lower an interleaved load into a ldN intrinsic.
7009 ///
7010 /// E.g. Lower an interleaved load (Factor = 2):
7011 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7012 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7013 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7014 ///
7015 ///      Into:
7016 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7017 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7018 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7019 bool AArch64TargetLowering::lowerInterleavedLoad(
7020     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7021     ArrayRef<unsigned> Indices, unsigned Factor) const {
7022   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7023          "Invalid interleave factor");
7024   assert(!Shuffles.empty() && "Empty shufflevector input");
7025   assert(Shuffles.size() == Indices.size() &&
7026          "Unmatched number of shufflevectors and indices");
7027
7028   const DataLayout &DL = LI->getModule()->getDataLayout();
7029
7030   VectorType *VecTy = Shuffles[0]->getType();
7031   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7032
7033   // Skip if we do not have NEON and skip illegal vector types.
7034   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7035     return false;
7036
7037   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7038   // load integer vectors first and then convert to pointer vectors.
7039   Type *EltTy = VecTy->getVectorElementType();
7040   if (EltTy->isPointerTy())
7041     VecTy =
7042         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7043
7044   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7045   Type *Tys[2] = {VecTy, PtrTy};
7046   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7047                                             Intrinsic::aarch64_neon_ld3,
7048                                             Intrinsic::aarch64_neon_ld4};
7049   Function *LdNFunc =
7050       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7051
7052   IRBuilder<> Builder(LI);
7053   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7054
7055   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7056
7057   // Replace uses of each shufflevector with the corresponding vector loaded
7058   // by ldN.
7059   for (unsigned i = 0; i < Shuffles.size(); i++) {
7060     ShuffleVectorInst *SVI = Shuffles[i];
7061     unsigned Index = Indices[i];
7062
7063     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7064
7065     // Convert the integer vector to pointer vector if the element is pointer.
7066     if (EltTy->isPointerTy())
7067       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7068
7069     SVI->replaceAllUsesWith(SubVec);
7070   }
7071
7072   return true;
7073 }
7074
7075 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7076 ///
7077 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7078 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7079                                    unsigned NumElts) {
7080   SmallVector<Constant *, 16> Mask;
7081   for (unsigned i = 0; i < NumElts; i++)
7082     Mask.push_back(Builder.getInt32(Start + i));
7083
7084   return ConstantVector::get(Mask);
7085 }
7086
7087 /// \brief Lower an interleaved store into a stN intrinsic.
7088 ///
7089 /// E.g. Lower an interleaved store (Factor = 3):
7090 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7091 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7092 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7093 ///
7094 ///      Into:
7095 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7096 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7097 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7098 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7099 ///
7100 /// Note that the new shufflevectors will be removed and we'll only generate one
7101 /// st3 instruction in CodeGen.
7102 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7103                                                   ShuffleVectorInst *SVI,
7104                                                   unsigned Factor) const {
7105   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7106          "Invalid interleave factor");
7107
7108   VectorType *VecTy = SVI->getType();
7109   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7110          "Invalid interleaved store");
7111
7112   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7113   Type *EltTy = VecTy->getVectorElementType();
7114   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7115
7116   const DataLayout &DL = SI->getModule()->getDataLayout();
7117   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7118
7119   // Skip if we do not have NEON and skip illegal vector types.
7120   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7121     return false;
7122
7123   Value *Op0 = SVI->getOperand(0);
7124   Value *Op1 = SVI->getOperand(1);
7125   IRBuilder<> Builder(SI);
7126
7127   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7128   // vectors to integer vectors.
7129   if (EltTy->isPointerTy()) {
7130     Type *IntTy = DL.getIntPtrType(EltTy);
7131     unsigned NumOpElts =
7132         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7133
7134     // Convert to the corresponding integer vector.
7135     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7136     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7137     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7138
7139     SubVecTy = VectorType::get(IntTy, NumSubElts);
7140   }
7141
7142   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7143   Type *Tys[2] = {SubVecTy, PtrTy};
7144   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7145                                              Intrinsic::aarch64_neon_st3,
7146                                              Intrinsic::aarch64_neon_st4};
7147   Function *StNFunc =
7148       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7149
7150   SmallVector<Value *, 5> Ops;
7151
7152   // Split the shufflevector operands into sub vectors for the new stN call.
7153   for (unsigned i = 0; i < Factor; i++)
7154     Ops.push_back(Builder.CreateShuffleVector(
7155         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7156
7157   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7158   Builder.CreateCall(StNFunc, Ops);
7159   return true;
7160 }
7161
7162 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7163                        unsigned AlignCheck) {
7164   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7165           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7166 }
7167
7168 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7169                                                unsigned SrcAlign, bool IsMemset,
7170                                                bool ZeroMemset,
7171                                                bool MemcpyStrSrc,
7172                                                MachineFunction &MF) const {
7173   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7174   // instruction to materialize the v2i64 zero and one store (with restrictive
7175   // addressing mode). Just do two i64 store of zero-registers.
7176   bool Fast;
7177   const Function *F = MF.getFunction();
7178   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7179       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7180       (memOpAlign(SrcAlign, DstAlign, 16) ||
7181        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7182     return MVT::f128;
7183
7184   if (Size >= 8 &&
7185       (memOpAlign(SrcAlign, DstAlign, 8) ||
7186        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7187     return MVT::i64;
7188
7189   if (Size >= 4 &&
7190       (memOpAlign(SrcAlign, DstAlign, 4) ||
7191        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7192     return MVT::i32;
7193
7194   return MVT::Other;
7195 }
7196
7197 // 12-bit optionally shifted immediates are legal for adds.
7198 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7199   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7200     return true;
7201   return false;
7202 }
7203
7204 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7205 // immediates is the same as for an add or a sub.
7206 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7207   if (Immed < 0)
7208     Immed *= -1;
7209   return isLegalAddImmediate(Immed);
7210 }
7211
7212 /// isLegalAddressingMode - Return true if the addressing mode represented
7213 /// by AM is legal for this target, for a load/store of the specified type.
7214 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7215                                                   const AddrMode &AM, Type *Ty,
7216                                                   unsigned AS) const {
7217   // AArch64 has five basic addressing modes:
7218   //  reg
7219   //  reg + 9-bit signed offset
7220   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7221   //  reg1 + reg2
7222   //  reg + SIZE_IN_BYTES * reg
7223
7224   // No global is ever allowed as a base.
7225   if (AM.BaseGV)
7226     return false;
7227
7228   // No reg+reg+imm addressing.
7229   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7230     return false;
7231
7232   // check reg + imm case:
7233   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7234   uint64_t NumBytes = 0;
7235   if (Ty->isSized()) {
7236     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7237     NumBytes = NumBits / 8;
7238     if (!isPowerOf2_64(NumBits))
7239       NumBytes = 0;
7240   }
7241
7242   if (!AM.Scale) {
7243     int64_t Offset = AM.BaseOffs;
7244
7245     // 9-bit signed offset
7246     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7247       return true;
7248
7249     // 12-bit unsigned offset
7250     unsigned shift = Log2_64(NumBytes);
7251     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7252         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7253         (Offset >> shift) << shift == Offset)
7254       return true;
7255     return false;
7256   }
7257
7258   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7259
7260   if (!AM.Scale || AM.Scale == 1 ||
7261       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7262     return true;
7263   return false;
7264 }
7265
7266 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7267                                                 const AddrMode &AM, Type *Ty,
7268                                                 unsigned AS) const {
7269   // Scaling factors are not free at all.
7270   // Operands                     | Rt Latency
7271   // -------------------------------------------
7272   // Rt, [Xn, Xm]                 | 4
7273   // -------------------------------------------
7274   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7275   // Rt, [Xn, Wm, <extend> #imm]  |
7276   if (isLegalAddressingMode(DL, AM, Ty, AS))
7277     // Scale represents reg2 * scale, thus account for 1 if
7278     // it is not equal to 0 or 1.
7279     return AM.Scale != 0 && AM.Scale != 1;
7280   return -1;
7281 }
7282
7283 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7284   VT = VT.getScalarType();
7285
7286   if (!VT.isSimple())
7287     return false;
7288
7289   switch (VT.getSimpleVT().SimpleTy) {
7290   case MVT::f32:
7291   case MVT::f64:
7292     return true;
7293   default:
7294     break;
7295   }
7296
7297   return false;
7298 }
7299
7300 const MCPhysReg *
7301 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7302   // LR is a callee-save register, but we must treat it as clobbered by any call
7303   // site. Hence we include LR in the scratch registers, which are in turn added
7304   // as implicit-defs for stackmaps and patchpoints.
7305   static const MCPhysReg ScratchRegs[] = {
7306     AArch64::X16, AArch64::X17, AArch64::LR, 0
7307   };
7308   return ScratchRegs;
7309 }
7310
7311 bool
7312 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7313   EVT VT = N->getValueType(0);
7314     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7315     // it with shift to let it be lowered to UBFX.
7316   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7317       isa<ConstantSDNode>(N->getOperand(1))) {
7318     uint64_t TruncMask = N->getConstantOperandVal(1);
7319     if (isMask_64(TruncMask) &&
7320       N->getOperand(0).getOpcode() == ISD::SRL &&
7321       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7322       return false;
7323   }
7324   return true;
7325 }
7326
7327 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7328                                                               Type *Ty) const {
7329   assert(Ty->isIntegerTy());
7330
7331   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7332   if (BitSize == 0)
7333     return false;
7334
7335   int64_t Val = Imm.getSExtValue();
7336   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7337     return true;
7338
7339   if ((int64_t)Val < 0)
7340     Val = ~Val;
7341   if (BitSize == 32)
7342     Val &= (1LL << 32) - 1;
7343
7344   unsigned LZ = countLeadingZeros((uint64_t)Val);
7345   unsigned Shift = (63 - LZ) / 16;
7346   // MOVZ is free so return true for one or fewer MOVK.
7347   return Shift < 3;
7348 }
7349
7350 // Generate SUBS and CSEL for integer abs.
7351 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7352   EVT VT = N->getValueType(0);
7353
7354   SDValue N0 = N->getOperand(0);
7355   SDValue N1 = N->getOperand(1);
7356   SDLoc DL(N);
7357
7358   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7359   // and change it to SUB and CSEL.
7360   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7361       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7362       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7363     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7364       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7365         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7366                                   N0.getOperand(0));
7367         // Generate SUBS & CSEL.
7368         SDValue Cmp =
7369             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7370                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7371         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7372                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7373                            SDValue(Cmp.getNode(), 1));
7374       }
7375   return SDValue();
7376 }
7377
7378 // performXorCombine - Attempts to handle integer ABS.
7379 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7380                                  TargetLowering::DAGCombinerInfo &DCI,
7381                                  const AArch64Subtarget *Subtarget) {
7382   if (DCI.isBeforeLegalizeOps())
7383     return SDValue();
7384
7385   return performIntegerAbsCombine(N, DAG);
7386 }
7387
7388 SDValue
7389 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7390                                      SelectionDAG &DAG,
7391                                      std::vector<SDNode *> *Created) const {
7392   // fold (sdiv X, pow2)
7393   EVT VT = N->getValueType(0);
7394   if ((VT != MVT::i32 && VT != MVT::i64) ||
7395       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7396     return SDValue();
7397
7398   SDLoc DL(N);
7399   SDValue N0 = N->getOperand(0);
7400   unsigned Lg2 = Divisor.countTrailingZeros();
7401   SDValue Zero = DAG.getConstant(0, DL, VT);
7402   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7403
7404   // Add (N0 < 0) ? Pow2 - 1 : 0;
7405   SDValue CCVal;
7406   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7407   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7408   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7409
7410   if (Created) {
7411     Created->push_back(Cmp.getNode());
7412     Created->push_back(Add.getNode());
7413     Created->push_back(CSel.getNode());
7414   }
7415
7416   // Divide by pow2.
7417   SDValue SRA =
7418       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7419
7420   // If we're dividing by a positive value, we're done.  Otherwise, we must
7421   // negate the result.
7422   if (Divisor.isNonNegative())
7423     return SRA;
7424
7425   if (Created)
7426     Created->push_back(SRA.getNode());
7427   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7428 }
7429
7430 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7431                                  TargetLowering::DAGCombinerInfo &DCI,
7432                                  const AArch64Subtarget *Subtarget) {
7433   if (DCI.isBeforeLegalizeOps())
7434     return SDValue();
7435
7436   // Multiplication of a power of two plus/minus one can be done more
7437   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7438   // future CPUs have a cheaper MADD instruction, this may need to be
7439   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7440   // 64-bit is 5 cycles, so this is always a win.
7441   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7442     APInt Value = C->getAPIntValue();
7443     EVT VT = N->getValueType(0);
7444     SDLoc DL(N);
7445     if (Value.isNonNegative()) {
7446       // (mul x, 2^N + 1) => (add (shl x, N), x)
7447       APInt VM1 = Value - 1;
7448       if (VM1.isPowerOf2()) {
7449         SDValue ShiftedVal =
7450             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7451                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7452         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7453                            N->getOperand(0));
7454       }
7455       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7456       APInt VP1 = Value + 1;
7457       if (VP1.isPowerOf2()) {
7458         SDValue ShiftedVal =
7459             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7460                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7461         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7462                            N->getOperand(0));
7463       }
7464     } else {
7465       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7466       APInt VNP1 = -Value + 1;
7467       if (VNP1.isPowerOf2()) {
7468         SDValue ShiftedVal =
7469             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7470                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7471         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7472                            ShiftedVal);
7473       }
7474       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7475       APInt VNM1 = -Value - 1;
7476       if (VNM1.isPowerOf2()) {
7477         SDValue ShiftedVal =
7478             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7479                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7480         SDValue Add =
7481             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7482         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7483       }
7484     }
7485   }
7486   return SDValue();
7487 }
7488
7489 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7490                                                          SelectionDAG &DAG) {
7491   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7492   // optimize away operation when it's from a constant.
7493   //
7494   // The general transformation is:
7495   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7496   //       AND(VECTOR_CMP(x,y), constant2)
7497   //    constant2 = UNARYOP(constant)
7498
7499   // Early exit if this isn't a vector operation, the operand of the
7500   // unary operation isn't a bitwise AND, or if the sizes of the operations
7501   // aren't the same.
7502   EVT VT = N->getValueType(0);
7503   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7504       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7505       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7506     return SDValue();
7507
7508   // Now check that the other operand of the AND is a constant. We could
7509   // make the transformation for non-constant splats as well, but it's unclear
7510   // that would be a benefit as it would not eliminate any operations, just
7511   // perform one more step in scalar code before moving to the vector unit.
7512   if (BuildVectorSDNode *BV =
7513           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7514     // Bail out if the vector isn't a constant.
7515     if (!BV->isConstant())
7516       return SDValue();
7517
7518     // Everything checks out. Build up the new and improved node.
7519     SDLoc DL(N);
7520     EVT IntVT = BV->getValueType(0);
7521     // Create a new constant of the appropriate type for the transformed
7522     // DAG.
7523     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7524     // The AND node needs bitcasts to/from an integer vector type around it.
7525     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7526     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7527                                  N->getOperand(0)->getOperand(0), MaskConst);
7528     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7529     return Res;
7530   }
7531
7532   return SDValue();
7533 }
7534
7535 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7536                                      const AArch64Subtarget *Subtarget) {
7537   // First try to optimize away the conversion when it's conditionally from
7538   // a constant. Vectors only.
7539   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7540     return Res;
7541
7542   EVT VT = N->getValueType(0);
7543   if (VT != MVT::f32 && VT != MVT::f64)
7544     return SDValue();
7545
7546   // Only optimize when the source and destination types have the same width.
7547   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7548     return SDValue();
7549
7550   // If the result of an integer load is only used by an integer-to-float
7551   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7552   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7553   SDValue N0 = N->getOperand(0);
7554   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7555       // Do not change the width of a volatile load.
7556       !cast<LoadSDNode>(N0)->isVolatile()) {
7557     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7558     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7559                                LN0->getPointerInfo(), LN0->isVolatile(),
7560                                LN0->isNonTemporal(), LN0->isInvariant(),
7561                                LN0->getAlignment());
7562
7563     // Make sure successors of the original load stay after it by updating them
7564     // to use the new Chain.
7565     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7566
7567     unsigned Opcode =
7568         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7569     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7570   }
7571
7572   return SDValue();
7573 }
7574
7575 /// Fold a floating-point multiply by power of two into floating-point to
7576 /// fixed-point conversion.
7577 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7578                                      TargetLowering::DAGCombinerInfo &DCI,
7579                                      const AArch64Subtarget *Subtarget) {
7580   if (!Subtarget->hasNEON())
7581     return SDValue();
7582
7583   SDValue Op = N->getOperand(0);
7584   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7585       Op.getOpcode() != ISD::FMUL)
7586     return SDValue();
7587
7588   SDValue ConstVec = Op->getOperand(1);
7589   if (!isa<BuildVectorSDNode>(ConstVec))
7590     return SDValue();
7591
7592   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7593   uint32_t FloatBits = FloatTy.getSizeInBits();
7594   if (FloatBits != 32 && FloatBits != 64)
7595     return SDValue();
7596
7597   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7598   uint32_t IntBits = IntTy.getSizeInBits();
7599   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7600     return SDValue();
7601
7602   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7603   if (IntBits > FloatBits)
7604     return SDValue();
7605
7606   BitVector UndefElements;
7607   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7608   int32_t Bits = IntBits == 64 ? 64 : 32;
7609   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7610   if (C == -1 || C == 0 || C > Bits)
7611     return SDValue();
7612
7613   MVT ResTy;
7614   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7615   switch (NumLanes) {
7616   default:
7617     return SDValue();
7618   case 2:
7619     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7620     break;
7621   case 4:
7622     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7623     break;
7624   }
7625
7626   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7627     return SDValue();
7628
7629   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7630          "Illegal vector type after legalization");
7631
7632   SDLoc DL(N);
7633   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7634   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7635                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7636   SDValue FixConv =
7637       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7638                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7639                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7640   // We can handle smaller integers by generating an extra trunc.
7641   if (IntBits < FloatBits)
7642     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7643
7644   return FixConv;
7645 }
7646
7647 /// Fold a floating-point divide by power of two into fixed-point to
7648 /// floating-point conversion.
7649 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7650                                   const AArch64Subtarget *Subtarget) {
7651   if (!Subtarget->hasNEON())
7652     return SDValue();
7653
7654   SDValue Op = N->getOperand(0);
7655   unsigned Opc = Op->getOpcode();
7656   if (!Op.getValueType().isVector() ||
7657       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7658     return SDValue();
7659
7660   SDValue ConstVec = N->getOperand(1);
7661   if (!isa<BuildVectorSDNode>(ConstVec))
7662     return SDValue();
7663
7664   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7665   int32_t IntBits = IntTy.getSizeInBits();
7666   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7667     return SDValue();
7668
7669   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7670   int32_t FloatBits = FloatTy.getSizeInBits();
7671   if (FloatBits != 32 && FloatBits != 64)
7672     return SDValue();
7673
7674   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7675   if (IntBits > FloatBits)
7676     return SDValue();
7677
7678   BitVector UndefElements;
7679   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7680   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7681   if (C == -1 || C == 0 || C > FloatBits)
7682     return SDValue();
7683
7684   MVT ResTy;
7685   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7686   switch (NumLanes) {
7687   default:
7688     return SDValue();
7689   case 2:
7690     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7691     break;
7692   case 4:
7693     ResTy = MVT::v4i32;
7694     break;
7695   }
7696
7697   SDLoc DL(N);
7698   SDValue ConvInput = Op.getOperand(0);
7699   bool IsSigned = Opc == ISD::SINT_TO_FP;
7700   if (IntBits < FloatBits)
7701     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7702                             ResTy, ConvInput);
7703
7704   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7705                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7706   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7707                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7708                      DAG.getConstant(C, DL, MVT::i32));
7709 }
7710
7711 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7712 /// searches for and classifies those shifts.
7713 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7714                          bool &FromHi) {
7715   if (N.getOpcode() == ISD::SHL)
7716     FromHi = false;
7717   else if (N.getOpcode() == ISD::SRL)
7718     FromHi = true;
7719   else
7720     return false;
7721
7722   if (!isa<ConstantSDNode>(N.getOperand(1)))
7723     return false;
7724
7725   ShiftAmount = N->getConstantOperandVal(1);
7726   Src = N->getOperand(0);
7727   return true;
7728 }
7729
7730 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7731 /// registers viewed as a high/low pair. This function looks for the pattern:
7732 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7733 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7734 /// independent.
7735 static SDValue tryCombineToEXTR(SDNode *N,
7736                                 TargetLowering::DAGCombinerInfo &DCI) {
7737   SelectionDAG &DAG = DCI.DAG;
7738   SDLoc DL(N);
7739   EVT VT = N->getValueType(0);
7740
7741   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7742
7743   if (VT != MVT::i32 && VT != MVT::i64)
7744     return SDValue();
7745
7746   SDValue LHS;
7747   uint32_t ShiftLHS = 0;
7748   bool LHSFromHi = 0;
7749   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7750     return SDValue();
7751
7752   SDValue RHS;
7753   uint32_t ShiftRHS = 0;
7754   bool RHSFromHi = 0;
7755   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7756     return SDValue();
7757
7758   // If they're both trying to come from the high part of the register, they're
7759   // not really an EXTR.
7760   if (LHSFromHi == RHSFromHi)
7761     return SDValue();
7762
7763   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7764     return SDValue();
7765
7766   if (LHSFromHi) {
7767     std::swap(LHS, RHS);
7768     std::swap(ShiftLHS, ShiftRHS);
7769   }
7770
7771   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7772                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7773 }
7774
7775 static SDValue tryCombineToBSL(SDNode *N,
7776                                 TargetLowering::DAGCombinerInfo &DCI) {
7777   EVT VT = N->getValueType(0);
7778   SelectionDAG &DAG = DCI.DAG;
7779   SDLoc DL(N);
7780
7781   if (!VT.isVector())
7782     return SDValue();
7783
7784   SDValue N0 = N->getOperand(0);
7785   if (N0.getOpcode() != ISD::AND)
7786     return SDValue();
7787
7788   SDValue N1 = N->getOperand(1);
7789   if (N1.getOpcode() != ISD::AND)
7790     return SDValue();
7791
7792   // We only have to look for constant vectors here since the general, variable
7793   // case can be handled in TableGen.
7794   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7795   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7796   for (int i = 1; i >= 0; --i)
7797     for (int j = 1; j >= 0; --j) {
7798       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7799       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7800       if (!BVN0 || !BVN1)
7801         continue;
7802
7803       bool FoundMatch = true;
7804       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7805         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7806         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7807         if (!CN0 || !CN1 ||
7808             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7809           FoundMatch = false;
7810           break;
7811         }
7812       }
7813
7814       if (FoundMatch)
7815         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7816                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7817     }
7818
7819   return SDValue();
7820 }
7821
7822 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7823                                 const AArch64Subtarget *Subtarget) {
7824   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7825   if (!EnableAArch64ExtrGeneration)
7826     return SDValue();
7827   SelectionDAG &DAG = DCI.DAG;
7828   EVT VT = N->getValueType(0);
7829
7830   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7831     return SDValue();
7832
7833   SDValue Res = tryCombineToEXTR(N, DCI);
7834   if (Res.getNode())
7835     return Res;
7836
7837   Res = tryCombineToBSL(N, DCI);
7838   if (Res.getNode())
7839     return Res;
7840
7841   return SDValue();
7842 }
7843
7844 static SDValue performBitcastCombine(SDNode *N,
7845                                      TargetLowering::DAGCombinerInfo &DCI,
7846                                      SelectionDAG &DAG) {
7847   // Wait 'til after everything is legalized to try this. That way we have
7848   // legal vector types and such.
7849   if (DCI.isBeforeLegalizeOps())
7850     return SDValue();
7851
7852   // Remove extraneous bitcasts around an extract_subvector.
7853   // For example,
7854   //    (v4i16 (bitconvert
7855   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7856   //  becomes
7857   //    (extract_subvector ((v8i16 ...), (i64 4)))
7858
7859   // Only interested in 64-bit vectors as the ultimate result.
7860   EVT VT = N->getValueType(0);
7861   if (!VT.isVector())
7862     return SDValue();
7863   if (VT.getSimpleVT().getSizeInBits() != 64)
7864     return SDValue();
7865   // Is the operand an extract_subvector starting at the beginning or halfway
7866   // point of the vector? A low half may also come through as an
7867   // EXTRACT_SUBREG, so look for that, too.
7868   SDValue Op0 = N->getOperand(0);
7869   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7870       !(Op0->isMachineOpcode() &&
7871         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7872     return SDValue();
7873   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7874   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7875     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7876       return SDValue();
7877   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7878     if (idx != AArch64::dsub)
7879       return SDValue();
7880     // The dsub reference is equivalent to a lane zero subvector reference.
7881     idx = 0;
7882   }
7883   // Look through the bitcast of the input to the extract.
7884   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7885     return SDValue();
7886   SDValue Source = Op0->getOperand(0)->getOperand(0);
7887   // If the source type has twice the number of elements as our destination
7888   // type, we know this is an extract of the high or low half of the vector.
7889   EVT SVT = Source->getValueType(0);
7890   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7891     return SDValue();
7892
7893   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7894
7895   // Create the simplified form to just extract the low or high half of the
7896   // vector directly rather than bothering with the bitcasts.
7897   SDLoc dl(N);
7898   unsigned NumElements = VT.getVectorNumElements();
7899   if (idx) {
7900     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7901     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7902   } else {
7903     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7904     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7905                                       Source, SubReg),
7906                    0);
7907   }
7908 }
7909
7910 static SDValue performConcatVectorsCombine(SDNode *N,
7911                                            TargetLowering::DAGCombinerInfo &DCI,
7912                                            SelectionDAG &DAG) {
7913   SDLoc dl(N);
7914   EVT VT = N->getValueType(0);
7915   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7916
7917   // Optimize concat_vectors of truncated vectors, where the intermediate
7918   // type is illegal, to avoid said illegality,  e.g.,
7919   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7920   //                          (v2i16 (truncate (v2i64)))))
7921   // ->
7922   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7923   //                                    (v4i32 (bitcast (v2i64))),
7924   //                                    <0, 2, 4, 6>)))
7925   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7926   // on both input and result type, so we might generate worse code.
7927   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7928   if (N->getNumOperands() == 2 &&
7929       N0->getOpcode() == ISD::TRUNCATE &&
7930       N1->getOpcode() == ISD::TRUNCATE) {
7931     SDValue N00 = N0->getOperand(0);
7932     SDValue N10 = N1->getOperand(0);
7933     EVT N00VT = N00.getValueType();
7934
7935     if (N00VT == N10.getValueType() &&
7936         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7937         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7938       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7939       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7940       for (size_t i = 0; i < Mask.size(); ++i)
7941         Mask[i] = i * 2;
7942       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7943                          DAG.getVectorShuffle(
7944                              MidVT, dl,
7945                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7946                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7947     }
7948   }
7949
7950   // Wait 'til after everything is legalized to try this. That way we have
7951   // legal vector types and such.
7952   if (DCI.isBeforeLegalizeOps())
7953     return SDValue();
7954
7955   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7956   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7957   // canonicalise to that.
7958   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7959     assert(VT.getVectorElementType().getSizeInBits() == 64);
7960     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7961                        DAG.getConstant(0, dl, MVT::i64));
7962   }
7963
7964   // Canonicalise concat_vectors so that the right-hand vector has as few
7965   // bit-casts as possible before its real operation. The primary matching
7966   // destination for these operations will be the narrowing "2" instructions,
7967   // which depend on the operation being performed on this right-hand vector.
7968   // For example,
7969   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7970   // becomes
7971   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7972
7973   if (N1->getOpcode() != ISD::BITCAST)
7974     return SDValue();
7975   SDValue RHS = N1->getOperand(0);
7976   MVT RHSTy = RHS.getValueType().getSimpleVT();
7977   // If the RHS is not a vector, this is not the pattern we're looking for.
7978   if (!RHSTy.isVector())
7979     return SDValue();
7980
7981   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7982
7983   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7984                                   RHSTy.getVectorNumElements() * 2);
7985   return DAG.getNode(ISD::BITCAST, dl, VT,
7986                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7987                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7988                                  RHS));
7989 }
7990
7991 static SDValue tryCombineFixedPointConvert(SDNode *N,
7992                                            TargetLowering::DAGCombinerInfo &DCI,
7993                                            SelectionDAG &DAG) {
7994   // Wait 'til after everything is legalized to try this. That way we have
7995   // legal vector types and such.
7996   if (DCI.isBeforeLegalizeOps())
7997     return SDValue();
7998   // Transform a scalar conversion of a value from a lane extract into a
7999   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8000   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8001   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8002   //
8003   // The second form interacts better with instruction selection and the
8004   // register allocator to avoid cross-class register copies that aren't
8005   // coalescable due to a lane reference.
8006
8007   // Check the operand and see if it originates from a lane extract.
8008   SDValue Op1 = N->getOperand(1);
8009   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8010     // Yep, no additional predication needed. Perform the transform.
8011     SDValue IID = N->getOperand(0);
8012     SDValue Shift = N->getOperand(2);
8013     SDValue Vec = Op1.getOperand(0);
8014     SDValue Lane = Op1.getOperand(1);
8015     EVT ResTy = N->getValueType(0);
8016     EVT VecResTy;
8017     SDLoc DL(N);
8018
8019     // The vector width should be 128 bits by the time we get here, even
8020     // if it started as 64 bits (the extract_vector handling will have
8021     // done so).
8022     assert(Vec.getValueType().getSizeInBits() == 128 &&
8023            "unexpected vector size on extract_vector_elt!");
8024     if (Vec.getValueType() == MVT::v4i32)
8025       VecResTy = MVT::v4f32;
8026     else if (Vec.getValueType() == MVT::v2i64)
8027       VecResTy = MVT::v2f64;
8028     else
8029       llvm_unreachable("unexpected vector type!");
8030
8031     SDValue Convert =
8032         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8033     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8034   }
8035   return SDValue();
8036 }
8037
8038 // AArch64 high-vector "long" operations are formed by performing the non-high
8039 // version on an extract_subvector of each operand which gets the high half:
8040 //
8041 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8042 //
8043 // However, there are cases which don't have an extract_high explicitly, but
8044 // have another operation that can be made compatible with one for free. For
8045 // example:
8046 //
8047 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8048 //
8049 // This routine does the actual conversion of such DUPs, once outer routines
8050 // have determined that everything else is in order.
8051 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8052 // similarly here.
8053 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8054   switch (N.getOpcode()) {
8055   case AArch64ISD::DUP:
8056   case AArch64ISD::DUPLANE8:
8057   case AArch64ISD::DUPLANE16:
8058   case AArch64ISD::DUPLANE32:
8059   case AArch64ISD::DUPLANE64:
8060   case AArch64ISD::MOVI:
8061   case AArch64ISD::MOVIshift:
8062   case AArch64ISD::MOVIedit:
8063   case AArch64ISD::MOVImsl:
8064   case AArch64ISD::MVNIshift:
8065   case AArch64ISD::MVNImsl:
8066     break;
8067   default:
8068     // FMOV could be supported, but isn't very useful, as it would only occur
8069     // if you passed a bitcast' floating point immediate to an eligible long
8070     // integer op (addl, smull, ...).
8071     return SDValue();
8072   }
8073
8074   MVT NarrowTy = N.getSimpleValueType();
8075   if (!NarrowTy.is64BitVector())
8076     return SDValue();
8077
8078   MVT ElementTy = NarrowTy.getVectorElementType();
8079   unsigned NumElems = NarrowTy.getVectorNumElements();
8080   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8081
8082   SDLoc dl(N);
8083   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8084                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8085                      DAG.getConstant(NumElems, dl, MVT::i64));
8086 }
8087
8088 static bool isEssentiallyExtractSubvector(SDValue N) {
8089   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8090     return true;
8091
8092   return N.getOpcode() == ISD::BITCAST &&
8093          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8094 }
8095
8096 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8097 struct GenericSetCCInfo {
8098   const SDValue *Opnd0;
8099   const SDValue *Opnd1;
8100   ISD::CondCode CC;
8101 };
8102
8103 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8104 struct AArch64SetCCInfo {
8105   const SDValue *Cmp;
8106   AArch64CC::CondCode CC;
8107 };
8108
8109 /// \brief Helper structure to keep track of SetCC information.
8110 union SetCCInfo {
8111   GenericSetCCInfo Generic;
8112   AArch64SetCCInfo AArch64;
8113 };
8114
8115 /// \brief Helper structure to be able to read SetCC information.  If set to
8116 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8117 /// GenericSetCCInfo.
8118 struct SetCCInfoAndKind {
8119   SetCCInfo Info;
8120   bool IsAArch64;
8121 };
8122
8123 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8124 /// an
8125 /// AArch64 lowered one.
8126 /// \p SetCCInfo is filled accordingly.
8127 /// \post SetCCInfo is meanginfull only when this function returns true.
8128 /// \return True when Op is a kind of SET_CC operation.
8129 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8130   // If this is a setcc, this is straight forward.
8131   if (Op.getOpcode() == ISD::SETCC) {
8132     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8133     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8134     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8135     SetCCInfo.IsAArch64 = false;
8136     return true;
8137   }
8138   // Otherwise, check if this is a matching csel instruction.
8139   // In other words:
8140   // - csel 1, 0, cc
8141   // - csel 0, 1, !cc
8142   if (Op.getOpcode() != AArch64ISD::CSEL)
8143     return false;
8144   // Set the information about the operands.
8145   // TODO: we want the operands of the Cmp not the csel
8146   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8147   SetCCInfo.IsAArch64 = true;
8148   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8149       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8150
8151   // Check that the operands matches the constraints:
8152   // (1) Both operands must be constants.
8153   // (2) One must be 1 and the other must be 0.
8154   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8155   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8156
8157   // Check (1).
8158   if (!TValue || !FValue)
8159     return false;
8160
8161   // Check (2).
8162   if (!TValue->isOne()) {
8163     // Update the comparison when we are interested in !cc.
8164     std::swap(TValue, FValue);
8165     SetCCInfo.Info.AArch64.CC =
8166         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8167   }
8168   return TValue->isOne() && FValue->isNullValue();
8169 }
8170
8171 // Returns true if Op is setcc or zext of setcc.
8172 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8173   if (isSetCC(Op, Info))
8174     return true;
8175   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8176     isSetCC(Op->getOperand(0), Info));
8177 }
8178
8179 // The folding we want to perform is:
8180 // (add x, [zext] (setcc cc ...) )
8181 //   -->
8182 // (csel x, (add x, 1), !cc ...)
8183 //
8184 // The latter will get matched to a CSINC instruction.
8185 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8186   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8187   SDValue LHS = Op->getOperand(0);
8188   SDValue RHS = Op->getOperand(1);
8189   SetCCInfoAndKind InfoAndKind;
8190
8191   // If neither operand is a SET_CC, give up.
8192   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8193     std::swap(LHS, RHS);
8194     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8195       return SDValue();
8196   }
8197
8198   // FIXME: This could be generatized to work for FP comparisons.
8199   EVT CmpVT = InfoAndKind.IsAArch64
8200                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8201                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8202   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8203     return SDValue();
8204
8205   SDValue CCVal;
8206   SDValue Cmp;
8207   SDLoc dl(Op);
8208   if (InfoAndKind.IsAArch64) {
8209     CCVal = DAG.getConstant(
8210         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8211         MVT::i32);
8212     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8213   } else
8214     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8215                       *InfoAndKind.Info.Generic.Opnd1,
8216                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8217                       CCVal, DAG, dl);
8218
8219   EVT VT = Op->getValueType(0);
8220   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8221   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8222 }
8223
8224 // The basic add/sub long vector instructions have variants with "2" on the end
8225 // which act on the high-half of their inputs. They are normally matched by
8226 // patterns like:
8227 //
8228 // (add (zeroext (extract_high LHS)),
8229 //      (zeroext (extract_high RHS)))
8230 // -> uaddl2 vD, vN, vM
8231 //
8232 // However, if one of the extracts is something like a duplicate, this
8233 // instruction can still be used profitably. This function puts the DAG into a
8234 // more appropriate form for those patterns to trigger.
8235 static SDValue performAddSubLongCombine(SDNode *N,
8236                                         TargetLowering::DAGCombinerInfo &DCI,
8237                                         SelectionDAG &DAG) {
8238   if (DCI.isBeforeLegalizeOps())
8239     return SDValue();
8240
8241   MVT VT = N->getSimpleValueType(0);
8242   if (!VT.is128BitVector()) {
8243     if (N->getOpcode() == ISD::ADD)
8244       return performSetccAddFolding(N, DAG);
8245     return SDValue();
8246   }
8247
8248   // Make sure both branches are extended in the same way.
8249   SDValue LHS = N->getOperand(0);
8250   SDValue RHS = N->getOperand(1);
8251   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8252        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8253       LHS.getOpcode() != RHS.getOpcode())
8254     return SDValue();
8255
8256   unsigned ExtType = LHS.getOpcode();
8257
8258   // It's not worth doing if at least one of the inputs isn't already an
8259   // extract, but we don't know which it'll be so we have to try both.
8260   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8261     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8262     if (!RHS.getNode())
8263       return SDValue();
8264
8265     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8266   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8267     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8268     if (!LHS.getNode())
8269       return SDValue();
8270
8271     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8272   }
8273
8274   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8275 }
8276
8277 // Massage DAGs which we can use the high-half "long" operations on into
8278 // something isel will recognize better. E.g.
8279 //
8280 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8281 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8282 //                     (extract_high (v2i64 (dup128 scalar)))))
8283 //
8284 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8285                                        TargetLowering::DAGCombinerInfo &DCI,
8286                                        SelectionDAG &DAG) {
8287   if (DCI.isBeforeLegalizeOps())
8288     return SDValue();
8289
8290   SDValue LHS = N->getOperand(1);
8291   SDValue RHS = N->getOperand(2);
8292   assert(LHS.getValueType().is64BitVector() &&
8293          RHS.getValueType().is64BitVector() &&
8294          "unexpected shape for long operation");
8295
8296   // Either node could be a DUP, but it's not worth doing both of them (you'd
8297   // just as well use the non-high version) so look for a corresponding extract
8298   // operation on the other "wing".
8299   if (isEssentiallyExtractSubvector(LHS)) {
8300     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8301     if (!RHS.getNode())
8302       return SDValue();
8303   } else if (isEssentiallyExtractSubvector(RHS)) {
8304     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8305     if (!LHS.getNode())
8306       return SDValue();
8307   }
8308
8309   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8310                      N->getOperand(0), LHS, RHS);
8311 }
8312
8313 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8314   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8315   unsigned ElemBits = ElemTy.getSizeInBits();
8316
8317   int64_t ShiftAmount;
8318   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8319     APInt SplatValue, SplatUndef;
8320     unsigned SplatBitSize;
8321     bool HasAnyUndefs;
8322     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8323                               HasAnyUndefs, ElemBits) ||
8324         SplatBitSize != ElemBits)
8325       return SDValue();
8326
8327     ShiftAmount = SplatValue.getSExtValue();
8328   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8329     ShiftAmount = CVN->getSExtValue();
8330   } else
8331     return SDValue();
8332
8333   unsigned Opcode;
8334   bool IsRightShift;
8335   switch (IID) {
8336   default:
8337     llvm_unreachable("Unknown shift intrinsic");
8338   case Intrinsic::aarch64_neon_sqshl:
8339     Opcode = AArch64ISD::SQSHL_I;
8340     IsRightShift = false;
8341     break;
8342   case Intrinsic::aarch64_neon_uqshl:
8343     Opcode = AArch64ISD::UQSHL_I;
8344     IsRightShift = false;
8345     break;
8346   case Intrinsic::aarch64_neon_srshl:
8347     Opcode = AArch64ISD::SRSHR_I;
8348     IsRightShift = true;
8349     break;
8350   case Intrinsic::aarch64_neon_urshl:
8351     Opcode = AArch64ISD::URSHR_I;
8352     IsRightShift = true;
8353     break;
8354   case Intrinsic::aarch64_neon_sqshlu:
8355     Opcode = AArch64ISD::SQSHLU_I;
8356     IsRightShift = false;
8357     break;
8358   }
8359
8360   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8361     SDLoc dl(N);
8362     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8363                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8364   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8365     SDLoc dl(N);
8366     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8367                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8368   }
8369
8370   return SDValue();
8371 }
8372
8373 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8374 // the intrinsics must be legal and take an i32, this means there's almost
8375 // certainly going to be a zext in the DAG which we can eliminate.
8376 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8377   SDValue AndN = N->getOperand(2);
8378   if (AndN.getOpcode() != ISD::AND)
8379     return SDValue();
8380
8381   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8382   if (!CMask || CMask->getZExtValue() != Mask)
8383     return SDValue();
8384
8385   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8386                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8387 }
8388
8389 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8390                                            SelectionDAG &DAG) {
8391   SDLoc dl(N);
8392   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8393                      DAG.getNode(Opc, dl,
8394                                  N->getOperand(1).getSimpleValueType(),
8395                                  N->getOperand(1)),
8396                      DAG.getConstant(0, dl, MVT::i64));
8397 }
8398
8399 static SDValue performIntrinsicCombine(SDNode *N,
8400                                        TargetLowering::DAGCombinerInfo &DCI,
8401                                        const AArch64Subtarget *Subtarget) {
8402   SelectionDAG &DAG = DCI.DAG;
8403   unsigned IID = getIntrinsicID(N);
8404   switch (IID) {
8405   default:
8406     break;
8407   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8408   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8409     return tryCombineFixedPointConvert(N, DCI, DAG);
8410   case Intrinsic::aarch64_neon_saddv:
8411     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8412   case Intrinsic::aarch64_neon_uaddv:
8413     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8414   case Intrinsic::aarch64_neon_sminv:
8415     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8416   case Intrinsic::aarch64_neon_uminv:
8417     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8418   case Intrinsic::aarch64_neon_smaxv:
8419     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8420   case Intrinsic::aarch64_neon_umaxv:
8421     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8422   case Intrinsic::aarch64_neon_fmax:
8423     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8424                        N->getOperand(1), N->getOperand(2));
8425   case Intrinsic::aarch64_neon_fmin:
8426     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8427                        N->getOperand(1), N->getOperand(2));
8428   case Intrinsic::aarch64_neon_fmaxnm:
8429     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8430                        N->getOperand(1), N->getOperand(2));
8431   case Intrinsic::aarch64_neon_fminnm:
8432     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8433                        N->getOperand(1), N->getOperand(2));
8434   case Intrinsic::aarch64_neon_smull:
8435   case Intrinsic::aarch64_neon_umull:
8436   case Intrinsic::aarch64_neon_pmull:
8437   case Intrinsic::aarch64_neon_sqdmull:
8438     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8439   case Intrinsic::aarch64_neon_sqshl:
8440   case Intrinsic::aarch64_neon_uqshl:
8441   case Intrinsic::aarch64_neon_sqshlu:
8442   case Intrinsic::aarch64_neon_srshl:
8443   case Intrinsic::aarch64_neon_urshl:
8444     return tryCombineShiftImm(IID, N, DAG);
8445   case Intrinsic::aarch64_crc32b:
8446   case Intrinsic::aarch64_crc32cb:
8447     return tryCombineCRC32(0xff, N, DAG);
8448   case Intrinsic::aarch64_crc32h:
8449   case Intrinsic::aarch64_crc32ch:
8450     return tryCombineCRC32(0xffff, N, DAG);
8451   }
8452   return SDValue();
8453 }
8454
8455 static SDValue performExtendCombine(SDNode *N,
8456                                     TargetLowering::DAGCombinerInfo &DCI,
8457                                     SelectionDAG &DAG) {
8458   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8459   // we can convert that DUP into another extract_high (of a bigger DUP), which
8460   // helps the backend to decide that an sabdl2 would be useful, saving a real
8461   // extract_high operation.
8462   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8463       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8464     SDNode *ABDNode = N->getOperand(0).getNode();
8465     unsigned IID = getIntrinsicID(ABDNode);
8466     if (IID == Intrinsic::aarch64_neon_sabd ||
8467         IID == Intrinsic::aarch64_neon_uabd) {
8468       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8469       if (!NewABD.getNode())
8470         return SDValue();
8471
8472       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8473                          NewABD);
8474     }
8475   }
8476
8477   // This is effectively a custom type legalization for AArch64.
8478   //
8479   // Type legalization will split an extend of a small, legal, type to a larger
8480   // illegal type by first splitting the destination type, often creating
8481   // illegal source types, which then get legalized in isel-confusing ways,
8482   // leading to really terrible codegen. E.g.,
8483   //   %result = v8i32 sext v8i8 %value
8484   // becomes
8485   //   %losrc = extract_subreg %value, ...
8486   //   %hisrc = extract_subreg %value, ...
8487   //   %lo = v4i32 sext v4i8 %losrc
8488   //   %hi = v4i32 sext v4i8 %hisrc
8489   // Things go rapidly downhill from there.
8490   //
8491   // For AArch64, the [sz]ext vector instructions can only go up one element
8492   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8493   // take two instructions.
8494   //
8495   // This implies that the most efficient way to do the extend from v8i8
8496   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8497   // the normal splitting to happen for the v8i16->v8i32.
8498
8499   // This is pre-legalization to catch some cases where the default
8500   // type legalization will create ill-tempered code.
8501   if (!DCI.isBeforeLegalizeOps())
8502     return SDValue();
8503
8504   // We're only interested in cleaning things up for non-legal vector types
8505   // here. If both the source and destination are legal, things will just
8506   // work naturally without any fiddling.
8507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8508   EVT ResVT = N->getValueType(0);
8509   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8510     return SDValue();
8511   // If the vector type isn't a simple VT, it's beyond the scope of what
8512   // we're  worried about here. Let legalization do its thing and hope for
8513   // the best.
8514   SDValue Src = N->getOperand(0);
8515   EVT SrcVT = Src->getValueType(0);
8516   if (!ResVT.isSimple() || !SrcVT.isSimple())
8517     return SDValue();
8518
8519   // If the source VT is a 64-bit vector, we can play games and get the
8520   // better results we want.
8521   if (SrcVT.getSizeInBits() != 64)
8522     return SDValue();
8523
8524   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8525   unsigned ElementCount = SrcVT.getVectorNumElements();
8526   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8527   SDLoc DL(N);
8528   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8529
8530   // Now split the rest of the operation into two halves, each with a 64
8531   // bit source.
8532   EVT LoVT, HiVT;
8533   SDValue Lo, Hi;
8534   unsigned NumElements = ResVT.getVectorNumElements();
8535   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8536   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8537                                  ResVT.getVectorElementType(), NumElements / 2);
8538
8539   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8540                                LoVT.getVectorNumElements());
8541   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8542                    DAG.getConstant(0, DL, MVT::i64));
8543   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8544                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8545   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8546   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8547
8548   // Now combine the parts back together so we still have a single result
8549   // like the combiner expects.
8550   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8551 }
8552
8553 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8554 /// value. The load store optimizer pass will merge them to store pair stores.
8555 /// This has better performance than a splat of the scalar followed by a split
8556 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8557 /// followed by an ext.b and two stores.
8558 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8559   SDValue StVal = St->getValue();
8560   EVT VT = StVal.getValueType();
8561
8562   // Don't replace floating point stores, they possibly won't be transformed to
8563   // stp because of the store pair suppress pass.
8564   if (VT.isFloatingPoint())
8565     return SDValue();
8566
8567   // Check for insert vector elements.
8568   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8569     return SDValue();
8570
8571   // We can express a splat as store pair(s) for 2 or 4 elements.
8572   unsigned NumVecElts = VT.getVectorNumElements();
8573   if (NumVecElts != 4 && NumVecElts != 2)
8574     return SDValue();
8575   SDValue SplatVal = StVal.getOperand(1);
8576   unsigned RemainInsertElts = NumVecElts - 1;
8577
8578   // Check that this is a splat.
8579   while (--RemainInsertElts) {
8580     SDValue NextInsertElt = StVal.getOperand(0);
8581     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8582       return SDValue();
8583     if (NextInsertElt.getOperand(1) != SplatVal)
8584       return SDValue();
8585     StVal = NextInsertElt;
8586   }
8587   unsigned OrigAlignment = St->getAlignment();
8588   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8589   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8590
8591   // Create scalar stores. This is at least as good as the code sequence for a
8592   // split unaligned store which is a dup.s, ext.b, and two stores.
8593   // Most of the time the three stores should be replaced by store pair
8594   // instructions (stp).
8595   SDLoc DL(St);
8596   SDValue BasePtr = St->getBasePtr();
8597   SDValue NewST1 =
8598       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8599                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8600
8601   unsigned Offset = EltOffset;
8602   while (--NumVecElts) {
8603     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8604                                     DAG.getConstant(Offset, DL, MVT::i64));
8605     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8606                           St->getPointerInfo(), St->isVolatile(),
8607                           St->isNonTemporal(), Alignment);
8608     Offset += EltOffset;
8609   }
8610   return NewST1;
8611 }
8612
8613 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8614                               SelectionDAG &DAG,
8615                               const AArch64Subtarget *Subtarget) {
8616   if (!DCI.isBeforeLegalize())
8617     return SDValue();
8618
8619   StoreSDNode *S = cast<StoreSDNode>(N);
8620   if (S->isVolatile())
8621     return SDValue();
8622
8623   // FIXME: The logic for deciding if an unaligned store should be split should
8624   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8625   // a call to that function here.
8626
8627   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8628   // page boundaries. We want to split such stores.
8629   if (!Subtarget->isCyclone())
8630     return SDValue();
8631
8632   // Don't split at -Oz.
8633   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8634     return SDValue();
8635
8636   SDValue StVal = S->getValue();
8637   EVT VT = StVal.getValueType();
8638
8639   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8640   // those up regresses performance on micro-benchmarks and olden/bh.
8641   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8642     return SDValue();
8643
8644   // Split unaligned 16B stores. They are terrible for performance.
8645   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8646   // extensions can use this to mark that it does not want splitting to happen
8647   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8648   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8649   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8650       S->getAlignment() <= 2)
8651     return SDValue();
8652
8653   // If we get a splat of a scalar convert this vector store to a store of
8654   // scalars. They will be merged into store pairs thereby removing two
8655   // instructions.
8656   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8657     return ReplacedSplat;
8658
8659   SDLoc DL(S);
8660   unsigned NumElts = VT.getVectorNumElements() / 2;
8661   // Split VT into two.
8662   EVT HalfVT =
8663       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8664   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8665                                    DAG.getConstant(0, DL, MVT::i64));
8666   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8667                                    DAG.getConstant(NumElts, DL, MVT::i64));
8668   SDValue BasePtr = S->getBasePtr();
8669   SDValue NewST1 =
8670       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8671                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8672   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8673                                   DAG.getConstant(8, DL, MVT::i64));
8674   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8675                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8676                       S->getAlignment());
8677 }
8678
8679 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8680 /// post-increment LD1R.
8681 static SDValue performPostLD1Combine(SDNode *N,
8682                                      TargetLowering::DAGCombinerInfo &DCI,
8683                                      bool IsLaneOp) {
8684   if (DCI.isBeforeLegalizeOps())
8685     return SDValue();
8686
8687   SelectionDAG &DAG = DCI.DAG;
8688   EVT VT = N->getValueType(0);
8689
8690   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8691   SDNode *LD = N->getOperand(LoadIdx).getNode();
8692   // If it is not LOAD, can not do such combine.
8693   if (LD->getOpcode() != ISD::LOAD)
8694     return SDValue();
8695
8696   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8697   EVT MemVT = LoadSDN->getMemoryVT();
8698   // Check if memory operand is the same type as the vector element.
8699   if (MemVT != VT.getVectorElementType())
8700     return SDValue();
8701
8702   // Check if there are other uses. If so, do not combine as it will introduce
8703   // an extra load.
8704   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8705        ++UI) {
8706     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8707       continue;
8708     if (*UI != N)
8709       return SDValue();
8710   }
8711
8712   SDValue Addr = LD->getOperand(1);
8713   SDValue Vector = N->getOperand(0);
8714   // Search for a use of the address operand that is an increment.
8715   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8716        Addr.getNode()->use_end(); UI != UE; ++UI) {
8717     SDNode *User = *UI;
8718     if (User->getOpcode() != ISD::ADD
8719         || UI.getUse().getResNo() != Addr.getResNo())
8720       continue;
8721
8722     // Check that the add is independent of the load.  Otherwise, folding it
8723     // would create a cycle.
8724     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8725       continue;
8726     // Also check that add is not used in the vector operand.  This would also
8727     // create a cycle.
8728     if (User->isPredecessorOf(Vector.getNode()))
8729       continue;
8730
8731     // If the increment is a constant, it must match the memory ref size.
8732     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8733     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8734       uint32_t IncVal = CInc->getZExtValue();
8735       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8736       if (IncVal != NumBytes)
8737         continue;
8738       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8739     }
8740
8741     // Finally, check that the vector doesn't depend on the load.
8742     // Again, this would create a cycle.
8743     // The load depending on the vector is fine, as that's the case for the
8744     // LD1*post we'll eventually generate anyway.
8745     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8746       continue;
8747
8748     SmallVector<SDValue, 8> Ops;
8749     Ops.push_back(LD->getOperand(0));  // Chain
8750     if (IsLaneOp) {
8751       Ops.push_back(Vector);           // The vector to be inserted
8752       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8753     }
8754     Ops.push_back(Addr);
8755     Ops.push_back(Inc);
8756
8757     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8758     SDVTList SDTys = DAG.getVTList(Tys);
8759     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8760     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8761                                            MemVT,
8762                                            LoadSDN->getMemOperand());
8763
8764     // Update the uses.
8765     SmallVector<SDValue, 2> NewResults;
8766     NewResults.push_back(SDValue(LD, 0));             // The result of load
8767     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8768     DCI.CombineTo(LD, NewResults);
8769     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8770     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8771
8772     break;
8773   }
8774   return SDValue();
8775 }
8776
8777 /// Simplify \Addr given that the top byte of it is ignored by HW during
8778 /// address translation.
8779 static bool performTBISimplification(SDValue Addr,
8780                                      TargetLowering::DAGCombinerInfo &DCI,
8781                                      SelectionDAG &DAG) {
8782   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8783   APInt KnownZero, KnownOne;
8784   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8785                                         DCI.isBeforeLegalizeOps());
8786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8787   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8788     DCI.CommitTargetLoweringOpt(TLO);
8789     return true;
8790   }
8791   return false;
8792 }
8793
8794 static SDValue performSTORECombine(SDNode *N,
8795                                    TargetLowering::DAGCombinerInfo &DCI,
8796                                    SelectionDAG &DAG,
8797                                    const AArch64Subtarget *Subtarget) {
8798   SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8799   if (Split.getNode())
8800     return Split;
8801
8802   if (Subtarget->supportsAddressTopByteIgnored() &&
8803       performTBISimplification(N->getOperand(2), DCI, DAG))
8804     return SDValue(N, 0);
8805
8806   return SDValue();
8807 }
8808
8809   /// This function handles the log2-shuffle pattern produced by the
8810 /// LoopVectorizer for the across vector reduction. It consists of
8811 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8812 /// are reduced, where s is an induction variable from 0 to
8813 /// log2(NumVectorElements).
8814 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8815                                                      unsigned Op,
8816                                                      SelectionDAG &DAG) {
8817   EVT VTy = OpV->getOperand(0).getValueType();
8818   if (!VTy.isVector())
8819     return SDValue();
8820
8821   int NumVecElts = VTy.getVectorNumElements();
8822   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8823     if (NumVecElts != 4)
8824       return SDValue();
8825   } else {
8826     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8827       return SDValue();
8828   }
8829
8830   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8831   SDValue PreOp = OpV;
8832   // Iterate over each step of the across vector reduction.
8833   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8834     SDValue CurOp = PreOp.getOperand(0);
8835     SDValue Shuffle = PreOp.getOperand(1);
8836     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8837       // Try to swap the 1st and 2nd operand as add and min/max instructions
8838       // are commutative.
8839       CurOp = PreOp.getOperand(1);
8840       Shuffle = PreOp.getOperand(0);
8841       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8842         return SDValue();
8843     }
8844
8845     // Check if the input vector is fed by the operator we want to handle,
8846     // except the last step; the very first input vector is not necessarily
8847     // the same operator we are handling.
8848     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8849       return SDValue();
8850
8851     // Check if it forms one step of the across vector reduction.
8852     // E.g.,
8853     //   %cur = add %1, %0
8854     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8855     //   %pre = add %cur, %shuffle
8856     if (Shuffle.getOperand(0) != CurOp)
8857       return SDValue();
8858
8859     int NumMaskElts = 1 << CurStep;
8860     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8861     // Check mask values in each step.
8862     // We expect the shuffle mask in each step follows a specific pattern
8863     // denoted here by the <M, U> form, where M is a sequence of integers
8864     // starting from NumMaskElts, increasing by 1, and the number integers
8865     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8866     // of undef in U should be NumVecElts - NumMaskElts.
8867     // E.g., for <8 x i16>, mask values in each step should be :
8868     //   step 0 : <1,u,u,u,u,u,u,u>
8869     //   step 1 : <2,3,u,u,u,u,u,u>
8870     //   step 2 : <4,5,6,7,u,u,u,u>
8871     for (int i = 0; i < NumVecElts; ++i)
8872       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8873           (i >= NumMaskElts && !(Mask[i] < 0)))
8874         return SDValue();
8875
8876     PreOp = CurOp;
8877   }
8878   unsigned Opcode;
8879   bool IsIntrinsic = false;
8880
8881   switch (Op) {
8882   default:
8883     llvm_unreachable("Unexpected operator for across vector reduction");
8884   case ISD::ADD:
8885     Opcode = AArch64ISD::UADDV;
8886     break;
8887   case ISD::SMAX:
8888     Opcode = AArch64ISD::SMAXV;
8889     break;
8890   case ISD::UMAX:
8891     Opcode = AArch64ISD::UMAXV;
8892     break;
8893   case ISD::SMIN:
8894     Opcode = AArch64ISD::SMINV;
8895     break;
8896   case ISD::UMIN:
8897     Opcode = AArch64ISD::UMINV;
8898     break;
8899   case ISD::FMAXNUM:
8900     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8901     IsIntrinsic = true;
8902     break;
8903   case ISD::FMINNUM:
8904     Opcode = Intrinsic::aarch64_neon_fminnmv;
8905     IsIntrinsic = true;
8906     break;
8907   }
8908   SDLoc DL(N);
8909
8910   return IsIntrinsic
8911              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8912                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8913              : DAG.getNode(
8914                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8915                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8916                    DAG.getConstant(0, DL, MVT::i64));
8917 }
8918
8919 /// Target-specific DAG combine for the across vector min/max reductions.
8920 /// This function specifically handles the final clean-up step of the vector
8921 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8922 /// pattern, which narrows down and finds the final min/max value from all
8923 /// elements of the vector.
8924 /// For example, for a <16 x i8> vector :
8925 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8926 ///   %smax0 = smax %arr, svn0
8927 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8928 ///   %smax1 = smax %smax0, %svn1
8929 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8930 ///   %smax2 = smax %smax1, svn2
8931 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8932 ///   %sc = setcc %smax2, %svn3, gt
8933 ///   %n0 = extract_vector_elt %sc, #0
8934 ///   %n1 = extract_vector_elt %smax2, #0
8935 ///   %n2 = extract_vector_elt $smax2, #1
8936 ///   %result = select %n0, %n1, n2
8937 ///     becomes :
8938 ///   %1 = smaxv %0
8939 ///   %result = extract_vector_elt %1, 0
8940 static SDValue
8941 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8942                                         const AArch64Subtarget *Subtarget) {
8943   if (!Subtarget->hasNEON())
8944     return SDValue();
8945
8946   SDValue N0 = N->getOperand(0);
8947   SDValue IfTrue = N->getOperand(1);
8948   SDValue IfFalse = N->getOperand(2);
8949
8950   // Check if the SELECT merges up the final result of the min/max
8951   // from a vector.
8952   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8953       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8954       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8955     return SDValue();
8956
8957   // Expect N0 is fed by SETCC.
8958   SDValue SetCC = N0.getOperand(0);
8959   EVT SetCCVT = SetCC.getValueType();
8960   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8961       SetCCVT.getVectorElementType() != MVT::i1)
8962     return SDValue();
8963
8964   SDValue VectorOp = SetCC.getOperand(0);
8965   unsigned Op = VectorOp->getOpcode();
8966   // Check if the input vector is fed by the operator we want to handle.
8967   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8968       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8969     return SDValue();
8970
8971   EVT VTy = VectorOp.getValueType();
8972   if (!VTy.isVector())
8973     return SDValue();
8974
8975   if (VTy.getSizeInBits() < 64)
8976     return SDValue();
8977
8978   EVT EltTy = VTy.getVectorElementType();
8979   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8980     if (EltTy != MVT::f32)
8981       return SDValue();
8982   } else {
8983     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8984       return SDValue();
8985   }
8986
8987   // Check if extracting from the same vector.
8988   // For example,
8989   //   %sc = setcc %vector, %svn1, gt
8990   //   %n0 = extract_vector_elt %sc, #0
8991   //   %n1 = extract_vector_elt %vector, #0
8992   //   %n2 = extract_vector_elt $vector, #1
8993   if (!(VectorOp == IfTrue->getOperand(0) &&
8994         VectorOp == IfFalse->getOperand(0)))
8995     return SDValue();
8996
8997   // Check if the condition code is matched with the operator type.
8998   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8999   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9000       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9001       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9002       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9003       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9004        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9005        CC != ISD::SETGE) ||
9006       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9007        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9008        CC != ISD::SETLE))
9009     return SDValue();
9010
9011   // Expect to check only lane 0 from the vector SETCC.
9012   if (!isNullConstant(N0.getOperand(1)))
9013     return SDValue();
9014
9015   // Expect to extract the true value from lane 0.
9016   if (!isNullConstant(IfTrue.getOperand(1)))
9017     return SDValue();
9018
9019   // Expect to extract the false value from lane 1.
9020   if (!isOneConstant(IfFalse.getOperand(1)))
9021     return SDValue();
9022
9023   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9024 }
9025
9026 /// Target-specific DAG combine for the across vector add reduction.
9027 /// This function specifically handles the final clean-up step of the vector
9028 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9029 /// pattern, which adds all elements of a vector together.
9030 /// For example, for a <4 x i32> vector :
9031 ///   %1 = vector_shuffle %0, <2,3,u,u>
9032 ///   %2 = add %0, %1
9033 ///   %3 = vector_shuffle %2, <1,u,u,u>
9034 ///   %4 = add %2, %3
9035 ///   %result = extract_vector_elt %4, 0
9036 /// becomes :
9037 ///   %0 = uaddv %0
9038 ///   %result = extract_vector_elt %0, 0
9039 static SDValue
9040 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9041                                      const AArch64Subtarget *Subtarget) {
9042   if (!Subtarget->hasNEON())
9043     return SDValue();
9044   SDValue N0 = N->getOperand(0);
9045   SDValue N1 = N->getOperand(1);
9046
9047   // Check if the input vector is fed by the ADD.
9048   if (N0->getOpcode() != ISD::ADD)
9049     return SDValue();
9050
9051   // The vector extract idx must constant zero because we only expect the final
9052   // result of the reduction is placed in lane 0.
9053   if (!isNullConstant(N1))
9054     return SDValue();
9055
9056   EVT VTy = N0.getValueType();
9057   if (!VTy.isVector())
9058     return SDValue();
9059
9060   EVT EltTy = VTy.getVectorElementType();
9061   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9062     return SDValue();
9063
9064   if (VTy.getSizeInBits() < 64)
9065     return SDValue();
9066
9067   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9068 }
9069
9070 /// Target-specific DAG combine function for NEON load/store intrinsics
9071 /// to merge base address updates.
9072 static SDValue performNEONPostLDSTCombine(SDNode *N,
9073                                           TargetLowering::DAGCombinerInfo &DCI,
9074                                           SelectionDAG &DAG) {
9075   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9076     return SDValue();
9077
9078   unsigned AddrOpIdx = N->getNumOperands() - 1;
9079   SDValue Addr = N->getOperand(AddrOpIdx);
9080
9081   // Search for a use of the address operand that is an increment.
9082   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9083        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9084     SDNode *User = *UI;
9085     if (User->getOpcode() != ISD::ADD ||
9086         UI.getUse().getResNo() != Addr.getResNo())
9087       continue;
9088
9089     // Check that the add is independent of the load/store.  Otherwise, folding
9090     // it would create a cycle.
9091     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9092       continue;
9093
9094     // Find the new opcode for the updating load/store.
9095     bool IsStore = false;
9096     bool IsLaneOp = false;
9097     bool IsDupOp = false;
9098     unsigned NewOpc = 0;
9099     unsigned NumVecs = 0;
9100     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9101     switch (IntNo) {
9102     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9103     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9104       NumVecs = 2; break;
9105     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9106       NumVecs = 3; break;
9107     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9108       NumVecs = 4; break;
9109     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9110       NumVecs = 2; IsStore = true; break;
9111     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9112       NumVecs = 3; IsStore = true; break;
9113     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9114       NumVecs = 4; IsStore = true; break;
9115     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9116       NumVecs = 2; break;
9117     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9118       NumVecs = 3; break;
9119     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9120       NumVecs = 4; break;
9121     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9122       NumVecs = 2; IsStore = true; break;
9123     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9124       NumVecs = 3; IsStore = true; break;
9125     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9126       NumVecs = 4; IsStore = true; break;
9127     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9128       NumVecs = 2; IsDupOp = true; break;
9129     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9130       NumVecs = 3; IsDupOp = true; break;
9131     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9132       NumVecs = 4; IsDupOp = true; break;
9133     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9134       NumVecs = 2; IsLaneOp = true; break;
9135     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9136       NumVecs = 3; IsLaneOp = true; break;
9137     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9138       NumVecs = 4; IsLaneOp = true; break;
9139     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9140       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9141     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9142       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9143     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9144       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9145     }
9146
9147     EVT VecTy;
9148     if (IsStore)
9149       VecTy = N->getOperand(2).getValueType();
9150     else
9151       VecTy = N->getValueType(0);
9152
9153     // If the increment is a constant, it must match the memory ref size.
9154     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9155     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9156       uint32_t IncVal = CInc->getZExtValue();
9157       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9158       if (IsLaneOp || IsDupOp)
9159         NumBytes /= VecTy.getVectorNumElements();
9160       if (IncVal != NumBytes)
9161         continue;
9162       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9163     }
9164     SmallVector<SDValue, 8> Ops;
9165     Ops.push_back(N->getOperand(0)); // Incoming chain
9166     // Load lane and store have vector list as input.
9167     if (IsLaneOp || IsStore)
9168       for (unsigned i = 2; i < AddrOpIdx; ++i)
9169         Ops.push_back(N->getOperand(i));
9170     Ops.push_back(Addr); // Base register
9171     Ops.push_back(Inc);
9172
9173     // Return Types.
9174     EVT Tys[6];
9175     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9176     unsigned n;
9177     for (n = 0; n < NumResultVecs; ++n)
9178       Tys[n] = VecTy;
9179     Tys[n++] = MVT::i64;  // Type of write back register
9180     Tys[n] = MVT::Other;  // Type of the chain
9181     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9182
9183     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9184     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9185                                            MemInt->getMemoryVT(),
9186                                            MemInt->getMemOperand());
9187
9188     // Update the uses.
9189     std::vector<SDValue> NewResults;
9190     for (unsigned i = 0; i < NumResultVecs; ++i) {
9191       NewResults.push_back(SDValue(UpdN.getNode(), i));
9192     }
9193     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9194     DCI.CombineTo(N, NewResults);
9195     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9196
9197     break;
9198   }
9199   return SDValue();
9200 }
9201
9202 // Checks to see if the value is the prescribed width and returns information
9203 // about its extension mode.
9204 static
9205 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9206   ExtType = ISD::NON_EXTLOAD;
9207   switch(V.getNode()->getOpcode()) {
9208   default:
9209     return false;
9210   case ISD::LOAD: {
9211     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9212     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9213        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9214       ExtType = LoadNode->getExtensionType();
9215       return true;
9216     }
9217     return false;
9218   }
9219   case ISD::AssertSext: {
9220     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9221     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9222        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9223       ExtType = ISD::SEXTLOAD;
9224       return true;
9225     }
9226     return false;
9227   }
9228   case ISD::AssertZext: {
9229     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9230     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9231        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9232       ExtType = ISD::ZEXTLOAD;
9233       return true;
9234     }
9235     return false;
9236   }
9237   case ISD::Constant:
9238   case ISD::TargetConstant: {
9239     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9240         1LL << (width - 1))
9241       return true;
9242     return false;
9243   }
9244   }
9245
9246   return true;
9247 }
9248
9249 // This function does a whole lot of voodoo to determine if the tests are
9250 // equivalent without and with a mask. Essentially what happens is that given a
9251 // DAG resembling:
9252 //
9253 //  +-------------+ +-------------+ +-------------+ +-------------+
9254 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9255 //  +-------------+ +-------------+ +-------------+ +-------------+
9256 //           |           |           |               |
9257 //           V           V           |    +----------+
9258 //          +-------------+  +----+  |    |
9259 //          |     ADD     |  |0xff|  |    |
9260 //          +-------------+  +----+  |    |
9261 //                  |           |    |    |
9262 //                  V           V    |    |
9263 //                 +-------------+   |    |
9264 //                 |     AND     |   |    |
9265 //                 +-------------+   |    |
9266 //                      |            |    |
9267 //                      +-----+      |    |
9268 //                            |      |    |
9269 //                            V      V    V
9270 //                           +-------------+
9271 //                           |     CMP     |
9272 //                           +-------------+
9273 //
9274 // The AND node may be safely removed for some combinations of inputs. In
9275 // particular we need to take into account the extension type of the Input,
9276 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9277 // width of the input (this can work for any width inputs, the above graph is
9278 // specific to 8 bits.
9279 //
9280 // The specific equations were worked out by generating output tables for each
9281 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9282 // problem was simplified by working with 4 bit inputs, which means we only
9283 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9284 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9285 // patterns present in both extensions (0,7). For every distinct set of
9286 // AddConstant and CompConstants bit patterns we can consider the masked and
9287 // unmasked versions to be equivalent if the result of this function is true for
9288 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9289 //
9290 //   sub      w8, w0, w1
9291 //   and      w10, w8, #0x0f
9292 //   cmp      w8, w2
9293 //   cset     w9, AArch64CC
9294 //   cmp      w10, w2
9295 //   cset     w11, AArch64CC
9296 //   cmp      w9, w11
9297 //   cset     w0, eq
9298 //   ret
9299 //
9300 // Since the above function shows when the outputs are equivalent it defines
9301 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9302 // would be expensive to run during compiles. The equations below were written
9303 // in a test harness that confirmed they gave equivalent outputs to the above
9304 // for all inputs function, so they can be used determine if the removal is
9305 // legal instead.
9306 //
9307 // isEquivalentMaskless() is the code for testing if the AND can be removed
9308 // factored out of the DAG recognition as the DAG can take several forms.
9309
9310 static
9311 bool isEquivalentMaskless(unsigned CC, unsigned width,
9312                           ISD::LoadExtType ExtType, signed AddConstant,
9313                           signed CompConstant) {
9314   // By being careful about our equations and only writing the in term
9315   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9316   // make them generally applicable to all bit widths.
9317   signed MaxUInt = (1 << width);
9318
9319   // For the purposes of these comparisons sign extending the type is
9320   // equivalent to zero extending the add and displacing it by half the integer
9321   // width. Provided we are careful and make sure our equations are valid over
9322   // the whole range we can just adjust the input and avoid writing equations
9323   // for sign extended inputs.
9324   if (ExtType == ISD::SEXTLOAD)
9325     AddConstant -= (1 << (width-1));
9326
9327   switch(CC) {
9328   case AArch64CC::LE:
9329   case AArch64CC::GT: {
9330     if ((AddConstant == 0) ||
9331         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9332         (AddConstant >= 0 && CompConstant < 0) ||
9333         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9334       return true;
9335   } break;
9336   case AArch64CC::LT:
9337   case AArch64CC::GE: {
9338     if ((AddConstant == 0) ||
9339         (AddConstant >= 0 && CompConstant <= 0) ||
9340         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9341       return true;
9342   } break;
9343   case AArch64CC::HI:
9344   case AArch64CC::LS: {
9345     if ((AddConstant >= 0 && CompConstant < 0) ||
9346        (AddConstant <= 0 && CompConstant >= -1 &&
9347         CompConstant < AddConstant + MaxUInt))
9348       return true;
9349   } break;
9350   case AArch64CC::PL:
9351   case AArch64CC::MI: {
9352     if ((AddConstant == 0) ||
9353         (AddConstant > 0 && CompConstant <= 0) ||
9354         (AddConstant < 0 && CompConstant <= AddConstant))
9355       return true;
9356   } break;
9357   case AArch64CC::LO:
9358   case AArch64CC::HS: {
9359     if ((AddConstant >= 0 && CompConstant <= 0) ||
9360         (AddConstant <= 0 && CompConstant >= 0 &&
9361          CompConstant <= AddConstant + MaxUInt))
9362       return true;
9363   } break;
9364   case AArch64CC::EQ:
9365   case AArch64CC::NE: {
9366     if ((AddConstant > 0 && CompConstant < 0) ||
9367         (AddConstant < 0 && CompConstant >= 0 &&
9368          CompConstant < AddConstant + MaxUInt) ||
9369         (AddConstant >= 0 && CompConstant >= 0 &&
9370          CompConstant >= AddConstant) ||
9371         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9372
9373       return true;
9374   } break;
9375   case AArch64CC::VS:
9376   case AArch64CC::VC:
9377   case AArch64CC::AL:
9378   case AArch64CC::NV:
9379     return true;
9380   case AArch64CC::Invalid:
9381     break;
9382   }
9383
9384   return false;
9385 }
9386
9387 static
9388 SDValue performCONDCombine(SDNode *N,
9389                            TargetLowering::DAGCombinerInfo &DCI,
9390                            SelectionDAG &DAG, unsigned CCIndex,
9391                            unsigned CmpIndex) {
9392   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9393   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9394   unsigned CondOpcode = SubsNode->getOpcode();
9395
9396   if (CondOpcode != AArch64ISD::SUBS)
9397     return SDValue();
9398
9399   // There is a SUBS feeding this condition. Is it fed by a mask we can
9400   // use?
9401
9402   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9403   unsigned MaskBits = 0;
9404
9405   if (AndNode->getOpcode() != ISD::AND)
9406     return SDValue();
9407
9408   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9409     uint32_t CNV = CN->getZExtValue();
9410     if (CNV == 255)
9411       MaskBits = 8;
9412     else if (CNV == 65535)
9413       MaskBits = 16;
9414   }
9415
9416   if (!MaskBits)
9417     return SDValue();
9418
9419   SDValue AddValue = AndNode->getOperand(0);
9420
9421   if (AddValue.getOpcode() != ISD::ADD)
9422     return SDValue();
9423
9424   // The basic dag structure is correct, grab the inputs and validate them.
9425
9426   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9427   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9428   SDValue SubsInputValue = SubsNode->getOperand(1);
9429
9430   // The mask is present and the provenance of all the values is a smaller type,
9431   // lets see if the mask is superfluous.
9432
9433   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9434       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9435     return SDValue();
9436
9437   ISD::LoadExtType ExtType;
9438
9439   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9440       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9441       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9442     return SDValue();
9443
9444   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9445                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9446                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9447     return SDValue();
9448
9449   // The AND is not necessary, remove it.
9450
9451   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9452                                SubsNode->getValueType(1));
9453   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9454
9455   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9456   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9457
9458   return SDValue(N, 0);
9459 }
9460
9461 // Optimize compare with zero and branch.
9462 static SDValue performBRCONDCombine(SDNode *N,
9463                                     TargetLowering::DAGCombinerInfo &DCI,
9464                                     SelectionDAG &DAG) {
9465   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9466   if (NV.getNode())
9467     N = NV.getNode();
9468   SDValue Chain = N->getOperand(0);
9469   SDValue Dest = N->getOperand(1);
9470   SDValue CCVal = N->getOperand(2);
9471   SDValue Cmp = N->getOperand(3);
9472
9473   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9474   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9475   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9476     return SDValue();
9477
9478   unsigned CmpOpc = Cmp.getOpcode();
9479   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9480     return SDValue();
9481
9482   // Only attempt folding if there is only one use of the flag and no use of the
9483   // value.
9484   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9485     return SDValue();
9486
9487   SDValue LHS = Cmp.getOperand(0);
9488   SDValue RHS = Cmp.getOperand(1);
9489
9490   assert(LHS.getValueType() == RHS.getValueType() &&
9491          "Expected the value type to be the same for both operands!");
9492   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9493     return SDValue();
9494
9495   if (isNullConstant(LHS))
9496     std::swap(LHS, RHS);
9497
9498   if (!isNullConstant(RHS))
9499     return SDValue();
9500
9501   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9502       LHS.getOpcode() == ISD::SRL)
9503     return SDValue();
9504
9505   // Fold the compare into the branch instruction.
9506   SDValue BR;
9507   if (CC == AArch64CC::EQ)
9508     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9509   else
9510     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9511
9512   // Do not add new nodes to DAG combiner worklist.
9513   DCI.CombineTo(N, BR, false);
9514
9515   return SDValue();
9516 }
9517
9518 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9519 // as well as whether the test should be inverted.  This code is required to
9520 // catch these cases (as opposed to standard dag combines) because
9521 // AArch64ISD::TBZ is matched during legalization.
9522 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9523                                  SelectionDAG &DAG) {
9524
9525   if (!Op->hasOneUse())
9526     return Op;
9527
9528   // We don't handle undef/constant-fold cases below, as they should have
9529   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9530   // etc.)
9531
9532   // (tbz (trunc x), b) -> (tbz x, b)
9533   // This case is just here to enable more of the below cases to be caught.
9534   if (Op->getOpcode() == ISD::TRUNCATE &&
9535       Bit < Op->getValueType(0).getSizeInBits()) {
9536     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9537   }
9538
9539   if (Op->getNumOperands() != 2)
9540     return Op;
9541
9542   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9543   if (!C)
9544     return Op;
9545
9546   switch (Op->getOpcode()) {
9547   default:
9548     return Op;
9549
9550   // (tbz (and x, m), b) -> (tbz x, b)
9551   case ISD::AND:
9552     if ((C->getZExtValue() >> Bit) & 1)
9553       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9554     return Op;
9555
9556   // (tbz (shl x, c), b) -> (tbz x, b-c)
9557   case ISD::SHL:
9558     if (C->getZExtValue() <= Bit &&
9559         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9560       Bit = Bit - C->getZExtValue();
9561       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9562     }
9563     return Op;
9564
9565   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9566   case ISD::SRA:
9567     Bit = Bit + C->getZExtValue();
9568     if (Bit >= Op->getValueType(0).getSizeInBits())
9569       Bit = Op->getValueType(0).getSizeInBits() - 1;
9570     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9571
9572   // (tbz (srl x, c), b) -> (tbz x, b+c)
9573   case ISD::SRL:
9574     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9575       Bit = Bit + C->getZExtValue();
9576       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9577     }
9578     return Op;
9579
9580   // (tbz (xor x, -1), b) -> (tbnz x, b)
9581   case ISD::XOR:
9582     if ((C->getZExtValue() >> Bit) & 1)
9583       Invert = !Invert;
9584     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9585   }
9586 }
9587
9588 // Optimize test single bit zero/non-zero and branch.
9589 static SDValue performTBZCombine(SDNode *N,
9590                                  TargetLowering::DAGCombinerInfo &DCI,
9591                                  SelectionDAG &DAG) {
9592   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9593   bool Invert = false;
9594   SDValue TestSrc = N->getOperand(1);
9595   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9596
9597   if (TestSrc == NewTestSrc)
9598     return SDValue();
9599
9600   unsigned NewOpc = N->getOpcode();
9601   if (Invert) {
9602     if (NewOpc == AArch64ISD::TBZ)
9603       NewOpc = AArch64ISD::TBNZ;
9604     else {
9605       assert(NewOpc == AArch64ISD::TBNZ);
9606       NewOpc = AArch64ISD::TBZ;
9607     }
9608   }
9609
9610   SDLoc DL(N);
9611   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9612                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9613 }
9614
9615 // vselect (v1i1 setcc) ->
9616 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9617 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9618 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9619 // such VSELECT.
9620 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9621   SDValue N0 = N->getOperand(0);
9622   EVT CCVT = N0.getValueType();
9623
9624   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9625       CCVT.getVectorElementType() != MVT::i1)
9626     return SDValue();
9627
9628   EVT ResVT = N->getValueType(0);
9629   EVT CmpVT = N0.getOperand(0).getValueType();
9630   // Only combine when the result type is of the same size as the compared
9631   // operands.
9632   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9633     return SDValue();
9634
9635   SDValue IfTrue = N->getOperand(1);
9636   SDValue IfFalse = N->getOperand(2);
9637   SDValue SetCC =
9638       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9639                    N0.getOperand(0), N0.getOperand(1),
9640                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9641   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9642                      IfTrue, IfFalse);
9643 }
9644
9645 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9646 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9647 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9648 /// with a vector one followed by a DUP shuffle on the result.
9649 static SDValue performSelectCombine(SDNode *N,
9650                                     TargetLowering::DAGCombinerInfo &DCI) {
9651   SelectionDAG &DAG = DCI.DAG;
9652   SDValue N0 = N->getOperand(0);
9653   EVT ResVT = N->getValueType(0);
9654
9655   if (N0.getOpcode() != ISD::SETCC)
9656     return SDValue();
9657
9658   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9659   // scalar SetCCResultType. We also don't expect vectors, because we assume
9660   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9661   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9662          "Scalar-SETCC feeding SELECT has unexpected result type!");
9663
9664   // If NumMaskElts == 0, the comparison is larger than select result. The
9665   // largest real NEON comparison is 64-bits per lane, which means the result is
9666   // at most 32-bits and an illegal vector. Just bail out for now.
9667   EVT SrcVT = N0.getOperand(0).getValueType();
9668
9669   // Don't try to do this optimization when the setcc itself has i1 operands.
9670   // There are no legal vectors of i1, so this would be pointless.
9671   if (SrcVT == MVT::i1)
9672     return SDValue();
9673
9674   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9675   if (!ResVT.isVector() || NumMaskElts == 0)
9676     return SDValue();
9677
9678   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9679   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9680
9681   // Also bail out if the vector CCVT isn't the same size as ResVT.
9682   // This can happen if the SETCC operand size doesn't divide the ResVT size
9683   // (e.g., f64 vs v3f32).
9684   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9685     return SDValue();
9686
9687   // Make sure we didn't create illegal types, if we're not supposed to.
9688   assert(DCI.isBeforeLegalize() ||
9689          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9690
9691   // First perform a vector comparison, where lane 0 is the one we're interested
9692   // in.
9693   SDLoc DL(N0);
9694   SDValue LHS =
9695       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9696   SDValue RHS =
9697       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9698   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9699
9700   // Now duplicate the comparison mask we want across all other lanes.
9701   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9702   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9703   Mask = DAG.getNode(ISD::BITCAST, DL,
9704                      ResVT.changeVectorElementTypeToInteger(), Mask);
9705
9706   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9707 }
9708
9709 /// Get rid of unnecessary NVCASTs (that don't change the type).
9710 static SDValue performNVCASTCombine(SDNode *N) {
9711   if (N->getValueType(0) == N->getOperand(0).getValueType())
9712     return N->getOperand(0);
9713
9714   return SDValue();
9715 }
9716
9717 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9718                                                  DAGCombinerInfo &DCI) const {
9719   SelectionDAG &DAG = DCI.DAG;
9720   switch (N->getOpcode()) {
9721   default:
9722     break;
9723   case ISD::ADD:
9724   case ISD::SUB:
9725     return performAddSubLongCombine(N, DCI, DAG);
9726   case ISD::XOR:
9727     return performXorCombine(N, DAG, DCI, Subtarget);
9728   case ISD::MUL:
9729     return performMulCombine(N, DAG, DCI, Subtarget);
9730   case ISD::SINT_TO_FP:
9731   case ISD::UINT_TO_FP:
9732     return performIntToFpCombine(N, DAG, Subtarget);
9733   case ISD::FP_TO_SINT:
9734   case ISD::FP_TO_UINT:
9735     return performFpToIntCombine(N, DAG, DCI, Subtarget);
9736   case ISD::FDIV:
9737     return performFDivCombine(N, DAG, Subtarget);
9738   case ISD::OR:
9739     return performORCombine(N, DCI, Subtarget);
9740   case ISD::INTRINSIC_WO_CHAIN:
9741     return performIntrinsicCombine(N, DCI, Subtarget);
9742   case ISD::ANY_EXTEND:
9743   case ISD::ZERO_EXTEND:
9744   case ISD::SIGN_EXTEND:
9745     return performExtendCombine(N, DCI, DAG);
9746   case ISD::BITCAST:
9747     return performBitcastCombine(N, DCI, DAG);
9748   case ISD::CONCAT_VECTORS:
9749     return performConcatVectorsCombine(N, DCI, DAG);
9750   case ISD::SELECT: {
9751     SDValue RV = performSelectCombine(N, DCI);
9752     if (!RV.getNode())
9753       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9754     return RV;
9755   }
9756   case ISD::VSELECT:
9757     return performVSelectCombine(N, DCI.DAG);
9758   case ISD::LOAD:
9759     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9760       return SDValue(N, 0);
9761     break;
9762   case ISD::STORE:
9763     return performSTORECombine(N, DCI, DAG, Subtarget);
9764   case AArch64ISD::BRCOND:
9765     return performBRCONDCombine(N, DCI, DAG);
9766   case AArch64ISD::TBNZ:
9767   case AArch64ISD::TBZ:
9768     return performTBZCombine(N, DCI, DAG);
9769   case AArch64ISD::CSEL:
9770     return performCONDCombine(N, DCI, DAG, 2, 3);
9771   case AArch64ISD::DUP:
9772     return performPostLD1Combine(N, DCI, false);
9773   case AArch64ISD::NVCAST:
9774     return performNVCASTCombine(N);
9775   case ISD::INSERT_VECTOR_ELT:
9776     return performPostLD1Combine(N, DCI, true);
9777   case ISD::EXTRACT_VECTOR_ELT:
9778     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9779   case ISD::INTRINSIC_VOID:
9780   case ISD::INTRINSIC_W_CHAIN:
9781     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9782     case Intrinsic::aarch64_neon_ld2:
9783     case Intrinsic::aarch64_neon_ld3:
9784     case Intrinsic::aarch64_neon_ld4:
9785     case Intrinsic::aarch64_neon_ld1x2:
9786     case Intrinsic::aarch64_neon_ld1x3:
9787     case Intrinsic::aarch64_neon_ld1x4:
9788     case Intrinsic::aarch64_neon_ld2lane:
9789     case Intrinsic::aarch64_neon_ld3lane:
9790     case Intrinsic::aarch64_neon_ld4lane:
9791     case Intrinsic::aarch64_neon_ld2r:
9792     case Intrinsic::aarch64_neon_ld3r:
9793     case Intrinsic::aarch64_neon_ld4r:
9794     case Intrinsic::aarch64_neon_st2:
9795     case Intrinsic::aarch64_neon_st3:
9796     case Intrinsic::aarch64_neon_st4:
9797     case Intrinsic::aarch64_neon_st1x2:
9798     case Intrinsic::aarch64_neon_st1x3:
9799     case Intrinsic::aarch64_neon_st1x4:
9800     case Intrinsic::aarch64_neon_st2lane:
9801     case Intrinsic::aarch64_neon_st3lane:
9802     case Intrinsic::aarch64_neon_st4lane:
9803       return performNEONPostLDSTCombine(N, DCI, DAG);
9804     default:
9805       break;
9806     }
9807   }
9808   return SDValue();
9809 }
9810
9811 // Check if the return value is used as only a return value, as otherwise
9812 // we can't perform a tail-call. In particular, we need to check for
9813 // target ISD nodes that are returns and any other "odd" constructs
9814 // that the generic analysis code won't necessarily catch.
9815 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9816                                                SDValue &Chain) const {
9817   if (N->getNumValues() != 1)
9818     return false;
9819   if (!N->hasNUsesOfValue(1, 0))
9820     return false;
9821
9822   SDValue TCChain = Chain;
9823   SDNode *Copy = *N->use_begin();
9824   if (Copy->getOpcode() == ISD::CopyToReg) {
9825     // If the copy has a glue operand, we conservatively assume it isn't safe to
9826     // perform a tail call.
9827     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9828         MVT::Glue)
9829       return false;
9830     TCChain = Copy->getOperand(0);
9831   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9832     return false;
9833
9834   bool HasRet = false;
9835   for (SDNode *Node : Copy->uses()) {
9836     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9837       return false;
9838     HasRet = true;
9839   }
9840
9841   if (!HasRet)
9842     return false;
9843
9844   Chain = TCChain;
9845   return true;
9846 }
9847
9848 // Return whether the an instruction can potentially be optimized to a tail
9849 // call. This will cause the optimizers to attempt to move, or duplicate,
9850 // return instructions to help enable tail call optimizations for this
9851 // instruction.
9852 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9853   if (!CI->isTailCall())
9854     return false;
9855
9856   return true;
9857 }
9858
9859 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9860                                                    SDValue &Offset,
9861                                                    ISD::MemIndexedMode &AM,
9862                                                    bool &IsInc,
9863                                                    SelectionDAG &DAG) const {
9864   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9865     return false;
9866
9867   Base = Op->getOperand(0);
9868   // All of the indexed addressing mode instructions take a signed
9869   // 9 bit immediate offset.
9870   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9871     int64_t RHSC = (int64_t)RHS->getZExtValue();
9872     if (RHSC >= 256 || RHSC <= -256)
9873       return false;
9874     IsInc = (Op->getOpcode() == ISD::ADD);
9875     Offset = Op->getOperand(1);
9876     return true;
9877   }
9878   return false;
9879 }
9880
9881 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9882                                                       SDValue &Offset,
9883                                                       ISD::MemIndexedMode &AM,
9884                                                       SelectionDAG &DAG) const {
9885   EVT VT;
9886   SDValue Ptr;
9887   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9888     VT = LD->getMemoryVT();
9889     Ptr = LD->getBasePtr();
9890   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9891     VT = ST->getMemoryVT();
9892     Ptr = ST->getBasePtr();
9893   } else
9894     return false;
9895
9896   bool IsInc;
9897   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9898     return false;
9899   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9900   return true;
9901 }
9902
9903 bool AArch64TargetLowering::getPostIndexedAddressParts(
9904     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9905     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9906   EVT VT;
9907   SDValue Ptr;
9908   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9909     VT = LD->getMemoryVT();
9910     Ptr = LD->getBasePtr();
9911   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9912     VT = ST->getMemoryVT();
9913     Ptr = ST->getBasePtr();
9914   } else
9915     return false;
9916
9917   bool IsInc;
9918   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9919     return false;
9920   // Post-indexing updates the base, so it's not a valid transform
9921   // if that's not the same as the load's pointer.
9922   if (Ptr != Base)
9923     return false;
9924   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9925   return true;
9926 }
9927
9928 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9929                                   SelectionDAG &DAG) {
9930   SDLoc DL(N);
9931   SDValue Op = N->getOperand(0);
9932
9933   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9934     return;
9935
9936   Op = SDValue(
9937       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9938                          DAG.getUNDEF(MVT::i32), Op,
9939                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9940       0);
9941   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9942   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9943 }
9944
9945 static void ReplaceReductionResults(SDNode *N,
9946                                     SmallVectorImpl<SDValue> &Results,
9947                                     SelectionDAG &DAG, unsigned InterOp,
9948                                     unsigned AcrossOp) {
9949   EVT LoVT, HiVT;
9950   SDValue Lo, Hi;
9951   SDLoc dl(N);
9952   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9953   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9954   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9955   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9956   Results.push_back(SplitVal);
9957 }
9958
9959 void AArch64TargetLowering::ReplaceNodeResults(
9960     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9961   switch (N->getOpcode()) {
9962   default:
9963     llvm_unreachable("Don't know how to custom expand this");
9964   case ISD::BITCAST:
9965     ReplaceBITCASTResults(N, Results, DAG);
9966     return;
9967   case AArch64ISD::SADDV:
9968     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9969     return;
9970   case AArch64ISD::UADDV:
9971     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9972     return;
9973   case AArch64ISD::SMINV:
9974     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9975     return;
9976   case AArch64ISD::UMINV:
9977     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9978     return;
9979   case AArch64ISD::SMAXV:
9980     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9981     return;
9982   case AArch64ISD::UMAXV:
9983     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9984     return;
9985   case ISD::FP_TO_UINT:
9986   case ISD::FP_TO_SINT:
9987     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9988     // Let normal code take care of it by not adding anything to Results.
9989     return;
9990   }
9991 }
9992
9993 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9994   return true;
9995 }
9996
9997 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9998   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9999   // reciprocal if there are three or more FDIVs.
10000   return 3;
10001 }
10002
10003 TargetLoweringBase::LegalizeTypeAction
10004 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10005   MVT SVT = VT.getSimpleVT();
10006   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10007   // v4i16, v2i32 instead of to promote.
10008   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10009       || SVT == MVT::v1f32)
10010     return TypeWidenVector;
10011
10012   return TargetLoweringBase::getPreferredVectorAction(VT);
10013 }
10014
10015 // Loads and stores less than 128-bits are already atomic; ones above that
10016 // are doomed anyway, so defer to the default libcall and blame the OS when
10017 // things go wrong.
10018 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10019   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10020   return Size == 128;
10021 }
10022
10023 // Loads and stores less than 128-bits are already atomic; ones above that
10024 // are doomed anyway, so defer to the default libcall and blame the OS when
10025 // things go wrong.
10026 TargetLowering::AtomicExpansionKind
10027 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10028   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10029   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10030 }
10031
10032 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10033 TargetLowering::AtomicExpansionKind
10034 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10035   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10036   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10037 }
10038
10039 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10040     AtomicCmpXchgInst *AI) const {
10041   return true;
10042 }
10043
10044 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10045                                              AtomicOrdering Ord) const {
10046   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10047   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10048   bool IsAcquire = isAtLeastAcquire(Ord);
10049
10050   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10051   // intrinsic must return {i64, i64} and we have to recombine them into a
10052   // single i128 here.
10053   if (ValTy->getPrimitiveSizeInBits() == 128) {
10054     Intrinsic::ID Int =
10055         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10056     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10057
10058     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10059     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10060
10061     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10062     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10063     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10064     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10065     return Builder.CreateOr(
10066         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10067   }
10068
10069   Type *Tys[] = { Addr->getType() };
10070   Intrinsic::ID Int =
10071       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10072   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10073
10074   return Builder.CreateTruncOrBitCast(
10075       Builder.CreateCall(Ldxr, Addr),
10076       cast<PointerType>(Addr->getType())->getElementType());
10077 }
10078
10079 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10080     IRBuilder<> &Builder) const {
10081   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10082   Builder.CreateCall(
10083       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10084 }
10085
10086 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10087                                                    Value *Val, Value *Addr,
10088                                                    AtomicOrdering Ord) const {
10089   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10090   bool IsRelease = isAtLeastRelease(Ord);
10091
10092   // Since the intrinsics must have legal type, the i128 intrinsics take two
10093   // parameters: "i64, i64". We must marshal Val into the appropriate form
10094   // before the call.
10095   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10096     Intrinsic::ID Int =
10097         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10098     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10099     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10100
10101     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10102     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10103     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10104     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10105   }
10106
10107   Intrinsic::ID Int =
10108       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10109   Type *Tys[] = { Addr->getType() };
10110   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10111
10112   return Builder.CreateCall(Stxr,
10113                             {Builder.CreateZExtOrBitCast(
10114                                  Val, Stxr->getFunctionType()->getParamType(0)),
10115                              Addr});
10116 }
10117
10118 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10119     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10120   return Ty->isArrayTy();
10121 }
10122
10123 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10124                                                             EVT) const {
10125   return false;
10126 }
10127
10128 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10129   if (!Subtarget->isTargetAndroid())
10130     return TargetLowering::getSafeStackPointerLocation(IRB);
10131
10132   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10133   // definition of TLS_SLOT_SAFESTACK in
10134   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10135   const unsigned TlsOffset = 0x48;
10136   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10137   Function *ThreadPointerFunc =
10138       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10139   return IRB.CreatePointerCast(
10140       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10141       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10142 }
10143
10144 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10145   // Update IsSplitCSR in AArch64unctionInfo.
10146   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10147   AFI->setIsSplitCSR(true);
10148 }
10149
10150 void AArch64TargetLowering::insertCopiesSplitCSR(
10151     MachineBasicBlock *Entry,
10152     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10153   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10154   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10155   if (!IStart)
10156     return;
10157
10158   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10159   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10160   MachineBasicBlock::iterator MBBI = Entry->begin();
10161   for (const MCPhysReg *I = IStart; *I; ++I) {
10162     const TargetRegisterClass *RC = nullptr;
10163     if (AArch64::GPR64RegClass.contains(*I))
10164       RC = &AArch64::GPR64RegClass;
10165     else if (AArch64::FPR64RegClass.contains(*I))
10166       RC = &AArch64::FPR64RegClass;
10167     else
10168       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10169
10170     unsigned NewVR = MRI->createVirtualRegister(RC);
10171     // Create copy from CSR to a virtual register.
10172     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10173     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10174     // nounwind. If we want to generalize this later, we may need to emit
10175     // CFI pseudo-instructions.
10176     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10177                Attribute::NoUnwind) &&
10178            "Function should be nounwind in insertCopiesSplitCSR!");
10179     Entry->addLiveIn(*I);
10180     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10181         .addReg(*I);
10182
10183     // Insert the copy-back instructions right before the terminator.
10184     for (auto *Exit : Exits)
10185       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10186               TII->get(TargetOpcode::COPY), *I)
10187           .addReg(NewVR);
10188   }
10189 }