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