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