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