Expose isXxxConstant() functions from SelectionDAGNodes.h (NFC)
[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   setOperationAction(ISD::SREM, MVT::i32, Expand);
241   setOperationAction(ISD::SREM, MVT::i64, Expand);
242   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
244   setOperationAction(ISD::UREM, MVT::i32, Expand);
245   setOperationAction(ISD::UREM, MVT::i64, Expand);
246
247   // Custom lower Add/Sub/Mul with overflow.
248   setOperationAction(ISD::SADDO, MVT::i32, Custom);
249   setOperationAction(ISD::SADDO, MVT::i64, Custom);
250   setOperationAction(ISD::UADDO, MVT::i32, Custom);
251   setOperationAction(ISD::UADDO, MVT::i64, Custom);
252   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
253   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
254   setOperationAction(ISD::USUBO, MVT::i32, Custom);
255   setOperationAction(ISD::USUBO, MVT::i64, Custom);
256   setOperationAction(ISD::SMULO, MVT::i32, Custom);
257   setOperationAction(ISD::SMULO, MVT::i64, Custom);
258   setOperationAction(ISD::UMULO, MVT::i32, Custom);
259   setOperationAction(ISD::UMULO, MVT::i64, Custom);
260
261   setOperationAction(ISD::FSIN, MVT::f32, Expand);
262   setOperationAction(ISD::FSIN, MVT::f64, Expand);
263   setOperationAction(ISD::FCOS, MVT::f32, Expand);
264   setOperationAction(ISD::FCOS, MVT::f64, Expand);
265   setOperationAction(ISD::FPOW, MVT::f32, Expand);
266   setOperationAction(ISD::FPOW, MVT::f64, Expand);
267   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
268   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
269
270   // f16 is a storage-only type, always promote it to f32.
271   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
272   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
273   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
274   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
275   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
276   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
277   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
278   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
279   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
280   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
281   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
282   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
283   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
284   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
285   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
286   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
287   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
288   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
289   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
290   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
291   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
292   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
293   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
294   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
295   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
296   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
297   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
298   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
299   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
300   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
301   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
302   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
303   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
304   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
305
306   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
307   // known to be safe.
308   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
309   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
310   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
311   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
312   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
313   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
314   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
315   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
318   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
320
321   // Expand all other v4f16 operations.
322   // FIXME: We could generate better code by promoting some operations to
323   // a pair of v4f32s
324   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
325   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
326   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
327   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
328   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
329   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
330   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
331   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
332   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
333   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
334   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
335   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
336   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
337   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
338   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
339   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
340   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
341   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
342   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
343   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
344   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
345   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
346   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
347   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
348   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
349   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
350
351
352   // v8f16 is also a storage-only type, so expand it.
353   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
354   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
355   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
356   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
357   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
358   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
359   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
360   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
361   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
362   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
363   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
364   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
365   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
366   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
367   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
368   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
369   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
371   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
372   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
373   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
374   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
375   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
376   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
377   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
378   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
379   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
380   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
381   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
382   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
383   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
384
385   // AArch64 has implementations of a lot of rounding-like FP operations.
386   for (MVT Ty : {MVT::f32, MVT::f64}) {
387     setOperationAction(ISD::FFLOOR, Ty, Legal);
388     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
389     setOperationAction(ISD::FCEIL, Ty, Legal);
390     setOperationAction(ISD::FRINT, Ty, Legal);
391     setOperationAction(ISD::FTRUNC, Ty, Legal);
392     setOperationAction(ISD::FROUND, Ty, Legal);
393     setOperationAction(ISD::FMINNUM, Ty, Legal);
394     setOperationAction(ISD::FMAXNUM, Ty, Legal);
395     setOperationAction(ISD::FMINNAN, Ty, Legal);
396     setOperationAction(ISD::FMAXNAN, Ty, Legal);
397   }
398
399   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
400
401   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
402   // This requires the Performance Monitors extension.
403   if (Subtarget->hasPerfMon())
404     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
405
406   if (Subtarget->isTargetMachO()) {
407     // For iOS, we don't want to the normal expansion of a libcall to
408     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
409     // traffic.
410     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
411     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
412   } else {
413     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
414     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
415   }
416
417   // Make floating-point constants legal for the large code model, so they don't
418   // become loads from the constant pool.
419   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
420     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
421     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
422   }
423
424   // AArch64 does not have floating-point extending loads, i1 sign-extending
425   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
426   for (MVT VT : MVT::fp_valuetypes()) {
427     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
431   }
432   for (MVT VT : MVT::integer_valuetypes())
433     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
434
435   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
436   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
438   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
442
443   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
444   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
445
446   // Indexed loads and stores are supported.
447   for (unsigned im = (unsigned)ISD::PRE_INC;
448        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
449     setIndexedLoadAction(im, MVT::i8, Legal);
450     setIndexedLoadAction(im, MVT::i16, Legal);
451     setIndexedLoadAction(im, MVT::i32, Legal);
452     setIndexedLoadAction(im, MVT::i64, Legal);
453     setIndexedLoadAction(im, MVT::f64, Legal);
454     setIndexedLoadAction(im, MVT::f32, Legal);
455     setIndexedLoadAction(im, MVT::f16, Legal);
456     setIndexedStoreAction(im, MVT::i8, Legal);
457     setIndexedStoreAction(im, MVT::i16, Legal);
458     setIndexedStoreAction(im, MVT::i32, Legal);
459     setIndexedStoreAction(im, MVT::i64, Legal);
460     setIndexedStoreAction(im, MVT::f64, Legal);
461     setIndexedStoreAction(im, MVT::f32, Legal);
462     setIndexedStoreAction(im, MVT::f16, Legal);
463   }
464
465   // Trap.
466   setOperationAction(ISD::TRAP, MVT::Other, Legal);
467
468   // We combine OR nodes for bitfield operations.
469   setTargetDAGCombine(ISD::OR);
470
471   // Vector add and sub nodes may conceal a high-half opportunity.
472   // Also, try to fold ADD into CSINC/CSINV..
473   setTargetDAGCombine(ISD::ADD);
474   setTargetDAGCombine(ISD::SUB);
475
476   setTargetDAGCombine(ISD::XOR);
477   setTargetDAGCombine(ISD::SINT_TO_FP);
478   setTargetDAGCombine(ISD::UINT_TO_FP);
479
480   setTargetDAGCombine(ISD::FP_TO_SINT);
481   setTargetDAGCombine(ISD::FP_TO_UINT);
482   setTargetDAGCombine(ISD::FDIV);
483
484   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
485
486   setTargetDAGCombine(ISD::ANY_EXTEND);
487   setTargetDAGCombine(ISD::ZERO_EXTEND);
488   setTargetDAGCombine(ISD::SIGN_EXTEND);
489   setTargetDAGCombine(ISD::BITCAST);
490   setTargetDAGCombine(ISD::CONCAT_VECTORS);
491   setTargetDAGCombine(ISD::STORE);
492   if (Subtarget->supportsAddressTopByteIgnored())
493     setTargetDAGCombine(ISD::LOAD);
494
495   setTargetDAGCombine(ISD::MUL);
496
497   setTargetDAGCombine(ISD::SELECT);
498   setTargetDAGCombine(ISD::VSELECT);
499
500   setTargetDAGCombine(ISD::INTRINSIC_VOID);
501   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
503   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
504
505   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
506   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
507   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
508
509   setStackPointerRegisterToSaveRestore(AArch64::SP);
510
511   setSchedulingPreference(Sched::Hybrid);
512
513   // Enable TBZ/TBNZ
514   MaskAndBranchFoldingIsLegal = true;
515   EnableExtLdPromotion = true;
516
517   setMinFunctionAlignment(2);
518
519   setHasExtractBitsInsn(true);
520
521   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
522
523   if (Subtarget->hasNEON()) {
524     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
525     // silliness like this:
526     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
527     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
528     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
529     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
530     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
531     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
532     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
533     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
534     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
535     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
536     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
537     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
538     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
539     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
540     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
543     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
544     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
545     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
546     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
547     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
548     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
549     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
550     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
551
552     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
553     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
554     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
555     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
556     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
557
558     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559
560     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
561     // elements smaller than i32, so promote the input to i32 first.
562     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
563     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
564     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
565     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
566     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
567     // -> v8f16 conversions.
568     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
569     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
570     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
571     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
572     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
573     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
575     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
576     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
577     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
578     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
579     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
581
582     // AArch64 doesn't have MUL.2d:
583     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
584     // Custom handling for some quad-vector types to detect MULL.
585     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
586     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
587     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
588
589     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
590     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
591     // Likewise, narrowing and extending vector loads/stores aren't handled
592     // directly.
593     for (MVT VT : MVT::vector_valuetypes()) {
594       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
595
596       setOperationAction(ISD::MULHS, VT, Expand);
597       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
598       setOperationAction(ISD::MULHU, VT, Expand);
599       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
600
601       setOperationAction(ISD::BSWAP, VT, Expand);
602
603       for (MVT InnerVT : MVT::vector_valuetypes()) {
604         setTruncStoreAction(VT, InnerVT, Expand);
605         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
606         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
607         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
608       }
609     }
610
611     // AArch64 has implementations of a lot of rounding-like FP operations.
612     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
613       setOperationAction(ISD::FFLOOR, Ty, Legal);
614       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
615       setOperationAction(ISD::FCEIL, Ty, Legal);
616       setOperationAction(ISD::FRINT, Ty, Legal);
617       setOperationAction(ISD::FTRUNC, Ty, Legal);
618       setOperationAction(ISD::FROUND, Ty, Legal);
619     }
620   }
621
622   // Prefer likely predicted branches to selects on out-of-order cores.
623   if (Subtarget->isCortexA57())
624     PredictableSelectIsExpensive = true;
625 }
626
627 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
628   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
629     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
631
632     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
634   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
635     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
636     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
637
638     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
639     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
640   }
641
642   // Mark vector float intrinsics as expand.
643   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
644     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
647     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
648     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
652     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
653
654     // But we do support custom-lowering for FCOPYSIGN.
655     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
656   }
657
658   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
669   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
670
671   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
672   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
673   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
674   for (MVT InnerVT : MVT::all_valuetypes())
675     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
676
677   // CNT supports only B element sizes.
678   if (VT != MVT::v8i8 && VT != MVT::v16i8)
679     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
680
681   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
682   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
683   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
684   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
685   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
686
687   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
688   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
689
690   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
691   // i64.
692   if (!VT.isFloatingPoint() &&
693       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
694     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
695                             ISD::SABSDIFF, ISD::UABSDIFF})
696       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
697
698   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
699   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
700     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
701                             ISD::FMINNUM, ISD::FMAXNUM})
702       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
703
704   if (Subtarget->isLittleEndian()) {
705     for (unsigned im = (unsigned)ISD::PRE_INC;
706          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
707       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
708       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
709     }
710   }
711 }
712
713 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
714   addRegisterClass(VT, &AArch64::FPR64RegClass);
715   addTypeForNEON(VT, MVT::v2i32);
716 }
717
718 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
719   addRegisterClass(VT, &AArch64::FPR128RegClass);
720   addTypeForNEON(VT, MVT::v4i32);
721 }
722
723 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
724                                               EVT VT) const {
725   if (!VT.isVector())
726     return MVT::i32;
727   return VT.changeVectorElementTypeToInteger();
728 }
729
730 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
731 /// Mask are known to be either zero or one and return them in the
732 /// KnownZero/KnownOne bitsets.
733 void AArch64TargetLowering::computeKnownBitsForTargetNode(
734     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
735     const SelectionDAG &DAG, unsigned Depth) const {
736   switch (Op.getOpcode()) {
737   default:
738     break;
739   case AArch64ISD::CSEL: {
740     APInt KnownZero2, KnownOne2;
741     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
742     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
743     KnownZero &= KnownZero2;
744     KnownOne &= KnownOne2;
745     break;
746   }
747   case ISD::INTRINSIC_W_CHAIN: {
748     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
749     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
750     switch (IntID) {
751     default: return;
752     case Intrinsic::aarch64_ldaxr:
753     case Intrinsic::aarch64_ldxr: {
754       unsigned BitWidth = KnownOne.getBitWidth();
755       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
756       unsigned MemBits = VT.getScalarType().getSizeInBits();
757       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
758       return;
759     }
760     }
761     break;
762   }
763   case ISD::INTRINSIC_WO_CHAIN:
764   case ISD::INTRINSIC_VOID: {
765     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
766     switch (IntNo) {
767     default:
768       break;
769     case Intrinsic::aarch64_neon_umaxv:
770     case Intrinsic::aarch64_neon_uminv: {
771       // Figure out the datatype of the vector operand. The UMINV instruction
772       // will zero extend the result, so we can mark as known zero all the
773       // bits larger than the element datatype. 32-bit or larget doesn't need
774       // this as those are legal types and will be handled by isel directly.
775       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
776       unsigned BitWidth = KnownZero.getBitWidth();
777       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
778         assert(BitWidth >= 8 && "Unexpected width!");
779         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
780         KnownZero |= Mask;
781       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
782         assert(BitWidth >= 16 && "Unexpected width!");
783         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
784         KnownZero |= Mask;
785       }
786       break;
787     } break;
788     }
789   }
790   }
791 }
792
793 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
794                                                   EVT) const {
795   return MVT::i64;
796 }
797
798 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
799                                                            unsigned AddrSpace,
800                                                            unsigned Align,
801                                                            bool *Fast) const {
802   if (Subtarget->requiresStrictAlign())
803     return false;
804
805   // FIXME: This is mostly true for Cyclone, but not necessarily others.
806   if (Fast) {
807     // FIXME: Define an attribute for slow unaligned accesses instead of
808     // relying on the CPU type as a proxy.
809     // On Cyclone, unaligned 128-bit stores are slow.
810     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
811             // See comments in performSTORECombine() for more details about
812             // these conditions.
813
814             // Code that uses clang vector extensions can mark that it
815             // wants unaligned accesses to be treated as fast by
816             // underspecifying alignment to be 1 or 2.
817             Align <= 2 ||
818
819             // Disregard v2i64. Memcpy lowering produces those and splitting
820             // them regresses performance on micro-benchmarks and olden/bh.
821             VT == MVT::v2i64;
822   }
823   return true;
824 }
825
826 FastISel *
827 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
828                                       const TargetLibraryInfo *libInfo) const {
829   return AArch64::createFastISel(funcInfo, libInfo);
830 }
831
832 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
833   switch ((AArch64ISD::NodeType)Opcode) {
834   case AArch64ISD::FIRST_NUMBER:      break;
835   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
836   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
837   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
838   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
839   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
840   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
841   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
842   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
843   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
844   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
845   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
846   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
847   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
848   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
849   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
850   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
851   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
852   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
853   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
854   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
855   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
856   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
857   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
858   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
859   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
860   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
861   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
862   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
863   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
864   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
865   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
866   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
867   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
868   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
869   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
870   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
871   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
872   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
873   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
874   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
875   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
876   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
877   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
878   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
879   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
880   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
881   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
882   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
883   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
884   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
885   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
886   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
887   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
888   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
889   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
890   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
891   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
892   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
893   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
894   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
895   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
896   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
897   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
898   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
899   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
900   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
901   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
902   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
903   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
904   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
905   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
906   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
907   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
908   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
909   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
910   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
911   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
912   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
913   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
914   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
915   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
916   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
917   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
918   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
919   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
920   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
921   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
922   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
923   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
924   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
925   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
926   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
927   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
928   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
929   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
930   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
931   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
932   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
933   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
934   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
935   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
936   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
937   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
938   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
939   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
940   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
941   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
942   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
943   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
944   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
945   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
946   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
947   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
948   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
949   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
950   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
951   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
952   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
953   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
954   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
955   }
956   return nullptr;
957 }
958
959 MachineBasicBlock *
960 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
961                                     MachineBasicBlock *MBB) const {
962   // We materialise the F128CSEL pseudo-instruction as some control flow and a
963   // phi node:
964
965   // OrigBB:
966   //     [... previous instrs leading to comparison ...]
967   //     b.ne TrueBB
968   //     b EndBB
969   // TrueBB:
970   //     ; Fallthrough
971   // EndBB:
972   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
973
974   MachineFunction *MF = MBB->getParent();
975   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
976   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
977   DebugLoc DL = MI->getDebugLoc();
978   MachineFunction::iterator It = ++MBB->getIterator();
979
980   unsigned DestReg = MI->getOperand(0).getReg();
981   unsigned IfTrueReg = MI->getOperand(1).getReg();
982   unsigned IfFalseReg = MI->getOperand(2).getReg();
983   unsigned CondCode = MI->getOperand(3).getImm();
984   bool NZCVKilled = MI->getOperand(4).isKill();
985
986   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
987   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
988   MF->insert(It, TrueBB);
989   MF->insert(It, EndBB);
990
991   // Transfer rest of current basic-block to EndBB
992   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
993                 MBB->end());
994   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
995
996   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
997   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
998   MBB->addSuccessor(TrueBB);
999   MBB->addSuccessor(EndBB);
1000
1001   // TrueBB falls through to the end.
1002   TrueBB->addSuccessor(EndBB);
1003
1004   if (!NZCVKilled) {
1005     TrueBB->addLiveIn(AArch64::NZCV);
1006     EndBB->addLiveIn(AArch64::NZCV);
1007   }
1008
1009   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1010       .addReg(IfTrueReg)
1011       .addMBB(TrueBB)
1012       .addReg(IfFalseReg)
1013       .addMBB(MBB);
1014
1015   MI->eraseFromParent();
1016   return EndBB;
1017 }
1018
1019 MachineBasicBlock *
1020 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1021                                                  MachineBasicBlock *BB) const {
1022   switch (MI->getOpcode()) {
1023   default:
1024 #ifndef NDEBUG
1025     MI->dump();
1026 #endif
1027     llvm_unreachable("Unexpected instruction for custom inserter!");
1028
1029   case AArch64::F128CSEL:
1030     return EmitF128CSEL(MI, BB);
1031
1032   case TargetOpcode::STACKMAP:
1033   case TargetOpcode::PATCHPOINT:
1034     return emitPatchPoint(MI, BB);
1035   }
1036 }
1037
1038 //===----------------------------------------------------------------------===//
1039 // AArch64 Lowering private implementation.
1040 //===----------------------------------------------------------------------===//
1041
1042 //===----------------------------------------------------------------------===//
1043 // Lowering Code
1044 //===----------------------------------------------------------------------===//
1045
1046 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1047 /// CC
1048 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1049   switch (CC) {
1050   default:
1051     llvm_unreachable("Unknown condition code!");
1052   case ISD::SETNE:
1053     return AArch64CC::NE;
1054   case ISD::SETEQ:
1055     return AArch64CC::EQ;
1056   case ISD::SETGT:
1057     return AArch64CC::GT;
1058   case ISD::SETGE:
1059     return AArch64CC::GE;
1060   case ISD::SETLT:
1061     return AArch64CC::LT;
1062   case ISD::SETLE:
1063     return AArch64CC::LE;
1064   case ISD::SETUGT:
1065     return AArch64CC::HI;
1066   case ISD::SETUGE:
1067     return AArch64CC::HS;
1068   case ISD::SETULT:
1069     return AArch64CC::LO;
1070   case ISD::SETULE:
1071     return AArch64CC::LS;
1072   }
1073 }
1074
1075 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1076 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1077                                   AArch64CC::CondCode &CondCode,
1078                                   AArch64CC::CondCode &CondCode2) {
1079   CondCode2 = AArch64CC::AL;
1080   switch (CC) {
1081   default:
1082     llvm_unreachable("Unknown FP condition!");
1083   case ISD::SETEQ:
1084   case ISD::SETOEQ:
1085     CondCode = AArch64CC::EQ;
1086     break;
1087   case ISD::SETGT:
1088   case ISD::SETOGT:
1089     CondCode = AArch64CC::GT;
1090     break;
1091   case ISD::SETGE:
1092   case ISD::SETOGE:
1093     CondCode = AArch64CC::GE;
1094     break;
1095   case ISD::SETOLT:
1096     CondCode = AArch64CC::MI;
1097     break;
1098   case ISD::SETOLE:
1099     CondCode = AArch64CC::LS;
1100     break;
1101   case ISD::SETONE:
1102     CondCode = AArch64CC::MI;
1103     CondCode2 = AArch64CC::GT;
1104     break;
1105   case ISD::SETO:
1106     CondCode = AArch64CC::VC;
1107     break;
1108   case ISD::SETUO:
1109     CondCode = AArch64CC::VS;
1110     break;
1111   case ISD::SETUEQ:
1112     CondCode = AArch64CC::EQ;
1113     CondCode2 = AArch64CC::VS;
1114     break;
1115   case ISD::SETUGT:
1116     CondCode = AArch64CC::HI;
1117     break;
1118   case ISD::SETUGE:
1119     CondCode = AArch64CC::PL;
1120     break;
1121   case ISD::SETLT:
1122   case ISD::SETULT:
1123     CondCode = AArch64CC::LT;
1124     break;
1125   case ISD::SETLE:
1126   case ISD::SETULE:
1127     CondCode = AArch64CC::LE;
1128     break;
1129   case ISD::SETNE:
1130   case ISD::SETUNE:
1131     CondCode = AArch64CC::NE;
1132     break;
1133   }
1134 }
1135
1136 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1137 /// CC usable with the vector instructions. Fewer operations are available
1138 /// without a real NZCV register, so we have to use less efficient combinations
1139 /// to get the same effect.
1140 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1141                                         AArch64CC::CondCode &CondCode,
1142                                         AArch64CC::CondCode &CondCode2,
1143                                         bool &Invert) {
1144   Invert = false;
1145   switch (CC) {
1146   default:
1147     // Mostly the scalar mappings work fine.
1148     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1149     break;
1150   case ISD::SETUO:
1151     Invert = true; // Fallthrough
1152   case ISD::SETO:
1153     CondCode = AArch64CC::MI;
1154     CondCode2 = AArch64CC::GE;
1155     break;
1156   case ISD::SETUEQ:
1157   case ISD::SETULT:
1158   case ISD::SETULE:
1159   case ISD::SETUGT:
1160   case ISD::SETUGE:
1161     // All of the compare-mask comparisons are ordered, but we can switch
1162     // between the two by a double inversion. E.g. ULE == !OGT.
1163     Invert = true;
1164     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1165     break;
1166   }
1167 }
1168
1169 static bool isLegalArithImmed(uint64_t C) {
1170   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1171   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1172 }
1173
1174 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1175                               SDLoc dl, SelectionDAG &DAG) {
1176   EVT VT = LHS.getValueType();
1177
1178   if (VT.isFloatingPoint())
1179     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1180
1181   // The CMP instruction is just an alias for SUBS, and representing it as
1182   // SUBS means that it's possible to get CSE with subtract operations.
1183   // A later phase can perform the optimization of setting the destination
1184   // register to WZR/XZR if it ends up being unused.
1185   unsigned Opcode = AArch64ISD::SUBS;
1186
1187   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1188       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1189     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1190     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1191     // can be set differently by this operation. It comes down to whether
1192     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1193     // everything is fine. If not then the optimization is wrong. Thus general
1194     // comparisons are only valid if op2 != 0.
1195
1196     // So, finally, the only LLVM-native comparisons that don't mention C and V
1197     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1198     // the absence of information about op2.
1199     Opcode = AArch64ISD::ADDS;
1200     RHS = RHS.getOperand(1);
1201   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1202              !isUnsignedIntSetCC(CC)) {
1203     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1204     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1205     // of the signed comparisons.
1206     Opcode = AArch64ISD::ANDS;
1207     RHS = LHS.getOperand(1);
1208     LHS = LHS.getOperand(0);
1209   }
1210
1211   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1212       .getValue(1);
1213 }
1214
1215 /// \defgroup AArch64CCMP CMP;CCMP matching
1216 ///
1217 /// These functions deal with the formation of CMP;CCMP;... sequences.
1218 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1219 /// a comparison. They set the NZCV flags to a predefined value if their
1220 /// predicate is false. This allows to express arbitrary conjunctions, for
1221 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1222 /// expressed as:
1223 ///   cmp A
1224 ///   ccmp B, inv(CB), CA
1225 ///   check for CB flags
1226 ///
1227 /// In general we can create code for arbitrary "... (and (and A B) C)"
1228 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1229 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1230 /// negation operations:
1231 /// We can negate the results of a single comparison by inverting the flags
1232 /// used when the predicate fails and inverting the flags tested in the next
1233 /// instruction; We can also negate the results of the whole previous
1234 /// conditional compare sequence by inverting the flags tested in the next
1235 /// instruction. However there is no way to negate the result of a partial
1236 /// sequence.
1237 ///
1238 /// Therefore on encountering an "or" expression we can negate the subtree on
1239 /// one side and have to be able to push the negate to the leafs of the subtree
1240 /// on the other side (see also the comments in code). As complete example:
1241 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1242 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1243 /// is transformed to
1244 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1245 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1246 /// and implemented as:
1247 ///   cmp C
1248 ///   ccmp D, inv(CD), CC
1249 ///   ccmp A, CA, inv(CD)
1250 ///   ccmp B, CB, inv(CA)
1251 ///   check for CB flags
1252 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1253 /// by conditional compare sequences.
1254 /// @{
1255
1256 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1257 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1258                                          ISD::CondCode CC, SDValue CCOp,
1259                                          SDValue Condition, unsigned NZCV,
1260                                          SDLoc DL, SelectionDAG &DAG) {
1261   unsigned Opcode = 0;
1262   if (LHS.getValueType().isFloatingPoint())
1263     Opcode = AArch64ISD::FCCMP;
1264   else if (RHS.getOpcode() == ISD::SUB) {
1265     SDValue SubOp0 = RHS.getOperand(0);
1266     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1267         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1268         Opcode = AArch64ISD::CCMN;
1269         RHS = RHS.getOperand(1);
1270       }
1271   }
1272   if (Opcode == 0)
1273     Opcode = AArch64ISD::CCMP;
1274
1275   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1276   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1277 }
1278
1279 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1280 /// CanPushNegate is set to true if we can push a negate operation through
1281 /// the tree in a was that we are left with AND operations and negate operations
1282 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1283 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1284 /// brought into such a form.
1285 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1286                                          unsigned Depth = 0) {
1287   if (!Val.hasOneUse())
1288     return false;
1289   unsigned Opcode = Val->getOpcode();
1290   if (Opcode == ISD::SETCC) {
1291     CanPushNegate = true;
1292     return true;
1293   }
1294   // Protect against stack overflow.
1295   if (Depth > 15)
1296     return false;
1297   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1298     SDValue O0 = Val->getOperand(0);
1299     SDValue O1 = Val->getOperand(1);
1300     bool CanPushNegateL;
1301     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1302       return false;
1303     bool CanPushNegateR;
1304     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1305       return false;
1306     // We cannot push a negate through an AND operation (it would become an OR),
1307     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1308     // push the negate through the x/y subtrees.
1309     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1310     return true;
1311   }
1312   return false;
1313 }
1314
1315 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1316 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1317 /// Tries to transform the given i1 producing node @p Val to a series compare
1318 /// and conditional compare operations. @returns an NZCV flags producing node
1319 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1320 /// transformation was not possible.
1321 /// On recursive invocations @p PushNegate may be set to true to have negation
1322 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1323 /// for the comparisons in the current subtree; @p Depth limits the search
1324 /// depth to avoid stack overflow.
1325 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1326     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1327     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1328     unsigned Depth = 0) {
1329   // We're at a tree leaf, produce a conditional comparison operation.
1330   unsigned Opcode = Val->getOpcode();
1331   if (Opcode == ISD::SETCC) {
1332     SDValue LHS = Val->getOperand(0);
1333     SDValue RHS = Val->getOperand(1);
1334     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1335     bool isInteger = LHS.getValueType().isInteger();
1336     if (PushNegate)
1337       CC = getSetCCInverse(CC, isInteger);
1338     SDLoc DL(Val);
1339     // Determine OutCC and handle FP special case.
1340     if (isInteger) {
1341       OutCC = changeIntCCToAArch64CC(CC);
1342     } else {
1343       assert(LHS.getValueType().isFloatingPoint());
1344       AArch64CC::CondCode ExtraCC;
1345       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1346       // Surpisingly some floating point conditions can't be tested with a
1347       // single condition code. Construct an additional comparison in this case.
1348       // See comment below on how we deal with OR conditions.
1349       if (ExtraCC != AArch64CC::AL) {
1350         SDValue ExtraCmp;
1351         if (!CCOp.getNode())
1352           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1353         else {
1354           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1355           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1356           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1357           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1358                                                NZCV, DL, DAG);
1359         }
1360         CCOp = ExtraCmp;
1361         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1362         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1363       }
1364     }
1365
1366     // Produce a normal comparison if we are first in the chain
1367     if (!CCOp.getNode())
1368       return emitComparison(LHS, RHS, CC, DL, DAG);
1369     // Otherwise produce a ccmp.
1370     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1371     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1372     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1373     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1374                                      DAG);
1375   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1376     return SDValue();
1377
1378   assert((Opcode == ISD::OR || !PushNegate)
1379          && "Can only push negate through OR operation");
1380
1381   // Check if both sides can be transformed.
1382   SDValue LHS = Val->getOperand(0);
1383   SDValue RHS = Val->getOperand(1);
1384   bool CanPushNegateL;
1385   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1386     return SDValue();
1387   bool CanPushNegateR;
1388   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1389     return SDValue();
1390
1391   // Do we need to negate our operands?
1392   bool NegateOperands = Opcode == ISD::OR;
1393   // We can negate the results of all previous operations by inverting the
1394   // predicate flags giving us a free negation for one side. For the other side
1395   // we need to be able to push the negation to the leafs of the tree.
1396   if (NegateOperands) {
1397     if (!CanPushNegateL && !CanPushNegateR)
1398       return SDValue();
1399     // Order the side where we can push the negate through to LHS.
1400     if (!CanPushNegateL && CanPushNegateR)
1401       std::swap(LHS, RHS);
1402   } else {
1403     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1404     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1405     if (NeedsNegOutL && NeedsNegOutR)
1406       return SDValue();
1407     // Order the side where we need to negate the output flags to RHS so it
1408     // gets emitted first.
1409     if (NeedsNegOutL)
1410       std::swap(LHS, RHS);
1411   }
1412
1413   // Emit RHS. If we want to negate the tree we only need to push a negate
1414   // through if we are already in a PushNegate case, otherwise we can negate
1415   // the "flags to test" afterwards.
1416   AArch64CC::CondCode RHSCC;
1417   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1418                                                 CCOp, Predicate, Depth+1);
1419   if (NegateOperands && !PushNegate)
1420     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1421   // Emit LHS. We must push the negate through if we need to negate it.
1422   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1423                                                 CmpR, RHSCC, Depth+1);
1424   // If we transformed an OR to and AND then we have to negate the result
1425   // (or absorb a PushNegate resulting in a double negation).
1426   if (Opcode == ISD::OR && !PushNegate)
1427     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1428   return CmpL;
1429 }
1430
1431 /// @}
1432
1433 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1434                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1435   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1436     EVT VT = RHS.getValueType();
1437     uint64_t C = RHSC->getZExtValue();
1438     if (!isLegalArithImmed(C)) {
1439       // Constant does not fit, try adjusting it by one?
1440       switch (CC) {
1441       default:
1442         break;
1443       case ISD::SETLT:
1444       case ISD::SETGE:
1445         if ((VT == MVT::i32 && C != 0x80000000 &&
1446              isLegalArithImmed((uint32_t)(C - 1))) ||
1447             (VT == MVT::i64 && C != 0x80000000ULL &&
1448              isLegalArithImmed(C - 1ULL))) {
1449           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1450           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1451           RHS = DAG.getConstant(C, dl, VT);
1452         }
1453         break;
1454       case ISD::SETULT:
1455       case ISD::SETUGE:
1456         if ((VT == MVT::i32 && C != 0 &&
1457              isLegalArithImmed((uint32_t)(C - 1))) ||
1458             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1459           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1460           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1461           RHS = DAG.getConstant(C, dl, VT);
1462         }
1463         break;
1464       case ISD::SETLE:
1465       case ISD::SETGT:
1466         if ((VT == MVT::i32 && C != INT32_MAX &&
1467              isLegalArithImmed((uint32_t)(C + 1))) ||
1468             (VT == MVT::i64 && C != INT64_MAX &&
1469              isLegalArithImmed(C + 1ULL))) {
1470           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1471           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1472           RHS = DAG.getConstant(C, dl, VT);
1473         }
1474         break;
1475       case ISD::SETULE:
1476       case ISD::SETUGT:
1477         if ((VT == MVT::i32 && C != UINT32_MAX &&
1478              isLegalArithImmed((uint32_t)(C + 1))) ||
1479             (VT == MVT::i64 && C != UINT64_MAX &&
1480              isLegalArithImmed(C + 1ULL))) {
1481           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1482           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1483           RHS = DAG.getConstant(C, dl, VT);
1484         }
1485         break;
1486       }
1487     }
1488   }
1489   SDValue Cmp;
1490   AArch64CC::CondCode AArch64CC;
1491   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1492     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1493
1494     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1495     // For the i8 operand, the largest immediate is 255, so this can be easily
1496     // encoded in the compare instruction. For the i16 operand, however, the
1497     // largest immediate cannot be encoded in the compare.
1498     // Therefore, use a sign extending load and cmn to avoid materializing the
1499     // -1 constant. For example,
1500     // movz w1, #65535
1501     // ldrh w0, [x0, #0]
1502     // cmp w0, w1
1503     // >
1504     // ldrsh w0, [x0, #0]
1505     // cmn w0, #1
1506     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1507     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1508     // ensure both the LHS and RHS are truly zero extended and to make sure the
1509     // transformation is profitable.
1510     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1511         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1512         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1513         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1514       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1515       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1516         SDValue SExt =
1517             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1518                         DAG.getValueType(MVT::i16));
1519         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1520                                                    RHS.getValueType()),
1521                              CC, dl, DAG);
1522         AArch64CC = changeIntCCToAArch64CC(CC);
1523       }
1524     }
1525
1526     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1527       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1528         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1529           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1530       }
1531     }
1532   }
1533
1534   if (!Cmp) {
1535     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1536     AArch64CC = changeIntCCToAArch64CC(CC);
1537   }
1538   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1539   return Cmp;
1540 }
1541
1542 static std::pair<SDValue, SDValue>
1543 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1544   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1545          "Unsupported value type");
1546   SDValue Value, Overflow;
1547   SDLoc DL(Op);
1548   SDValue LHS = Op.getOperand(0);
1549   SDValue RHS = Op.getOperand(1);
1550   unsigned Opc = 0;
1551   switch (Op.getOpcode()) {
1552   default:
1553     llvm_unreachable("Unknown overflow instruction!");
1554   case ISD::SADDO:
1555     Opc = AArch64ISD::ADDS;
1556     CC = AArch64CC::VS;
1557     break;
1558   case ISD::UADDO:
1559     Opc = AArch64ISD::ADDS;
1560     CC = AArch64CC::HS;
1561     break;
1562   case ISD::SSUBO:
1563     Opc = AArch64ISD::SUBS;
1564     CC = AArch64CC::VS;
1565     break;
1566   case ISD::USUBO:
1567     Opc = AArch64ISD::SUBS;
1568     CC = AArch64CC::LO;
1569     break;
1570   // Multiply needs a little bit extra work.
1571   case ISD::SMULO:
1572   case ISD::UMULO: {
1573     CC = AArch64CC::NE;
1574     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1575     if (Op.getValueType() == MVT::i32) {
1576       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1577       // For a 32 bit multiply with overflow check we want the instruction
1578       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1579       // need to generate the following pattern:
1580       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1581       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1582       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1583       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1584       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1585                                 DAG.getConstant(0, DL, MVT::i64));
1586       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1587       // operation. We need to clear out the upper 32 bits, because we used a
1588       // widening multiply that wrote all 64 bits. In the end this should be a
1589       // noop.
1590       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1591       if (IsSigned) {
1592         // The signed overflow check requires more than just a simple check for
1593         // any bit set in the upper 32 bits of the result. These bits could be
1594         // just the sign bits of a negative number. To perform the overflow
1595         // check we have to arithmetic shift right the 32nd bit of the result by
1596         // 31 bits. Then we compare the result to the upper 32 bits.
1597         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1598                                         DAG.getConstant(32, DL, MVT::i64));
1599         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1600         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1601                                         DAG.getConstant(31, DL, MVT::i64));
1602         // It is important that LowerBits is last, otherwise the arithmetic
1603         // shift will not be folded into the compare (SUBS).
1604         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1605         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1606                        .getValue(1);
1607       } else {
1608         // The overflow check for unsigned multiply is easy. We only need to
1609         // check if any of the upper 32 bits are set. This can be done with a
1610         // CMP (shifted register). For that we need to generate the following
1611         // pattern:
1612         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1613         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1614                                         DAG.getConstant(32, DL, MVT::i64));
1615         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1616         Overflow =
1617             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1618                         DAG.getConstant(0, DL, MVT::i64),
1619                         UpperBits).getValue(1);
1620       }
1621       break;
1622     }
1623     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1624     // For the 64 bit multiply
1625     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1626     if (IsSigned) {
1627       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1628       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1629                                       DAG.getConstant(63, DL, MVT::i64));
1630       // It is important that LowerBits is last, otherwise the arithmetic
1631       // shift will not be folded into the compare (SUBS).
1632       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1633       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1634                      .getValue(1);
1635     } else {
1636       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1637       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1638       Overflow =
1639           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1640                       DAG.getConstant(0, DL, MVT::i64),
1641                       UpperBits).getValue(1);
1642     }
1643     break;
1644   }
1645   } // switch (...)
1646
1647   if (Opc) {
1648     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1649
1650     // Emit the AArch64 operation with overflow check.
1651     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1652     Overflow = Value.getValue(1);
1653   }
1654   return std::make_pair(Value, Overflow);
1655 }
1656
1657 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1658                                              RTLIB::Libcall Call) const {
1659   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1660   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1661 }
1662
1663 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1664   SDValue Sel = Op.getOperand(0);
1665   SDValue Other = Op.getOperand(1);
1666
1667   // If neither operand is a SELECT_CC, give up.
1668   if (Sel.getOpcode() != ISD::SELECT_CC)
1669     std::swap(Sel, Other);
1670   if (Sel.getOpcode() != ISD::SELECT_CC)
1671     return Op;
1672
1673   // The folding we want to perform is:
1674   // (xor x, (select_cc a, b, cc, 0, -1) )
1675   //   -->
1676   // (csel x, (xor x, -1), cc ...)
1677   //
1678   // The latter will get matched to a CSINV instruction.
1679
1680   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1681   SDValue LHS = Sel.getOperand(0);
1682   SDValue RHS = Sel.getOperand(1);
1683   SDValue TVal = Sel.getOperand(2);
1684   SDValue FVal = Sel.getOperand(3);
1685   SDLoc dl(Sel);
1686
1687   // FIXME: This could be generalized to non-integer comparisons.
1688   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1689     return Op;
1690
1691   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1692   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1693
1694   // The values aren't constants, this isn't the pattern we're looking for.
1695   if (!CFVal || !CTVal)
1696     return Op;
1697
1698   // We can commute the SELECT_CC by inverting the condition.  This
1699   // might be needed to make this fit into a CSINV pattern.
1700   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1701     std::swap(TVal, FVal);
1702     std::swap(CTVal, CFVal);
1703     CC = ISD::getSetCCInverse(CC, true);
1704   }
1705
1706   // If the constants line up, perform the transform!
1707   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1708     SDValue CCVal;
1709     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1710
1711     FVal = Other;
1712     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1713                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1714
1715     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1716                        CCVal, Cmp);
1717   }
1718
1719   return Op;
1720 }
1721
1722 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1723   EVT VT = Op.getValueType();
1724
1725   // Let legalize expand this if it isn't a legal type yet.
1726   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1727     return SDValue();
1728
1729   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1730
1731   unsigned Opc;
1732   bool ExtraOp = false;
1733   switch (Op.getOpcode()) {
1734   default:
1735     llvm_unreachable("Invalid code");
1736   case ISD::ADDC:
1737     Opc = AArch64ISD::ADDS;
1738     break;
1739   case ISD::SUBC:
1740     Opc = AArch64ISD::SUBS;
1741     break;
1742   case ISD::ADDE:
1743     Opc = AArch64ISD::ADCS;
1744     ExtraOp = true;
1745     break;
1746   case ISD::SUBE:
1747     Opc = AArch64ISD::SBCS;
1748     ExtraOp = true;
1749     break;
1750   }
1751
1752   if (!ExtraOp)
1753     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1754   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1755                      Op.getOperand(2));
1756 }
1757
1758 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1759   // Let legalize expand this if it isn't a legal type yet.
1760   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1761     return SDValue();
1762
1763   SDLoc dl(Op);
1764   AArch64CC::CondCode CC;
1765   // The actual operation that sets the overflow or carry flag.
1766   SDValue Value, Overflow;
1767   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1768
1769   // We use 0 and 1 as false and true values.
1770   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1771   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1772
1773   // We use an inverted condition, because the conditional select is inverted
1774   // too. This will allow it to be selected to a single instruction:
1775   // CSINC Wd, WZR, WZR, invert(cond).
1776   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1777   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1778                          CCVal, Overflow);
1779
1780   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1781   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1782 }
1783
1784 // Prefetch operands are:
1785 // 1: Address to prefetch
1786 // 2: bool isWrite
1787 // 3: int locality (0 = no locality ... 3 = extreme locality)
1788 // 4: bool isDataCache
1789 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1790   SDLoc DL(Op);
1791   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1792   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1793   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1794
1795   bool IsStream = !Locality;
1796   // When the locality number is set
1797   if (Locality) {
1798     // The front-end should have filtered out the out-of-range values
1799     assert(Locality <= 3 && "Prefetch locality out-of-range");
1800     // The locality degree is the opposite of the cache speed.
1801     // Put the number the other way around.
1802     // The encoding starts at 0 for level 1
1803     Locality = 3 - Locality;
1804   }
1805
1806   // built the mask value encoding the expected behavior.
1807   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1808                    (!IsData << 3) |     // IsDataCache bit
1809                    (Locality << 1) |    // Cache level bits
1810                    (unsigned)IsStream;  // Stream bit
1811   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1812                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1813 }
1814
1815 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1816                                               SelectionDAG &DAG) const {
1817   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1818
1819   RTLIB::Libcall LC;
1820   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1821
1822   return LowerF128Call(Op, DAG, LC);
1823 }
1824
1825 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1826                                              SelectionDAG &DAG) const {
1827   if (Op.getOperand(0).getValueType() != MVT::f128) {
1828     // It's legal except when f128 is involved
1829     return Op;
1830   }
1831
1832   RTLIB::Libcall LC;
1833   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1834
1835   // FP_ROUND node has a second operand indicating whether it is known to be
1836   // precise. That doesn't take part in the LibCall so we can't directly use
1837   // LowerF128Call.
1838   SDValue SrcVal = Op.getOperand(0);
1839   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1840                      SDLoc(Op)).first;
1841 }
1842
1843 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1844   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1845   // Any additional optimization in this function should be recorded
1846   // in the cost tables.
1847   EVT InVT = Op.getOperand(0).getValueType();
1848   EVT VT = Op.getValueType();
1849
1850   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1851     SDLoc dl(Op);
1852     SDValue Cv =
1853         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1854                     Op.getOperand(0));
1855     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1856   }
1857
1858   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1859     SDLoc dl(Op);
1860     MVT ExtVT =
1861         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1862                          VT.getVectorNumElements());
1863     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1864     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1865   }
1866
1867   // Type changing conversions are illegal.
1868   return Op;
1869 }
1870
1871 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1872                                               SelectionDAG &DAG) const {
1873   if (Op.getOperand(0).getValueType().isVector())
1874     return LowerVectorFP_TO_INT(Op, DAG);
1875
1876   // f16 conversions are promoted to f32.
1877   if (Op.getOperand(0).getValueType() == MVT::f16) {
1878     SDLoc dl(Op);
1879     return DAG.getNode(
1880         Op.getOpcode(), dl, Op.getValueType(),
1881         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1882   }
1883
1884   if (Op.getOperand(0).getValueType() != MVT::f128) {
1885     // It's legal except when f128 is involved
1886     return Op;
1887   }
1888
1889   RTLIB::Libcall LC;
1890   if (Op.getOpcode() == ISD::FP_TO_SINT)
1891     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1892   else
1893     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1894
1895   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1896   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1897 }
1898
1899 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1900   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1901   // Any additional optimization in this function should be recorded
1902   // in the cost tables.
1903   EVT VT = Op.getValueType();
1904   SDLoc dl(Op);
1905   SDValue In = Op.getOperand(0);
1906   EVT InVT = In.getValueType();
1907
1908   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1909     MVT CastVT =
1910         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1911                          InVT.getVectorNumElements());
1912     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1913     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1914   }
1915
1916   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1917     unsigned CastOpc =
1918         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1919     EVT CastVT = VT.changeVectorElementTypeToInteger();
1920     In = DAG.getNode(CastOpc, dl, CastVT, In);
1921     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1922   }
1923
1924   return Op;
1925 }
1926
1927 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1928                                             SelectionDAG &DAG) const {
1929   if (Op.getValueType().isVector())
1930     return LowerVectorINT_TO_FP(Op, DAG);
1931
1932   // f16 conversions are promoted to f32.
1933   if (Op.getValueType() == MVT::f16) {
1934     SDLoc dl(Op);
1935     return DAG.getNode(
1936         ISD::FP_ROUND, dl, MVT::f16,
1937         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1938         DAG.getIntPtrConstant(0, dl));
1939   }
1940
1941   // i128 conversions are libcalls.
1942   if (Op.getOperand(0).getValueType() == MVT::i128)
1943     return SDValue();
1944
1945   // Other conversions are legal, unless it's to the completely software-based
1946   // fp128.
1947   if (Op.getValueType() != MVT::f128)
1948     return Op;
1949
1950   RTLIB::Libcall LC;
1951   if (Op.getOpcode() == ISD::SINT_TO_FP)
1952     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1953   else
1954     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1955
1956   return LowerF128Call(Op, DAG, LC);
1957 }
1958
1959 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1960                                             SelectionDAG &DAG) const {
1961   // For iOS, we want to call an alternative entry point: __sincos_stret,
1962   // which returns the values in two S / D registers.
1963   SDLoc dl(Op);
1964   SDValue Arg = Op.getOperand(0);
1965   EVT ArgVT = Arg.getValueType();
1966   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1967
1968   ArgListTy Args;
1969   ArgListEntry Entry;
1970
1971   Entry.Node = Arg;
1972   Entry.Ty = ArgTy;
1973   Entry.isSExt = false;
1974   Entry.isZExt = false;
1975   Args.push_back(Entry);
1976
1977   const char *LibcallName =
1978       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1979   SDValue Callee =
1980       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1981
1982   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1983   TargetLowering::CallLoweringInfo CLI(DAG);
1984   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1985     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1986
1987   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1988   return CallResult.first;
1989 }
1990
1991 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1992   if (Op.getValueType() != MVT::f16)
1993     return SDValue();
1994
1995   assert(Op.getOperand(0).getValueType() == MVT::i16);
1996   SDLoc DL(Op);
1997
1998   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1999   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2000   return SDValue(
2001       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2002                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2003       0);
2004 }
2005
2006 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2007   if (OrigVT.getSizeInBits() >= 64)
2008     return OrigVT;
2009
2010   assert(OrigVT.isSimple() && "Expecting a simple value type");
2011
2012   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2013   switch (OrigSimpleTy) {
2014   default: llvm_unreachable("Unexpected Vector Type");
2015   case MVT::v2i8:
2016   case MVT::v2i16:
2017      return MVT::v2i32;
2018   case MVT::v4i8:
2019     return  MVT::v4i16;
2020   }
2021 }
2022
2023 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2024                                                  const EVT &OrigTy,
2025                                                  const EVT &ExtTy,
2026                                                  unsigned ExtOpcode) {
2027   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2028   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2029   // 64-bits we need to insert a new extension so that it will be 64-bits.
2030   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2031   if (OrigTy.getSizeInBits() >= 64)
2032     return N;
2033
2034   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2035   EVT NewVT = getExtensionTo64Bits(OrigTy);
2036
2037   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2038 }
2039
2040 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2041                                    bool isSigned) {
2042   EVT VT = N->getValueType(0);
2043
2044   if (N->getOpcode() != ISD::BUILD_VECTOR)
2045     return false;
2046
2047   for (const SDValue &Elt : N->op_values()) {
2048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2049       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2050       unsigned HalfSize = EltSize / 2;
2051       if (isSigned) {
2052         if (!isIntN(HalfSize, C->getSExtValue()))
2053           return false;
2054       } else {
2055         if (!isUIntN(HalfSize, C->getZExtValue()))
2056           return false;
2057       }
2058       continue;
2059     }
2060     return false;
2061   }
2062
2063   return true;
2064 }
2065
2066 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2067   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2068     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2069                                              N->getOperand(0)->getValueType(0),
2070                                              N->getValueType(0),
2071                                              N->getOpcode());
2072
2073   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2074   EVT VT = N->getValueType(0);
2075   SDLoc dl(N);
2076   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2077   unsigned NumElts = VT.getVectorNumElements();
2078   MVT TruncVT = MVT::getIntegerVT(EltSize);
2079   SmallVector<SDValue, 8> Ops;
2080   for (unsigned i = 0; i != NumElts; ++i) {
2081     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2082     const APInt &CInt = C->getAPIntValue();
2083     // Element types smaller than 32 bits are not legal, so use i32 elements.
2084     // The values are implicitly truncated so sext vs. zext doesn't matter.
2085     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2086   }
2087   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2088                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2089 }
2090
2091 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2092   if (N->getOpcode() == ISD::SIGN_EXTEND)
2093     return true;
2094   if (isExtendedBUILD_VECTOR(N, DAG, true))
2095     return true;
2096   return false;
2097 }
2098
2099 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2100   if (N->getOpcode() == ISD::ZERO_EXTEND)
2101     return true;
2102   if (isExtendedBUILD_VECTOR(N, DAG, false))
2103     return true;
2104   return false;
2105 }
2106
2107 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2108   unsigned Opcode = N->getOpcode();
2109   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2110     SDNode *N0 = N->getOperand(0).getNode();
2111     SDNode *N1 = N->getOperand(1).getNode();
2112     return N0->hasOneUse() && N1->hasOneUse() &&
2113       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2114   }
2115   return false;
2116 }
2117
2118 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2119   unsigned Opcode = N->getOpcode();
2120   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2121     SDNode *N0 = N->getOperand(0).getNode();
2122     SDNode *N1 = N->getOperand(1).getNode();
2123     return N0->hasOneUse() && N1->hasOneUse() &&
2124       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2125   }
2126   return false;
2127 }
2128
2129 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2130   // Multiplications are only custom-lowered for 128-bit vectors so that
2131   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2132   EVT VT = Op.getValueType();
2133   assert(VT.is128BitVector() && VT.isInteger() &&
2134          "unexpected type for custom-lowering ISD::MUL");
2135   SDNode *N0 = Op.getOperand(0).getNode();
2136   SDNode *N1 = Op.getOperand(1).getNode();
2137   unsigned NewOpc = 0;
2138   bool isMLA = false;
2139   bool isN0SExt = isSignExtended(N0, DAG);
2140   bool isN1SExt = isSignExtended(N1, DAG);
2141   if (isN0SExt && isN1SExt)
2142     NewOpc = AArch64ISD::SMULL;
2143   else {
2144     bool isN0ZExt = isZeroExtended(N0, DAG);
2145     bool isN1ZExt = isZeroExtended(N1, DAG);
2146     if (isN0ZExt && isN1ZExt)
2147       NewOpc = AArch64ISD::UMULL;
2148     else if (isN1SExt || isN1ZExt) {
2149       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2150       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2151       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2152         NewOpc = AArch64ISD::SMULL;
2153         isMLA = true;
2154       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2155         NewOpc =  AArch64ISD::UMULL;
2156         isMLA = true;
2157       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2158         std::swap(N0, N1);
2159         NewOpc =  AArch64ISD::UMULL;
2160         isMLA = true;
2161       }
2162     }
2163
2164     if (!NewOpc) {
2165       if (VT == MVT::v2i64)
2166         // Fall through to expand this.  It is not legal.
2167         return SDValue();
2168       else
2169         // Other vector multiplications are legal.
2170         return Op;
2171     }
2172   }
2173
2174   // Legalize to a S/UMULL instruction
2175   SDLoc DL(Op);
2176   SDValue Op0;
2177   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2178   if (!isMLA) {
2179     Op0 = skipExtensionForVectorMULL(N0, DAG);
2180     assert(Op0.getValueType().is64BitVector() &&
2181            Op1.getValueType().is64BitVector() &&
2182            "unexpected types for extended operands to VMULL");
2183     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2184   }
2185   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2186   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2187   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2188   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2189   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2190   EVT Op1VT = Op1.getValueType();
2191   return DAG.getNode(N0->getOpcode(), DL, VT,
2192                      DAG.getNode(NewOpc, DL, VT,
2193                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2194                      DAG.getNode(NewOpc, DL, VT,
2195                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2196 }
2197
2198 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2199                                                      SelectionDAG &DAG) const {
2200   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2201   SDLoc dl(Op);
2202   switch (IntNo) {
2203   default: return SDValue();    // Don't custom lower most intrinsics.
2204   case Intrinsic::aarch64_thread_pointer: {
2205     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2206     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2207   }
2208   case Intrinsic::aarch64_neon_smax:
2209     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2210                        Op.getOperand(1), Op.getOperand(2));
2211   case Intrinsic::aarch64_neon_umax:
2212     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2213                        Op.getOperand(1), Op.getOperand(2));
2214   case Intrinsic::aarch64_neon_smin:
2215     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2216                        Op.getOperand(1), Op.getOperand(2));
2217   case Intrinsic::aarch64_neon_umin:
2218     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2219                        Op.getOperand(1), Op.getOperand(2));
2220   }
2221 }
2222
2223 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2224                                               SelectionDAG &DAG) const {
2225   switch (Op.getOpcode()) {
2226   default:
2227     llvm_unreachable("unimplemented operand");
2228     return SDValue();
2229   case ISD::BITCAST:
2230     return LowerBITCAST(Op, DAG);
2231   case ISD::GlobalAddress:
2232     return LowerGlobalAddress(Op, DAG);
2233   case ISD::GlobalTLSAddress:
2234     return LowerGlobalTLSAddress(Op, DAG);
2235   case ISD::SETCC:
2236     return LowerSETCC(Op, DAG);
2237   case ISD::BR_CC:
2238     return LowerBR_CC(Op, DAG);
2239   case ISD::SELECT:
2240     return LowerSELECT(Op, DAG);
2241   case ISD::SELECT_CC:
2242     return LowerSELECT_CC(Op, DAG);
2243   case ISD::JumpTable:
2244     return LowerJumpTable(Op, DAG);
2245   case ISD::ConstantPool:
2246     return LowerConstantPool(Op, DAG);
2247   case ISD::BlockAddress:
2248     return LowerBlockAddress(Op, DAG);
2249   case ISD::VASTART:
2250     return LowerVASTART(Op, DAG);
2251   case ISD::VACOPY:
2252     return LowerVACOPY(Op, DAG);
2253   case ISD::VAARG:
2254     return LowerVAARG(Op, DAG);
2255   case ISD::ADDC:
2256   case ISD::ADDE:
2257   case ISD::SUBC:
2258   case ISD::SUBE:
2259     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2260   case ISD::SADDO:
2261   case ISD::UADDO:
2262   case ISD::SSUBO:
2263   case ISD::USUBO:
2264   case ISD::SMULO:
2265   case ISD::UMULO:
2266     return LowerXALUO(Op, DAG);
2267   case ISD::FADD:
2268     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2269   case ISD::FSUB:
2270     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2271   case ISD::FMUL:
2272     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2273   case ISD::FDIV:
2274     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2275   case ISD::FP_ROUND:
2276     return LowerFP_ROUND(Op, DAG);
2277   case ISD::FP_EXTEND:
2278     return LowerFP_EXTEND(Op, DAG);
2279   case ISD::FRAMEADDR:
2280     return LowerFRAMEADDR(Op, DAG);
2281   case ISD::RETURNADDR:
2282     return LowerRETURNADDR(Op, DAG);
2283   case ISD::INSERT_VECTOR_ELT:
2284     return LowerINSERT_VECTOR_ELT(Op, DAG);
2285   case ISD::EXTRACT_VECTOR_ELT:
2286     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2287   case ISD::BUILD_VECTOR:
2288     return LowerBUILD_VECTOR(Op, DAG);
2289   case ISD::VECTOR_SHUFFLE:
2290     return LowerVECTOR_SHUFFLE(Op, DAG);
2291   case ISD::EXTRACT_SUBVECTOR:
2292     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2293   case ISD::SRA:
2294   case ISD::SRL:
2295   case ISD::SHL:
2296     return LowerVectorSRA_SRL_SHL(Op, DAG);
2297   case ISD::SHL_PARTS:
2298     return LowerShiftLeftParts(Op, DAG);
2299   case ISD::SRL_PARTS:
2300   case ISD::SRA_PARTS:
2301     return LowerShiftRightParts(Op, DAG);
2302   case ISD::CTPOP:
2303     return LowerCTPOP(Op, DAG);
2304   case ISD::FCOPYSIGN:
2305     return LowerFCOPYSIGN(Op, DAG);
2306   case ISD::AND:
2307     return LowerVectorAND(Op, DAG);
2308   case ISD::OR:
2309     return LowerVectorOR(Op, DAG);
2310   case ISD::XOR:
2311     return LowerXOR(Op, DAG);
2312   case ISD::PREFETCH:
2313     return LowerPREFETCH(Op, DAG);
2314   case ISD::SINT_TO_FP:
2315   case ISD::UINT_TO_FP:
2316     return LowerINT_TO_FP(Op, DAG);
2317   case ISD::FP_TO_SINT:
2318   case ISD::FP_TO_UINT:
2319     return LowerFP_TO_INT(Op, DAG);
2320   case ISD::FSINCOS:
2321     return LowerFSINCOS(Op, DAG);
2322   case ISD::MUL:
2323     return LowerMUL(Op, DAG);
2324   case ISD::INTRINSIC_WO_CHAIN:
2325     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2326   }
2327 }
2328
2329 /// getFunctionAlignment - Return the Log2 alignment of this function.
2330 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2331   return 2;
2332 }
2333
2334 //===----------------------------------------------------------------------===//
2335 //                      Calling Convention Implementation
2336 //===----------------------------------------------------------------------===//
2337
2338 #include "AArch64GenCallingConv.inc"
2339
2340 /// Selects the correct CCAssignFn for a given CallingConvention value.
2341 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2342                                                      bool IsVarArg) const {
2343   switch (CC) {
2344   default:
2345     llvm_unreachable("Unsupported calling convention.");
2346   case CallingConv::WebKit_JS:
2347     return CC_AArch64_WebKit_JS;
2348   case CallingConv::GHC:
2349     return CC_AArch64_GHC;
2350   case CallingConv::C:
2351   case CallingConv::Fast:
2352     if (!Subtarget->isTargetDarwin())
2353       return CC_AArch64_AAPCS;
2354     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2355   }
2356 }
2357
2358 SDValue AArch64TargetLowering::LowerFormalArguments(
2359     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2360     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2361     SmallVectorImpl<SDValue> &InVals) const {
2362   MachineFunction &MF = DAG.getMachineFunction();
2363   MachineFrameInfo *MFI = MF.getFrameInfo();
2364
2365   // Assign locations to all of the incoming arguments.
2366   SmallVector<CCValAssign, 16> ArgLocs;
2367   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2368                  *DAG.getContext());
2369
2370   // At this point, Ins[].VT may already be promoted to i32. To correctly
2371   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2372   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2373   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2374   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2375   // LocVT.
2376   unsigned NumArgs = Ins.size();
2377   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2378   unsigned CurArgIdx = 0;
2379   for (unsigned i = 0; i != NumArgs; ++i) {
2380     MVT ValVT = Ins[i].VT;
2381     if (Ins[i].isOrigArg()) {
2382       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2383       CurArgIdx = Ins[i].getOrigArgIndex();
2384
2385       // Get type of the original argument.
2386       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2387                                   /*AllowUnknown*/ true);
2388       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2389       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2390       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2391         ValVT = MVT::i8;
2392       else if (ActualMVT == MVT::i16)
2393         ValVT = MVT::i16;
2394     }
2395     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2396     bool Res =
2397         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2398     assert(!Res && "Call operand has unhandled type");
2399     (void)Res;
2400   }
2401   assert(ArgLocs.size() == Ins.size());
2402   SmallVector<SDValue, 16> ArgValues;
2403   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2404     CCValAssign &VA = ArgLocs[i];
2405
2406     if (Ins[i].Flags.isByVal()) {
2407       // Byval is used for HFAs in the PCS, but the system should work in a
2408       // non-compliant manner for larger structs.
2409       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2410       int Size = Ins[i].Flags.getByValSize();
2411       unsigned NumRegs = (Size + 7) / 8;
2412
2413       // FIXME: This works on big-endian for composite byvals, which are the common
2414       // case. It should also work for fundamental types too.
2415       unsigned FrameIdx =
2416         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2417       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2418       InVals.push_back(FrameIdxN);
2419
2420       continue;
2421     }
2422     
2423     if (VA.isRegLoc()) {
2424       // Arguments stored in registers.
2425       EVT RegVT = VA.getLocVT();
2426
2427       SDValue ArgValue;
2428       const TargetRegisterClass *RC;
2429
2430       if (RegVT == MVT::i32)
2431         RC = &AArch64::GPR32RegClass;
2432       else if (RegVT == MVT::i64)
2433         RC = &AArch64::GPR64RegClass;
2434       else if (RegVT == MVT::f16)
2435         RC = &AArch64::FPR16RegClass;
2436       else if (RegVT == MVT::f32)
2437         RC = &AArch64::FPR32RegClass;
2438       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2439         RC = &AArch64::FPR64RegClass;
2440       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2441         RC = &AArch64::FPR128RegClass;
2442       else
2443         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2444
2445       // Transform the arguments in physical registers into virtual ones.
2446       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2447       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2448
2449       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2450       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2451       // truncate to the right size.
2452       switch (VA.getLocInfo()) {
2453       default:
2454         llvm_unreachable("Unknown loc info!");
2455       case CCValAssign::Full:
2456         break;
2457       case CCValAssign::BCvt:
2458         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2459         break;
2460       case CCValAssign::AExt:
2461       case CCValAssign::SExt:
2462       case CCValAssign::ZExt:
2463         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2464         // nodes after our lowering.
2465         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2466         break;
2467       }
2468
2469       InVals.push_back(ArgValue);
2470
2471     } else { // VA.isRegLoc()
2472       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2473       unsigned ArgOffset = VA.getLocMemOffset();
2474       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2475
2476       uint32_t BEAlign = 0;
2477       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2478           !Ins[i].Flags.isInConsecutiveRegs())
2479         BEAlign = 8 - ArgSize;
2480
2481       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2482
2483       // Create load nodes to retrieve arguments from the stack.
2484       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2485       SDValue ArgValue;
2486
2487       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2488       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2489       MVT MemVT = VA.getValVT();
2490
2491       switch (VA.getLocInfo()) {
2492       default:
2493         break;
2494       case CCValAssign::BCvt:
2495         MemVT = VA.getLocVT();
2496         break;
2497       case CCValAssign::SExt:
2498         ExtType = ISD::SEXTLOAD;
2499         break;
2500       case CCValAssign::ZExt:
2501         ExtType = ISD::ZEXTLOAD;
2502         break;
2503       case CCValAssign::AExt:
2504         ExtType = ISD::EXTLOAD;
2505         break;
2506       }
2507
2508       ArgValue = DAG.getExtLoad(
2509           ExtType, DL, VA.getLocVT(), Chain, FIN,
2510           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2511           MemVT, false, false, false, 0);
2512
2513       InVals.push_back(ArgValue);
2514     }
2515   }
2516
2517   // varargs
2518   if (isVarArg) {
2519     if (!Subtarget->isTargetDarwin()) {
2520       // The AAPCS variadic function ABI is identical to the non-variadic
2521       // one. As a result there may be more arguments in registers and we should
2522       // save them for future reference.
2523       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2524     }
2525
2526     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2527     // This will point to the next argument passed via stack.
2528     unsigned StackOffset = CCInfo.getNextStackOffset();
2529     // We currently pass all varargs at 8-byte alignment.
2530     StackOffset = ((StackOffset + 7) & ~7);
2531     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2532   }
2533
2534   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2535   unsigned StackArgSize = CCInfo.getNextStackOffset();
2536   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2537   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2538     // This is a non-standard ABI so by fiat I say we're allowed to make full
2539     // use of the stack area to be popped, which must be aligned to 16 bytes in
2540     // any case:
2541     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2542
2543     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2544     // a multiple of 16.
2545     FuncInfo->setArgumentStackToRestore(StackArgSize);
2546
2547     // This realignment carries over to the available bytes below. Our own
2548     // callers will guarantee the space is free by giving an aligned value to
2549     // CALLSEQ_START.
2550   }
2551   // Even if we're not expected to free up the space, it's useful to know how
2552   // much is there while considering tail calls (because we can reuse it).
2553   FuncInfo->setBytesInStackArgArea(StackArgSize);
2554
2555   return Chain;
2556 }
2557
2558 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2559                                                 SelectionDAG &DAG, SDLoc DL,
2560                                                 SDValue &Chain) const {
2561   MachineFunction &MF = DAG.getMachineFunction();
2562   MachineFrameInfo *MFI = MF.getFrameInfo();
2563   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2564   auto PtrVT = getPointerTy(DAG.getDataLayout());
2565
2566   SmallVector<SDValue, 8> MemOps;
2567
2568   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2569                                           AArch64::X3, AArch64::X4, AArch64::X5,
2570                                           AArch64::X6, AArch64::X7 };
2571   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2572   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2573
2574   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2575   int GPRIdx = 0;
2576   if (GPRSaveSize != 0) {
2577     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2578
2579     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2580
2581     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2582       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2583       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2584       SDValue Store = DAG.getStore(
2585           Val.getValue(1), DL, Val, FIN,
2586           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2587           false, 0);
2588       MemOps.push_back(Store);
2589       FIN =
2590           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2591     }
2592   }
2593   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2594   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2595
2596   if (Subtarget->hasFPARMv8()) {
2597     static const MCPhysReg FPRArgRegs[] = {
2598         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2599         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2600     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2601     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2602
2603     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2604     int FPRIdx = 0;
2605     if (FPRSaveSize != 0) {
2606       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2607
2608       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2609
2610       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2611         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2612         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2613
2614         SDValue Store = DAG.getStore(
2615             Val.getValue(1), DL, Val, FIN,
2616             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2617             false, false, 0);
2618         MemOps.push_back(Store);
2619         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2620                           DAG.getConstant(16, DL, PtrVT));
2621       }
2622     }
2623     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2624     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2625   }
2626
2627   if (!MemOps.empty()) {
2628     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2629   }
2630 }
2631
2632 /// LowerCallResult - Lower the result values of a call into the
2633 /// appropriate copies out of appropriate physical registers.
2634 SDValue AArch64TargetLowering::LowerCallResult(
2635     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2636     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2637     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2638     SDValue ThisVal) const {
2639   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2640                           ? RetCC_AArch64_WebKit_JS
2641                           : RetCC_AArch64_AAPCS;
2642   // Assign locations to each value returned by this call.
2643   SmallVector<CCValAssign, 16> RVLocs;
2644   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2645                  *DAG.getContext());
2646   CCInfo.AnalyzeCallResult(Ins, RetCC);
2647
2648   // Copy all of the result registers out of their specified physreg.
2649   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2650     CCValAssign VA = RVLocs[i];
2651
2652     // Pass 'this' value directly from the argument to return value, to avoid
2653     // reg unit interference
2654     if (i == 0 && isThisReturn) {
2655       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2656              "unexpected return calling convention register assignment");
2657       InVals.push_back(ThisVal);
2658       continue;
2659     }
2660
2661     SDValue Val =
2662         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2663     Chain = Val.getValue(1);
2664     InFlag = Val.getValue(2);
2665
2666     switch (VA.getLocInfo()) {
2667     default:
2668       llvm_unreachable("Unknown loc info!");
2669     case CCValAssign::Full:
2670       break;
2671     case CCValAssign::BCvt:
2672       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2673       break;
2674     }
2675
2676     InVals.push_back(Val);
2677   }
2678
2679   return Chain;
2680 }
2681
2682 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2683     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2684     bool isCalleeStructRet, bool isCallerStructRet,
2685     const SmallVectorImpl<ISD::OutputArg> &Outs,
2686     const SmallVectorImpl<SDValue> &OutVals,
2687     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2688   // For CallingConv::C this function knows whether the ABI needs
2689   // changing. That's not true for other conventions so they will have to opt in
2690   // manually.
2691   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2692     return false;
2693
2694   const MachineFunction &MF = DAG.getMachineFunction();
2695   const Function *CallerF = MF.getFunction();
2696   CallingConv::ID CallerCC = CallerF->getCallingConv();
2697   bool CCMatch = CallerCC == CalleeCC;
2698
2699   // Byval parameters hand the function a pointer directly into the stack area
2700   // we want to reuse during a tail call. Working around this *is* possible (see
2701   // X86) but less efficient and uglier in LowerCall.
2702   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2703                                     e = CallerF->arg_end();
2704        i != e; ++i)
2705     if (i->hasByValAttr())
2706       return false;
2707
2708   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2709     if (IsTailCallConvention(CalleeCC) && CCMatch)
2710       return true;
2711     return false;
2712   }
2713
2714   // Externally-defined functions with weak linkage should not be
2715   // tail-called on AArch64 when the OS does not support dynamic
2716   // pre-emption of symbols, as the AAELF spec requires normal calls
2717   // to undefined weak functions to be replaced with a NOP or jump to the
2718   // next instruction. The behaviour of branch instructions in this
2719   // situation (as used for tail calls) is implementation-defined, so we
2720   // cannot rely on the linker replacing the tail call with a return.
2721   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2722     const GlobalValue *GV = G->getGlobal();
2723     const Triple &TT = getTargetMachine().getTargetTriple();
2724     if (GV->hasExternalWeakLinkage() &&
2725         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2726       return false;
2727   }
2728
2729   // Now we search for cases where we can use a tail call without changing the
2730   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2731   // concept.
2732
2733   // I want anyone implementing a new calling convention to think long and hard
2734   // about this assert.
2735   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2736          "Unexpected variadic calling convention");
2737
2738   if (isVarArg && !Outs.empty()) {
2739     // At least two cases here: if caller is fastcc then we can't have any
2740     // memory arguments (we'd be expected to clean up the stack afterwards). If
2741     // caller is C then we could potentially use its argument area.
2742
2743     // FIXME: for now we take the most conservative of these in both cases:
2744     // disallow all variadic memory operands.
2745     SmallVector<CCValAssign, 16> ArgLocs;
2746     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2747                    *DAG.getContext());
2748
2749     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2750     for (const CCValAssign &ArgLoc : ArgLocs)
2751       if (!ArgLoc.isRegLoc())
2752         return false;
2753   }
2754
2755   // If the calling conventions do not match, then we'd better make sure the
2756   // results are returned in the same way as what the caller expects.
2757   if (!CCMatch) {
2758     SmallVector<CCValAssign, 16> RVLocs1;
2759     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2760                     *DAG.getContext());
2761     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2762
2763     SmallVector<CCValAssign, 16> RVLocs2;
2764     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2765                     *DAG.getContext());
2766     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2767
2768     if (RVLocs1.size() != RVLocs2.size())
2769       return false;
2770     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2771       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2772         return false;
2773       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2774         return false;
2775       if (RVLocs1[i].isRegLoc()) {
2776         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2777           return false;
2778       } else {
2779         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2780           return false;
2781       }
2782     }
2783   }
2784
2785   // Nothing more to check if the callee is taking no arguments
2786   if (Outs.empty())
2787     return true;
2788
2789   SmallVector<CCValAssign, 16> ArgLocs;
2790   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2791                  *DAG.getContext());
2792
2793   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2794
2795   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2796
2797   // If the stack arguments for this call would fit into our own save area then
2798   // the call can be made tail.
2799   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2800 }
2801
2802 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2803                                                    SelectionDAG &DAG,
2804                                                    MachineFrameInfo *MFI,
2805                                                    int ClobberedFI) const {
2806   SmallVector<SDValue, 8> ArgChains;
2807   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2808   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2809
2810   // Include the original chain at the beginning of the list. When this is
2811   // used by target LowerCall hooks, this helps legalize find the
2812   // CALLSEQ_BEGIN node.
2813   ArgChains.push_back(Chain);
2814
2815   // Add a chain value for each stack argument corresponding
2816   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2817                             UE = DAG.getEntryNode().getNode()->use_end();
2818        U != UE; ++U)
2819     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2820       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2821         if (FI->getIndex() < 0) {
2822           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2823           int64_t InLastByte = InFirstByte;
2824           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2825
2826           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2827               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2828             ArgChains.push_back(SDValue(L, 1));
2829         }
2830
2831   // Build a tokenfactor for all the chains.
2832   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2833 }
2834
2835 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2836                                                    bool TailCallOpt) const {
2837   return CallCC == CallingConv::Fast && TailCallOpt;
2838 }
2839
2840 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2841   return CallCC == CallingConv::Fast;
2842 }
2843
2844 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2845 /// and add input and output parameter nodes.
2846 SDValue
2847 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2848                                  SmallVectorImpl<SDValue> &InVals) const {
2849   SelectionDAG &DAG = CLI.DAG;
2850   SDLoc &DL = CLI.DL;
2851   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2852   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2853   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2854   SDValue Chain = CLI.Chain;
2855   SDValue Callee = CLI.Callee;
2856   bool &IsTailCall = CLI.IsTailCall;
2857   CallingConv::ID CallConv = CLI.CallConv;
2858   bool IsVarArg = CLI.IsVarArg;
2859
2860   MachineFunction &MF = DAG.getMachineFunction();
2861   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2862   bool IsThisReturn = false;
2863
2864   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2865   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2866   bool IsSibCall = false;
2867
2868   if (IsTailCall) {
2869     // Check if it's really possible to do a tail call.
2870     IsTailCall = isEligibleForTailCallOptimization(
2871         Callee, CallConv, IsVarArg, IsStructRet,
2872         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2873     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2874       report_fatal_error("failed to perform tail call elimination on a call "
2875                          "site marked musttail");
2876
2877     // A sibling call is one where we're under the usual C ABI and not planning
2878     // to change that but can still do a tail call:
2879     if (!TailCallOpt && IsTailCall)
2880       IsSibCall = true;
2881
2882     if (IsTailCall)
2883       ++NumTailCalls;
2884   }
2885
2886   // Analyze operands of the call, assigning locations to each operand.
2887   SmallVector<CCValAssign, 16> ArgLocs;
2888   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2889                  *DAG.getContext());
2890
2891   if (IsVarArg) {
2892     // Handle fixed and variable vector arguments differently.
2893     // Variable vector arguments always go into memory.
2894     unsigned NumArgs = Outs.size();
2895
2896     for (unsigned i = 0; i != NumArgs; ++i) {
2897       MVT ArgVT = Outs[i].VT;
2898       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2899       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2900                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2901       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2902       assert(!Res && "Call operand has unhandled type");
2903       (void)Res;
2904     }
2905   } else {
2906     // At this point, Outs[].VT may already be promoted to i32. To correctly
2907     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2908     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2909     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2910     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2911     // LocVT.
2912     unsigned NumArgs = Outs.size();
2913     for (unsigned i = 0; i != NumArgs; ++i) {
2914       MVT ValVT = Outs[i].VT;
2915       // Get type of the original argument.
2916       EVT ActualVT = getValueType(DAG.getDataLayout(),
2917                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2918                                   /*AllowUnknown*/ true);
2919       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2920       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2921       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2922       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2923         ValVT = MVT::i8;
2924       else if (ActualMVT == MVT::i16)
2925         ValVT = MVT::i16;
2926
2927       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2928       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2929       assert(!Res && "Call operand has unhandled type");
2930       (void)Res;
2931     }
2932   }
2933
2934   // Get a count of how many bytes are to be pushed on the stack.
2935   unsigned NumBytes = CCInfo.getNextStackOffset();
2936
2937   if (IsSibCall) {
2938     // Since we're not changing the ABI to make this a tail call, the memory
2939     // operands are already available in the caller's incoming argument space.
2940     NumBytes = 0;
2941   }
2942
2943   // FPDiff is the byte offset of the call's argument area from the callee's.
2944   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2945   // by this amount for a tail call. In a sibling call it must be 0 because the
2946   // caller will deallocate the entire stack and the callee still expects its
2947   // arguments to begin at SP+0. Completely unused for non-tail calls.
2948   int FPDiff = 0;
2949
2950   if (IsTailCall && !IsSibCall) {
2951     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2952
2953     // Since callee will pop argument stack as a tail call, we must keep the
2954     // popped size 16-byte aligned.
2955     NumBytes = RoundUpToAlignment(NumBytes, 16);
2956
2957     // FPDiff will be negative if this tail call requires more space than we
2958     // would automatically have in our incoming argument space. Positive if we
2959     // can actually shrink the stack.
2960     FPDiff = NumReusableBytes - NumBytes;
2961
2962     // The stack pointer must be 16-byte aligned at all times it's used for a
2963     // memory operation, which in practice means at *all* times and in
2964     // particular across call boundaries. Therefore our own arguments started at
2965     // a 16-byte aligned SP and the delta applied for the tail call should
2966     // satisfy the same constraint.
2967     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2968   }
2969
2970   // Adjust the stack pointer for the new arguments...
2971   // These operations are automatically eliminated by the prolog/epilog pass
2972   if (!IsSibCall)
2973     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2974                                                               true),
2975                                  DL);
2976
2977   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2978                                         getPointerTy(DAG.getDataLayout()));
2979
2980   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2981   SmallVector<SDValue, 8> MemOpChains;
2982   auto PtrVT = getPointerTy(DAG.getDataLayout());
2983
2984   // Walk the register/memloc assignments, inserting copies/loads.
2985   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2986        ++i, ++realArgIdx) {
2987     CCValAssign &VA = ArgLocs[i];
2988     SDValue Arg = OutVals[realArgIdx];
2989     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2990
2991     // Promote the value if needed.
2992     switch (VA.getLocInfo()) {
2993     default:
2994       llvm_unreachable("Unknown loc info!");
2995     case CCValAssign::Full:
2996       break;
2997     case CCValAssign::SExt:
2998       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2999       break;
3000     case CCValAssign::ZExt:
3001       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3002       break;
3003     case CCValAssign::AExt:
3004       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3005         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3006         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3007         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3008       }
3009       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3010       break;
3011     case CCValAssign::BCvt:
3012       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3013       break;
3014     case CCValAssign::FPExt:
3015       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3016       break;
3017     }
3018
3019     if (VA.isRegLoc()) {
3020       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3021         assert(VA.getLocVT() == MVT::i64 &&
3022                "unexpected calling convention register assignment");
3023         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3024                "unexpected use of 'returned'");
3025         IsThisReturn = true;
3026       }
3027       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3028     } else {
3029       assert(VA.isMemLoc());
3030
3031       SDValue DstAddr;
3032       MachinePointerInfo DstInfo;
3033
3034       // FIXME: This works on big-endian for composite byvals, which are the
3035       // common case. It should also work for fundamental types too.
3036       uint32_t BEAlign = 0;
3037       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3038                                         : VA.getValVT().getSizeInBits();
3039       OpSize = (OpSize + 7) / 8;
3040       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3041           !Flags.isInConsecutiveRegs()) {
3042         if (OpSize < 8)
3043           BEAlign = 8 - OpSize;
3044       }
3045       unsigned LocMemOffset = VA.getLocMemOffset();
3046       int32_t Offset = LocMemOffset + BEAlign;
3047       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3048       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3049
3050       if (IsTailCall) {
3051         Offset = Offset + FPDiff;
3052         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3053
3054         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3055         DstInfo =
3056             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3057
3058         // Make sure any stack arguments overlapping with where we're storing
3059         // are loaded before this eventual operation. Otherwise they'll be
3060         // clobbered.
3061         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3062       } else {
3063         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3064
3065         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3066         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3067                                                LocMemOffset);
3068       }
3069
3070       if (Outs[i].Flags.isByVal()) {
3071         SDValue SizeNode =
3072             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3073         SDValue Cpy = DAG.getMemcpy(
3074             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3075             /*isVol = */ false, /*AlwaysInline = */ false,
3076             /*isTailCall = */ false,
3077             DstInfo, MachinePointerInfo());
3078
3079         MemOpChains.push_back(Cpy);
3080       } else {
3081         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3082         // promoted to a legal register type i32, we should truncate Arg back to
3083         // i1/i8/i16.
3084         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3085             VA.getValVT() == MVT::i16)
3086           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3087
3088         SDValue Store =
3089             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3090         MemOpChains.push_back(Store);
3091       }
3092     }
3093   }
3094
3095   if (!MemOpChains.empty())
3096     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3097
3098   // Build a sequence of copy-to-reg nodes chained together with token chain
3099   // and flag operands which copy the outgoing args into the appropriate regs.
3100   SDValue InFlag;
3101   for (auto &RegToPass : RegsToPass) {
3102     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3103                              RegToPass.second, InFlag);
3104     InFlag = Chain.getValue(1);
3105   }
3106
3107   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3108   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3109   // node so that legalize doesn't hack it.
3110   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3111       Subtarget->isTargetMachO()) {
3112     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3113       const GlobalValue *GV = G->getGlobal();
3114       bool InternalLinkage = GV->hasInternalLinkage();
3115       if (InternalLinkage)
3116         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3117       else {
3118         Callee =
3119             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3120         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3121       }
3122     } else if (ExternalSymbolSDNode *S =
3123                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3124       const char *Sym = S->getSymbol();
3125       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3126       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3127     }
3128   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3129     const GlobalValue *GV = G->getGlobal();
3130     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3131   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3132     const char *Sym = S->getSymbol();
3133     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3134   }
3135
3136   // We don't usually want to end the call-sequence here because we would tidy
3137   // the frame up *after* the call, however in the ABI-changing tail-call case
3138   // we've carefully laid out the parameters so that when sp is reset they'll be
3139   // in the correct location.
3140   if (IsTailCall && !IsSibCall) {
3141     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3142                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3143     InFlag = Chain.getValue(1);
3144   }
3145
3146   std::vector<SDValue> Ops;
3147   Ops.push_back(Chain);
3148   Ops.push_back(Callee);
3149
3150   if (IsTailCall) {
3151     // Each tail call may have to adjust the stack by a different amount, so
3152     // this information must travel along with the operation for eventual
3153     // consumption by emitEpilogue.
3154     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3155   }
3156
3157   // Add argument registers to the end of the list so that they are known live
3158   // into the call.
3159   for (auto &RegToPass : RegsToPass)
3160     Ops.push_back(DAG.getRegister(RegToPass.first,
3161                                   RegToPass.second.getValueType()));
3162
3163   // Add a register mask operand representing the call-preserved registers.
3164   const uint32_t *Mask;
3165   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3166   if (IsThisReturn) {
3167     // For 'this' returns, use the X0-preserving mask if applicable
3168     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3169     if (!Mask) {
3170       IsThisReturn = false;
3171       Mask = TRI->getCallPreservedMask(MF, CallConv);
3172     }
3173   } else
3174     Mask = TRI->getCallPreservedMask(MF, CallConv);
3175
3176   assert(Mask && "Missing call preserved mask for calling convention");
3177   Ops.push_back(DAG.getRegisterMask(Mask));
3178
3179   if (InFlag.getNode())
3180     Ops.push_back(InFlag);
3181
3182   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3183
3184   // If we're doing a tall call, use a TC_RETURN here rather than an
3185   // actual call instruction.
3186   if (IsTailCall) {
3187     MF.getFrameInfo()->setHasTailCall();
3188     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3189   }
3190
3191   // Returns a chain and a flag for retval copy to use.
3192   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3193   InFlag = Chain.getValue(1);
3194
3195   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3196                                 ? RoundUpToAlignment(NumBytes, 16)
3197                                 : 0;
3198
3199   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3200                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3201                              InFlag, DL);
3202   if (!Ins.empty())
3203     InFlag = Chain.getValue(1);
3204
3205   // Handle result values, copying them out of physregs into vregs that we
3206   // return.
3207   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3208                          InVals, IsThisReturn,
3209                          IsThisReturn ? OutVals[0] : SDValue());
3210 }
3211
3212 bool AArch64TargetLowering::CanLowerReturn(
3213     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3214     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3215   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3216                           ? RetCC_AArch64_WebKit_JS
3217                           : RetCC_AArch64_AAPCS;
3218   SmallVector<CCValAssign, 16> RVLocs;
3219   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3220   return CCInfo.CheckReturn(Outs, RetCC);
3221 }
3222
3223 SDValue
3224 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3225                                    bool isVarArg,
3226                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3227                                    const SmallVectorImpl<SDValue> &OutVals,
3228                                    SDLoc DL, SelectionDAG &DAG) const {
3229   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3230                           ? RetCC_AArch64_WebKit_JS
3231                           : RetCC_AArch64_AAPCS;
3232   SmallVector<CCValAssign, 16> RVLocs;
3233   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3234                  *DAG.getContext());
3235   CCInfo.AnalyzeReturn(Outs, RetCC);
3236
3237   // Copy the result values into the output registers.
3238   SDValue Flag;
3239   SmallVector<SDValue, 4> RetOps(1, Chain);
3240   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3241        ++i, ++realRVLocIdx) {
3242     CCValAssign &VA = RVLocs[i];
3243     assert(VA.isRegLoc() && "Can only return in registers!");
3244     SDValue Arg = OutVals[realRVLocIdx];
3245
3246     switch (VA.getLocInfo()) {
3247     default:
3248       llvm_unreachable("Unknown loc info!");
3249     case CCValAssign::Full:
3250       if (Outs[i].ArgVT == MVT::i1) {
3251         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3252         // value. This is strictly redundant on Darwin (which uses "zeroext
3253         // i1"), but will be optimised out before ISel.
3254         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3255         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3256       }
3257       break;
3258     case CCValAssign::BCvt:
3259       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3260       break;
3261     }
3262
3263     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3264     Flag = Chain.getValue(1);
3265     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3266   }
3267
3268   RetOps[0] = Chain; // Update chain.
3269
3270   // Add the flag if we have it.
3271   if (Flag.getNode())
3272     RetOps.push_back(Flag);
3273
3274   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3275 }
3276
3277 //===----------------------------------------------------------------------===//
3278 //  Other Lowering Code
3279 //===----------------------------------------------------------------------===//
3280
3281 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3282                                                   SelectionDAG &DAG) const {
3283   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3284   SDLoc DL(Op);
3285   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3286   const GlobalValue *GV = GN->getGlobal();
3287   unsigned char OpFlags =
3288       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3289
3290   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3291          "unexpected offset in global node");
3292
3293   // This also catched the large code model case for Darwin.
3294   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3295     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3296     // FIXME: Once remat is capable of dealing with instructions with register
3297     // operands, expand this into two nodes instead of using a wrapper node.
3298     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3299   }
3300
3301   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3302     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3303            "use of MO_CONSTPOOL only supported on small model");
3304     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3305     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3306     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3307     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3308     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3309     SDValue GlobalAddr = DAG.getLoad(
3310         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3311         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3312         /*isVolatile=*/false,
3313         /*isNonTemporal=*/true,
3314         /*isInvariant=*/true, 8);
3315     if (GN->getOffset() != 0)
3316       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3317                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3318     return GlobalAddr;
3319   }
3320
3321   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3322     const unsigned char MO_NC = AArch64II::MO_NC;
3323     return DAG.getNode(
3324         AArch64ISD::WrapperLarge, DL, PtrVT,
3325         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3326         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3327         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3328         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3329   } else {
3330     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3331     // the only correct model on Darwin.
3332     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3333                                             OpFlags | AArch64II::MO_PAGE);
3334     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3335     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3336
3337     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3338     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3339   }
3340 }
3341
3342 /// \brief Convert a TLS address reference into the correct sequence of loads
3343 /// and calls to compute the variable's address (for Darwin, currently) and
3344 /// return an SDValue containing the final node.
3345
3346 /// Darwin only has one TLS scheme which must be capable of dealing with the
3347 /// fully general situation, in the worst case. This means:
3348 ///     + "extern __thread" declaration.
3349 ///     + Defined in a possibly unknown dynamic library.
3350 ///
3351 /// The general system is that each __thread variable has a [3 x i64] descriptor
3352 /// which contains information used by the runtime to calculate the address. The
3353 /// only part of this the compiler needs to know about is the first xword, which
3354 /// contains a function pointer that must be called with the address of the
3355 /// entire descriptor in "x0".
3356 ///
3357 /// Since this descriptor may be in a different unit, in general even the
3358 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3359 /// is:
3360 ///     adrp x0, _var@TLVPPAGE
3361 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3362 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3363 ///                                      ; the function pointer
3364 ///     blr x1                           ; Uses descriptor address in x0
3365 ///     ; Address of _var is now in x0.
3366 ///
3367 /// If the address of _var's descriptor *is* known to the linker, then it can
3368 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3369 /// a slight efficiency gain.
3370 SDValue
3371 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3372                                                    SelectionDAG &DAG) const {
3373   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3374
3375   SDLoc DL(Op);
3376   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3377   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3378
3379   SDValue TLVPAddr =
3380       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3381   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3382
3383   // The first entry in the descriptor is a function pointer that we must call
3384   // to obtain the address of the variable.
3385   SDValue Chain = DAG.getEntryNode();
3386   SDValue FuncTLVGet =
3387       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3388                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3389                   true, true, 8);
3390   Chain = FuncTLVGet.getValue(1);
3391
3392   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3393   MFI->setAdjustsStack(true);
3394
3395   // TLS calls preserve all registers except those that absolutely must be
3396   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3397   // silly).
3398   const uint32_t *Mask =
3399       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3400
3401   // Finally, we can make the call. This is just a degenerate version of a
3402   // normal AArch64 call node: x0 takes the address of the descriptor, and
3403   // returns the address of the variable in this thread.
3404   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3405   Chain =
3406       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3407                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3408                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3409   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3410 }
3411
3412 /// When accessing thread-local variables under either the general-dynamic or
3413 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3414 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3415 /// is a function pointer to carry out the resolution.
3416 ///
3417 /// The sequence is:
3418 ///    adrp  x0, :tlsdesc:var
3419 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3420 ///    add   x0, x0, #:tlsdesc_lo12:var
3421 ///    .tlsdesccall var
3422 ///    blr   x1
3423 ///    (TPIDR_EL0 offset now in x0)
3424 ///
3425 ///  The above sequence must be produced unscheduled, to enable the linker to
3426 ///  optimize/relax this sequence.
3427 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3428 ///  above sequence, and expanded really late in the compilation flow, to ensure
3429 ///  the sequence is produced as per above.
3430 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3431                                                       SelectionDAG &DAG) const {
3432   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3433
3434   SDValue Chain = DAG.getEntryNode();
3435   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3436
3437   SmallVector<SDValue, 2> Ops;
3438   Ops.push_back(Chain);
3439   Ops.push_back(SymAddr);
3440
3441   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3442   SDValue Glue = Chain.getValue(1);
3443
3444   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3445 }
3446
3447 SDValue
3448 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3449                                                 SelectionDAG &DAG) const {
3450   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3451   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3452          "ELF TLS only supported in small memory model");
3453   // Different choices can be made for the maximum size of the TLS area for a
3454   // module. For the small address model, the default TLS size is 16MiB and the
3455   // maximum TLS size is 4GiB.
3456   // FIXME: add -mtls-size command line option and make it control the 16MiB
3457   // vs. 4GiB code sequence generation.
3458   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3459
3460   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3461
3462   if (DAG.getTarget().Options.EmulatedTLS)
3463     return LowerToTLSEmulatedModel(GA, DAG);
3464
3465   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3466     if (Model == TLSModel::LocalDynamic)
3467       Model = TLSModel::GeneralDynamic;
3468   }
3469
3470   SDValue TPOff;
3471   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3472   SDLoc DL(Op);
3473   const GlobalValue *GV = GA->getGlobal();
3474
3475   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3476
3477   if (Model == TLSModel::LocalExec) {
3478     SDValue HiVar = DAG.getTargetGlobalAddress(
3479         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3480     SDValue LoVar = DAG.getTargetGlobalAddress(
3481         GV, DL, PtrVT, 0,
3482         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3483
3484     SDValue TPWithOff_lo =
3485         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3486                                    HiVar,
3487                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3488                 0);
3489     SDValue TPWithOff =
3490         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3491                                    LoVar,
3492                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3493                 0);
3494     return TPWithOff;
3495   } else if (Model == TLSModel::InitialExec) {
3496     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3497     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3498   } else if (Model == TLSModel::LocalDynamic) {
3499     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3500     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3501     // the beginning of the module's TLS region, followed by a DTPREL offset
3502     // calculation.
3503
3504     // These accesses will need deduplicating if there's more than one.
3505     AArch64FunctionInfo *MFI =
3506         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3507     MFI->incNumLocalDynamicTLSAccesses();
3508
3509     // The call needs a relocation too for linker relaxation. It doesn't make
3510     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3511     // the address.
3512     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3513                                                   AArch64II::MO_TLS);
3514
3515     // Now we can calculate the offset from TPIDR_EL0 to this module's
3516     // thread-local area.
3517     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3518
3519     // Now use :dtprel_whatever: operations to calculate this variable's offset
3520     // in its thread-storage area.
3521     SDValue HiVar = DAG.getTargetGlobalAddress(
3522         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3523     SDValue LoVar = DAG.getTargetGlobalAddress(
3524         GV, DL, MVT::i64, 0,
3525         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3526
3527     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3528                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3529                     0);
3530     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3531                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3532                     0);
3533   } else if (Model == TLSModel::GeneralDynamic) {
3534     // The call needs a relocation too for linker relaxation. It doesn't make
3535     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3536     // the address.
3537     SDValue SymAddr =
3538         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3539
3540     // Finally we can make a call to calculate the offset from tpidr_el0.
3541     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3542   } else
3543     llvm_unreachable("Unsupported ELF TLS access model");
3544
3545   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3546 }
3547
3548 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3549                                                      SelectionDAG &DAG) const {
3550   if (Subtarget->isTargetDarwin())
3551     return LowerDarwinGlobalTLSAddress(Op, DAG);
3552   else if (Subtarget->isTargetELF())
3553     return LowerELFGlobalTLSAddress(Op, DAG);
3554
3555   llvm_unreachable("Unexpected platform trying to use TLS");
3556 }
3557 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3558   SDValue Chain = Op.getOperand(0);
3559   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3560   SDValue LHS = Op.getOperand(2);
3561   SDValue RHS = Op.getOperand(3);
3562   SDValue Dest = Op.getOperand(4);
3563   SDLoc dl(Op);
3564
3565   // Handle f128 first, since lowering it will result in comparing the return
3566   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3567   // is expecting to deal with.
3568   if (LHS.getValueType() == MVT::f128) {
3569     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3570
3571     // If softenSetCCOperands returned a scalar, we need to compare the result
3572     // against zero to select between true and false values.
3573     if (!RHS.getNode()) {
3574       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3575       CC = ISD::SETNE;
3576     }
3577   }
3578
3579   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3580   // instruction.
3581   unsigned Opc = LHS.getOpcode();
3582   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3583       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3584        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3585     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3586            "Unexpected condition code.");
3587     // Only lower legal XALUO ops.
3588     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3589       return SDValue();
3590
3591     // The actual operation with overflow check.
3592     AArch64CC::CondCode OFCC;
3593     SDValue Value, Overflow;
3594     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3595
3596     if (CC == ISD::SETNE)
3597       OFCC = getInvertedCondCode(OFCC);
3598     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3599
3600     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3601                        Overflow);
3602   }
3603
3604   if (LHS.getValueType().isInteger()) {
3605     assert((LHS.getValueType() == RHS.getValueType()) &&
3606            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3607
3608     // If the RHS of the comparison is zero, we can potentially fold this
3609     // to a specialized branch.
3610     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3611     if (RHSC && RHSC->getZExtValue() == 0) {
3612       if (CC == ISD::SETEQ) {
3613         // See if we can use a TBZ to fold in an AND as well.
3614         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3615         // out of bounds, a late MI-layer pass rewrites branches.
3616         // 403.gcc is an example that hits this case.
3617         if (LHS.getOpcode() == ISD::AND &&
3618             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3619             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3620           SDValue Test = LHS.getOperand(0);
3621           uint64_t Mask = LHS.getConstantOperandVal(1);
3622           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3623                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3624                              Dest);
3625         }
3626
3627         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3628       } else if (CC == ISD::SETNE) {
3629         // See if we can use a TBZ to fold in an AND as well.
3630         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3631         // out of bounds, a late MI-layer pass rewrites branches.
3632         // 403.gcc is an example that hits this case.
3633         if (LHS.getOpcode() == ISD::AND &&
3634             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3635             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3636           SDValue Test = LHS.getOperand(0);
3637           uint64_t Mask = LHS.getConstantOperandVal(1);
3638           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3639                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3640                              Dest);
3641         }
3642
3643         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3644       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3645         // Don't combine AND since emitComparison converts the AND to an ANDS
3646         // (a.k.a. TST) and the test in the test bit and branch instruction
3647         // becomes redundant.  This would also increase register pressure.
3648         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3649         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3650                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3651       }
3652     }
3653     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3654         LHS.getOpcode() != ISD::AND) {
3655       // Don't combine AND since emitComparison converts the AND to an ANDS
3656       // (a.k.a. TST) and the test in the test bit and branch instruction
3657       // becomes redundant.  This would also increase register pressure.
3658       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3659       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3660                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3661     }
3662
3663     SDValue CCVal;
3664     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3665     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3666                        Cmp);
3667   }
3668
3669   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3670
3671   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3672   // clean.  Some of them require two branches to implement.
3673   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3674   AArch64CC::CondCode CC1, CC2;
3675   changeFPCCToAArch64CC(CC, CC1, CC2);
3676   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3677   SDValue BR1 =
3678       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3679   if (CC2 != AArch64CC::AL) {
3680     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3681     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3682                        Cmp);
3683   }
3684
3685   return BR1;
3686 }
3687
3688 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3689                                               SelectionDAG &DAG) const {
3690   EVT VT = Op.getValueType();
3691   SDLoc DL(Op);
3692
3693   SDValue In1 = Op.getOperand(0);
3694   SDValue In2 = Op.getOperand(1);
3695   EVT SrcVT = In2.getValueType();
3696
3697   if (SrcVT.bitsLT(VT))
3698     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3699   else if (SrcVT.bitsGT(VT))
3700     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3701
3702   EVT VecVT;
3703   EVT EltVT;
3704   uint64_t EltMask;
3705   SDValue VecVal1, VecVal2;
3706   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3707     EltVT = MVT::i32;
3708     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3709     EltMask = 0x80000000ULL;
3710
3711     if (!VT.isVector()) {
3712       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3713                                           DAG.getUNDEF(VecVT), In1);
3714       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3715                                           DAG.getUNDEF(VecVT), In2);
3716     } else {
3717       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3718       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3719     }
3720   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3721     EltVT = MVT::i64;
3722     VecVT = MVT::v2i64;
3723
3724     // We want to materialize a mask with the high bit set, but the AdvSIMD
3725     // immediate moves cannot materialize that in a single instruction for
3726     // 64-bit elements. Instead, materialize zero and then negate it.
3727     EltMask = 0;
3728
3729     if (!VT.isVector()) {
3730       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3731                                           DAG.getUNDEF(VecVT), In1);
3732       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3733                                           DAG.getUNDEF(VecVT), In2);
3734     } else {
3735       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3736       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3737     }
3738   } else {
3739     llvm_unreachable("Invalid type for copysign!");
3740   }
3741
3742   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3743
3744   // If we couldn't materialize the mask above, then the mask vector will be
3745   // the zero vector, and we need to negate it here.
3746   if (VT == MVT::f64 || VT == MVT::v2f64) {
3747     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3748     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3749     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3750   }
3751
3752   SDValue Sel =
3753       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3754
3755   if (VT == MVT::f32)
3756     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3757   else if (VT == MVT::f64)
3758     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3759   else
3760     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3761 }
3762
3763 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3764   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3765           Attribute::NoImplicitFloat))
3766     return SDValue();
3767
3768   if (!Subtarget->hasNEON())
3769     return SDValue();
3770
3771   // While there is no integer popcount instruction, it can
3772   // be more efficiently lowered to the following sequence that uses
3773   // AdvSIMD registers/instructions as long as the copies to/from
3774   // the AdvSIMD registers are cheap.
3775   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3776   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3777   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3778   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3779   SDValue Val = Op.getOperand(0);
3780   SDLoc DL(Op);
3781   EVT VT = Op.getValueType();
3782
3783   if (VT == MVT::i32)
3784     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3785   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3786
3787   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3788   SDValue UaddLV = DAG.getNode(
3789       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3790       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3791
3792   if (VT == MVT::i64)
3793     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3794   return UaddLV;
3795 }
3796
3797 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3798
3799   if (Op.getValueType().isVector())
3800     return LowerVSETCC(Op, DAG);
3801
3802   SDValue LHS = Op.getOperand(0);
3803   SDValue RHS = Op.getOperand(1);
3804   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3805   SDLoc dl(Op);
3806
3807   // We chose ZeroOrOneBooleanContents, so use zero and one.
3808   EVT VT = Op.getValueType();
3809   SDValue TVal = DAG.getConstant(1, dl, VT);
3810   SDValue FVal = DAG.getConstant(0, dl, VT);
3811
3812   // Handle f128 first, since one possible outcome is a normal integer
3813   // comparison which gets picked up by the next if statement.
3814   if (LHS.getValueType() == MVT::f128) {
3815     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3816
3817     // If softenSetCCOperands returned a scalar, use it.
3818     if (!RHS.getNode()) {
3819       assert(LHS.getValueType() == Op.getValueType() &&
3820              "Unexpected setcc expansion!");
3821       return LHS;
3822     }
3823   }
3824
3825   if (LHS.getValueType().isInteger()) {
3826     SDValue CCVal;
3827     SDValue Cmp =
3828         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3829
3830     // Note that we inverted the condition above, so we reverse the order of
3831     // the true and false operands here.  This will allow the setcc to be
3832     // matched to a single CSINC instruction.
3833     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3834   }
3835
3836   // Now we know we're dealing with FP values.
3837   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3838
3839   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3840   // and do the comparison.
3841   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3842
3843   AArch64CC::CondCode CC1, CC2;
3844   changeFPCCToAArch64CC(CC, CC1, CC2);
3845   if (CC2 == AArch64CC::AL) {
3846     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3847     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3848
3849     // Note that we inverted the condition above, so we reverse the order of
3850     // the true and false operands here.  This will allow the setcc to be
3851     // matched to a single CSINC instruction.
3852     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3853   } else {
3854     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3855     // totally clean.  Some of them require two CSELs to implement.  As is in
3856     // this case, we emit the first CSEL and then emit a second using the output
3857     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3858
3859     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3860     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3861     SDValue CS1 =
3862         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3863
3864     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3865     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3866   }
3867 }
3868
3869 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3870                                               SDValue RHS, SDValue TVal,
3871                                               SDValue FVal, SDLoc dl,
3872                                               SelectionDAG &DAG) const {
3873   // Handle f128 first, because it will result in a comparison of some RTLIB
3874   // call result against zero.
3875   if (LHS.getValueType() == MVT::f128) {
3876     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3877
3878     // If softenSetCCOperands returned a scalar, we need to compare the result
3879     // against zero to select between true and false values.
3880     if (!RHS.getNode()) {
3881       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3882       CC = ISD::SETNE;
3883     }
3884   }
3885
3886   // Also handle f16, for which we need to do a f32 comparison.
3887   if (LHS.getValueType() == MVT::f16) {
3888     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3889     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3890   }
3891
3892   // Next, handle integers.
3893   if (LHS.getValueType().isInteger()) {
3894     assert((LHS.getValueType() == RHS.getValueType()) &&
3895            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3896
3897     unsigned Opcode = AArch64ISD::CSEL;
3898
3899     // If both the TVal and the FVal are constants, see if we can swap them in
3900     // order to for a CSINV or CSINC out of them.
3901     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3902     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3903
3904     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3905       std::swap(TVal, FVal);
3906       std::swap(CTVal, CFVal);
3907       CC = ISD::getSetCCInverse(CC, true);
3908     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3909       std::swap(TVal, FVal);
3910       std::swap(CTVal, CFVal);
3911       CC = ISD::getSetCCInverse(CC, true);
3912     } else if (TVal.getOpcode() == ISD::XOR) {
3913       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3914       // with a CSINV rather than a CSEL.
3915       if (isAllOnesConstant(TVal.getOperand(1))) {
3916         std::swap(TVal, FVal);
3917         std::swap(CTVal, CFVal);
3918         CC = ISD::getSetCCInverse(CC, true);
3919       }
3920     } else if (TVal.getOpcode() == ISD::SUB) {
3921       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3922       // that we can match with a CSNEG rather than a CSEL.
3923       if (isNullConstant(TVal.getOperand(0))) {
3924         std::swap(TVal, FVal);
3925         std::swap(CTVal, CFVal);
3926         CC = ISD::getSetCCInverse(CC, true);
3927       }
3928     } else if (CTVal && CFVal) {
3929       const int64_t TrueVal = CTVal->getSExtValue();
3930       const int64_t FalseVal = CFVal->getSExtValue();
3931       bool Swap = false;
3932
3933       // If both TVal and FVal are constants, see if FVal is the
3934       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3935       // instead of a CSEL in that case.
3936       if (TrueVal == ~FalseVal) {
3937         Opcode = AArch64ISD::CSINV;
3938       } else if (TrueVal == -FalseVal) {
3939         Opcode = AArch64ISD::CSNEG;
3940       } else if (TVal.getValueType() == MVT::i32) {
3941         // If our operands are only 32-bit wide, make sure we use 32-bit
3942         // arithmetic for the check whether we can use CSINC. This ensures that
3943         // the addition in the check will wrap around properly in case there is
3944         // an overflow (which would not be the case if we do the check with
3945         // 64-bit arithmetic).
3946         const uint32_t TrueVal32 = CTVal->getZExtValue();
3947         const uint32_t FalseVal32 = CFVal->getZExtValue();
3948
3949         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3950           Opcode = AArch64ISD::CSINC;
3951
3952           if (TrueVal32 > FalseVal32) {
3953             Swap = true;
3954           }
3955         }
3956         // 64-bit check whether we can use CSINC.
3957       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3958         Opcode = AArch64ISD::CSINC;
3959
3960         if (TrueVal > FalseVal) {
3961           Swap = true;
3962         }
3963       }
3964
3965       // Swap TVal and FVal if necessary.
3966       if (Swap) {
3967         std::swap(TVal, FVal);
3968         std::swap(CTVal, CFVal);
3969         CC = ISD::getSetCCInverse(CC, true);
3970       }
3971
3972       if (Opcode != AArch64ISD::CSEL) {
3973         // Drop FVal since we can get its value by simply inverting/negating
3974         // TVal.
3975         FVal = TVal;
3976       }
3977     }
3978
3979     SDValue CCVal;
3980     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3981
3982     EVT VT = TVal.getValueType();
3983     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3984   }
3985
3986   // Now we know we're dealing with FP values.
3987   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3988   assert(LHS.getValueType() == RHS.getValueType());
3989   EVT VT = TVal.getValueType();
3990   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3991
3992   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3993   // clean.  Some of them require two CSELs to implement.
3994   AArch64CC::CondCode CC1, CC2;
3995   changeFPCCToAArch64CC(CC, CC1, CC2);
3996   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3997   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3998
3999   // If we need a second CSEL, emit it, using the output of the first as the
4000   // RHS.  We're effectively OR'ing the two CC's together.
4001   if (CC2 != AArch64CC::AL) {
4002     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4003     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4004   }
4005
4006   // Otherwise, return the output of the first CSEL.
4007   return CS1;
4008 }
4009
4010 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4011                                               SelectionDAG &DAG) const {
4012   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4013   SDValue LHS = Op.getOperand(0);
4014   SDValue RHS = Op.getOperand(1);
4015   SDValue TVal = Op.getOperand(2);
4016   SDValue FVal = Op.getOperand(3);
4017   SDLoc DL(Op);
4018   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4019 }
4020
4021 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4022                                            SelectionDAG &DAG) const {
4023   SDValue CCVal = Op->getOperand(0);
4024   SDValue TVal = Op->getOperand(1);
4025   SDValue FVal = Op->getOperand(2);
4026   SDLoc DL(Op);
4027
4028   unsigned Opc = CCVal.getOpcode();
4029   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4030   // instruction.
4031   if (CCVal.getResNo() == 1 &&
4032       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4033        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4034     // Only lower legal XALUO ops.
4035     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4036       return SDValue();
4037
4038     AArch64CC::CondCode OFCC;
4039     SDValue Value, Overflow;
4040     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4041     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4042
4043     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4044                        CCVal, Overflow);
4045   }
4046
4047   // Lower it the same way as we would lower a SELECT_CC node.
4048   ISD::CondCode CC;
4049   SDValue LHS, RHS;
4050   if (CCVal.getOpcode() == ISD::SETCC) {
4051     LHS = CCVal.getOperand(0);
4052     RHS = CCVal.getOperand(1);
4053     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4054   } else {
4055     LHS = CCVal;
4056     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4057     CC = ISD::SETNE;
4058   }
4059   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4060 }
4061
4062 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4063                                               SelectionDAG &DAG) const {
4064   // Jump table entries as PC relative offsets. No additional tweaking
4065   // is necessary here. Just get the address of the jump table.
4066   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4067   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4068   SDLoc DL(Op);
4069
4070   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4071       !Subtarget->isTargetMachO()) {
4072     const unsigned char MO_NC = AArch64II::MO_NC;
4073     return DAG.getNode(
4074         AArch64ISD::WrapperLarge, DL, PtrVT,
4075         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4076         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4077         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4078         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4079                                AArch64II::MO_G0 | MO_NC));
4080   }
4081
4082   SDValue Hi =
4083       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4084   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4085                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4086   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4087   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4088 }
4089
4090 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4091                                                  SelectionDAG &DAG) const {
4092   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4093   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4094   SDLoc DL(Op);
4095
4096   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4097     // Use the GOT for the large code model on iOS.
4098     if (Subtarget->isTargetMachO()) {
4099       SDValue GotAddr = DAG.getTargetConstantPool(
4100           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4101           AArch64II::MO_GOT);
4102       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4103     }
4104
4105     const unsigned char MO_NC = AArch64II::MO_NC;
4106     return DAG.getNode(
4107         AArch64ISD::WrapperLarge, DL, PtrVT,
4108         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4109                                   CP->getOffset(), AArch64II::MO_G3),
4110         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4111                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4112         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4113                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4114         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4115                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4116   } else {
4117     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4118     // ELF, the only valid one on Darwin.
4119     SDValue Hi =
4120         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4121                                   CP->getOffset(), AArch64II::MO_PAGE);
4122     SDValue Lo = DAG.getTargetConstantPool(
4123         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4124         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4125
4126     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4127     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4128   }
4129 }
4130
4131 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4132                                                SelectionDAG &DAG) const {
4133   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4134   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4135   SDLoc DL(Op);
4136   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4137       !Subtarget->isTargetMachO()) {
4138     const unsigned char MO_NC = AArch64II::MO_NC;
4139     return DAG.getNode(
4140         AArch64ISD::WrapperLarge, DL, PtrVT,
4141         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4142         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4143         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4144         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4145   } else {
4146     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4147     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4148                                                              AArch64II::MO_NC);
4149     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4150     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4151   }
4152 }
4153
4154 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4155                                                  SelectionDAG &DAG) const {
4156   AArch64FunctionInfo *FuncInfo =
4157       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4158
4159   SDLoc DL(Op);
4160   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4161                                  getPointerTy(DAG.getDataLayout()));
4162   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4163   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4164                       MachinePointerInfo(SV), false, false, 0);
4165 }
4166
4167 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4168                                                 SelectionDAG &DAG) const {
4169   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4170   // Standard, section B.3.
4171   MachineFunction &MF = DAG.getMachineFunction();
4172   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4173   auto PtrVT = getPointerTy(DAG.getDataLayout());
4174   SDLoc DL(Op);
4175
4176   SDValue Chain = Op.getOperand(0);
4177   SDValue VAList = Op.getOperand(1);
4178   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4179   SmallVector<SDValue, 4> MemOps;
4180
4181   // void *__stack at offset 0
4182   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4183   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4184                                 MachinePointerInfo(SV), false, false, 8));
4185
4186   // void *__gr_top at offset 8
4187   int GPRSize = FuncInfo->getVarArgsGPRSize();
4188   if (GPRSize > 0) {
4189     SDValue GRTop, GRTopAddr;
4190
4191     GRTopAddr =
4192         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4193
4194     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4195     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4196                         DAG.getConstant(GPRSize, DL, PtrVT));
4197
4198     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4199                                   MachinePointerInfo(SV, 8), false, false, 8));
4200   }
4201
4202   // void *__vr_top at offset 16
4203   int FPRSize = FuncInfo->getVarArgsFPRSize();
4204   if (FPRSize > 0) {
4205     SDValue VRTop, VRTopAddr;
4206     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4207                             DAG.getConstant(16, DL, PtrVT));
4208
4209     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4210     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4211                         DAG.getConstant(FPRSize, DL, PtrVT));
4212
4213     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4214                                   MachinePointerInfo(SV, 16), false, false, 8));
4215   }
4216
4217   // int __gr_offs at offset 24
4218   SDValue GROffsAddr =
4219       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4220   MemOps.push_back(DAG.getStore(Chain, DL,
4221                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4222                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4223                                 false, 4));
4224
4225   // int __vr_offs at offset 28
4226   SDValue VROffsAddr =
4227       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4228   MemOps.push_back(DAG.getStore(Chain, DL,
4229                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4230                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4231                                 false, 4));
4232
4233   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4234 }
4235
4236 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4237                                             SelectionDAG &DAG) const {
4238   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4239                                      : LowerAAPCS_VASTART(Op, DAG);
4240 }
4241
4242 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4243                                            SelectionDAG &DAG) const {
4244   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4245   // pointer.
4246   SDLoc DL(Op);
4247   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4248   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4249   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4250
4251   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4252                        Op.getOperand(2),
4253                        DAG.getConstant(VaListSize, DL, MVT::i32),
4254                        8, false, false, false, MachinePointerInfo(DestSV),
4255                        MachinePointerInfo(SrcSV));
4256 }
4257
4258 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4259   assert(Subtarget->isTargetDarwin() &&
4260          "automatic va_arg instruction only works on Darwin");
4261
4262   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4263   EVT VT = Op.getValueType();
4264   SDLoc DL(Op);
4265   SDValue Chain = Op.getOperand(0);
4266   SDValue Addr = Op.getOperand(1);
4267   unsigned Align = Op.getConstantOperandVal(3);
4268   auto PtrVT = getPointerTy(DAG.getDataLayout());
4269
4270   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4271                                false, false, false, 0);
4272   Chain = VAList.getValue(1);
4273
4274   if (Align > 8) {
4275     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4276     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4277                          DAG.getConstant(Align - 1, DL, PtrVT));
4278     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4279                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4280   }
4281
4282   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4283   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4284
4285   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4286   // up to 64 bits.  At the very least, we have to increase the striding of the
4287   // vaargs list to match this, and for FP values we need to introduce
4288   // FP_ROUND nodes as well.
4289   if (VT.isInteger() && !VT.isVector())
4290     ArgSize = 8;
4291   bool NeedFPTrunc = false;
4292   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4293     ArgSize = 8;
4294     NeedFPTrunc = true;
4295   }
4296
4297   // Increment the pointer, VAList, to the next vaarg
4298   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4299                                DAG.getConstant(ArgSize, DL, PtrVT));
4300   // Store the incremented VAList to the legalized pointer
4301   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4302                                  false, false, 0);
4303
4304   // Load the actual argument out of the pointer VAList
4305   if (NeedFPTrunc) {
4306     // Load the value as an f64.
4307     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4308                                  MachinePointerInfo(), false, false, false, 0);
4309     // Round the value down to an f32.
4310     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4311                                    DAG.getIntPtrConstant(1, DL));
4312     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4313     // Merge the rounded value with the chain output of the load.
4314     return DAG.getMergeValues(Ops, DL);
4315   }
4316
4317   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4318                      false, false, 0);
4319 }
4320
4321 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4322                                               SelectionDAG &DAG) const {
4323   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4324   MFI->setFrameAddressIsTaken(true);
4325
4326   EVT VT = Op.getValueType();
4327   SDLoc DL(Op);
4328   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4329   SDValue FrameAddr =
4330       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4331   while (Depth--)
4332     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4333                             MachinePointerInfo(), false, false, false, 0);
4334   return FrameAddr;
4335 }
4336
4337 // FIXME? Maybe this could be a TableGen attribute on some registers and
4338 // this table could be generated automatically from RegInfo.
4339 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4340                                                   SelectionDAG &DAG) const {
4341   unsigned Reg = StringSwitch<unsigned>(RegName)
4342                        .Case("sp", AArch64::SP)
4343                        .Default(0);
4344   if (Reg)
4345     return Reg;
4346   report_fatal_error(Twine("Invalid register name \""
4347                               + StringRef(RegName)  + "\"."));
4348 }
4349
4350 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4351                                                SelectionDAG &DAG) const {
4352   MachineFunction &MF = DAG.getMachineFunction();
4353   MachineFrameInfo *MFI = MF.getFrameInfo();
4354   MFI->setReturnAddressIsTaken(true);
4355
4356   EVT VT = Op.getValueType();
4357   SDLoc DL(Op);
4358   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4359   if (Depth) {
4360     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4361     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4362     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4363                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4364                        MachinePointerInfo(), false, false, false, 0);
4365   }
4366
4367   // Return LR, which contains the return address. Mark it an implicit live-in.
4368   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4369   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4370 }
4371
4372 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4373 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4374 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4375                                                     SelectionDAG &DAG) const {
4376   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4377   EVT VT = Op.getValueType();
4378   unsigned VTBits = VT.getSizeInBits();
4379   SDLoc dl(Op);
4380   SDValue ShOpLo = Op.getOperand(0);
4381   SDValue ShOpHi = Op.getOperand(1);
4382   SDValue ShAmt = Op.getOperand(2);
4383   SDValue ARMcc;
4384   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4385
4386   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4387
4388   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4389                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4390   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4391   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4392                                    DAG.getConstant(VTBits, dl, MVT::i64));
4393   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4394
4395   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4396                                ISD::SETGE, dl, DAG);
4397   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4398
4399   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4400   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4401   SDValue Lo =
4402       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4403
4404   // AArch64 shifts larger than the register width are wrapped rather than
4405   // clamped, so we can't just emit "hi >> x".
4406   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4407   SDValue TrueValHi = Opc == ISD::SRA
4408                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4409                                         DAG.getConstant(VTBits - 1, dl,
4410                                                         MVT::i64))
4411                           : DAG.getConstant(0, dl, VT);
4412   SDValue Hi =
4413       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4414
4415   SDValue Ops[2] = { Lo, Hi };
4416   return DAG.getMergeValues(Ops, dl);
4417 }
4418
4419 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4420 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4421 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4422                                                  SelectionDAG &DAG) const {
4423   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4424   EVT VT = Op.getValueType();
4425   unsigned VTBits = VT.getSizeInBits();
4426   SDLoc dl(Op);
4427   SDValue ShOpLo = Op.getOperand(0);
4428   SDValue ShOpHi = Op.getOperand(1);
4429   SDValue ShAmt = Op.getOperand(2);
4430   SDValue ARMcc;
4431
4432   assert(Op.getOpcode() == ISD::SHL_PARTS);
4433   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4434                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4435   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4436   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4437                                    DAG.getConstant(VTBits, dl, MVT::i64));
4438   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4439   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4440
4441   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4442
4443   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4444                                ISD::SETGE, dl, DAG);
4445   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4446   SDValue Hi =
4447       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4448
4449   // AArch64 shifts of larger than register sizes are wrapped rather than
4450   // clamped, so we can't just emit "lo << a" if a is too big.
4451   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4452   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4453   SDValue Lo =
4454       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4455
4456   SDValue Ops[2] = { Lo, Hi };
4457   return DAG.getMergeValues(Ops, dl);
4458 }
4459
4460 bool AArch64TargetLowering::isOffsetFoldingLegal(
4461     const GlobalAddressSDNode *GA) const {
4462   // The AArch64 target doesn't support folding offsets into global addresses.
4463   return false;
4464 }
4465
4466 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4467   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4468   // FIXME: We should be able to handle f128 as well with a clever lowering.
4469   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4470     return true;
4471
4472   if (VT == MVT::f64)
4473     return AArch64_AM::getFP64Imm(Imm) != -1;
4474   else if (VT == MVT::f32)
4475     return AArch64_AM::getFP32Imm(Imm) != -1;
4476   return false;
4477 }
4478
4479 //===----------------------------------------------------------------------===//
4480 //                          AArch64 Optimization Hooks
4481 //===----------------------------------------------------------------------===//
4482
4483 //===----------------------------------------------------------------------===//
4484 //                          AArch64 Inline Assembly Support
4485 //===----------------------------------------------------------------------===//
4486
4487 // Table of Constraints
4488 // TODO: This is the current set of constraints supported by ARM for the
4489 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4490 //
4491 // r - A general register
4492 // w - An FP/SIMD register of some size in the range v0-v31
4493 // x - An FP/SIMD register of some size in the range v0-v15
4494 // I - Constant that can be used with an ADD instruction
4495 // J - Constant that can be used with a SUB instruction
4496 // K - Constant that can be used with a 32-bit logical instruction
4497 // L - Constant that can be used with a 64-bit logical instruction
4498 // M - Constant that can be used as a 32-bit MOV immediate
4499 // N - Constant that can be used as a 64-bit MOV immediate
4500 // Q - A memory reference with base register and no offset
4501 // S - A symbolic address
4502 // Y - Floating point constant zero
4503 // Z - Integer constant zero
4504 //
4505 //   Note that general register operands will be output using their 64-bit x
4506 // register name, whatever the size of the variable, unless the asm operand
4507 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4508 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4509 // %q modifier.
4510
4511 /// getConstraintType - Given a constraint letter, return the type of
4512 /// constraint it is for this target.
4513 AArch64TargetLowering::ConstraintType
4514 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4515   if (Constraint.size() == 1) {
4516     switch (Constraint[0]) {
4517     default:
4518       break;
4519     case 'z':
4520       return C_Other;
4521     case 'x':
4522     case 'w':
4523       return C_RegisterClass;
4524     // An address with a single base register. Due to the way we
4525     // currently handle addresses it is the same as 'r'.
4526     case 'Q':
4527       return C_Memory;
4528     }
4529   }
4530   return TargetLowering::getConstraintType(Constraint);
4531 }
4532
4533 /// Examine constraint type and operand type and determine a weight value.
4534 /// This object must already have been set up with the operand type
4535 /// and the current alternative constraint selected.
4536 TargetLowering::ConstraintWeight
4537 AArch64TargetLowering::getSingleConstraintMatchWeight(
4538     AsmOperandInfo &info, const char *constraint) const {
4539   ConstraintWeight weight = CW_Invalid;
4540   Value *CallOperandVal = info.CallOperandVal;
4541   // If we don't have a value, we can't do a match,
4542   // but allow it at the lowest weight.
4543   if (!CallOperandVal)
4544     return CW_Default;
4545   Type *type = CallOperandVal->getType();
4546   // Look at the constraint type.
4547   switch (*constraint) {
4548   default:
4549     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4550     break;
4551   case 'x':
4552   case 'w':
4553     if (type->isFloatingPointTy() || type->isVectorTy())
4554       weight = CW_Register;
4555     break;
4556   case 'z':
4557     weight = CW_Constant;
4558     break;
4559   }
4560   return weight;
4561 }
4562
4563 std::pair<unsigned, const TargetRegisterClass *>
4564 AArch64TargetLowering::getRegForInlineAsmConstraint(
4565     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4566   if (Constraint.size() == 1) {
4567     switch (Constraint[0]) {
4568     case 'r':
4569       if (VT.getSizeInBits() == 64)
4570         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4571       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4572     case 'w':
4573       if (VT == MVT::f32)
4574         return std::make_pair(0U, &AArch64::FPR32RegClass);
4575       if (VT.getSizeInBits() == 64)
4576         return std::make_pair(0U, &AArch64::FPR64RegClass);
4577       if (VT.getSizeInBits() == 128)
4578         return std::make_pair(0U, &AArch64::FPR128RegClass);
4579       break;
4580     // The instructions that this constraint is designed for can
4581     // only take 128-bit registers so just use that regclass.
4582     case 'x':
4583       if (VT.getSizeInBits() == 128)
4584         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4585       break;
4586     }
4587   }
4588   if (StringRef("{cc}").equals_lower(Constraint))
4589     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4590
4591   // Use the default implementation in TargetLowering to convert the register
4592   // constraint into a member of a register class.
4593   std::pair<unsigned, const TargetRegisterClass *> Res;
4594   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4595
4596   // Not found as a standard register?
4597   if (!Res.second) {
4598     unsigned Size = Constraint.size();
4599     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4600         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4601       int RegNo;
4602       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4603       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4604         // v0 - v31 are aliases of q0 - q31.
4605         // By default we'll emit v0-v31 for this unless there's a modifier where
4606         // we'll emit the correct register as well.
4607         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4608         Res.second = &AArch64::FPR128RegClass;
4609       }
4610     }
4611   }
4612
4613   return Res;
4614 }
4615
4616 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4617 /// vector.  If it is invalid, don't add anything to Ops.
4618 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4619     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4620     SelectionDAG &DAG) const {
4621   SDValue Result;
4622
4623   // Currently only support length 1 constraints.
4624   if (Constraint.length() != 1)
4625     return;
4626
4627   char ConstraintLetter = Constraint[0];
4628   switch (ConstraintLetter) {
4629   default:
4630     break;
4631
4632   // This set of constraints deal with valid constants for various instructions.
4633   // Validate and return a target constant for them if we can.
4634   case 'z': {
4635     // 'z' maps to xzr or wzr so it needs an input of 0.
4636     if (!isNullConstant(Op))
4637       return;
4638
4639     if (Op.getValueType() == MVT::i64)
4640       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4641     else
4642       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4643     break;
4644   }
4645
4646   case 'I':
4647   case 'J':
4648   case 'K':
4649   case 'L':
4650   case 'M':
4651   case 'N':
4652     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4653     if (!C)
4654       return;
4655
4656     // Grab the value and do some validation.
4657     uint64_t CVal = C->getZExtValue();
4658     switch (ConstraintLetter) {
4659     // The I constraint applies only to simple ADD or SUB immediate operands:
4660     // i.e. 0 to 4095 with optional shift by 12
4661     // The J constraint applies only to ADD or SUB immediates that would be
4662     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4663     // instruction [or vice versa], in other words -1 to -4095 with optional
4664     // left shift by 12.
4665     case 'I':
4666       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4667         break;
4668       return;
4669     case 'J': {
4670       uint64_t NVal = -C->getSExtValue();
4671       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4672         CVal = C->getSExtValue();
4673         break;
4674       }
4675       return;
4676     }
4677     // The K and L constraints apply *only* to logical immediates, including
4678     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4679     // been removed and MOV should be used). So these constraints have to
4680     // distinguish between bit patterns that are valid 32-bit or 64-bit
4681     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4682     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4683     // versa.
4684     case 'K':
4685       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4686         break;
4687       return;
4688     case 'L':
4689       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4690         break;
4691       return;
4692     // The M and N constraints are a superset of K and L respectively, for use
4693     // with the MOV (immediate) alias. As well as the logical immediates they
4694     // also match 32 or 64-bit immediates that can be loaded either using a
4695     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4696     // (M) or 64-bit 0x1234000000000000 (N) etc.
4697     // As a note some of this code is liberally stolen from the asm parser.
4698     case 'M': {
4699       if (!isUInt<32>(CVal))
4700         return;
4701       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4702         break;
4703       if ((CVal & 0xFFFF) == CVal)
4704         break;
4705       if ((CVal & 0xFFFF0000ULL) == CVal)
4706         break;
4707       uint64_t NCVal = ~(uint32_t)CVal;
4708       if ((NCVal & 0xFFFFULL) == NCVal)
4709         break;
4710       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4711         break;
4712       return;
4713     }
4714     case 'N': {
4715       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4716         break;
4717       if ((CVal & 0xFFFFULL) == CVal)
4718         break;
4719       if ((CVal & 0xFFFF0000ULL) == CVal)
4720         break;
4721       if ((CVal & 0xFFFF00000000ULL) == CVal)
4722         break;
4723       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4724         break;
4725       uint64_t NCVal = ~CVal;
4726       if ((NCVal & 0xFFFFULL) == NCVal)
4727         break;
4728       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4729         break;
4730       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4731         break;
4732       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4733         break;
4734       return;
4735     }
4736     default:
4737       return;
4738     }
4739
4740     // All assembler immediates are 64-bit integers.
4741     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4742     break;
4743   }
4744
4745   if (Result.getNode()) {
4746     Ops.push_back(Result);
4747     return;
4748   }
4749
4750   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4751 }
4752
4753 //===----------------------------------------------------------------------===//
4754 //                     AArch64 Advanced SIMD Support
4755 //===----------------------------------------------------------------------===//
4756
4757 /// WidenVector - Given a value in the V64 register class, produce the
4758 /// equivalent value in the V128 register class.
4759 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4760   EVT VT = V64Reg.getValueType();
4761   unsigned NarrowSize = VT.getVectorNumElements();
4762   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4763   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4764   SDLoc DL(V64Reg);
4765
4766   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4767                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4768 }
4769
4770 /// getExtFactor - Determine the adjustment factor for the position when
4771 /// generating an "extract from vector registers" instruction.
4772 static unsigned getExtFactor(SDValue &V) {
4773   EVT EltType = V.getValueType().getVectorElementType();
4774   return EltType.getSizeInBits() / 8;
4775 }
4776
4777 /// NarrowVector - Given a value in the V128 register class, produce the
4778 /// equivalent value in the V64 register class.
4779 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4780   EVT VT = V128Reg.getValueType();
4781   unsigned WideSize = VT.getVectorNumElements();
4782   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4783   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4784   SDLoc DL(V128Reg);
4785
4786   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4787 }
4788
4789 // Gather data to see if the operation can be modelled as a
4790 // shuffle in combination with VEXTs.
4791 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4792                                                   SelectionDAG &DAG) const {
4793   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4794   SDLoc dl(Op);
4795   EVT VT = Op.getValueType();
4796   unsigned NumElts = VT.getVectorNumElements();
4797
4798   struct ShuffleSourceInfo {
4799     SDValue Vec;
4800     unsigned MinElt;
4801     unsigned MaxElt;
4802
4803     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4804     // be compatible with the shuffle we intend to construct. As a result
4805     // ShuffleVec will be some sliding window into the original Vec.
4806     SDValue ShuffleVec;
4807
4808     // Code should guarantee that element i in Vec starts at element "WindowBase
4809     // + i * WindowScale in ShuffleVec".
4810     int WindowBase;
4811     int WindowScale;
4812
4813     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4814     ShuffleSourceInfo(SDValue Vec)
4815         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4816           WindowScale(1) {}
4817   };
4818
4819   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4820   // node.
4821   SmallVector<ShuffleSourceInfo, 2> Sources;
4822   for (unsigned i = 0; i < NumElts; ++i) {
4823     SDValue V = Op.getOperand(i);
4824     if (V.getOpcode() == ISD::UNDEF)
4825       continue;
4826     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4827       // A shuffle can only come from building a vector from various
4828       // elements of other vectors.
4829       return SDValue();
4830     }
4831
4832     // Add this element source to the list if it's not already there.
4833     SDValue SourceVec = V.getOperand(0);
4834     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4835     if (Source == Sources.end())
4836       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4837
4838     // Update the minimum and maximum lane number seen.
4839     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4840     Source->MinElt = std::min(Source->MinElt, EltNo);
4841     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4842   }
4843
4844   // Currently only do something sane when at most two source vectors
4845   // are involved.
4846   if (Sources.size() > 2)
4847     return SDValue();
4848
4849   // Find out the smallest element size among result and two sources, and use
4850   // it as element size to build the shuffle_vector.
4851   EVT SmallestEltTy = VT.getVectorElementType();
4852   for (auto &Source : Sources) {
4853     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4854     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4855       SmallestEltTy = SrcEltTy;
4856     }
4857   }
4858   unsigned ResMultiplier =
4859       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4860   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4861   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4862
4863   // If the source vector is too wide or too narrow, we may nevertheless be able
4864   // to construct a compatible shuffle either by concatenating it with UNDEF or
4865   // extracting a suitable range of elements.
4866   for (auto &Src : Sources) {
4867     EVT SrcVT = Src.ShuffleVec.getValueType();
4868
4869     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4870       continue;
4871
4872     // This stage of the search produces a source with the same element type as
4873     // the original, but with a total width matching the BUILD_VECTOR output.
4874     EVT EltVT = SrcVT.getVectorElementType();
4875     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4876     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4877
4878     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4879       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4880       // We can pad out the smaller vector for free, so if it's part of a
4881       // shuffle...
4882       Src.ShuffleVec =
4883           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4884                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4885       continue;
4886     }
4887
4888     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4889
4890     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4891       // Span too large for a VEXT to cope
4892       return SDValue();
4893     }
4894
4895     if (Src.MinElt >= NumSrcElts) {
4896       // The extraction can just take the second half
4897       Src.ShuffleVec =
4898           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4899                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4900       Src.WindowBase = -NumSrcElts;
4901     } else if (Src.MaxElt < NumSrcElts) {
4902       // The extraction can just take the first half
4903       Src.ShuffleVec =
4904           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4905                       DAG.getConstant(0, dl, MVT::i64));
4906     } else {
4907       // An actual VEXT is needed
4908       SDValue VEXTSrc1 =
4909           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4910                       DAG.getConstant(0, dl, MVT::i64));
4911       SDValue VEXTSrc2 =
4912           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4913                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4914       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4915
4916       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4917                                    VEXTSrc2,
4918                                    DAG.getConstant(Imm, dl, MVT::i32));
4919       Src.WindowBase = -Src.MinElt;
4920     }
4921   }
4922
4923   // Another possible incompatibility occurs from the vector element types. We
4924   // can fix this by bitcasting the source vectors to the same type we intend
4925   // for the shuffle.
4926   for (auto &Src : Sources) {
4927     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4928     if (SrcEltTy == SmallestEltTy)
4929       continue;
4930     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4931     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4932     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4933     Src.WindowBase *= Src.WindowScale;
4934   }
4935
4936   // Final sanity check before we try to actually produce a shuffle.
4937   DEBUG(
4938     for (auto Src : Sources)
4939       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4940   );
4941
4942   // The stars all align, our next step is to produce the mask for the shuffle.
4943   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4944   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4945   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4946     SDValue Entry = Op.getOperand(i);
4947     if (Entry.getOpcode() == ISD::UNDEF)
4948       continue;
4949
4950     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4951     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4952
4953     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4954     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4955     // segment.
4956     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4957     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4958                                VT.getVectorElementType().getSizeInBits());
4959     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4960
4961     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4962     // starting at the appropriate offset.
4963     int *LaneMask = &Mask[i * ResMultiplier];
4964
4965     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4966     ExtractBase += NumElts * (Src - Sources.begin());
4967     for (int j = 0; j < LanesDefined; ++j)
4968       LaneMask[j] = ExtractBase + j;
4969   }
4970
4971   // Final check before we try to produce nonsense...
4972   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4973     return SDValue();
4974
4975   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4976   for (unsigned i = 0; i < Sources.size(); ++i)
4977     ShuffleOps[i] = Sources[i].ShuffleVec;
4978
4979   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4980                                          ShuffleOps[1], &Mask[0]);
4981   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4982 }
4983
4984 // check if an EXT instruction can handle the shuffle mask when the
4985 // vector sources of the shuffle are the same.
4986 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4987   unsigned NumElts = VT.getVectorNumElements();
4988
4989   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4990   if (M[0] < 0)
4991     return false;
4992
4993   Imm = M[0];
4994
4995   // If this is a VEXT shuffle, the immediate value is the index of the first
4996   // element.  The other shuffle indices must be the successive elements after
4997   // the first one.
4998   unsigned ExpectedElt = Imm;
4999   for (unsigned i = 1; i < NumElts; ++i) {
5000     // Increment the expected index.  If it wraps around, just follow it
5001     // back to index zero and keep going.
5002     ++ExpectedElt;
5003     if (ExpectedElt == NumElts)
5004       ExpectedElt = 0;
5005
5006     if (M[i] < 0)
5007       continue; // ignore UNDEF indices
5008     if (ExpectedElt != static_cast<unsigned>(M[i]))
5009       return false;
5010   }
5011
5012   return true;
5013 }
5014
5015 // check if an EXT instruction can handle the shuffle mask when the
5016 // vector sources of the shuffle are different.
5017 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5018                       unsigned &Imm) {
5019   // Look for the first non-undef element.
5020   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5021       [](int Elt) {return Elt >= 0;});
5022
5023   // Benefit form APInt to handle overflow when calculating expected element.
5024   unsigned NumElts = VT.getVectorNumElements();
5025   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5026   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5027   // The following shuffle indices must be the successive elements after the
5028   // first real element.
5029   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5030       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5031   if (FirstWrongElt != M.end())
5032     return false;
5033
5034   // The index of an EXT is the first element if it is not UNDEF.
5035   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5036   // value of the first element.  E.g. 
5037   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5038   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5039   // ExpectedElt is the last mask index plus 1.
5040   Imm = ExpectedElt.getZExtValue();
5041
5042   // There are two difference cases requiring to reverse input vectors.
5043   // For example, for vector <4 x i32> we have the following cases,
5044   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5045   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5046   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5047   // to reverse two input vectors.
5048   if (Imm < NumElts)
5049     ReverseEXT = true;
5050   else
5051     Imm -= NumElts;
5052
5053   return true;
5054 }
5055
5056 /// isREVMask - Check if a vector shuffle corresponds to a REV
5057 /// instruction with the specified blocksize.  (The order of the elements
5058 /// within each block of the vector is reversed.)
5059 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5060   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5061          "Only possible block sizes for REV are: 16, 32, 64");
5062
5063   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5064   if (EltSz == 64)
5065     return false;
5066
5067   unsigned NumElts = VT.getVectorNumElements();
5068   unsigned BlockElts = M[0] + 1;
5069   // If the first shuffle index is UNDEF, be optimistic.
5070   if (M[0] < 0)
5071     BlockElts = BlockSize / EltSz;
5072
5073   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5074     return false;
5075
5076   for (unsigned i = 0; i < NumElts; ++i) {
5077     if (M[i] < 0)
5078       continue; // ignore UNDEF indices
5079     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5080       return false;
5081   }
5082
5083   return true;
5084 }
5085
5086 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5087   unsigned NumElts = VT.getVectorNumElements();
5088   WhichResult = (M[0] == 0 ? 0 : 1);
5089   unsigned Idx = WhichResult * NumElts / 2;
5090   for (unsigned i = 0; i != NumElts; i += 2) {
5091     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5092         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5093       return false;
5094     Idx += 1;
5095   }
5096
5097   return true;
5098 }
5099
5100 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5101   unsigned NumElts = VT.getVectorNumElements();
5102   WhichResult = (M[0] == 0 ? 0 : 1);
5103   for (unsigned i = 0; i != NumElts; ++i) {
5104     if (M[i] < 0)
5105       continue; // ignore UNDEF indices
5106     if ((unsigned)M[i] != 2 * i + WhichResult)
5107       return false;
5108   }
5109
5110   return true;
5111 }
5112
5113 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5114   unsigned NumElts = VT.getVectorNumElements();
5115   WhichResult = (M[0] == 0 ? 0 : 1);
5116   for (unsigned i = 0; i < NumElts; i += 2) {
5117     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5118         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5119       return false;
5120   }
5121   return true;
5122 }
5123
5124 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5125 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5126 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5127 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5128   unsigned NumElts = VT.getVectorNumElements();
5129   WhichResult = (M[0] == 0 ? 0 : 1);
5130   unsigned Idx = WhichResult * NumElts / 2;
5131   for (unsigned i = 0; i != NumElts; i += 2) {
5132     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5133         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5134       return false;
5135     Idx += 1;
5136   }
5137
5138   return true;
5139 }
5140
5141 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5142 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5143 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5144 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5145   unsigned Half = VT.getVectorNumElements() / 2;
5146   WhichResult = (M[0] == 0 ? 0 : 1);
5147   for (unsigned j = 0; j != 2; ++j) {
5148     unsigned Idx = WhichResult;
5149     for (unsigned i = 0; i != Half; ++i) {
5150       int MIdx = M[i + j * Half];
5151       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5152         return false;
5153       Idx += 2;
5154     }
5155   }
5156
5157   return true;
5158 }
5159
5160 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5161 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5162 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5163 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5164   unsigned NumElts = VT.getVectorNumElements();
5165   WhichResult = (M[0] == 0 ? 0 : 1);
5166   for (unsigned i = 0; i < NumElts; i += 2) {
5167     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5168         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5169       return false;
5170   }
5171   return true;
5172 }
5173
5174 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5175                       bool &DstIsLeft, int &Anomaly) {
5176   if (M.size() != static_cast<size_t>(NumInputElements))
5177     return false;
5178
5179   int NumLHSMatch = 0, NumRHSMatch = 0;
5180   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5181
5182   for (int i = 0; i < NumInputElements; ++i) {
5183     if (M[i] == -1) {
5184       ++NumLHSMatch;
5185       ++NumRHSMatch;
5186       continue;
5187     }
5188
5189     if (M[i] == i)
5190       ++NumLHSMatch;
5191     else
5192       LastLHSMismatch = i;
5193
5194     if (M[i] == i + NumInputElements)
5195       ++NumRHSMatch;
5196     else
5197       LastRHSMismatch = i;
5198   }
5199
5200   if (NumLHSMatch == NumInputElements - 1) {
5201     DstIsLeft = true;
5202     Anomaly = LastLHSMismatch;
5203     return true;
5204   } else if (NumRHSMatch == NumInputElements - 1) {
5205     DstIsLeft = false;
5206     Anomaly = LastRHSMismatch;
5207     return true;
5208   }
5209
5210   return false;
5211 }
5212
5213 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5214   if (VT.getSizeInBits() != 128)
5215     return false;
5216
5217   unsigned NumElts = VT.getVectorNumElements();
5218
5219   for (int I = 0, E = NumElts / 2; I != E; I++) {
5220     if (Mask[I] != I)
5221       return false;
5222   }
5223
5224   int Offset = NumElts / 2;
5225   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5226     if (Mask[I] != I + SplitLHS * Offset)
5227       return false;
5228   }
5229
5230   return true;
5231 }
5232
5233 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5234   SDLoc DL(Op);
5235   EVT VT = Op.getValueType();
5236   SDValue V0 = Op.getOperand(0);
5237   SDValue V1 = Op.getOperand(1);
5238   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5239
5240   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5241       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5242     return SDValue();
5243
5244   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5245
5246   if (!isConcatMask(Mask, VT, SplitV0))
5247     return SDValue();
5248
5249   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5250                                 VT.getVectorNumElements() / 2);
5251   if (SplitV0) {
5252     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5253                      DAG.getConstant(0, DL, MVT::i64));
5254   }
5255   if (V1.getValueType().getSizeInBits() == 128) {
5256     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5257                      DAG.getConstant(0, DL, MVT::i64));
5258   }
5259   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5260 }
5261
5262 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5263 /// the specified operations to build the shuffle.
5264 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5265                                       SDValue RHS, SelectionDAG &DAG,
5266                                       SDLoc dl) {
5267   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5268   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5269   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5270
5271   enum {
5272     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5273     OP_VREV,
5274     OP_VDUP0,
5275     OP_VDUP1,
5276     OP_VDUP2,
5277     OP_VDUP3,
5278     OP_VEXT1,
5279     OP_VEXT2,
5280     OP_VEXT3,
5281     OP_VUZPL, // VUZP, left result
5282     OP_VUZPR, // VUZP, right result
5283     OP_VZIPL, // VZIP, left result
5284     OP_VZIPR, // VZIP, right result
5285     OP_VTRNL, // VTRN, left result
5286     OP_VTRNR  // VTRN, right result
5287   };
5288
5289   if (OpNum == OP_COPY) {
5290     if (LHSID == (1 * 9 + 2) * 9 + 3)
5291       return LHS;
5292     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5293     return RHS;
5294   }
5295
5296   SDValue OpLHS, OpRHS;
5297   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5298   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5299   EVT VT = OpLHS.getValueType();
5300
5301   switch (OpNum) {
5302   default:
5303     llvm_unreachable("Unknown shuffle opcode!");
5304   case OP_VREV:
5305     // VREV divides the vector in half and swaps within the half.
5306     if (VT.getVectorElementType() == MVT::i32 ||
5307         VT.getVectorElementType() == MVT::f32)
5308       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5309     // vrev <4 x i16> -> REV32
5310     if (VT.getVectorElementType() == MVT::i16 ||
5311         VT.getVectorElementType() == MVT::f16)
5312       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5313     // vrev <4 x i8> -> REV16
5314     assert(VT.getVectorElementType() == MVT::i8);
5315     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5316   case OP_VDUP0:
5317   case OP_VDUP1:
5318   case OP_VDUP2:
5319   case OP_VDUP3: {
5320     EVT EltTy = VT.getVectorElementType();
5321     unsigned Opcode;
5322     if (EltTy == MVT::i8)
5323       Opcode = AArch64ISD::DUPLANE8;
5324     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5325       Opcode = AArch64ISD::DUPLANE16;
5326     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5327       Opcode = AArch64ISD::DUPLANE32;
5328     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5329       Opcode = AArch64ISD::DUPLANE64;
5330     else
5331       llvm_unreachable("Invalid vector element type?");
5332
5333     if (VT.getSizeInBits() == 64)
5334       OpLHS = WidenVector(OpLHS, DAG);
5335     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5336     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5337   }
5338   case OP_VEXT1:
5339   case OP_VEXT2:
5340   case OP_VEXT3: {
5341     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5342     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5343                        DAG.getConstant(Imm, dl, MVT::i32));
5344   }
5345   case OP_VUZPL:
5346     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5347                        OpRHS);
5348   case OP_VUZPR:
5349     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5350                        OpRHS);
5351   case OP_VZIPL:
5352     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5353                        OpRHS);
5354   case OP_VZIPR:
5355     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5356                        OpRHS);
5357   case OP_VTRNL:
5358     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5359                        OpRHS);
5360   case OP_VTRNR:
5361     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5362                        OpRHS);
5363   }
5364 }
5365
5366 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5367                            SelectionDAG &DAG) {
5368   // Check to see if we can use the TBL instruction.
5369   SDValue V1 = Op.getOperand(0);
5370   SDValue V2 = Op.getOperand(1);
5371   SDLoc DL(Op);
5372
5373   EVT EltVT = Op.getValueType().getVectorElementType();
5374   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5375
5376   SmallVector<SDValue, 8> TBLMask;
5377   for (int Val : ShuffleMask) {
5378     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5379       unsigned Offset = Byte + Val * BytesPerElt;
5380       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5381     }
5382   }
5383
5384   MVT IndexVT = MVT::v8i8;
5385   unsigned IndexLen = 8;
5386   if (Op.getValueType().getSizeInBits() == 128) {
5387     IndexVT = MVT::v16i8;
5388     IndexLen = 16;
5389   }
5390
5391   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5392   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5393
5394   SDValue Shuffle;
5395   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5396     if (IndexLen == 8)
5397       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5398     Shuffle = DAG.getNode(
5399         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5400         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5401         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5402                     makeArrayRef(TBLMask.data(), IndexLen)));
5403   } else {
5404     if (IndexLen == 8) {
5405       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5406       Shuffle = DAG.getNode(
5407           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5408           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5409           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5410                       makeArrayRef(TBLMask.data(), IndexLen)));
5411     } else {
5412       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5413       // cannot currently represent the register constraints on the input
5414       // table registers.
5415       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5416       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5417       //                               &TBLMask[0], IndexLen));
5418       Shuffle = DAG.getNode(
5419           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5420           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5421           V1Cst, V2Cst,
5422           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5423                       makeArrayRef(TBLMask.data(), IndexLen)));
5424     }
5425   }
5426   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5427 }
5428
5429 static unsigned getDUPLANEOp(EVT EltType) {
5430   if (EltType == MVT::i8)
5431     return AArch64ISD::DUPLANE8;
5432   if (EltType == MVT::i16 || EltType == MVT::f16)
5433     return AArch64ISD::DUPLANE16;
5434   if (EltType == MVT::i32 || EltType == MVT::f32)
5435     return AArch64ISD::DUPLANE32;
5436   if (EltType == MVT::i64 || EltType == MVT::f64)
5437     return AArch64ISD::DUPLANE64;
5438
5439   llvm_unreachable("Invalid vector element type?");
5440 }
5441
5442 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5443                                                    SelectionDAG &DAG) const {
5444   SDLoc dl(Op);
5445   EVT VT = Op.getValueType();
5446
5447   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5448
5449   // Convert shuffles that are directly supported on NEON to target-specific
5450   // DAG nodes, instead of keeping them as shuffles and matching them again
5451   // during code selection.  This is more efficient and avoids the possibility
5452   // of inconsistencies between legalization and selection.
5453   ArrayRef<int> ShuffleMask = SVN->getMask();
5454
5455   SDValue V1 = Op.getOperand(0);
5456   SDValue V2 = Op.getOperand(1);
5457
5458   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5459                                        V1.getValueType().getSimpleVT())) {
5460     int Lane = SVN->getSplatIndex();
5461     // If this is undef splat, generate it via "just" vdup, if possible.
5462     if (Lane == -1)
5463       Lane = 0;
5464
5465     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5466       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5467                          V1.getOperand(0));
5468     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5469     // constant. If so, we can just reference the lane's definition directly.
5470     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5471         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5472       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5473
5474     // Otherwise, duplicate from the lane of the input vector.
5475     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5476
5477     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5478     // to make a vector of the same size as this SHUFFLE. We can ignore the
5479     // extract entirely, and canonicalise the concat using WidenVector.
5480     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5481       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5482       V1 = V1.getOperand(0);
5483     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5484       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5485       Lane -= Idx * VT.getVectorNumElements() / 2;
5486       V1 = WidenVector(V1.getOperand(Idx), DAG);
5487     } else if (VT.getSizeInBits() == 64)
5488       V1 = WidenVector(V1, DAG);
5489
5490     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5491   }
5492
5493   if (isREVMask(ShuffleMask, VT, 64))
5494     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5495   if (isREVMask(ShuffleMask, VT, 32))
5496     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5497   if (isREVMask(ShuffleMask, VT, 16))
5498     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5499
5500   bool ReverseEXT = false;
5501   unsigned Imm;
5502   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5503     if (ReverseEXT)
5504       std::swap(V1, V2);
5505     Imm *= getExtFactor(V1);
5506     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5507                        DAG.getConstant(Imm, dl, MVT::i32));
5508   } else if (V2->getOpcode() == ISD::UNDEF &&
5509              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5510     Imm *= getExtFactor(V1);
5511     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5512                        DAG.getConstant(Imm, dl, MVT::i32));
5513   }
5514
5515   unsigned WhichResult;
5516   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5517     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5518     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5519   }
5520   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5521     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5522     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5523   }
5524   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5525     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5526     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5527   }
5528
5529   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5530     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5531     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5532   }
5533   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5534     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5535     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5536   }
5537   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5538     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5539     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5540   }
5541
5542   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5543   if (Concat.getNode())
5544     return Concat;
5545
5546   bool DstIsLeft;
5547   int Anomaly;
5548   int NumInputElements = V1.getValueType().getVectorNumElements();
5549   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5550     SDValue DstVec = DstIsLeft ? V1 : V2;
5551     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5552
5553     SDValue SrcVec = V1;
5554     int SrcLane = ShuffleMask[Anomaly];
5555     if (SrcLane >= NumInputElements) {
5556       SrcVec = V2;
5557       SrcLane -= VT.getVectorNumElements();
5558     }
5559     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5560
5561     EVT ScalarVT = VT.getVectorElementType();
5562
5563     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5564       ScalarVT = MVT::i32;
5565
5566     return DAG.getNode(
5567         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5568         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5569         DstLaneV);
5570   }
5571
5572   // If the shuffle is not directly supported and it has 4 elements, use
5573   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5574   unsigned NumElts = VT.getVectorNumElements();
5575   if (NumElts == 4) {
5576     unsigned PFIndexes[4];
5577     for (unsigned i = 0; i != 4; ++i) {
5578       if (ShuffleMask[i] < 0)
5579         PFIndexes[i] = 8;
5580       else
5581         PFIndexes[i] = ShuffleMask[i];
5582     }
5583
5584     // Compute the index in the perfect shuffle table.
5585     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5586                             PFIndexes[2] * 9 + PFIndexes[3];
5587     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5588     unsigned Cost = (PFEntry >> 30);
5589
5590     if (Cost <= 4)
5591       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5592   }
5593
5594   return GenerateTBL(Op, ShuffleMask, DAG);
5595 }
5596
5597 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5598                                APInt &UndefBits) {
5599   EVT VT = BVN->getValueType(0);
5600   APInt SplatBits, SplatUndef;
5601   unsigned SplatBitSize;
5602   bool HasAnyUndefs;
5603   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5604     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5605
5606     for (unsigned i = 0; i < NumSplats; ++i) {
5607       CnstBits <<= SplatBitSize;
5608       UndefBits <<= SplatBitSize;
5609       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5610       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5611     }
5612
5613     return true;
5614   }
5615
5616   return false;
5617 }
5618
5619 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5620                                               SelectionDAG &DAG) const {
5621   BuildVectorSDNode *BVN =
5622       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5623   SDValue LHS = Op.getOperand(0);
5624   SDLoc dl(Op);
5625   EVT VT = Op.getValueType();
5626
5627   if (!BVN)
5628     return Op;
5629
5630   APInt CnstBits(VT.getSizeInBits(), 0);
5631   APInt UndefBits(VT.getSizeInBits(), 0);
5632   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5633     // We only have BIC vector immediate instruction, which is and-not.
5634     CnstBits = ~CnstBits;
5635
5636     // We make use of a little bit of goto ickiness in order to avoid having to
5637     // duplicate the immediate matching logic for the undef toggled case.
5638     bool SecondTry = false;
5639   AttemptModImm:
5640
5641     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5642       CnstBits = CnstBits.zextOrTrunc(64);
5643       uint64_t CnstVal = CnstBits.getZExtValue();
5644
5645       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5646         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5647         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5648         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5649                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5650                                   DAG.getConstant(0, dl, MVT::i32));
5651         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5652       }
5653
5654       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5655         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5656         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5657         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5658                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5659                                   DAG.getConstant(8, dl, MVT::i32));
5660         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5661       }
5662
5663       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5664         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5665         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5666         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5667                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5668                                   DAG.getConstant(16, dl, MVT::i32));
5669         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5670       }
5671
5672       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5673         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5674         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5675         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5676                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5677                                   DAG.getConstant(24, dl, MVT::i32));
5678         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5679       }
5680
5681       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5682         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5683         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5684         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5685                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5686                                   DAG.getConstant(0, dl, MVT::i32));
5687         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5688       }
5689
5690       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5691         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5692         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5693         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5694                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5695                                   DAG.getConstant(8, dl, MVT::i32));
5696         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5697       }
5698     }
5699
5700     if (SecondTry)
5701       goto FailedModImm;
5702     SecondTry = true;
5703     CnstBits = ~UndefBits;
5704     goto AttemptModImm;
5705   }
5706
5707 // We can always fall back to a non-immediate AND.
5708 FailedModImm:
5709   return Op;
5710 }
5711
5712 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5713 // consists of only the same constant int value, returned in reference arg
5714 // ConstVal
5715 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5716                                      uint64_t &ConstVal) {
5717   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5718   if (!Bvec)
5719     return false;
5720   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5721   if (!FirstElt)
5722     return false;
5723   EVT VT = Bvec->getValueType(0);
5724   unsigned NumElts = VT.getVectorNumElements();
5725   for (unsigned i = 1; i < NumElts; ++i)
5726     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5727       return false;
5728   ConstVal = FirstElt->getZExtValue();
5729   return true;
5730 }
5731
5732 static unsigned getIntrinsicID(const SDNode *N) {
5733   unsigned Opcode = N->getOpcode();
5734   switch (Opcode) {
5735   default:
5736     return Intrinsic::not_intrinsic;
5737   case ISD::INTRINSIC_WO_CHAIN: {
5738     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5739     if (IID < Intrinsic::num_intrinsics)
5740       return IID;
5741     return Intrinsic::not_intrinsic;
5742   }
5743   }
5744 }
5745
5746 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5747 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5748 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5749 // Also, logical shift right -> sri, with the same structure.
5750 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5751   EVT VT = N->getValueType(0);
5752
5753   if (!VT.isVector())
5754     return SDValue();
5755
5756   SDLoc DL(N);
5757
5758   // Is the first op an AND?
5759   const SDValue And = N->getOperand(0);
5760   if (And.getOpcode() != ISD::AND)
5761     return SDValue();
5762
5763   // Is the second op an shl or lshr?
5764   SDValue Shift = N->getOperand(1);
5765   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5766   // or AArch64ISD::VLSHR vector, #shift
5767   unsigned ShiftOpc = Shift.getOpcode();
5768   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5769     return SDValue();
5770   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5771
5772   // Is the shift amount constant?
5773   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5774   if (!C2node)
5775     return SDValue();
5776
5777   // Is the and mask vector all constant?
5778   uint64_t C1;
5779   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5780     return SDValue();
5781
5782   // Is C1 == ~C2, taking into account how much one can shift elements of a
5783   // particular size?
5784   uint64_t C2 = C2node->getZExtValue();
5785   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5786   if (C2 > ElemSizeInBits)
5787     return SDValue();
5788   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5789   if ((C1 & ElemMask) != (~C2 & ElemMask))
5790     return SDValue();
5791
5792   SDValue X = And.getOperand(0);
5793   SDValue Y = Shift.getOperand(0);
5794
5795   unsigned Intrin =
5796       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5797   SDValue ResultSLI =
5798       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5799                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5800                   Shift.getOperand(1));
5801
5802   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5803   DEBUG(N->dump(&DAG));
5804   DEBUG(dbgs() << "into: \n");
5805   DEBUG(ResultSLI->dump(&DAG));
5806
5807   ++NumShiftInserts;
5808   return ResultSLI;
5809 }
5810
5811 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5812                                              SelectionDAG &DAG) const {
5813   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5814   if (EnableAArch64SlrGeneration) {
5815     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5816     if (Res.getNode())
5817       return Res;
5818   }
5819
5820   BuildVectorSDNode *BVN =
5821       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5822   SDValue LHS = Op.getOperand(1);
5823   SDLoc dl(Op);
5824   EVT VT = Op.getValueType();
5825
5826   // OR commutes, so try swapping the operands.
5827   if (!BVN) {
5828     LHS = Op.getOperand(0);
5829     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5830   }
5831   if (!BVN)
5832     return Op;
5833
5834   APInt CnstBits(VT.getSizeInBits(), 0);
5835   APInt UndefBits(VT.getSizeInBits(), 0);
5836   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5837     // We make use of a little bit of goto ickiness in order to avoid having to
5838     // duplicate the immediate matching logic for the undef toggled case.
5839     bool SecondTry = false;
5840   AttemptModImm:
5841
5842     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5843       CnstBits = CnstBits.zextOrTrunc(64);
5844       uint64_t CnstVal = CnstBits.getZExtValue();
5845
5846       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5847         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5848         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5849         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5850                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5851                                   DAG.getConstant(0, dl, MVT::i32));
5852         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5853       }
5854
5855       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5856         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5857         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5858         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5859                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5860                                   DAG.getConstant(8, dl, MVT::i32));
5861         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5862       }
5863
5864       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5865         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5866         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5867         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5868                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5869                                   DAG.getConstant(16, dl, MVT::i32));
5870         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5871       }
5872
5873       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5874         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5875         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5876         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5877                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5878                                   DAG.getConstant(24, dl, MVT::i32));
5879         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5880       }
5881
5882       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5883         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5884         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5885         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5886                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5887                                   DAG.getConstant(0, dl, MVT::i32));
5888         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5889       }
5890
5891       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5892         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5893         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5894         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5895                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5896                                   DAG.getConstant(8, dl, MVT::i32));
5897         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5898       }
5899     }
5900
5901     if (SecondTry)
5902       goto FailedModImm;
5903     SecondTry = true;
5904     CnstBits = UndefBits;
5905     goto AttemptModImm;
5906   }
5907
5908 // We can always fall back to a non-immediate OR.
5909 FailedModImm:
5910   return Op;
5911 }
5912
5913 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5914 // be truncated to fit element width.
5915 static SDValue NormalizeBuildVector(SDValue Op,
5916                                     SelectionDAG &DAG) {
5917   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5918   SDLoc dl(Op);
5919   EVT VT = Op.getValueType();
5920   EVT EltTy= VT.getVectorElementType();
5921
5922   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5923     return Op;
5924
5925   SmallVector<SDValue, 16> Ops;
5926   for (SDValue Lane : Op->ops()) {
5927     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5928       APInt LowBits(EltTy.getSizeInBits(),
5929                     CstLane->getZExtValue());
5930       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5931     }
5932     Ops.push_back(Lane);
5933   }
5934   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5935 }
5936
5937 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5938                                                  SelectionDAG &DAG) const {
5939   SDLoc dl(Op);
5940   EVT VT = Op.getValueType();
5941   Op = NormalizeBuildVector(Op, DAG);
5942   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5943
5944   APInt CnstBits(VT.getSizeInBits(), 0);
5945   APInt UndefBits(VT.getSizeInBits(), 0);
5946   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5947     // We make use of a little bit of goto ickiness in order to avoid having to
5948     // duplicate the immediate matching logic for the undef toggled case.
5949     bool SecondTry = false;
5950   AttemptModImm:
5951
5952     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5953       CnstBits = CnstBits.zextOrTrunc(64);
5954       uint64_t CnstVal = CnstBits.getZExtValue();
5955
5956       // Certain magic vector constants (used to express things like NOT
5957       // and NEG) are passed through unmodified.  This allows codegen patterns
5958       // for these operations to match.  Special-purpose patterns will lower
5959       // these immediates to MOVIs if it proves necessary.
5960       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5961         return Op;
5962
5963       // The many faces of MOVI...
5964       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5965         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5966         if (VT.getSizeInBits() == 128) {
5967           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5968                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5969           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5970         }
5971
5972         // Support the V64 version via subregister insertion.
5973         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5974                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5975         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5976       }
5977
5978       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5979         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5980         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5981         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5982                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5983                                   DAG.getConstant(0, dl, MVT::i32));
5984         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5985       }
5986
5987       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5988         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5989         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5990         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5991                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5992                                   DAG.getConstant(8, dl, MVT::i32));
5993         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5994       }
5995
5996       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5997         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5998         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5999         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6000                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6001                                   DAG.getConstant(16, dl, MVT::i32));
6002         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6003       }
6004
6005       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6006         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6007         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6008         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6009                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6010                                   DAG.getConstant(24, dl, MVT::i32));
6011         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6012       }
6013
6014       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6015         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6016         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6017         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6018                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6019                                   DAG.getConstant(0, dl, MVT::i32));
6020         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6021       }
6022
6023       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6024         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6025         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6026         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6027                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6028                                   DAG.getConstant(8, dl, MVT::i32));
6029         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6030       }
6031
6032       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6033         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6034         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6035         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6036                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6037                                   DAG.getConstant(264, dl, MVT::i32));
6038         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6039       }
6040
6041       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6042         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6043         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6044         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6045                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6046                                   DAG.getConstant(272, dl, MVT::i32));
6047         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6048       }
6049
6050       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6051         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6052         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6053         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6054                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6055         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6056       }
6057
6058       // The few faces of FMOV...
6059       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6060         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6061         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6062         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6063                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6064         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6065       }
6066
6067       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6068           VT.getSizeInBits() == 128) {
6069         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6070         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6071                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6072         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6073       }
6074
6075       // The many faces of MVNI...
6076       CnstVal = ~CnstVal;
6077       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6078         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6079         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6080         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6081                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6082                                   DAG.getConstant(0, dl, MVT::i32));
6083         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6084       }
6085
6086       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6087         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6088         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6089         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6090                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6091                                   DAG.getConstant(8, dl, MVT::i32));
6092         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6093       }
6094
6095       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6096         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6097         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6098         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6099                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6100                                   DAG.getConstant(16, dl, MVT::i32));
6101         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6102       }
6103
6104       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6105         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6106         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6107         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6108                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6109                                   DAG.getConstant(24, dl, MVT::i32));
6110         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6111       }
6112
6113       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6114         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6115         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6116         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6117                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6118                                   DAG.getConstant(0, dl, MVT::i32));
6119         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6120       }
6121
6122       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6123         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6124         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6125         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6126                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6127                                   DAG.getConstant(8, dl, MVT::i32));
6128         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6129       }
6130
6131       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6132         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6133         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6134         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6135                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6136                                   DAG.getConstant(264, dl, MVT::i32));
6137         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6138       }
6139
6140       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6141         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6142         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6143         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6144                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6145                                   DAG.getConstant(272, dl, MVT::i32));
6146         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6147       }
6148     }
6149
6150     if (SecondTry)
6151       goto FailedModImm;
6152     SecondTry = true;
6153     CnstBits = UndefBits;
6154     goto AttemptModImm;
6155   }
6156 FailedModImm:
6157
6158   // Scan through the operands to find some interesting properties we can
6159   // exploit:
6160   //   1) If only one value is used, we can use a DUP, or
6161   //   2) if only the low element is not undef, we can just insert that, or
6162   //   3) if only one constant value is used (w/ some non-constant lanes),
6163   //      we can splat the constant value into the whole vector then fill
6164   //      in the non-constant lanes.
6165   //   4) FIXME: If different constant values are used, but we can intelligently
6166   //             select the values we'll be overwriting for the non-constant
6167   //             lanes such that we can directly materialize the vector
6168   //             some other way (MOVI, e.g.), we can be sneaky.
6169   unsigned NumElts = VT.getVectorNumElements();
6170   bool isOnlyLowElement = true;
6171   bool usesOnlyOneValue = true;
6172   bool usesOnlyOneConstantValue = true;
6173   bool isConstant = true;
6174   unsigned NumConstantLanes = 0;
6175   SDValue Value;
6176   SDValue ConstantValue;
6177   for (unsigned i = 0; i < NumElts; ++i) {
6178     SDValue V = Op.getOperand(i);
6179     if (V.getOpcode() == ISD::UNDEF)
6180       continue;
6181     if (i > 0)
6182       isOnlyLowElement = false;
6183     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6184       isConstant = false;
6185
6186     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6187       ++NumConstantLanes;
6188       if (!ConstantValue.getNode())
6189         ConstantValue = V;
6190       else if (ConstantValue != V)
6191         usesOnlyOneConstantValue = false;
6192     }
6193
6194     if (!Value.getNode())
6195       Value = V;
6196     else if (V != Value)
6197       usesOnlyOneValue = false;
6198   }
6199
6200   if (!Value.getNode())
6201     return DAG.getUNDEF(VT);
6202
6203   if (isOnlyLowElement)
6204     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6205
6206   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6207   // i32 and try again.
6208   if (usesOnlyOneValue) {
6209     if (!isConstant) {
6210       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6211           Value.getValueType() != VT)
6212         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6213
6214       // This is actually a DUPLANExx operation, which keeps everything vectory.
6215
6216       // DUPLANE works on 128-bit vectors, widen it if necessary.
6217       SDValue Lane = Value.getOperand(1);
6218       Value = Value.getOperand(0);
6219       if (Value.getValueType().getSizeInBits() == 64)
6220         Value = WidenVector(Value, DAG);
6221
6222       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6223       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6224     }
6225
6226     if (VT.getVectorElementType().isFloatingPoint()) {
6227       SmallVector<SDValue, 8> Ops;
6228       EVT EltTy = VT.getVectorElementType();
6229       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6230               "Unsupported floating-point vector type");
6231       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6232       for (unsigned i = 0; i < NumElts; ++i)
6233         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6234       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6235       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6236       Val = LowerBUILD_VECTOR(Val, DAG);
6237       if (Val.getNode())
6238         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6239     }
6240   }
6241
6242   // If there was only one constant value used and for more than one lane,
6243   // start by splatting that value, then replace the non-constant lanes. This
6244   // is better than the default, which will perform a separate initialization
6245   // for each lane.
6246   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6247     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6248     // Now insert the non-constant lanes.
6249     for (unsigned i = 0; i < NumElts; ++i) {
6250       SDValue V = Op.getOperand(i);
6251       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6252       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6253         // Note that type legalization likely mucked about with the VT of the
6254         // source operand, so we may have to convert it here before inserting.
6255         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6256       }
6257     }
6258     return Val;
6259   }
6260
6261   // If all elements are constants and the case above didn't get hit, fall back
6262   // to the default expansion, which will generate a load from the constant
6263   // pool.
6264   if (isConstant)
6265     return SDValue();
6266
6267   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6268   if (NumElts >= 4) {
6269     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6270       return shuffle;
6271   }
6272
6273   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6274   // know the default expansion would otherwise fall back on something even
6275   // worse. For a vector with one or two non-undef values, that's
6276   // scalar_to_vector for the elements followed by a shuffle (provided the
6277   // shuffle is valid for the target) and materialization element by element
6278   // on the stack followed by a load for everything else.
6279   if (!isConstant && !usesOnlyOneValue) {
6280     SDValue Vec = DAG.getUNDEF(VT);
6281     SDValue Op0 = Op.getOperand(0);
6282     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6283     unsigned i = 0;
6284     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6285     // a) Avoid a RMW dependency on the full vector register, and
6286     // b) Allow the register coalescer to fold away the copy if the
6287     //    value is already in an S or D register.
6288     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6289     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6290     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6291         (ElemSize == 32 || ElemSize == 64)) {
6292       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6293       MachineSDNode *N =
6294           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6295                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6296       Vec = SDValue(N, 0);
6297       ++i;
6298     }
6299     for (; i < NumElts; ++i) {
6300       SDValue V = Op.getOperand(i);
6301       if (V.getOpcode() == ISD::UNDEF)
6302         continue;
6303       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6304       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6305     }
6306     return Vec;
6307   }
6308
6309   // Just use the default expansion. We failed to find a better alternative.
6310   return SDValue();
6311 }
6312
6313 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6314                                                       SelectionDAG &DAG) const {
6315   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6316
6317   // Check for non-constant or out of range lane.
6318   EVT VT = Op.getOperand(0).getValueType();
6319   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6320   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6321     return SDValue();
6322
6323
6324   // Insertion/extraction are legal for V128 types.
6325   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6326       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6327       VT == MVT::v8f16)
6328     return Op;
6329
6330   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6331       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6332     return SDValue();
6333
6334   // For V64 types, we perform insertion by expanding the value
6335   // to a V128 type and perform the insertion on that.
6336   SDLoc DL(Op);
6337   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6338   EVT WideTy = WideVec.getValueType();
6339
6340   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6341                              Op.getOperand(1), Op.getOperand(2));
6342   // Re-narrow the resultant vector.
6343   return NarrowVector(Node, DAG);
6344 }
6345
6346 SDValue
6347 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6348                                                SelectionDAG &DAG) const {
6349   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6350
6351   // Check for non-constant or out of range lane.
6352   EVT VT = Op.getOperand(0).getValueType();
6353   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6354   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6355     return SDValue();
6356
6357
6358   // Insertion/extraction are legal for V128 types.
6359   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6360       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6361       VT == MVT::v8f16)
6362     return Op;
6363
6364   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6365       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6366     return SDValue();
6367
6368   // For V64 types, we perform extraction by expanding the value
6369   // to a V128 type and perform the extraction on that.
6370   SDLoc DL(Op);
6371   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6372   EVT WideTy = WideVec.getValueType();
6373
6374   EVT ExtrTy = WideTy.getVectorElementType();
6375   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6376     ExtrTy = MVT::i32;
6377
6378   // For extractions, we just return the result directly.
6379   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6380                      Op.getOperand(1));
6381 }
6382
6383 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6384                                                       SelectionDAG &DAG) const {
6385   EVT VT = Op.getOperand(0).getValueType();
6386   SDLoc dl(Op);
6387   // Just in case...
6388   if (!VT.isVector())
6389     return SDValue();
6390
6391   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6392   if (!Cst)
6393     return SDValue();
6394   unsigned Val = Cst->getZExtValue();
6395
6396   unsigned Size = Op.getValueType().getSizeInBits();
6397
6398   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6399   if (Val == 0)
6400     return Op;
6401
6402   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6403   // that directly.
6404   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6405     return Op;
6406
6407   return SDValue();
6408 }
6409
6410 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6411                                                EVT VT) const {
6412   if (VT.getVectorNumElements() == 4 &&
6413       (VT.is128BitVector() || VT.is64BitVector())) {
6414     unsigned PFIndexes[4];
6415     for (unsigned i = 0; i != 4; ++i) {
6416       if (M[i] < 0)
6417         PFIndexes[i] = 8;
6418       else
6419         PFIndexes[i] = M[i];
6420     }
6421
6422     // Compute the index in the perfect shuffle table.
6423     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6424                             PFIndexes[2] * 9 + PFIndexes[3];
6425     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6426     unsigned Cost = (PFEntry >> 30);
6427
6428     if (Cost <= 4)
6429       return true;
6430   }
6431
6432   bool DummyBool;
6433   int DummyInt;
6434   unsigned DummyUnsigned;
6435
6436   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6437           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6438           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6439           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6440           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6441           isZIPMask(M, VT, DummyUnsigned) ||
6442           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6443           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6444           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6445           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6446           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6447 }
6448
6449 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6450 /// operand of a vector shift operation, where all the elements of the
6451 /// build_vector must have the same constant integer value.
6452 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6453   // Ignore bit_converts.
6454   while (Op.getOpcode() == ISD::BITCAST)
6455     Op = Op.getOperand(0);
6456   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6457   APInt SplatBits, SplatUndef;
6458   unsigned SplatBitSize;
6459   bool HasAnyUndefs;
6460   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6461                                     HasAnyUndefs, ElementBits) ||
6462       SplatBitSize > ElementBits)
6463     return false;
6464   Cnt = SplatBits.getSExtValue();
6465   return true;
6466 }
6467
6468 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6469 /// operand of a vector shift left operation.  That value must be in the range:
6470 ///   0 <= Value < ElementBits for a left shift; or
6471 ///   0 <= Value <= ElementBits for a long left shift.
6472 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6473   assert(VT.isVector() && "vector shift count is not a vector type");
6474   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6475   if (!getVShiftImm(Op, ElementBits, Cnt))
6476     return false;
6477   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6478 }
6479
6480 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6481 /// operand of a vector shift right operation. The value must be in the range:
6482 ///   1 <= Value <= ElementBits for a right shift; or
6483 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6484   assert(VT.isVector() && "vector shift count is not a vector type");
6485   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6486   if (!getVShiftImm(Op, ElementBits, Cnt))
6487     return false;
6488   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6489 }
6490
6491 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6492                                                       SelectionDAG &DAG) const {
6493   EVT VT = Op.getValueType();
6494   SDLoc DL(Op);
6495   int64_t Cnt;
6496
6497   if (!Op.getOperand(1).getValueType().isVector())
6498     return Op;
6499   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6500
6501   switch (Op.getOpcode()) {
6502   default:
6503     llvm_unreachable("unexpected shift opcode");
6504
6505   case ISD::SHL:
6506     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6507       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6508                          DAG.getConstant(Cnt, DL, MVT::i32));
6509     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6510                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6511                                        MVT::i32),
6512                        Op.getOperand(0), Op.getOperand(1));
6513   case ISD::SRA:
6514   case ISD::SRL:
6515     // Right shift immediate
6516     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6517       unsigned Opc =
6518           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6519       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6520                          DAG.getConstant(Cnt, DL, MVT::i32));
6521     }
6522
6523     // Right shift register.  Note, there is not a shift right register
6524     // instruction, but the shift left register instruction takes a signed
6525     // value, where negative numbers specify a right shift.
6526     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6527                                                 : Intrinsic::aarch64_neon_ushl;
6528     // negate the shift amount
6529     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6530     SDValue NegShiftLeft =
6531         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6532                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6533                     NegShift);
6534     return NegShiftLeft;
6535   }
6536
6537   return SDValue();
6538 }
6539
6540 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6541                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6542                                     SDLoc dl, SelectionDAG &DAG) {
6543   EVT SrcVT = LHS.getValueType();
6544   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6545          "function only supposed to emit natural comparisons");
6546
6547   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6548   APInt CnstBits(VT.getSizeInBits(), 0);
6549   APInt UndefBits(VT.getSizeInBits(), 0);
6550   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6551   bool IsZero = IsCnst && (CnstBits == 0);
6552
6553   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6554     switch (CC) {
6555     default:
6556       return SDValue();
6557     case AArch64CC::NE: {
6558       SDValue Fcmeq;
6559       if (IsZero)
6560         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6561       else
6562         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6563       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6564     }
6565     case AArch64CC::EQ:
6566       if (IsZero)
6567         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6568       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6569     case AArch64CC::GE:
6570       if (IsZero)
6571         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6572       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6573     case AArch64CC::GT:
6574       if (IsZero)
6575         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6576       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6577     case AArch64CC::LS:
6578       if (IsZero)
6579         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6580       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6581     case AArch64CC::LT:
6582       if (!NoNans)
6583         return SDValue();
6584     // If we ignore NaNs then we can use to the MI implementation.
6585     // Fallthrough.
6586     case AArch64CC::MI:
6587       if (IsZero)
6588         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6589       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6590     }
6591   }
6592
6593   switch (CC) {
6594   default:
6595     return SDValue();
6596   case AArch64CC::NE: {
6597     SDValue Cmeq;
6598     if (IsZero)
6599       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6600     else
6601       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6602     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6603   }
6604   case AArch64CC::EQ:
6605     if (IsZero)
6606       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6607     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6608   case AArch64CC::GE:
6609     if (IsZero)
6610       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6611     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6612   case AArch64CC::GT:
6613     if (IsZero)
6614       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6615     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6616   case AArch64CC::LE:
6617     if (IsZero)
6618       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6619     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6620   case AArch64CC::LS:
6621     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6622   case AArch64CC::LO:
6623     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6624   case AArch64CC::LT:
6625     if (IsZero)
6626       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6627     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6628   case AArch64CC::HI:
6629     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6630   case AArch64CC::HS:
6631     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6632   }
6633 }
6634
6635 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6636                                            SelectionDAG &DAG) const {
6637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6638   SDValue LHS = Op.getOperand(0);
6639   SDValue RHS = Op.getOperand(1);
6640   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6641   SDLoc dl(Op);
6642
6643   if (LHS.getValueType().getVectorElementType().isInteger()) {
6644     assert(LHS.getValueType() == RHS.getValueType());
6645     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6646     SDValue Cmp =
6647         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6648     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6649   }
6650
6651   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6652          LHS.getValueType().getVectorElementType() == MVT::f64);
6653
6654   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6655   // clean.  Some of them require two branches to implement.
6656   AArch64CC::CondCode CC1, CC2;
6657   bool ShouldInvert;
6658   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6659
6660   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6661   SDValue Cmp =
6662       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6663   if (!Cmp.getNode())
6664     return SDValue();
6665
6666   if (CC2 != AArch64CC::AL) {
6667     SDValue Cmp2 =
6668         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6669     if (!Cmp2.getNode())
6670       return SDValue();
6671
6672     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6673   }
6674
6675   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6676
6677   if (ShouldInvert)
6678     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6679
6680   return Cmp;
6681 }
6682
6683 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6684 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6685 /// specified in the intrinsic calls.
6686 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6687                                                const CallInst &I,
6688                                                unsigned Intrinsic) const {
6689   auto &DL = I.getModule()->getDataLayout();
6690   switch (Intrinsic) {
6691   case Intrinsic::aarch64_neon_ld2:
6692   case Intrinsic::aarch64_neon_ld3:
6693   case Intrinsic::aarch64_neon_ld4:
6694   case Intrinsic::aarch64_neon_ld1x2:
6695   case Intrinsic::aarch64_neon_ld1x3:
6696   case Intrinsic::aarch64_neon_ld1x4:
6697   case Intrinsic::aarch64_neon_ld2lane:
6698   case Intrinsic::aarch64_neon_ld3lane:
6699   case Intrinsic::aarch64_neon_ld4lane:
6700   case Intrinsic::aarch64_neon_ld2r:
6701   case Intrinsic::aarch64_neon_ld3r:
6702   case Intrinsic::aarch64_neon_ld4r: {
6703     Info.opc = ISD::INTRINSIC_W_CHAIN;
6704     // Conservatively set memVT to the entire set of vectors loaded.
6705     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6706     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6707     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6708     Info.offset = 0;
6709     Info.align = 0;
6710     Info.vol = false; // volatile loads with NEON intrinsics not supported
6711     Info.readMem = true;
6712     Info.writeMem = false;
6713     return true;
6714   }
6715   case Intrinsic::aarch64_neon_st2:
6716   case Intrinsic::aarch64_neon_st3:
6717   case Intrinsic::aarch64_neon_st4:
6718   case Intrinsic::aarch64_neon_st1x2:
6719   case Intrinsic::aarch64_neon_st1x3:
6720   case Intrinsic::aarch64_neon_st1x4:
6721   case Intrinsic::aarch64_neon_st2lane:
6722   case Intrinsic::aarch64_neon_st3lane:
6723   case Intrinsic::aarch64_neon_st4lane: {
6724     Info.opc = ISD::INTRINSIC_VOID;
6725     // Conservatively set memVT to the entire set of vectors stored.
6726     unsigned NumElts = 0;
6727     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6728       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6729       if (!ArgTy->isVectorTy())
6730         break;
6731       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6732     }
6733     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6734     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6735     Info.offset = 0;
6736     Info.align = 0;
6737     Info.vol = false; // volatile stores with NEON intrinsics not supported
6738     Info.readMem = false;
6739     Info.writeMem = true;
6740     return true;
6741   }
6742   case Intrinsic::aarch64_ldaxr:
6743   case Intrinsic::aarch64_ldxr: {
6744     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6745     Info.opc = ISD::INTRINSIC_W_CHAIN;
6746     Info.memVT = MVT::getVT(PtrTy->getElementType());
6747     Info.ptrVal = I.getArgOperand(0);
6748     Info.offset = 0;
6749     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6750     Info.vol = true;
6751     Info.readMem = true;
6752     Info.writeMem = false;
6753     return true;
6754   }
6755   case Intrinsic::aarch64_stlxr:
6756   case Intrinsic::aarch64_stxr: {
6757     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6758     Info.opc = ISD::INTRINSIC_W_CHAIN;
6759     Info.memVT = MVT::getVT(PtrTy->getElementType());
6760     Info.ptrVal = I.getArgOperand(1);
6761     Info.offset = 0;
6762     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6763     Info.vol = true;
6764     Info.readMem = false;
6765     Info.writeMem = true;
6766     return true;
6767   }
6768   case Intrinsic::aarch64_ldaxp:
6769   case Intrinsic::aarch64_ldxp: {
6770     Info.opc = ISD::INTRINSIC_W_CHAIN;
6771     Info.memVT = MVT::i128;
6772     Info.ptrVal = I.getArgOperand(0);
6773     Info.offset = 0;
6774     Info.align = 16;
6775     Info.vol = true;
6776     Info.readMem = true;
6777     Info.writeMem = false;
6778     return true;
6779   }
6780   case Intrinsic::aarch64_stlxp:
6781   case Intrinsic::aarch64_stxp: {
6782     Info.opc = ISD::INTRINSIC_W_CHAIN;
6783     Info.memVT = MVT::i128;
6784     Info.ptrVal = I.getArgOperand(2);
6785     Info.offset = 0;
6786     Info.align = 16;
6787     Info.vol = true;
6788     Info.readMem = false;
6789     Info.writeMem = true;
6790     return true;
6791   }
6792   default:
6793     break;
6794   }
6795
6796   return false;
6797 }
6798
6799 // Truncations from 64-bit GPR to 32-bit GPR is free.
6800 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6801   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6802     return false;
6803   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6804   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6805   return NumBits1 > NumBits2;
6806 }
6807 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6808   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6809     return false;
6810   unsigned NumBits1 = VT1.getSizeInBits();
6811   unsigned NumBits2 = VT2.getSizeInBits();
6812   return NumBits1 > NumBits2;
6813 }
6814
6815 /// Check if it is profitable to hoist instruction in then/else to if.
6816 /// Not profitable if I and it's user can form a FMA instruction
6817 /// because we prefer FMSUB/FMADD.
6818 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6819   if (I->getOpcode() != Instruction::FMul)
6820     return true;
6821
6822   if (I->getNumUses() != 1)
6823     return true;
6824
6825   Instruction *User = I->user_back();
6826
6827   if (User &&
6828       !(User->getOpcode() == Instruction::FSub ||
6829         User->getOpcode() == Instruction::FAdd))
6830     return true;
6831
6832   const TargetOptions &Options = getTargetMachine().Options;
6833   const DataLayout &DL = I->getModule()->getDataLayout();
6834   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6835
6836   if (isFMAFasterThanFMulAndFAdd(VT) &&
6837       isOperationLegalOrCustom(ISD::FMA, VT) &&
6838       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6839     return false;
6840
6841   return true;
6842 }
6843
6844 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6845 // 64-bit GPR.
6846 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6847   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6848     return false;
6849   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6850   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6851   return NumBits1 == 32 && NumBits2 == 64;
6852 }
6853 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6854   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6855     return false;
6856   unsigned NumBits1 = VT1.getSizeInBits();
6857   unsigned NumBits2 = VT2.getSizeInBits();
6858   return NumBits1 == 32 && NumBits2 == 64;
6859 }
6860
6861 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6862   EVT VT1 = Val.getValueType();
6863   if (isZExtFree(VT1, VT2)) {
6864     return true;
6865   }
6866
6867   if (Val.getOpcode() != ISD::LOAD)
6868     return false;
6869
6870   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6871   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6872           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6873           VT1.getSizeInBits() <= 32);
6874 }
6875
6876 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6877   if (isa<FPExtInst>(Ext))
6878     return false;
6879
6880   // Vector types are next free.
6881   if (Ext->getType()->isVectorTy())
6882     return false;
6883
6884   for (const Use &U : Ext->uses()) {
6885     // The extension is free if we can fold it with a left shift in an
6886     // addressing mode or an arithmetic operation: add, sub, and cmp.
6887
6888     // Is there a shift?
6889     const Instruction *Instr = cast<Instruction>(U.getUser());
6890
6891     // Is this a constant shift?
6892     switch (Instr->getOpcode()) {
6893     case Instruction::Shl:
6894       if (!isa<ConstantInt>(Instr->getOperand(1)))
6895         return false;
6896       break;
6897     case Instruction::GetElementPtr: {
6898       gep_type_iterator GTI = gep_type_begin(Instr);
6899       auto &DL = Ext->getModule()->getDataLayout();
6900       std::advance(GTI, U.getOperandNo());
6901       Type *IdxTy = *GTI;
6902       // This extension will end up with a shift because of the scaling factor.
6903       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6904       // Get the shift amount based on the scaling factor:
6905       // log2(sizeof(IdxTy)) - log2(8).
6906       uint64_t ShiftAmt =
6907           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6908       // Is the constant foldable in the shift of the addressing mode?
6909       // I.e., shift amount is between 1 and 4 inclusive.
6910       if (ShiftAmt == 0 || ShiftAmt > 4)
6911         return false;
6912       break;
6913     }
6914     case Instruction::Trunc:
6915       // Check if this is a noop.
6916       // trunc(sext ty1 to ty2) to ty1.
6917       if (Instr->getType() == Ext->getOperand(0)->getType())
6918         continue;
6919     // FALL THROUGH.
6920     default:
6921       return false;
6922     }
6923
6924     // At this point we can use the bfm family, so this extension is free
6925     // for that use.
6926   }
6927   return true;
6928 }
6929
6930 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6931                                           unsigned &RequiredAligment) const {
6932   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6933     return false;
6934   // Cyclone supports unaligned accesses.
6935   RequiredAligment = 0;
6936   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6937   return NumBits == 32 || NumBits == 64;
6938 }
6939
6940 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6941                                           unsigned &RequiredAligment) const {
6942   if (!LoadedType.isSimple() ||
6943       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6944     return false;
6945   // Cyclone supports unaligned accesses.
6946   RequiredAligment = 0;
6947   unsigned NumBits = LoadedType.getSizeInBits();
6948   return NumBits == 32 || NumBits == 64;
6949 }
6950
6951 /// \brief Lower an interleaved load into a ldN intrinsic.
6952 ///
6953 /// E.g. Lower an interleaved load (Factor = 2):
6954 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6955 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6956 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6957 ///
6958 ///      Into:
6959 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6960 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6961 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6962 bool AArch64TargetLowering::lowerInterleavedLoad(
6963     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6964     ArrayRef<unsigned> Indices, unsigned Factor) const {
6965   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6966          "Invalid interleave factor");
6967   assert(!Shuffles.empty() && "Empty shufflevector input");
6968   assert(Shuffles.size() == Indices.size() &&
6969          "Unmatched number of shufflevectors and indices");
6970
6971   const DataLayout &DL = LI->getModule()->getDataLayout();
6972
6973   VectorType *VecTy = Shuffles[0]->getType();
6974   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6975
6976   // Skip if we do not have NEON and skip illegal vector types.
6977   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
6978     return false;
6979
6980   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6981   // load integer vectors first and then convert to pointer vectors.
6982   Type *EltTy = VecTy->getVectorElementType();
6983   if (EltTy->isPointerTy())
6984     VecTy =
6985         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6986
6987   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6988   Type *Tys[2] = {VecTy, PtrTy};
6989   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6990                                             Intrinsic::aarch64_neon_ld3,
6991                                             Intrinsic::aarch64_neon_ld4};
6992   Function *LdNFunc =
6993       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6994
6995   IRBuilder<> Builder(LI);
6996   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6997
6998   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6999
7000   // Replace uses of each shufflevector with the corresponding vector loaded
7001   // by ldN.
7002   for (unsigned i = 0; i < Shuffles.size(); i++) {
7003     ShuffleVectorInst *SVI = Shuffles[i];
7004     unsigned Index = Indices[i];
7005
7006     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7007
7008     // Convert the integer vector to pointer vector if the element is pointer.
7009     if (EltTy->isPointerTy())
7010       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7011
7012     SVI->replaceAllUsesWith(SubVec);
7013   }
7014
7015   return true;
7016 }
7017
7018 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7019 ///
7020 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7021 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7022                                    unsigned NumElts) {
7023   SmallVector<Constant *, 16> Mask;
7024   for (unsigned i = 0; i < NumElts; i++)
7025     Mask.push_back(Builder.getInt32(Start + i));
7026
7027   return ConstantVector::get(Mask);
7028 }
7029
7030 /// \brief Lower an interleaved store into a stN intrinsic.
7031 ///
7032 /// E.g. Lower an interleaved store (Factor = 3):
7033 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7034 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7035 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7036 ///
7037 ///      Into:
7038 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7039 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7040 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7041 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7042 ///
7043 /// Note that the new shufflevectors will be removed and we'll only generate one
7044 /// st3 instruction in CodeGen.
7045 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7046                                                   ShuffleVectorInst *SVI,
7047                                                   unsigned Factor) const {
7048   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7049          "Invalid interleave factor");
7050
7051   VectorType *VecTy = SVI->getType();
7052   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7053          "Invalid interleaved store");
7054
7055   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7056   Type *EltTy = VecTy->getVectorElementType();
7057   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7058
7059   const DataLayout &DL = SI->getModule()->getDataLayout();
7060   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7061
7062   // Skip if we do not have NEON and skip illegal vector types.
7063   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7064     return false;
7065
7066   Value *Op0 = SVI->getOperand(0);
7067   Value *Op1 = SVI->getOperand(1);
7068   IRBuilder<> Builder(SI);
7069
7070   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7071   // vectors to integer vectors.
7072   if (EltTy->isPointerTy()) {
7073     Type *IntTy = DL.getIntPtrType(EltTy);
7074     unsigned NumOpElts =
7075         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7076
7077     // Convert to the corresponding integer vector.
7078     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7079     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7080     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7081
7082     SubVecTy = VectorType::get(IntTy, NumSubElts);
7083   }
7084
7085   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7086   Type *Tys[2] = {SubVecTy, PtrTy};
7087   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7088                                              Intrinsic::aarch64_neon_st3,
7089                                              Intrinsic::aarch64_neon_st4};
7090   Function *StNFunc =
7091       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7092
7093   SmallVector<Value *, 5> Ops;
7094
7095   // Split the shufflevector operands into sub vectors for the new stN call.
7096   for (unsigned i = 0; i < Factor; i++)
7097     Ops.push_back(Builder.CreateShuffleVector(
7098         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7099
7100   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7101   Builder.CreateCall(StNFunc, Ops);
7102   return true;
7103 }
7104
7105 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7106                        unsigned AlignCheck) {
7107   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7108           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7109 }
7110
7111 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7112                                                unsigned SrcAlign, bool IsMemset,
7113                                                bool ZeroMemset,
7114                                                bool MemcpyStrSrc,
7115                                                MachineFunction &MF) const {
7116   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7117   // instruction to materialize the v2i64 zero and one store (with restrictive
7118   // addressing mode). Just do two i64 store of zero-registers.
7119   bool Fast;
7120   const Function *F = MF.getFunction();
7121   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7122       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7123       (memOpAlign(SrcAlign, DstAlign, 16) ||
7124        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7125     return MVT::f128;
7126
7127   if (Size >= 8 &&
7128       (memOpAlign(SrcAlign, DstAlign, 8) ||
7129        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7130     return MVT::i64;
7131
7132   if (Size >= 4 &&
7133       (memOpAlign(SrcAlign, DstAlign, 4) ||
7134        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7135     return MVT::i32;
7136
7137   return MVT::Other;
7138 }
7139
7140 // 12-bit optionally shifted immediates are legal for adds.
7141 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7142   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7143     return true;
7144   return false;
7145 }
7146
7147 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7148 // immediates is the same as for an add or a sub.
7149 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7150   if (Immed < 0)
7151     Immed *= -1;
7152   return isLegalAddImmediate(Immed);
7153 }
7154
7155 /// isLegalAddressingMode - Return true if the addressing mode represented
7156 /// by AM is legal for this target, for a load/store of the specified type.
7157 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7158                                                   const AddrMode &AM, Type *Ty,
7159                                                   unsigned AS) const {
7160   // AArch64 has five basic addressing modes:
7161   //  reg
7162   //  reg + 9-bit signed offset
7163   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7164   //  reg1 + reg2
7165   //  reg + SIZE_IN_BYTES * reg
7166
7167   // No global is ever allowed as a base.
7168   if (AM.BaseGV)
7169     return false;
7170
7171   // No reg+reg+imm addressing.
7172   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7173     return false;
7174
7175   // check reg + imm case:
7176   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7177   uint64_t NumBytes = 0;
7178   if (Ty->isSized()) {
7179     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7180     NumBytes = NumBits / 8;
7181     if (!isPowerOf2_64(NumBits))
7182       NumBytes = 0;
7183   }
7184
7185   if (!AM.Scale) {
7186     int64_t Offset = AM.BaseOffs;
7187
7188     // 9-bit signed offset
7189     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7190       return true;
7191
7192     // 12-bit unsigned offset
7193     unsigned shift = Log2_64(NumBytes);
7194     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7195         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7196         (Offset >> shift) << shift == Offset)
7197       return true;
7198     return false;
7199   }
7200
7201   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7202
7203   if (!AM.Scale || AM.Scale == 1 ||
7204       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7205     return true;
7206   return false;
7207 }
7208
7209 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7210                                                 const AddrMode &AM, Type *Ty,
7211                                                 unsigned AS) const {
7212   // Scaling factors are not free at all.
7213   // Operands                     | Rt Latency
7214   // -------------------------------------------
7215   // Rt, [Xn, Xm]                 | 4
7216   // -------------------------------------------
7217   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7218   // Rt, [Xn, Wm, <extend> #imm]  |
7219   if (isLegalAddressingMode(DL, AM, Ty, AS))
7220     // Scale represents reg2 * scale, thus account for 1 if
7221     // it is not equal to 0 or 1.
7222     return AM.Scale != 0 && AM.Scale != 1;
7223   return -1;
7224 }
7225
7226 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7227   VT = VT.getScalarType();
7228
7229   if (!VT.isSimple())
7230     return false;
7231
7232   switch (VT.getSimpleVT().SimpleTy) {
7233   case MVT::f32:
7234   case MVT::f64:
7235     return true;
7236   default:
7237     break;
7238   }
7239
7240   return false;
7241 }
7242
7243 const MCPhysReg *
7244 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7245   // LR is a callee-save register, but we must treat it as clobbered by any call
7246   // site. Hence we include LR in the scratch registers, which are in turn added
7247   // as implicit-defs for stackmaps and patchpoints.
7248   static const MCPhysReg ScratchRegs[] = {
7249     AArch64::X16, AArch64::X17, AArch64::LR, 0
7250   };
7251   return ScratchRegs;
7252 }
7253
7254 bool
7255 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7256   EVT VT = N->getValueType(0);
7257     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7258     // it with shift to let it be lowered to UBFX.
7259   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7260       isa<ConstantSDNode>(N->getOperand(1))) {
7261     uint64_t TruncMask = N->getConstantOperandVal(1);
7262     if (isMask_64(TruncMask) &&
7263       N->getOperand(0).getOpcode() == ISD::SRL &&
7264       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7265       return false;
7266   }
7267   return true;
7268 }
7269
7270 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7271                                                               Type *Ty) const {
7272   assert(Ty->isIntegerTy());
7273
7274   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7275   if (BitSize == 0)
7276     return false;
7277
7278   int64_t Val = Imm.getSExtValue();
7279   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7280     return true;
7281
7282   if ((int64_t)Val < 0)
7283     Val = ~Val;
7284   if (BitSize == 32)
7285     Val &= (1LL << 32) - 1;
7286
7287   unsigned LZ = countLeadingZeros((uint64_t)Val);
7288   unsigned Shift = (63 - LZ) / 16;
7289   // MOVZ is free so return true for one or fewer MOVK.
7290   return Shift < 3;
7291 }
7292
7293 // Generate SUBS and CSEL for integer abs.
7294 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7295   EVT VT = N->getValueType(0);
7296
7297   SDValue N0 = N->getOperand(0);
7298   SDValue N1 = N->getOperand(1);
7299   SDLoc DL(N);
7300
7301   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7302   // and change it to SUB and CSEL.
7303   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7304       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7305       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7306     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7307       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7308         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7309                                   N0.getOperand(0));
7310         // Generate SUBS & CSEL.
7311         SDValue Cmp =
7312             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7313                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7314         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7315                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7316                            SDValue(Cmp.getNode(), 1));
7317       }
7318   return SDValue();
7319 }
7320
7321 // performXorCombine - Attempts to handle integer ABS.
7322 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7323                                  TargetLowering::DAGCombinerInfo &DCI,
7324                                  const AArch64Subtarget *Subtarget) {
7325   if (DCI.isBeforeLegalizeOps())
7326     return SDValue();
7327
7328   return performIntegerAbsCombine(N, DAG);
7329 }
7330
7331 SDValue
7332 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7333                                      SelectionDAG &DAG,
7334                                      std::vector<SDNode *> *Created) const {
7335   // fold (sdiv X, pow2)
7336   EVT VT = N->getValueType(0);
7337   if ((VT != MVT::i32 && VT != MVT::i64) ||
7338       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7339     return SDValue();
7340
7341   SDLoc DL(N);
7342   SDValue N0 = N->getOperand(0);
7343   unsigned Lg2 = Divisor.countTrailingZeros();
7344   SDValue Zero = DAG.getConstant(0, DL, VT);
7345   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7346
7347   // Add (N0 < 0) ? Pow2 - 1 : 0;
7348   SDValue CCVal;
7349   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7350   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7351   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7352
7353   if (Created) {
7354     Created->push_back(Cmp.getNode());
7355     Created->push_back(Add.getNode());
7356     Created->push_back(CSel.getNode());
7357   }
7358
7359   // Divide by pow2.
7360   SDValue SRA =
7361       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7362
7363   // If we're dividing by a positive value, we're done.  Otherwise, we must
7364   // negate the result.
7365   if (Divisor.isNonNegative())
7366     return SRA;
7367
7368   if (Created)
7369     Created->push_back(SRA.getNode());
7370   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7371 }
7372
7373 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7374                                  TargetLowering::DAGCombinerInfo &DCI,
7375                                  const AArch64Subtarget *Subtarget) {
7376   if (DCI.isBeforeLegalizeOps())
7377     return SDValue();
7378
7379   // Multiplication of a power of two plus/minus one can be done more
7380   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7381   // future CPUs have a cheaper MADD instruction, this may need to be
7382   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7383   // 64-bit is 5 cycles, so this is always a win.
7384   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7385     APInt Value = C->getAPIntValue();
7386     EVT VT = N->getValueType(0);
7387     SDLoc DL(N);
7388     if (Value.isNonNegative()) {
7389       // (mul x, 2^N + 1) => (add (shl x, N), x)
7390       APInt VM1 = Value - 1;
7391       if (VM1.isPowerOf2()) {
7392         SDValue ShiftedVal =
7393             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7394                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7395         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7396                            N->getOperand(0));
7397       }
7398       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7399       APInt VP1 = Value + 1;
7400       if (VP1.isPowerOf2()) {
7401         SDValue ShiftedVal =
7402             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7403                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7404         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7405                            N->getOperand(0));
7406       }
7407     } else {
7408       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7409       APInt VNP1 = -Value + 1;
7410       if (VNP1.isPowerOf2()) {
7411         SDValue ShiftedVal =
7412             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7413                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7414         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7415                            ShiftedVal);
7416       }
7417       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7418       APInt VNM1 = -Value - 1;
7419       if (VNM1.isPowerOf2()) {
7420         SDValue ShiftedVal =
7421             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7422                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7423         SDValue Add =
7424             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7425         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7426       }
7427     }
7428   }
7429   return SDValue();
7430 }
7431
7432 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7433                                                          SelectionDAG &DAG) {
7434   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7435   // optimize away operation when it's from a constant.
7436   //
7437   // The general transformation is:
7438   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7439   //       AND(VECTOR_CMP(x,y), constant2)
7440   //    constant2 = UNARYOP(constant)
7441
7442   // Early exit if this isn't a vector operation, the operand of the
7443   // unary operation isn't a bitwise AND, or if the sizes of the operations
7444   // aren't the same.
7445   EVT VT = N->getValueType(0);
7446   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7447       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7448       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7449     return SDValue();
7450
7451   // Now check that the other operand of the AND is a constant. We could
7452   // make the transformation for non-constant splats as well, but it's unclear
7453   // that would be a benefit as it would not eliminate any operations, just
7454   // perform one more step in scalar code before moving to the vector unit.
7455   if (BuildVectorSDNode *BV =
7456           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7457     // Bail out if the vector isn't a constant.
7458     if (!BV->isConstant())
7459       return SDValue();
7460
7461     // Everything checks out. Build up the new and improved node.
7462     SDLoc DL(N);
7463     EVT IntVT = BV->getValueType(0);
7464     // Create a new constant of the appropriate type for the transformed
7465     // DAG.
7466     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7467     // The AND node needs bitcasts to/from an integer vector type around it.
7468     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7469     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7470                                  N->getOperand(0)->getOperand(0), MaskConst);
7471     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7472     return Res;
7473   }
7474
7475   return SDValue();
7476 }
7477
7478 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7479                                      const AArch64Subtarget *Subtarget) {
7480   // First try to optimize away the conversion when it's conditionally from
7481   // a constant. Vectors only.
7482   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7483     return Res;
7484
7485   EVT VT = N->getValueType(0);
7486   if (VT != MVT::f32 && VT != MVT::f64)
7487     return SDValue();
7488
7489   // Only optimize when the source and destination types have the same width.
7490   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7491     return SDValue();
7492
7493   // If the result of an integer load is only used by an integer-to-float
7494   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7495   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7496   SDValue N0 = N->getOperand(0);
7497   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7498       // Do not change the width of a volatile load.
7499       !cast<LoadSDNode>(N0)->isVolatile()) {
7500     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7501     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7502                                LN0->getPointerInfo(), LN0->isVolatile(),
7503                                LN0->isNonTemporal(), LN0->isInvariant(),
7504                                LN0->getAlignment());
7505
7506     // Make sure successors of the original load stay after it by updating them
7507     // to use the new Chain.
7508     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7509
7510     unsigned Opcode =
7511         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7512     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7513   }
7514
7515   return SDValue();
7516 }
7517
7518 /// Fold a floating-point multiply by power of two into floating-point to
7519 /// fixed-point conversion.
7520 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7521                                      const AArch64Subtarget *Subtarget) {
7522   if (!Subtarget->hasNEON())
7523     return SDValue();
7524
7525   SDValue Op = N->getOperand(0);
7526   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7527     return SDValue();
7528
7529   SDValue ConstVec = Op->getOperand(1);
7530   if (!isa<BuildVectorSDNode>(ConstVec))
7531     return SDValue();
7532
7533   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7534   uint32_t FloatBits = FloatTy.getSizeInBits();
7535   if (FloatBits != 32 && FloatBits != 64)
7536     return SDValue();
7537
7538   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7539   uint32_t IntBits = IntTy.getSizeInBits();
7540   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7541     return SDValue();
7542
7543   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7544   if (IntBits > FloatBits)
7545     return SDValue();
7546
7547   BitVector UndefElements;
7548   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7549   int32_t Bits = IntBits == 64 ? 64 : 32;
7550   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7551   if (C == -1 || C == 0 || C > Bits)
7552     return SDValue();
7553
7554   MVT ResTy;
7555   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7556   switch (NumLanes) {
7557   default:
7558     return SDValue();
7559   case 2:
7560     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7561     break;
7562   case 4:
7563     ResTy = MVT::v4i32;
7564     break;
7565   }
7566
7567   SDLoc DL(N);
7568   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7569   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7570                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7571   SDValue FixConv =
7572       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7573                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7574                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7575   // We can handle smaller integers by generating an extra trunc.
7576   if (IntBits < FloatBits)
7577     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7578
7579   return FixConv;
7580 }
7581
7582 /// Fold a floating-point divide by power of two into fixed-point to
7583 /// floating-point conversion.
7584 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7585                                   const AArch64Subtarget *Subtarget) {
7586   if (!Subtarget->hasNEON())
7587     return SDValue();
7588
7589   SDValue Op = N->getOperand(0);
7590   unsigned Opc = Op->getOpcode();
7591   if (!Op.getValueType().isVector() ||
7592       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7593     return SDValue();
7594
7595   SDValue ConstVec = N->getOperand(1);
7596   if (!isa<BuildVectorSDNode>(ConstVec))
7597     return SDValue();
7598
7599   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7600   int32_t IntBits = IntTy.getSizeInBits();
7601   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7602     return SDValue();
7603
7604   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7605   int32_t FloatBits = FloatTy.getSizeInBits();
7606   if (FloatBits != 32 && FloatBits != 64)
7607     return SDValue();
7608
7609   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7610   if (IntBits > FloatBits)
7611     return SDValue();
7612
7613   BitVector UndefElements;
7614   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7615   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7616   if (C == -1 || C == 0 || C > FloatBits)
7617     return SDValue();
7618
7619   MVT ResTy;
7620   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7621   switch (NumLanes) {
7622   default:
7623     return SDValue();
7624   case 2:
7625     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7626     break;
7627   case 4:
7628     ResTy = MVT::v4i32;
7629     break;
7630   }
7631
7632   SDLoc DL(N);
7633   SDValue ConvInput = Op.getOperand(0);
7634   bool IsSigned = Opc == ISD::SINT_TO_FP;
7635   if (IntBits < FloatBits)
7636     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7637                             ResTy, ConvInput);
7638
7639   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7640                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7641   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7642                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7643                      DAG.getConstant(C, DL, MVT::i32));
7644 }
7645
7646 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7647 /// searches for and classifies those shifts.
7648 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7649                          bool &FromHi) {
7650   if (N.getOpcode() == ISD::SHL)
7651     FromHi = false;
7652   else if (N.getOpcode() == ISD::SRL)
7653     FromHi = true;
7654   else
7655     return false;
7656
7657   if (!isa<ConstantSDNode>(N.getOperand(1)))
7658     return false;
7659
7660   ShiftAmount = N->getConstantOperandVal(1);
7661   Src = N->getOperand(0);
7662   return true;
7663 }
7664
7665 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7666 /// registers viewed as a high/low pair. This function looks for the pattern:
7667 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7668 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7669 /// independent.
7670 static SDValue tryCombineToEXTR(SDNode *N,
7671                                 TargetLowering::DAGCombinerInfo &DCI) {
7672   SelectionDAG &DAG = DCI.DAG;
7673   SDLoc DL(N);
7674   EVT VT = N->getValueType(0);
7675
7676   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7677
7678   if (VT != MVT::i32 && VT != MVT::i64)
7679     return SDValue();
7680
7681   SDValue LHS;
7682   uint32_t ShiftLHS = 0;
7683   bool LHSFromHi = 0;
7684   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7685     return SDValue();
7686
7687   SDValue RHS;
7688   uint32_t ShiftRHS = 0;
7689   bool RHSFromHi = 0;
7690   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7691     return SDValue();
7692
7693   // If they're both trying to come from the high part of the register, they're
7694   // not really an EXTR.
7695   if (LHSFromHi == RHSFromHi)
7696     return SDValue();
7697
7698   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7699     return SDValue();
7700
7701   if (LHSFromHi) {
7702     std::swap(LHS, RHS);
7703     std::swap(ShiftLHS, ShiftRHS);
7704   }
7705
7706   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7707                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7708 }
7709
7710 static SDValue tryCombineToBSL(SDNode *N,
7711                                 TargetLowering::DAGCombinerInfo &DCI) {
7712   EVT VT = N->getValueType(0);
7713   SelectionDAG &DAG = DCI.DAG;
7714   SDLoc DL(N);
7715
7716   if (!VT.isVector())
7717     return SDValue();
7718
7719   SDValue N0 = N->getOperand(0);
7720   if (N0.getOpcode() != ISD::AND)
7721     return SDValue();
7722
7723   SDValue N1 = N->getOperand(1);
7724   if (N1.getOpcode() != ISD::AND)
7725     return SDValue();
7726
7727   // We only have to look for constant vectors here since the general, variable
7728   // case can be handled in TableGen.
7729   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7730   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7731   for (int i = 1; i >= 0; --i)
7732     for (int j = 1; j >= 0; --j) {
7733       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7734       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7735       if (!BVN0 || !BVN1)
7736         continue;
7737
7738       bool FoundMatch = true;
7739       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7740         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7741         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7742         if (!CN0 || !CN1 ||
7743             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7744           FoundMatch = false;
7745           break;
7746         }
7747       }
7748
7749       if (FoundMatch)
7750         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7751                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7752     }
7753
7754   return SDValue();
7755 }
7756
7757 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7758                                 const AArch64Subtarget *Subtarget) {
7759   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7760   if (!EnableAArch64ExtrGeneration)
7761     return SDValue();
7762   SelectionDAG &DAG = DCI.DAG;
7763   EVT VT = N->getValueType(0);
7764
7765   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7766     return SDValue();
7767
7768   SDValue Res = tryCombineToEXTR(N, DCI);
7769   if (Res.getNode())
7770     return Res;
7771
7772   Res = tryCombineToBSL(N, DCI);
7773   if (Res.getNode())
7774     return Res;
7775
7776   return SDValue();
7777 }
7778
7779 static SDValue performBitcastCombine(SDNode *N,
7780                                      TargetLowering::DAGCombinerInfo &DCI,
7781                                      SelectionDAG &DAG) {
7782   // Wait 'til after everything is legalized to try this. That way we have
7783   // legal vector types and such.
7784   if (DCI.isBeforeLegalizeOps())
7785     return SDValue();
7786
7787   // Remove extraneous bitcasts around an extract_subvector.
7788   // For example,
7789   //    (v4i16 (bitconvert
7790   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7791   //  becomes
7792   //    (extract_subvector ((v8i16 ...), (i64 4)))
7793
7794   // Only interested in 64-bit vectors as the ultimate result.
7795   EVT VT = N->getValueType(0);
7796   if (!VT.isVector())
7797     return SDValue();
7798   if (VT.getSimpleVT().getSizeInBits() != 64)
7799     return SDValue();
7800   // Is the operand an extract_subvector starting at the beginning or halfway
7801   // point of the vector? A low half may also come through as an
7802   // EXTRACT_SUBREG, so look for that, too.
7803   SDValue Op0 = N->getOperand(0);
7804   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7805       !(Op0->isMachineOpcode() &&
7806         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7807     return SDValue();
7808   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7809   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7810     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7811       return SDValue();
7812   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7813     if (idx != AArch64::dsub)
7814       return SDValue();
7815     // The dsub reference is equivalent to a lane zero subvector reference.
7816     idx = 0;
7817   }
7818   // Look through the bitcast of the input to the extract.
7819   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7820     return SDValue();
7821   SDValue Source = Op0->getOperand(0)->getOperand(0);
7822   // If the source type has twice the number of elements as our destination
7823   // type, we know this is an extract of the high or low half of the vector.
7824   EVT SVT = Source->getValueType(0);
7825   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7826     return SDValue();
7827
7828   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7829
7830   // Create the simplified form to just extract the low or high half of the
7831   // vector directly rather than bothering with the bitcasts.
7832   SDLoc dl(N);
7833   unsigned NumElements = VT.getVectorNumElements();
7834   if (idx) {
7835     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7836     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7837   } else {
7838     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7839     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7840                                       Source, SubReg),
7841                    0);
7842   }
7843 }
7844
7845 static SDValue performConcatVectorsCombine(SDNode *N,
7846                                            TargetLowering::DAGCombinerInfo &DCI,
7847                                            SelectionDAG &DAG) {
7848   SDLoc dl(N);
7849   EVT VT = N->getValueType(0);
7850   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7851
7852   // Optimize concat_vectors of truncated vectors, where the intermediate
7853   // type is illegal, to avoid said illegality,  e.g.,
7854   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7855   //                          (v2i16 (truncate (v2i64)))))
7856   // ->
7857   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7858   //                                    (v4i32 (bitcast (v2i64))),
7859   //                                    <0, 2, 4, 6>)))
7860   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7861   // on both input and result type, so we might generate worse code.
7862   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7863   if (N->getNumOperands() == 2 &&
7864       N0->getOpcode() == ISD::TRUNCATE &&
7865       N1->getOpcode() == ISD::TRUNCATE) {
7866     SDValue N00 = N0->getOperand(0);
7867     SDValue N10 = N1->getOperand(0);
7868     EVT N00VT = N00.getValueType();
7869
7870     if (N00VT == N10.getValueType() &&
7871         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7872         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7873       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7874       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7875       for (size_t i = 0; i < Mask.size(); ++i)
7876         Mask[i] = i * 2;
7877       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7878                          DAG.getVectorShuffle(
7879                              MidVT, dl,
7880                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7881                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7882     }
7883   }
7884
7885   // Wait 'til after everything is legalized to try this. That way we have
7886   // legal vector types and such.
7887   if (DCI.isBeforeLegalizeOps())
7888     return SDValue();
7889
7890   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7891   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7892   // canonicalise to that.
7893   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7894     assert(VT.getVectorElementType().getSizeInBits() == 64);
7895     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7896                        DAG.getConstant(0, dl, MVT::i64));
7897   }
7898
7899   // Canonicalise concat_vectors so that the right-hand vector has as few
7900   // bit-casts as possible before its real operation. The primary matching
7901   // destination for these operations will be the narrowing "2" instructions,
7902   // which depend on the operation being performed on this right-hand vector.
7903   // For example,
7904   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7905   // becomes
7906   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7907
7908   if (N1->getOpcode() != ISD::BITCAST)
7909     return SDValue();
7910   SDValue RHS = N1->getOperand(0);
7911   MVT RHSTy = RHS.getValueType().getSimpleVT();
7912   // If the RHS is not a vector, this is not the pattern we're looking for.
7913   if (!RHSTy.isVector())
7914     return SDValue();
7915
7916   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7917
7918   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7919                                   RHSTy.getVectorNumElements() * 2);
7920   return DAG.getNode(ISD::BITCAST, dl, VT,
7921                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7922                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7923                                  RHS));
7924 }
7925
7926 static SDValue tryCombineFixedPointConvert(SDNode *N,
7927                                            TargetLowering::DAGCombinerInfo &DCI,
7928                                            SelectionDAG &DAG) {
7929   // Wait 'til after everything is legalized to try this. That way we have
7930   // legal vector types and such.
7931   if (DCI.isBeforeLegalizeOps())
7932     return SDValue();
7933   // Transform a scalar conversion of a value from a lane extract into a
7934   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7935   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7936   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7937   //
7938   // The second form interacts better with instruction selection and the
7939   // register allocator to avoid cross-class register copies that aren't
7940   // coalescable due to a lane reference.
7941
7942   // Check the operand and see if it originates from a lane extract.
7943   SDValue Op1 = N->getOperand(1);
7944   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7945     // Yep, no additional predication needed. Perform the transform.
7946     SDValue IID = N->getOperand(0);
7947     SDValue Shift = N->getOperand(2);
7948     SDValue Vec = Op1.getOperand(0);
7949     SDValue Lane = Op1.getOperand(1);
7950     EVT ResTy = N->getValueType(0);
7951     EVT VecResTy;
7952     SDLoc DL(N);
7953
7954     // The vector width should be 128 bits by the time we get here, even
7955     // if it started as 64 bits (the extract_vector handling will have
7956     // done so).
7957     assert(Vec.getValueType().getSizeInBits() == 128 &&
7958            "unexpected vector size on extract_vector_elt!");
7959     if (Vec.getValueType() == MVT::v4i32)
7960       VecResTy = MVT::v4f32;
7961     else if (Vec.getValueType() == MVT::v2i64)
7962       VecResTy = MVT::v2f64;
7963     else
7964       llvm_unreachable("unexpected vector type!");
7965
7966     SDValue Convert =
7967         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7968     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7969   }
7970   return SDValue();
7971 }
7972
7973 // AArch64 high-vector "long" operations are formed by performing the non-high
7974 // version on an extract_subvector of each operand which gets the high half:
7975 //
7976 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7977 //
7978 // However, there are cases which don't have an extract_high explicitly, but
7979 // have another operation that can be made compatible with one for free. For
7980 // example:
7981 //
7982 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7983 //
7984 // This routine does the actual conversion of such DUPs, once outer routines
7985 // have determined that everything else is in order.
7986 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7987 // similarly here.
7988 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7989   switch (N.getOpcode()) {
7990   case AArch64ISD::DUP:
7991   case AArch64ISD::DUPLANE8:
7992   case AArch64ISD::DUPLANE16:
7993   case AArch64ISD::DUPLANE32:
7994   case AArch64ISD::DUPLANE64:
7995   case AArch64ISD::MOVI:
7996   case AArch64ISD::MOVIshift:
7997   case AArch64ISD::MOVIedit:
7998   case AArch64ISD::MOVImsl:
7999   case AArch64ISD::MVNIshift:
8000   case AArch64ISD::MVNImsl:
8001     break;
8002   default:
8003     // FMOV could be supported, but isn't very useful, as it would only occur
8004     // if you passed a bitcast' floating point immediate to an eligible long
8005     // integer op (addl, smull, ...).
8006     return SDValue();
8007   }
8008
8009   MVT NarrowTy = N.getSimpleValueType();
8010   if (!NarrowTy.is64BitVector())
8011     return SDValue();
8012
8013   MVT ElementTy = NarrowTy.getVectorElementType();
8014   unsigned NumElems = NarrowTy.getVectorNumElements();
8015   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8016
8017   SDLoc dl(N);
8018   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8019                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8020                      DAG.getConstant(NumElems, dl, MVT::i64));
8021 }
8022
8023 static bool isEssentiallyExtractSubvector(SDValue N) {
8024   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8025     return true;
8026
8027   return N.getOpcode() == ISD::BITCAST &&
8028          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8029 }
8030
8031 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8032 struct GenericSetCCInfo {
8033   const SDValue *Opnd0;
8034   const SDValue *Opnd1;
8035   ISD::CondCode CC;
8036 };
8037
8038 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8039 struct AArch64SetCCInfo {
8040   const SDValue *Cmp;
8041   AArch64CC::CondCode CC;
8042 };
8043
8044 /// \brief Helper structure to keep track of SetCC information.
8045 union SetCCInfo {
8046   GenericSetCCInfo Generic;
8047   AArch64SetCCInfo AArch64;
8048 };
8049
8050 /// \brief Helper structure to be able to read SetCC information.  If set to
8051 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8052 /// GenericSetCCInfo.
8053 struct SetCCInfoAndKind {
8054   SetCCInfo Info;
8055   bool IsAArch64;
8056 };
8057
8058 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8059 /// an
8060 /// AArch64 lowered one.
8061 /// \p SetCCInfo is filled accordingly.
8062 /// \post SetCCInfo is meanginfull only when this function returns true.
8063 /// \return True when Op is a kind of SET_CC operation.
8064 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8065   // If this is a setcc, this is straight forward.
8066   if (Op.getOpcode() == ISD::SETCC) {
8067     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8068     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8069     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8070     SetCCInfo.IsAArch64 = false;
8071     return true;
8072   }
8073   // Otherwise, check if this is a matching csel instruction.
8074   // In other words:
8075   // - csel 1, 0, cc
8076   // - csel 0, 1, !cc
8077   if (Op.getOpcode() != AArch64ISD::CSEL)
8078     return false;
8079   // Set the information about the operands.
8080   // TODO: we want the operands of the Cmp not the csel
8081   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8082   SetCCInfo.IsAArch64 = true;
8083   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8084       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8085
8086   // Check that the operands matches the constraints:
8087   // (1) Both operands must be constants.
8088   // (2) One must be 1 and the other must be 0.
8089   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8090   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8091
8092   // Check (1).
8093   if (!TValue || !FValue)
8094     return false;
8095
8096   // Check (2).
8097   if (!TValue->isOne()) {
8098     // Update the comparison when we are interested in !cc.
8099     std::swap(TValue, FValue);
8100     SetCCInfo.Info.AArch64.CC =
8101         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8102   }
8103   return TValue->isOne() && FValue->isNullValue();
8104 }
8105
8106 // Returns true if Op is setcc or zext of setcc.
8107 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8108   if (isSetCC(Op, Info))
8109     return true;
8110   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8111     isSetCC(Op->getOperand(0), Info));
8112 }
8113
8114 // The folding we want to perform is:
8115 // (add x, [zext] (setcc cc ...) )
8116 //   -->
8117 // (csel x, (add x, 1), !cc ...)
8118 //
8119 // The latter will get matched to a CSINC instruction.
8120 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8121   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8122   SDValue LHS = Op->getOperand(0);
8123   SDValue RHS = Op->getOperand(1);
8124   SetCCInfoAndKind InfoAndKind;
8125
8126   // If neither operand is a SET_CC, give up.
8127   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8128     std::swap(LHS, RHS);
8129     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8130       return SDValue();
8131   }
8132
8133   // FIXME: This could be generatized to work for FP comparisons.
8134   EVT CmpVT = InfoAndKind.IsAArch64
8135                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8136                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8137   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8138     return SDValue();
8139
8140   SDValue CCVal;
8141   SDValue Cmp;
8142   SDLoc dl(Op);
8143   if (InfoAndKind.IsAArch64) {
8144     CCVal = DAG.getConstant(
8145         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8146         MVT::i32);
8147     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8148   } else
8149     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8150                       *InfoAndKind.Info.Generic.Opnd1,
8151                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8152                       CCVal, DAG, dl);
8153
8154   EVT VT = Op->getValueType(0);
8155   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8156   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8157 }
8158
8159 // The basic add/sub long vector instructions have variants with "2" on the end
8160 // which act on the high-half of their inputs. They are normally matched by
8161 // patterns like:
8162 //
8163 // (add (zeroext (extract_high LHS)),
8164 //      (zeroext (extract_high RHS)))
8165 // -> uaddl2 vD, vN, vM
8166 //
8167 // However, if one of the extracts is something like a duplicate, this
8168 // instruction can still be used profitably. This function puts the DAG into a
8169 // more appropriate form for those patterns to trigger.
8170 static SDValue performAddSubLongCombine(SDNode *N,
8171                                         TargetLowering::DAGCombinerInfo &DCI,
8172                                         SelectionDAG &DAG) {
8173   if (DCI.isBeforeLegalizeOps())
8174     return SDValue();
8175
8176   MVT VT = N->getSimpleValueType(0);
8177   if (!VT.is128BitVector()) {
8178     if (N->getOpcode() == ISD::ADD)
8179       return performSetccAddFolding(N, DAG);
8180     return SDValue();
8181   }
8182
8183   // Make sure both branches are extended in the same way.
8184   SDValue LHS = N->getOperand(0);
8185   SDValue RHS = N->getOperand(1);
8186   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8187        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8188       LHS.getOpcode() != RHS.getOpcode())
8189     return SDValue();
8190
8191   unsigned ExtType = LHS.getOpcode();
8192
8193   // It's not worth doing if at least one of the inputs isn't already an
8194   // extract, but we don't know which it'll be so we have to try both.
8195   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8196     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8197     if (!RHS.getNode())
8198       return SDValue();
8199
8200     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8201   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8202     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8203     if (!LHS.getNode())
8204       return SDValue();
8205
8206     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8207   }
8208
8209   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8210 }
8211
8212 // Massage DAGs which we can use the high-half "long" operations on into
8213 // something isel will recognize better. E.g.
8214 //
8215 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8216 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8217 //                     (extract_high (v2i64 (dup128 scalar)))))
8218 //
8219 static SDValue tryCombineLongOpWithDup(SDNode *N,
8220                                        TargetLowering::DAGCombinerInfo &DCI,
8221                                        SelectionDAG &DAG) {
8222   if (DCI.isBeforeLegalizeOps())
8223     return SDValue();
8224
8225   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8226   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8227   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8228   assert(LHS.getValueType().is64BitVector() &&
8229          RHS.getValueType().is64BitVector() &&
8230          "unexpected shape for long operation");
8231
8232   // Either node could be a DUP, but it's not worth doing both of them (you'd
8233   // just as well use the non-high version) so look for a corresponding extract
8234   // operation on the other "wing".
8235   if (isEssentiallyExtractSubvector(LHS)) {
8236     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8237     if (!RHS.getNode())
8238       return SDValue();
8239   } else if (isEssentiallyExtractSubvector(RHS)) {
8240     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8241     if (!LHS.getNode())
8242       return SDValue();
8243   }
8244
8245   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8246   if (IsIntrinsic)
8247     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8248                        N->getOperand(0), LHS, RHS);
8249   else
8250     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8251                        LHS, RHS);
8252 }
8253
8254 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8255   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8256   unsigned ElemBits = ElemTy.getSizeInBits();
8257
8258   int64_t ShiftAmount;
8259   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8260     APInt SplatValue, SplatUndef;
8261     unsigned SplatBitSize;
8262     bool HasAnyUndefs;
8263     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8264                               HasAnyUndefs, ElemBits) ||
8265         SplatBitSize != ElemBits)
8266       return SDValue();
8267
8268     ShiftAmount = SplatValue.getSExtValue();
8269   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8270     ShiftAmount = CVN->getSExtValue();
8271   } else
8272     return SDValue();
8273
8274   unsigned Opcode;
8275   bool IsRightShift;
8276   switch (IID) {
8277   default:
8278     llvm_unreachable("Unknown shift intrinsic");
8279   case Intrinsic::aarch64_neon_sqshl:
8280     Opcode = AArch64ISD::SQSHL_I;
8281     IsRightShift = false;
8282     break;
8283   case Intrinsic::aarch64_neon_uqshl:
8284     Opcode = AArch64ISD::UQSHL_I;
8285     IsRightShift = false;
8286     break;
8287   case Intrinsic::aarch64_neon_srshl:
8288     Opcode = AArch64ISD::SRSHR_I;
8289     IsRightShift = true;
8290     break;
8291   case Intrinsic::aarch64_neon_urshl:
8292     Opcode = AArch64ISD::URSHR_I;
8293     IsRightShift = true;
8294     break;
8295   case Intrinsic::aarch64_neon_sqshlu:
8296     Opcode = AArch64ISD::SQSHLU_I;
8297     IsRightShift = false;
8298     break;
8299   }
8300
8301   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8302     SDLoc dl(N);
8303     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8304                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8305   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8306     SDLoc dl(N);
8307     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8308                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8309   }
8310
8311   return SDValue();
8312 }
8313
8314 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8315 // the intrinsics must be legal and take an i32, this means there's almost
8316 // certainly going to be a zext in the DAG which we can eliminate.
8317 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8318   SDValue AndN = N->getOperand(2);
8319   if (AndN.getOpcode() != ISD::AND)
8320     return SDValue();
8321
8322   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8323   if (!CMask || CMask->getZExtValue() != Mask)
8324     return SDValue();
8325
8326   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8327                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8328 }
8329
8330 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8331                                            SelectionDAG &DAG) {
8332   SDLoc dl(N);
8333   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8334                      DAG.getNode(Opc, dl,
8335                                  N->getOperand(1).getSimpleValueType(),
8336                                  N->getOperand(1)),
8337                      DAG.getConstant(0, dl, MVT::i64));
8338 }
8339
8340 static SDValue performIntrinsicCombine(SDNode *N,
8341                                        TargetLowering::DAGCombinerInfo &DCI,
8342                                        const AArch64Subtarget *Subtarget) {
8343   SelectionDAG &DAG = DCI.DAG;
8344   unsigned IID = getIntrinsicID(N);
8345   switch (IID) {
8346   default:
8347     break;
8348   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8349   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8350     return tryCombineFixedPointConvert(N, DCI, DAG);
8351   case Intrinsic::aarch64_neon_saddv:
8352     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8353   case Intrinsic::aarch64_neon_uaddv:
8354     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8355   case Intrinsic::aarch64_neon_sminv:
8356     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8357   case Intrinsic::aarch64_neon_uminv:
8358     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8359   case Intrinsic::aarch64_neon_smaxv:
8360     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8361   case Intrinsic::aarch64_neon_umaxv:
8362     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8363   case Intrinsic::aarch64_neon_fmax:
8364     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8365                        N->getOperand(1), N->getOperand(2));
8366   case Intrinsic::aarch64_neon_fmin:
8367     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8368                        N->getOperand(1), N->getOperand(2));
8369   case Intrinsic::aarch64_neon_sabd:
8370     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8371                        N->getOperand(1), N->getOperand(2));
8372   case Intrinsic::aarch64_neon_uabd:
8373     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8374                        N->getOperand(1), N->getOperand(2));
8375   case Intrinsic::aarch64_neon_fmaxnm:
8376     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8377                        N->getOperand(1), N->getOperand(2));
8378   case Intrinsic::aarch64_neon_fminnm:
8379     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8380                        N->getOperand(1), N->getOperand(2));
8381   case Intrinsic::aarch64_neon_smull:
8382   case Intrinsic::aarch64_neon_umull:
8383   case Intrinsic::aarch64_neon_pmull:
8384   case Intrinsic::aarch64_neon_sqdmull:
8385     return tryCombineLongOpWithDup(N, DCI, DAG);
8386   case Intrinsic::aarch64_neon_sqshl:
8387   case Intrinsic::aarch64_neon_uqshl:
8388   case Intrinsic::aarch64_neon_sqshlu:
8389   case Intrinsic::aarch64_neon_srshl:
8390   case Intrinsic::aarch64_neon_urshl:
8391     return tryCombineShiftImm(IID, N, DAG);
8392   case Intrinsic::aarch64_crc32b:
8393   case Intrinsic::aarch64_crc32cb:
8394     return tryCombineCRC32(0xff, N, DAG);
8395   case Intrinsic::aarch64_crc32h:
8396   case Intrinsic::aarch64_crc32ch:
8397     return tryCombineCRC32(0xffff, N, DAG);
8398   }
8399   return SDValue();
8400 }
8401
8402 static SDValue performExtendCombine(SDNode *N,
8403                                     TargetLowering::DAGCombinerInfo &DCI,
8404                                     SelectionDAG &DAG) {
8405   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8406   // we can convert that DUP into another extract_high (of a bigger DUP), which
8407   // helps the backend to decide that an sabdl2 would be useful, saving a real
8408   // extract_high operation.
8409   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8410       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8411        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8412     SDNode *ABDNode = N->getOperand(0).getNode();
8413     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8414     if (!NewABD.getNode())
8415       return SDValue();
8416
8417     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8418                        NewABD);
8419   }
8420
8421   // This is effectively a custom type legalization for AArch64.
8422   //
8423   // Type legalization will split an extend of a small, legal, type to a larger
8424   // illegal type by first splitting the destination type, often creating
8425   // illegal source types, which then get legalized in isel-confusing ways,
8426   // leading to really terrible codegen. E.g.,
8427   //   %result = v8i32 sext v8i8 %value
8428   // becomes
8429   //   %losrc = extract_subreg %value, ...
8430   //   %hisrc = extract_subreg %value, ...
8431   //   %lo = v4i32 sext v4i8 %losrc
8432   //   %hi = v4i32 sext v4i8 %hisrc
8433   // Things go rapidly downhill from there.
8434   //
8435   // For AArch64, the [sz]ext vector instructions can only go up one element
8436   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8437   // take two instructions.
8438   //
8439   // This implies that the most efficient way to do the extend from v8i8
8440   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8441   // the normal splitting to happen for the v8i16->v8i32.
8442
8443   // This is pre-legalization to catch some cases where the default
8444   // type legalization will create ill-tempered code.
8445   if (!DCI.isBeforeLegalizeOps())
8446     return SDValue();
8447
8448   // We're only interested in cleaning things up for non-legal vector types
8449   // here. If both the source and destination are legal, things will just
8450   // work naturally without any fiddling.
8451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8452   EVT ResVT = N->getValueType(0);
8453   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8454     return SDValue();
8455   // If the vector type isn't a simple VT, it's beyond the scope of what
8456   // we're  worried about here. Let legalization do its thing and hope for
8457   // the best.
8458   SDValue Src = N->getOperand(0);
8459   EVT SrcVT = Src->getValueType(0);
8460   if (!ResVT.isSimple() || !SrcVT.isSimple())
8461     return SDValue();
8462
8463   // If the source VT is a 64-bit vector, we can play games and get the
8464   // better results we want.
8465   if (SrcVT.getSizeInBits() != 64)
8466     return SDValue();
8467
8468   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8469   unsigned ElementCount = SrcVT.getVectorNumElements();
8470   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8471   SDLoc DL(N);
8472   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8473
8474   // Now split the rest of the operation into two halves, each with a 64
8475   // bit source.
8476   EVT LoVT, HiVT;
8477   SDValue Lo, Hi;
8478   unsigned NumElements = ResVT.getVectorNumElements();
8479   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8480   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8481                                  ResVT.getVectorElementType(), NumElements / 2);
8482
8483   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8484                                LoVT.getVectorNumElements());
8485   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8486                    DAG.getConstant(0, DL, MVT::i64));
8487   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8488                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8489   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8490   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8491
8492   // Now combine the parts back together so we still have a single result
8493   // like the combiner expects.
8494   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8495 }
8496
8497 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8498 /// value. The load store optimizer pass will merge them to store pair stores.
8499 /// This has better performance than a splat of the scalar followed by a split
8500 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8501 /// followed by an ext.b and two stores.
8502 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8503   SDValue StVal = St->getValue();
8504   EVT VT = StVal.getValueType();
8505
8506   // Don't replace floating point stores, they possibly won't be transformed to
8507   // stp because of the store pair suppress pass.
8508   if (VT.isFloatingPoint())
8509     return SDValue();
8510
8511   // Check for insert vector elements.
8512   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8513     return SDValue();
8514
8515   // We can express a splat as store pair(s) for 2 or 4 elements.
8516   unsigned NumVecElts = VT.getVectorNumElements();
8517   if (NumVecElts != 4 && NumVecElts != 2)
8518     return SDValue();
8519   SDValue SplatVal = StVal.getOperand(1);
8520   unsigned RemainInsertElts = NumVecElts - 1;
8521
8522   // Check that this is a splat.
8523   while (--RemainInsertElts) {
8524     SDValue NextInsertElt = StVal.getOperand(0);
8525     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8526       return SDValue();
8527     if (NextInsertElt.getOperand(1) != SplatVal)
8528       return SDValue();
8529     StVal = NextInsertElt;
8530   }
8531   unsigned OrigAlignment = St->getAlignment();
8532   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8533   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8534
8535   // Create scalar stores. This is at least as good as the code sequence for a
8536   // split unaligned store which is a dup.s, ext.b, and two stores.
8537   // Most of the time the three stores should be replaced by store pair
8538   // instructions (stp).
8539   SDLoc DL(St);
8540   SDValue BasePtr = St->getBasePtr();
8541   SDValue NewST1 =
8542       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8543                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8544
8545   unsigned Offset = EltOffset;
8546   while (--NumVecElts) {
8547     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8548                                     DAG.getConstant(Offset, DL, MVT::i64));
8549     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8550                           St->getPointerInfo(), St->isVolatile(),
8551                           St->isNonTemporal(), Alignment);
8552     Offset += EltOffset;
8553   }
8554   return NewST1;
8555 }
8556
8557 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8558                               SelectionDAG &DAG,
8559                               const AArch64Subtarget *Subtarget) {
8560   if (!DCI.isBeforeLegalize())
8561     return SDValue();
8562
8563   StoreSDNode *S = cast<StoreSDNode>(N);
8564   if (S->isVolatile())
8565     return SDValue();
8566
8567   // FIXME: The logic for deciding if an unaligned store should be split should
8568   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8569   // a call to that function here.
8570
8571   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8572   // page boundaries. We want to split such stores.
8573   if (!Subtarget->isCyclone())
8574     return SDValue();
8575
8576   // Don't split at -Oz.
8577   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8578     return SDValue();
8579
8580   SDValue StVal = S->getValue();
8581   EVT VT = StVal.getValueType();
8582
8583   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8584   // those up regresses performance on micro-benchmarks and olden/bh.
8585   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8586     return SDValue();
8587
8588   // Split unaligned 16B stores. They are terrible for performance.
8589   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8590   // extensions can use this to mark that it does not want splitting to happen
8591   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8592   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8593   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8594       S->getAlignment() <= 2)
8595     return SDValue();
8596
8597   // If we get a splat of a scalar convert this vector store to a store of
8598   // scalars. They will be merged into store pairs thereby removing two
8599   // instructions.
8600   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8601     return ReplacedSplat;
8602
8603   SDLoc DL(S);
8604   unsigned NumElts = VT.getVectorNumElements() / 2;
8605   // Split VT into two.
8606   EVT HalfVT =
8607       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8608   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8609                                    DAG.getConstant(0, DL, MVT::i64));
8610   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8611                                    DAG.getConstant(NumElts, DL, MVT::i64));
8612   SDValue BasePtr = S->getBasePtr();
8613   SDValue NewST1 =
8614       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8615                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8616   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8617                                   DAG.getConstant(8, DL, MVT::i64));
8618   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8619                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8620                       S->getAlignment());
8621 }
8622
8623 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8624 /// post-increment LD1R.
8625 static SDValue performPostLD1Combine(SDNode *N,
8626                                      TargetLowering::DAGCombinerInfo &DCI,
8627                                      bool IsLaneOp) {
8628   if (DCI.isBeforeLegalizeOps())
8629     return SDValue();
8630
8631   SelectionDAG &DAG = DCI.DAG;
8632   EVT VT = N->getValueType(0);
8633
8634   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8635   SDNode *LD = N->getOperand(LoadIdx).getNode();
8636   // If it is not LOAD, can not do such combine.
8637   if (LD->getOpcode() != ISD::LOAD)
8638     return SDValue();
8639
8640   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8641   EVT MemVT = LoadSDN->getMemoryVT();
8642   // Check if memory operand is the same type as the vector element.
8643   if (MemVT != VT.getVectorElementType())
8644     return SDValue();
8645
8646   // Check if there are other uses. If so, do not combine as it will introduce
8647   // an extra load.
8648   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8649        ++UI) {
8650     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8651       continue;
8652     if (*UI != N)
8653       return SDValue();
8654   }
8655
8656   SDValue Addr = LD->getOperand(1);
8657   SDValue Vector = N->getOperand(0);
8658   // Search for a use of the address operand that is an increment.
8659   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8660        Addr.getNode()->use_end(); UI != UE; ++UI) {
8661     SDNode *User = *UI;
8662     if (User->getOpcode() != ISD::ADD
8663         || UI.getUse().getResNo() != Addr.getResNo())
8664       continue;
8665
8666     // Check that the add is independent of the load.  Otherwise, folding it
8667     // would create a cycle.
8668     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8669       continue;
8670     // Also check that add is not used in the vector operand.  This would also
8671     // create a cycle.
8672     if (User->isPredecessorOf(Vector.getNode()))
8673       continue;
8674
8675     // If the increment is a constant, it must match the memory ref size.
8676     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8677     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8678       uint32_t IncVal = CInc->getZExtValue();
8679       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8680       if (IncVal != NumBytes)
8681         continue;
8682       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8683     }
8684
8685     // Finally, check that the vector doesn't depend on the load.
8686     // Again, this would create a cycle.
8687     // The load depending on the vector is fine, as that's the case for the
8688     // LD1*post we'll eventually generate anyway.
8689     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8690       continue;
8691
8692     SmallVector<SDValue, 8> Ops;
8693     Ops.push_back(LD->getOperand(0));  // Chain
8694     if (IsLaneOp) {
8695       Ops.push_back(Vector);           // The vector to be inserted
8696       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8697     }
8698     Ops.push_back(Addr);
8699     Ops.push_back(Inc);
8700
8701     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8702     SDVTList SDTys = DAG.getVTList(Tys);
8703     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8704     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8705                                            MemVT,
8706                                            LoadSDN->getMemOperand());
8707
8708     // Update the uses.
8709     SmallVector<SDValue, 2> NewResults;
8710     NewResults.push_back(SDValue(LD, 0));             // The result of load
8711     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8712     DCI.CombineTo(LD, NewResults);
8713     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8714     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8715
8716     break;
8717   }
8718   return SDValue();
8719 }
8720
8721 /// Simplify \Addr given that the top byte of it is ignored by HW during
8722 /// address translation.
8723 static bool performTBISimplification(SDValue Addr,
8724                                      TargetLowering::DAGCombinerInfo &DCI,
8725                                      SelectionDAG &DAG) {
8726   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8727   APInt KnownZero, KnownOne;
8728   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8729                                         DCI.isBeforeLegalizeOps());
8730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8731   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8732     DCI.CommitTargetLoweringOpt(TLO);
8733     return true;
8734   }
8735   return false;
8736 }
8737
8738 static SDValue performSTORECombine(SDNode *N,
8739                                    TargetLowering::DAGCombinerInfo &DCI,
8740                                    SelectionDAG &DAG,
8741                                    const AArch64Subtarget *Subtarget) {
8742   SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8743   if (Split.getNode())
8744     return Split;
8745
8746   if (Subtarget->supportsAddressTopByteIgnored() &&
8747       performTBISimplification(N->getOperand(2), DCI, DAG))
8748     return SDValue(N, 0);
8749
8750   return SDValue();
8751 }
8752
8753   /// This function handles the log2-shuffle pattern produced by the
8754 /// LoopVectorizer for the across vector reduction. It consists of
8755 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8756 /// are reduced, where s is an induction variable from 0 to
8757 /// log2(NumVectorElements).
8758 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8759                                                      unsigned Op,
8760                                                      SelectionDAG &DAG) {
8761   EVT VTy = OpV->getOperand(0).getValueType();
8762   if (!VTy.isVector())
8763     return SDValue();
8764
8765   int NumVecElts = VTy.getVectorNumElements();
8766   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8767     if (NumVecElts != 4)
8768       return SDValue();
8769   } else {
8770     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8771       return SDValue();
8772   }
8773
8774   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8775   SDValue PreOp = OpV;
8776   // Iterate over each step of the across vector reduction.
8777   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8778     SDValue CurOp = PreOp.getOperand(0);
8779     SDValue Shuffle = PreOp.getOperand(1);
8780     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8781       // Try to swap the 1st and 2nd operand as add and min/max instructions
8782       // are commutative.
8783       CurOp = PreOp.getOperand(1);
8784       Shuffle = PreOp.getOperand(0);
8785       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8786         return SDValue();
8787     }
8788
8789     // Check if the input vector is fed by the operator we want to handle,
8790     // except the last step; the very first input vector is not necessarily
8791     // the same operator we are handling.
8792     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8793       return SDValue();
8794
8795     // Check if it forms one step of the across vector reduction.
8796     // E.g.,
8797     //   %cur = add %1, %0
8798     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8799     //   %pre = add %cur, %shuffle
8800     if (Shuffle.getOperand(0) != CurOp)
8801       return SDValue();
8802
8803     int NumMaskElts = 1 << CurStep;
8804     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8805     // Check mask values in each step.
8806     // We expect the shuffle mask in each step follows a specific pattern
8807     // denoted here by the <M, U> form, where M is a sequence of integers
8808     // starting from NumMaskElts, increasing by 1, and the number integers
8809     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8810     // of undef in U should be NumVecElts - NumMaskElts.
8811     // E.g., for <8 x i16>, mask values in each step should be :
8812     //   step 0 : <1,u,u,u,u,u,u,u>
8813     //   step 1 : <2,3,u,u,u,u,u,u>
8814     //   step 2 : <4,5,6,7,u,u,u,u>
8815     for (int i = 0; i < NumVecElts; ++i)
8816       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8817           (i >= NumMaskElts && !(Mask[i] < 0)))
8818         return SDValue();
8819
8820     PreOp = CurOp;
8821   }
8822   unsigned Opcode;
8823   bool IsIntrinsic = false;
8824
8825   switch (Op) {
8826   default:
8827     llvm_unreachable("Unexpected operator for across vector reduction");
8828   case ISD::ADD:
8829     Opcode = AArch64ISD::UADDV;
8830     break;
8831   case ISD::SMAX:
8832     Opcode = AArch64ISD::SMAXV;
8833     break;
8834   case ISD::UMAX:
8835     Opcode = AArch64ISD::UMAXV;
8836     break;
8837   case ISD::SMIN:
8838     Opcode = AArch64ISD::SMINV;
8839     break;
8840   case ISD::UMIN:
8841     Opcode = AArch64ISD::UMINV;
8842     break;
8843   case ISD::FMAXNUM:
8844     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8845     IsIntrinsic = true;
8846     break;
8847   case ISD::FMINNUM:
8848     Opcode = Intrinsic::aarch64_neon_fminnmv;
8849     IsIntrinsic = true;
8850     break;
8851   }
8852   SDLoc DL(N);
8853
8854   return IsIntrinsic
8855              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8856                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8857              : DAG.getNode(
8858                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8859                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8860                    DAG.getConstant(0, DL, MVT::i64));
8861 }
8862
8863 /// Target-specific DAG combine for the across vector min/max reductions.
8864 /// This function specifically handles the final clean-up step of the vector
8865 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8866 /// pattern, which narrows down and finds the final min/max value from all
8867 /// elements of the vector.
8868 /// For example, for a <16 x i8> vector :
8869 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8870 ///   %smax0 = smax %arr, svn0
8871 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8872 ///   %smax1 = smax %smax0, %svn1
8873 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8874 ///   %smax2 = smax %smax1, svn2
8875 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8876 ///   %sc = setcc %smax2, %svn3, gt
8877 ///   %n0 = extract_vector_elt %sc, #0
8878 ///   %n1 = extract_vector_elt %smax2, #0
8879 ///   %n2 = extract_vector_elt $smax2, #1
8880 ///   %result = select %n0, %n1, n2
8881 ///     becomes :
8882 ///   %1 = smaxv %0
8883 ///   %result = extract_vector_elt %1, 0
8884 static SDValue
8885 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8886                                         const AArch64Subtarget *Subtarget) {
8887   if (!Subtarget->hasNEON())
8888     return SDValue();
8889
8890   SDValue N0 = N->getOperand(0);
8891   SDValue IfTrue = N->getOperand(1);
8892   SDValue IfFalse = N->getOperand(2);
8893
8894   // Check if the SELECT merges up the final result of the min/max
8895   // from a vector.
8896   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8897       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8898       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8899     return SDValue();
8900
8901   // Expect N0 is fed by SETCC.
8902   SDValue SetCC = N0.getOperand(0);
8903   EVT SetCCVT = SetCC.getValueType();
8904   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8905       SetCCVT.getVectorElementType() != MVT::i1)
8906     return SDValue();
8907
8908   SDValue VectorOp = SetCC.getOperand(0);
8909   unsigned Op = VectorOp->getOpcode();
8910   // Check if the input vector is fed by the operator we want to handle.
8911   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8912       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8913     return SDValue();
8914
8915   EVT VTy = VectorOp.getValueType();
8916   if (!VTy.isVector())
8917     return SDValue();
8918
8919   if (VTy.getSizeInBits() < 64)
8920     return SDValue();
8921
8922   EVT EltTy = VTy.getVectorElementType();
8923   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8924     if (EltTy != MVT::f32)
8925       return SDValue();
8926   } else {
8927     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8928       return SDValue();
8929   }
8930
8931   // Check if extracting from the same vector.
8932   // For example,
8933   //   %sc = setcc %vector, %svn1, gt
8934   //   %n0 = extract_vector_elt %sc, #0
8935   //   %n1 = extract_vector_elt %vector, #0
8936   //   %n2 = extract_vector_elt $vector, #1
8937   if (!(VectorOp == IfTrue->getOperand(0) &&
8938         VectorOp == IfFalse->getOperand(0)))
8939     return SDValue();
8940
8941   // Check if the condition code is matched with the operator type.
8942   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8943   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8944       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8945       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8946       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8947       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8948        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8949        CC != ISD::SETGE) ||
8950       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8951        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8952        CC != ISD::SETLE))
8953     return SDValue();
8954
8955   // Expect to check only lane 0 from the vector SETCC.
8956   if (!isNullConstant(N0.getOperand(1)))
8957     return SDValue();
8958
8959   // Expect to extract the true value from lane 0.
8960   if (!isNullConstant(IfTrue.getOperand(1)))
8961     return SDValue();
8962
8963   // Expect to extract the false value from lane 1.
8964   if (!isOneConstant(IfFalse.getOperand(1)))
8965     return SDValue();
8966
8967   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8968 }
8969
8970 /// Target-specific DAG combine for the across vector add reduction.
8971 /// This function specifically handles the final clean-up step of the vector
8972 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8973 /// pattern, which adds all elements of a vector together.
8974 /// For example, for a <4 x i32> vector :
8975 ///   %1 = vector_shuffle %0, <2,3,u,u>
8976 ///   %2 = add %0, %1
8977 ///   %3 = vector_shuffle %2, <1,u,u,u>
8978 ///   %4 = add %2, %3
8979 ///   %result = extract_vector_elt %4, 0
8980 /// becomes :
8981 ///   %0 = uaddv %0
8982 ///   %result = extract_vector_elt %0, 0
8983 static SDValue
8984 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
8985                                      const AArch64Subtarget *Subtarget) {
8986   if (!Subtarget->hasNEON())
8987     return SDValue();
8988   SDValue N0 = N->getOperand(0);
8989   SDValue N1 = N->getOperand(1);
8990
8991   // Check if the input vector is fed by the ADD.
8992   if (N0->getOpcode() != ISD::ADD)
8993     return SDValue();
8994
8995   // The vector extract idx must constant zero because we only expect the final
8996   // result of the reduction is placed in lane 0.
8997   if (!isNullConstant(N1))
8998     return SDValue();
8999
9000   EVT VTy = N0.getValueType();
9001   if (!VTy.isVector())
9002     return SDValue();
9003
9004   EVT EltTy = VTy.getVectorElementType();
9005   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9006     return SDValue();
9007
9008   if (VTy.getSizeInBits() < 64)
9009     return SDValue();
9010
9011   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9012 }
9013
9014 /// Target-specific DAG combine function for NEON load/store intrinsics
9015 /// to merge base address updates.
9016 static SDValue performNEONPostLDSTCombine(SDNode *N,
9017                                           TargetLowering::DAGCombinerInfo &DCI,
9018                                           SelectionDAG &DAG) {
9019   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9020     return SDValue();
9021
9022   unsigned AddrOpIdx = N->getNumOperands() - 1;
9023   SDValue Addr = N->getOperand(AddrOpIdx);
9024
9025   // Search for a use of the address operand that is an increment.
9026   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9027        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9028     SDNode *User = *UI;
9029     if (User->getOpcode() != ISD::ADD ||
9030         UI.getUse().getResNo() != Addr.getResNo())
9031       continue;
9032
9033     // Check that the add is independent of the load/store.  Otherwise, folding
9034     // it would create a cycle.
9035     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9036       continue;
9037
9038     // Find the new opcode for the updating load/store.
9039     bool IsStore = false;
9040     bool IsLaneOp = false;
9041     bool IsDupOp = false;
9042     unsigned NewOpc = 0;
9043     unsigned NumVecs = 0;
9044     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9045     switch (IntNo) {
9046     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9047     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9048       NumVecs = 2; break;
9049     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9050       NumVecs = 3; break;
9051     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9052       NumVecs = 4; break;
9053     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9054       NumVecs = 2; IsStore = true; break;
9055     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9056       NumVecs = 3; IsStore = true; break;
9057     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9058       NumVecs = 4; IsStore = true; break;
9059     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9060       NumVecs = 2; break;
9061     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9062       NumVecs = 3; break;
9063     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9064       NumVecs = 4; break;
9065     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9066       NumVecs = 2; IsStore = true; break;
9067     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9068       NumVecs = 3; IsStore = true; break;
9069     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9070       NumVecs = 4; IsStore = true; break;
9071     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9072       NumVecs = 2; IsDupOp = true; break;
9073     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9074       NumVecs = 3; IsDupOp = true; break;
9075     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9076       NumVecs = 4; IsDupOp = true; break;
9077     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9078       NumVecs = 2; IsLaneOp = true; break;
9079     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9080       NumVecs = 3; IsLaneOp = true; break;
9081     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9082       NumVecs = 4; IsLaneOp = true; break;
9083     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9084       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9085     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9086       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9087     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9088       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9089     }
9090
9091     EVT VecTy;
9092     if (IsStore)
9093       VecTy = N->getOperand(2).getValueType();
9094     else
9095       VecTy = N->getValueType(0);
9096
9097     // If the increment is a constant, it must match the memory ref size.
9098     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9099     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9100       uint32_t IncVal = CInc->getZExtValue();
9101       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9102       if (IsLaneOp || IsDupOp)
9103         NumBytes /= VecTy.getVectorNumElements();
9104       if (IncVal != NumBytes)
9105         continue;
9106       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9107     }
9108     SmallVector<SDValue, 8> Ops;
9109     Ops.push_back(N->getOperand(0)); // Incoming chain
9110     // Load lane and store have vector list as input.
9111     if (IsLaneOp || IsStore)
9112       for (unsigned i = 2; i < AddrOpIdx; ++i)
9113         Ops.push_back(N->getOperand(i));
9114     Ops.push_back(Addr); // Base register
9115     Ops.push_back(Inc);
9116
9117     // Return Types.
9118     EVT Tys[6];
9119     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9120     unsigned n;
9121     for (n = 0; n < NumResultVecs; ++n)
9122       Tys[n] = VecTy;
9123     Tys[n++] = MVT::i64;  // Type of write back register
9124     Tys[n] = MVT::Other;  // Type of the chain
9125     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9126
9127     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9128     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9129                                            MemInt->getMemoryVT(),
9130                                            MemInt->getMemOperand());
9131
9132     // Update the uses.
9133     std::vector<SDValue> NewResults;
9134     for (unsigned i = 0; i < NumResultVecs; ++i) {
9135       NewResults.push_back(SDValue(UpdN.getNode(), i));
9136     }
9137     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9138     DCI.CombineTo(N, NewResults);
9139     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9140
9141     break;
9142   }
9143   return SDValue();
9144 }
9145
9146 // Checks to see if the value is the prescribed width and returns information
9147 // about its extension mode.
9148 static
9149 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9150   ExtType = ISD::NON_EXTLOAD;
9151   switch(V.getNode()->getOpcode()) {
9152   default:
9153     return false;
9154   case ISD::LOAD: {
9155     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9156     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9157        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9158       ExtType = LoadNode->getExtensionType();
9159       return true;
9160     }
9161     return false;
9162   }
9163   case ISD::AssertSext: {
9164     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9165     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9166        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9167       ExtType = ISD::SEXTLOAD;
9168       return true;
9169     }
9170     return false;
9171   }
9172   case ISD::AssertZext: {
9173     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9174     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9175        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9176       ExtType = ISD::ZEXTLOAD;
9177       return true;
9178     }
9179     return false;
9180   }
9181   case ISD::Constant:
9182   case ISD::TargetConstant: {
9183     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9184         1LL << (width - 1))
9185       return true;
9186     return false;
9187   }
9188   }
9189
9190   return true;
9191 }
9192
9193 // This function does a whole lot of voodoo to determine if the tests are
9194 // equivalent without and with a mask. Essentially what happens is that given a
9195 // DAG resembling:
9196 //
9197 //  +-------------+ +-------------+ +-------------+ +-------------+
9198 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9199 //  +-------------+ +-------------+ +-------------+ +-------------+
9200 //           |           |           |               |
9201 //           V           V           |    +----------+
9202 //          +-------------+  +----+  |    |
9203 //          |     ADD     |  |0xff|  |    |
9204 //          +-------------+  +----+  |    |
9205 //                  |           |    |    |
9206 //                  V           V    |    |
9207 //                 +-------------+   |    |
9208 //                 |     AND     |   |    |
9209 //                 +-------------+   |    |
9210 //                      |            |    |
9211 //                      +-----+      |    |
9212 //                            |      |    |
9213 //                            V      V    V
9214 //                           +-------------+
9215 //                           |     CMP     |
9216 //                           +-------------+
9217 //
9218 // The AND node may be safely removed for some combinations of inputs. In
9219 // particular we need to take into account the extension type of the Input,
9220 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9221 // width of the input (this can work for any width inputs, the above graph is
9222 // specific to 8 bits.
9223 //
9224 // The specific equations were worked out by generating output tables for each
9225 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9226 // problem was simplified by working with 4 bit inputs, which means we only
9227 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9228 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9229 // patterns present in both extensions (0,7). For every distinct set of
9230 // AddConstant and CompConstants bit patterns we can consider the masked and
9231 // unmasked versions to be equivalent if the result of this function is true for
9232 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9233 //
9234 //   sub      w8, w0, w1
9235 //   and      w10, w8, #0x0f
9236 //   cmp      w8, w2
9237 //   cset     w9, AArch64CC
9238 //   cmp      w10, w2
9239 //   cset     w11, AArch64CC
9240 //   cmp      w9, w11
9241 //   cset     w0, eq
9242 //   ret
9243 //
9244 // Since the above function shows when the outputs are equivalent it defines
9245 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9246 // would be expensive to run during compiles. The equations below were written
9247 // in a test harness that confirmed they gave equivalent outputs to the above
9248 // for all inputs function, so they can be used determine if the removal is
9249 // legal instead.
9250 //
9251 // isEquivalentMaskless() is the code for testing if the AND can be removed
9252 // factored out of the DAG recognition as the DAG can take several forms.
9253
9254 static
9255 bool isEquivalentMaskless(unsigned CC, unsigned width,
9256                           ISD::LoadExtType ExtType, signed AddConstant,
9257                           signed CompConstant) {
9258   // By being careful about our equations and only writing the in term
9259   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9260   // make them generally applicable to all bit widths.
9261   signed MaxUInt = (1 << width);
9262
9263   // For the purposes of these comparisons sign extending the type is
9264   // equivalent to zero extending the add and displacing it by half the integer
9265   // width. Provided we are careful and make sure our equations are valid over
9266   // the whole range we can just adjust the input and avoid writing equations
9267   // for sign extended inputs.
9268   if (ExtType == ISD::SEXTLOAD)
9269     AddConstant -= (1 << (width-1));
9270
9271   switch(CC) {
9272   case AArch64CC::LE:
9273   case AArch64CC::GT: {
9274     if ((AddConstant == 0) ||
9275         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9276         (AddConstant >= 0 && CompConstant < 0) ||
9277         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9278       return true;
9279   } break;
9280   case AArch64CC::LT:
9281   case AArch64CC::GE: {
9282     if ((AddConstant == 0) ||
9283         (AddConstant >= 0 && CompConstant <= 0) ||
9284         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9285       return true;
9286   } break;
9287   case AArch64CC::HI:
9288   case AArch64CC::LS: {
9289     if ((AddConstant >= 0 && CompConstant < 0) ||
9290        (AddConstant <= 0 && CompConstant >= -1 &&
9291         CompConstant < AddConstant + MaxUInt))
9292       return true;
9293   } break;
9294   case AArch64CC::PL:
9295   case AArch64CC::MI: {
9296     if ((AddConstant == 0) ||
9297         (AddConstant > 0 && CompConstant <= 0) ||
9298         (AddConstant < 0 && CompConstant <= AddConstant))
9299       return true;
9300   } break;
9301   case AArch64CC::LO:
9302   case AArch64CC::HS: {
9303     if ((AddConstant >= 0 && CompConstant <= 0) ||
9304         (AddConstant <= 0 && CompConstant >= 0 &&
9305          CompConstant <= AddConstant + MaxUInt))
9306       return true;
9307   } break;
9308   case AArch64CC::EQ:
9309   case AArch64CC::NE: {
9310     if ((AddConstant > 0 && CompConstant < 0) ||
9311         (AddConstant < 0 && CompConstant >= 0 &&
9312          CompConstant < AddConstant + MaxUInt) ||
9313         (AddConstant >= 0 && CompConstant >= 0 &&
9314          CompConstant >= AddConstant) ||
9315         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9316
9317       return true;
9318   } break;
9319   case AArch64CC::VS:
9320   case AArch64CC::VC:
9321   case AArch64CC::AL:
9322   case AArch64CC::NV:
9323     return true;
9324   case AArch64CC::Invalid:
9325     break;
9326   }
9327
9328   return false;
9329 }
9330
9331 static
9332 SDValue performCONDCombine(SDNode *N,
9333                            TargetLowering::DAGCombinerInfo &DCI,
9334                            SelectionDAG &DAG, unsigned CCIndex,
9335                            unsigned CmpIndex) {
9336   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9337   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9338   unsigned CondOpcode = SubsNode->getOpcode();
9339
9340   if (CondOpcode != AArch64ISD::SUBS)
9341     return SDValue();
9342
9343   // There is a SUBS feeding this condition. Is it fed by a mask we can
9344   // use?
9345
9346   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9347   unsigned MaskBits = 0;
9348
9349   if (AndNode->getOpcode() != ISD::AND)
9350     return SDValue();
9351
9352   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9353     uint32_t CNV = CN->getZExtValue();
9354     if (CNV == 255)
9355       MaskBits = 8;
9356     else if (CNV == 65535)
9357       MaskBits = 16;
9358   }
9359
9360   if (!MaskBits)
9361     return SDValue();
9362
9363   SDValue AddValue = AndNode->getOperand(0);
9364
9365   if (AddValue.getOpcode() != ISD::ADD)
9366     return SDValue();
9367
9368   // The basic dag structure is correct, grab the inputs and validate them.
9369
9370   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9371   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9372   SDValue SubsInputValue = SubsNode->getOperand(1);
9373
9374   // The mask is present and the provenance of all the values is a smaller type,
9375   // lets see if the mask is superfluous.
9376
9377   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9378       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9379     return SDValue();
9380
9381   ISD::LoadExtType ExtType;
9382
9383   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9384       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9385       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9386     return SDValue();
9387
9388   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9389                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9390                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9391     return SDValue();
9392
9393   // The AND is not necessary, remove it.
9394
9395   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9396                                SubsNode->getValueType(1));
9397   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9398
9399   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9400   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9401
9402   return SDValue(N, 0);
9403 }
9404
9405 // Optimize compare with zero and branch.
9406 static SDValue performBRCONDCombine(SDNode *N,
9407                                     TargetLowering::DAGCombinerInfo &DCI,
9408                                     SelectionDAG &DAG) {
9409   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9410   if (NV.getNode())
9411     N = NV.getNode();
9412   SDValue Chain = N->getOperand(0);
9413   SDValue Dest = N->getOperand(1);
9414   SDValue CCVal = N->getOperand(2);
9415   SDValue Cmp = N->getOperand(3);
9416
9417   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9418   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9419   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9420     return SDValue();
9421
9422   unsigned CmpOpc = Cmp.getOpcode();
9423   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9424     return SDValue();
9425
9426   // Only attempt folding if there is only one use of the flag and no use of the
9427   // value.
9428   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9429     return SDValue();
9430
9431   SDValue LHS = Cmp.getOperand(0);
9432   SDValue RHS = Cmp.getOperand(1);
9433
9434   assert(LHS.getValueType() == RHS.getValueType() &&
9435          "Expected the value type to be the same for both operands!");
9436   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9437     return SDValue();
9438
9439   if (isNullConstant(LHS))
9440     std::swap(LHS, RHS);
9441
9442   if (!isNullConstant(RHS))
9443     return SDValue();
9444
9445   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9446       LHS.getOpcode() == ISD::SRL)
9447     return SDValue();
9448
9449   // Fold the compare into the branch instruction.
9450   SDValue BR;
9451   if (CC == AArch64CC::EQ)
9452     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9453   else
9454     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9455
9456   // Do not add new nodes to DAG combiner worklist.
9457   DCI.CombineTo(N, BR, false);
9458
9459   return SDValue();
9460 }
9461
9462 // vselect (v1i1 setcc) ->
9463 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9464 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9465 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9466 // such VSELECT.
9467 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9468   SDValue N0 = N->getOperand(0);
9469   EVT CCVT = N0.getValueType();
9470
9471   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9472       CCVT.getVectorElementType() != MVT::i1)
9473     return SDValue();
9474
9475   EVT ResVT = N->getValueType(0);
9476   EVT CmpVT = N0.getOperand(0).getValueType();
9477   // Only combine when the result type is of the same size as the compared
9478   // operands.
9479   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9480     return SDValue();
9481
9482   SDValue IfTrue = N->getOperand(1);
9483   SDValue IfFalse = N->getOperand(2);
9484   SDValue SetCC =
9485       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9486                    N0.getOperand(0), N0.getOperand(1),
9487                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9488   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9489                      IfTrue, IfFalse);
9490 }
9491
9492 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9493 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9494 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9495 /// with a vector one followed by a DUP shuffle on the result.
9496 static SDValue performSelectCombine(SDNode *N,
9497                                     TargetLowering::DAGCombinerInfo &DCI) {
9498   SelectionDAG &DAG = DCI.DAG;
9499   SDValue N0 = N->getOperand(0);
9500   EVT ResVT = N->getValueType(0);
9501
9502   if (N0.getOpcode() != ISD::SETCC)
9503     return SDValue();
9504
9505   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9506   // scalar SetCCResultType. We also don't expect vectors, because we assume
9507   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9508   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9509          "Scalar-SETCC feeding SELECT has unexpected result type!");
9510
9511   // If NumMaskElts == 0, the comparison is larger than select result. The
9512   // largest real NEON comparison is 64-bits per lane, which means the result is
9513   // at most 32-bits and an illegal vector. Just bail out for now.
9514   EVT SrcVT = N0.getOperand(0).getValueType();
9515
9516   // Don't try to do this optimization when the setcc itself has i1 operands.
9517   // There are no legal vectors of i1, so this would be pointless.
9518   if (SrcVT == MVT::i1)
9519     return SDValue();
9520
9521   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9522   if (!ResVT.isVector() || NumMaskElts == 0)
9523     return SDValue();
9524
9525   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9526   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9527
9528   // Also bail out if the vector CCVT isn't the same size as ResVT.
9529   // This can happen if the SETCC operand size doesn't divide the ResVT size
9530   // (e.g., f64 vs v3f32).
9531   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9532     return SDValue();
9533
9534   // Make sure we didn't create illegal types, if we're not supposed to.
9535   assert(DCI.isBeforeLegalize() ||
9536          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9537
9538   // First perform a vector comparison, where lane 0 is the one we're interested
9539   // in.
9540   SDLoc DL(N0);
9541   SDValue LHS =
9542       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9543   SDValue RHS =
9544       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9545   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9546
9547   // Now duplicate the comparison mask we want across all other lanes.
9548   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9549   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9550   Mask = DAG.getNode(ISD::BITCAST, DL,
9551                      ResVT.changeVectorElementTypeToInteger(), Mask);
9552
9553   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9554 }
9555
9556 /// Get rid of unnecessary NVCASTs (that don't change the type).
9557 static SDValue performNVCASTCombine(SDNode *N) {
9558   if (N->getValueType(0) == N->getOperand(0).getValueType())
9559     return N->getOperand(0);
9560
9561   return SDValue();
9562 }
9563
9564 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9565                                                  DAGCombinerInfo &DCI) const {
9566   SelectionDAG &DAG = DCI.DAG;
9567   switch (N->getOpcode()) {
9568   default:
9569     break;
9570   case ISD::ADD:
9571   case ISD::SUB:
9572     return performAddSubLongCombine(N, DCI, DAG);
9573   case ISD::XOR:
9574     return performXorCombine(N, DAG, DCI, Subtarget);
9575   case ISD::MUL:
9576     return performMulCombine(N, DAG, DCI, Subtarget);
9577   case ISD::SINT_TO_FP:
9578   case ISD::UINT_TO_FP:
9579     return performIntToFpCombine(N, DAG, Subtarget);
9580   case ISD::FP_TO_SINT:
9581   case ISD::FP_TO_UINT:
9582     return performFpToIntCombine(N, DAG, Subtarget);
9583   case ISD::FDIV:
9584     return performFDivCombine(N, DAG, Subtarget);
9585   case ISD::OR:
9586     return performORCombine(N, DCI, Subtarget);
9587   case ISD::INTRINSIC_WO_CHAIN:
9588     return performIntrinsicCombine(N, DCI, Subtarget);
9589   case ISD::ANY_EXTEND:
9590   case ISD::ZERO_EXTEND:
9591   case ISD::SIGN_EXTEND:
9592     return performExtendCombine(N, DCI, DAG);
9593   case ISD::BITCAST:
9594     return performBitcastCombine(N, DCI, DAG);
9595   case ISD::CONCAT_VECTORS:
9596     return performConcatVectorsCombine(N, DCI, DAG);
9597   case ISD::SELECT: {
9598     SDValue RV = performSelectCombine(N, DCI);
9599     if (!RV.getNode())
9600       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9601     return RV;
9602   }
9603   case ISD::VSELECT:
9604     return performVSelectCombine(N, DCI.DAG);
9605   case ISD::LOAD:
9606     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9607       return SDValue(N, 0);
9608     break;
9609   case ISD::STORE:
9610     return performSTORECombine(N, DCI, DAG, Subtarget);
9611   case AArch64ISD::BRCOND:
9612     return performBRCONDCombine(N, DCI, DAG);
9613   case AArch64ISD::CSEL:
9614     return performCONDCombine(N, DCI, DAG, 2, 3);
9615   case AArch64ISD::DUP:
9616     return performPostLD1Combine(N, DCI, false);
9617   case AArch64ISD::NVCAST:
9618     return performNVCASTCombine(N);
9619   case ISD::INSERT_VECTOR_ELT:
9620     return performPostLD1Combine(N, DCI, true);
9621   case ISD::EXTRACT_VECTOR_ELT:
9622     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9623   case ISD::INTRINSIC_VOID:
9624   case ISD::INTRINSIC_W_CHAIN:
9625     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9626     case Intrinsic::aarch64_neon_ld2:
9627     case Intrinsic::aarch64_neon_ld3:
9628     case Intrinsic::aarch64_neon_ld4:
9629     case Intrinsic::aarch64_neon_ld1x2:
9630     case Intrinsic::aarch64_neon_ld1x3:
9631     case Intrinsic::aarch64_neon_ld1x4:
9632     case Intrinsic::aarch64_neon_ld2lane:
9633     case Intrinsic::aarch64_neon_ld3lane:
9634     case Intrinsic::aarch64_neon_ld4lane:
9635     case Intrinsic::aarch64_neon_ld2r:
9636     case Intrinsic::aarch64_neon_ld3r:
9637     case Intrinsic::aarch64_neon_ld4r:
9638     case Intrinsic::aarch64_neon_st2:
9639     case Intrinsic::aarch64_neon_st3:
9640     case Intrinsic::aarch64_neon_st4:
9641     case Intrinsic::aarch64_neon_st1x2:
9642     case Intrinsic::aarch64_neon_st1x3:
9643     case Intrinsic::aarch64_neon_st1x4:
9644     case Intrinsic::aarch64_neon_st2lane:
9645     case Intrinsic::aarch64_neon_st3lane:
9646     case Intrinsic::aarch64_neon_st4lane:
9647       return performNEONPostLDSTCombine(N, DCI, DAG);
9648     default:
9649       break;
9650     }
9651   }
9652   return SDValue();
9653 }
9654
9655 // Check if the return value is used as only a return value, as otherwise
9656 // we can't perform a tail-call. In particular, we need to check for
9657 // target ISD nodes that are returns and any other "odd" constructs
9658 // that the generic analysis code won't necessarily catch.
9659 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9660                                                SDValue &Chain) const {
9661   if (N->getNumValues() != 1)
9662     return false;
9663   if (!N->hasNUsesOfValue(1, 0))
9664     return false;
9665
9666   SDValue TCChain = Chain;
9667   SDNode *Copy = *N->use_begin();
9668   if (Copy->getOpcode() == ISD::CopyToReg) {
9669     // If the copy has a glue operand, we conservatively assume it isn't safe to
9670     // perform a tail call.
9671     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9672         MVT::Glue)
9673       return false;
9674     TCChain = Copy->getOperand(0);
9675   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9676     return false;
9677
9678   bool HasRet = false;
9679   for (SDNode *Node : Copy->uses()) {
9680     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9681       return false;
9682     HasRet = true;
9683   }
9684
9685   if (!HasRet)
9686     return false;
9687
9688   Chain = TCChain;
9689   return true;
9690 }
9691
9692 // Return whether the an instruction can potentially be optimized to a tail
9693 // call. This will cause the optimizers to attempt to move, or duplicate,
9694 // return instructions to help enable tail call optimizations for this
9695 // instruction.
9696 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9697   if (!CI->isTailCall())
9698     return false;
9699
9700   return true;
9701 }
9702
9703 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9704                                                    SDValue &Offset,
9705                                                    ISD::MemIndexedMode &AM,
9706                                                    bool &IsInc,
9707                                                    SelectionDAG &DAG) const {
9708   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9709     return false;
9710
9711   Base = Op->getOperand(0);
9712   // All of the indexed addressing mode instructions take a signed
9713   // 9 bit immediate offset.
9714   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9715     int64_t RHSC = (int64_t)RHS->getZExtValue();
9716     if (RHSC >= 256 || RHSC <= -256)
9717       return false;
9718     IsInc = (Op->getOpcode() == ISD::ADD);
9719     Offset = Op->getOperand(1);
9720     return true;
9721   }
9722   return false;
9723 }
9724
9725 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9726                                                       SDValue &Offset,
9727                                                       ISD::MemIndexedMode &AM,
9728                                                       SelectionDAG &DAG) const {
9729   EVT VT;
9730   SDValue Ptr;
9731   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9732     VT = LD->getMemoryVT();
9733     Ptr = LD->getBasePtr();
9734   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9735     VT = ST->getMemoryVT();
9736     Ptr = ST->getBasePtr();
9737   } else
9738     return false;
9739
9740   bool IsInc;
9741   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9742     return false;
9743   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9744   return true;
9745 }
9746
9747 bool AArch64TargetLowering::getPostIndexedAddressParts(
9748     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9749     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9750   EVT VT;
9751   SDValue Ptr;
9752   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9753     VT = LD->getMemoryVT();
9754     Ptr = LD->getBasePtr();
9755   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9756     VT = ST->getMemoryVT();
9757     Ptr = ST->getBasePtr();
9758   } else
9759     return false;
9760
9761   bool IsInc;
9762   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9763     return false;
9764   // Post-indexing updates the base, so it's not a valid transform
9765   // if that's not the same as the load's pointer.
9766   if (Ptr != Base)
9767     return false;
9768   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9769   return true;
9770 }
9771
9772 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9773                                   SelectionDAG &DAG) {
9774   SDLoc DL(N);
9775   SDValue Op = N->getOperand(0);
9776
9777   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9778     return;
9779
9780   Op = SDValue(
9781       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9782                          DAG.getUNDEF(MVT::i32), Op,
9783                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9784       0);
9785   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9786   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9787 }
9788
9789 static void ReplaceReductionResults(SDNode *N,
9790                                     SmallVectorImpl<SDValue> &Results,
9791                                     SelectionDAG &DAG, unsigned InterOp,
9792                                     unsigned AcrossOp) {
9793   EVT LoVT, HiVT;
9794   SDValue Lo, Hi;
9795   SDLoc dl(N);
9796   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9797   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9798   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9799   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9800   Results.push_back(SplitVal);
9801 }
9802
9803 void AArch64TargetLowering::ReplaceNodeResults(
9804     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9805   switch (N->getOpcode()) {
9806   default:
9807     llvm_unreachable("Don't know how to custom expand this");
9808   case ISD::BITCAST:
9809     ReplaceBITCASTResults(N, Results, DAG);
9810     return;
9811   case AArch64ISD::SADDV:
9812     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9813     return;
9814   case AArch64ISD::UADDV:
9815     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9816     return;
9817   case AArch64ISD::SMINV:
9818     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9819     return;
9820   case AArch64ISD::UMINV:
9821     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9822     return;
9823   case AArch64ISD::SMAXV:
9824     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9825     return;
9826   case AArch64ISD::UMAXV:
9827     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9828     return;
9829   case ISD::FP_TO_UINT:
9830   case ISD::FP_TO_SINT:
9831     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9832     // Let normal code take care of it by not adding anything to Results.
9833     return;
9834   }
9835 }
9836
9837 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9838   return true;
9839 }
9840
9841 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9842   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9843   // reciprocal if there are three or more FDIVs.
9844   return 3;
9845 }
9846
9847 TargetLoweringBase::LegalizeTypeAction
9848 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9849   MVT SVT = VT.getSimpleVT();
9850   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9851   // v4i16, v2i32 instead of to promote.
9852   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9853       || SVT == MVT::v1f32)
9854     return TypeWidenVector;
9855
9856   return TargetLoweringBase::getPreferredVectorAction(VT);
9857 }
9858
9859 // Loads and stores less than 128-bits are already atomic; ones above that
9860 // are doomed anyway, so defer to the default libcall and blame the OS when
9861 // things go wrong.
9862 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9863   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9864   return Size == 128;
9865 }
9866
9867 // Loads and stores less than 128-bits are already atomic; ones above that
9868 // are doomed anyway, so defer to the default libcall and blame the OS when
9869 // things go wrong.
9870 TargetLowering::AtomicExpansionKind
9871 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9872   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9873   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9874 }
9875
9876 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9877 TargetLowering::AtomicExpansionKind
9878 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9879   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9880   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9881 }
9882
9883 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9884     AtomicCmpXchgInst *AI) const {
9885   return true;
9886 }
9887
9888 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9889                                              AtomicOrdering Ord) const {
9890   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9891   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9892   bool IsAcquire = isAtLeastAcquire(Ord);
9893
9894   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9895   // intrinsic must return {i64, i64} and we have to recombine them into a
9896   // single i128 here.
9897   if (ValTy->getPrimitiveSizeInBits() == 128) {
9898     Intrinsic::ID Int =
9899         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9900     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9901
9902     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9903     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9904
9905     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9906     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9907     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9908     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9909     return Builder.CreateOr(
9910         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9911   }
9912
9913   Type *Tys[] = { Addr->getType() };
9914   Intrinsic::ID Int =
9915       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9916   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9917
9918   return Builder.CreateTruncOrBitCast(
9919       Builder.CreateCall(Ldxr, Addr),
9920       cast<PointerType>(Addr->getType())->getElementType());
9921 }
9922
9923 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9924     IRBuilder<> &Builder) const {
9925   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9926   Builder.CreateCall(
9927       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9928 }
9929
9930 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9931                                                    Value *Val, Value *Addr,
9932                                                    AtomicOrdering Ord) const {
9933   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9934   bool IsRelease = isAtLeastRelease(Ord);
9935
9936   // Since the intrinsics must have legal type, the i128 intrinsics take two
9937   // parameters: "i64, i64". We must marshal Val into the appropriate form
9938   // before the call.
9939   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9940     Intrinsic::ID Int =
9941         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9942     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9943     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9944
9945     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9946     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9947     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9948     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9949   }
9950
9951   Intrinsic::ID Int =
9952       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9953   Type *Tys[] = { Addr->getType() };
9954   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9955
9956   return Builder.CreateCall(Stxr,
9957                             {Builder.CreateZExtOrBitCast(
9958                                  Val, Stxr->getFunctionType()->getParamType(0)),
9959                              Addr});
9960 }
9961
9962 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9963     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9964   return Ty->isArrayTy();
9965 }
9966
9967 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9968                                                             EVT) const {
9969   return false;
9970 }
9971
9972 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9973   if (!Subtarget->isTargetAndroid())
9974     return TargetLowering::getSafeStackPointerLocation(IRB);
9975
9976   // Android provides a fixed TLS slot for the SafeStack pointer. See the
9977   // definition of TLS_SLOT_SAFESTACK in
9978   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
9979   const unsigned TlsOffset = 0x48;
9980   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
9981   Function *ThreadPointerFunc =
9982       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
9983   return IRB.CreatePointerCast(
9984       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
9985       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
9986 }