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