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