Fix fptosi, fptoui from f16 vectors to i8, i16 vectors
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 #define DEBUG_TYPE "aarch64-lower"
39
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
43 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147   // Virtually no operation on f128 is legal, but LLVM can't expand them when
148   // there's a valid register class, so we need custom operations in most cases.
149   setOperationAction(ISD::FABS, MVT::f128, Expand);
150   setOperationAction(ISD::FADD, MVT::f128, Custom);
151   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152   setOperationAction(ISD::FCOS, MVT::f128, Expand);
153   setOperationAction(ISD::FDIV, MVT::f128, Custom);
154   setOperationAction(ISD::FMA, MVT::f128, Expand);
155   setOperationAction(ISD::FMUL, MVT::f128, Custom);
156   setOperationAction(ISD::FNEG, MVT::f128, Expand);
157   setOperationAction(ISD::FPOW, MVT::f128, Expand);
158   setOperationAction(ISD::FREM, MVT::f128, Expand);
159   setOperationAction(ISD::FRINT, MVT::f128, Expand);
160   setOperationAction(ISD::FSIN, MVT::f128, Expand);
161   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163   setOperationAction(ISD::FSUB, MVT::f128, Custom);
164   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165   setOperationAction(ISD::SETCC, MVT::f128, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167   setOperationAction(ISD::SELECT, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171   // Lowering for many of the conversions is actually specified by the non-f128
172   // type. The LowerXXX function will be trivial when f128 isn't involved.
173   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188   // Variable arguments.
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Custom);
191   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194   // Variable-sized objects.
195   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
199   // Constant pool entries
200   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201
202   // BlockAddress
203   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204
205   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206   setOperationAction(ISD::ADDC, MVT::i32, Custom);
207   setOperationAction(ISD::ADDE, MVT::i32, Custom);
208   setOperationAction(ISD::SUBC, MVT::i32, Custom);
209   setOperationAction(ISD::SUBE, MVT::i32, Custom);
210   setOperationAction(ISD::ADDC, MVT::i64, Custom);
211   setOperationAction(ISD::ADDE, MVT::i64, Custom);
212   setOperationAction(ISD::SUBC, MVT::i64, Custom);
213   setOperationAction(ISD::SUBE, MVT::i64, Custom);
214
215   // AArch64 lacks both left-rotate and popcount instructions.
216   setOperationAction(ISD::ROTL, MVT::i32, Expand);
217   setOperationAction(ISD::ROTL, MVT::i64, Expand);
218   for (MVT VT : MVT::vector_valuetypes()) {
219     setOperationAction(ISD::ROTL, VT, Expand);
220     setOperationAction(ISD::ROTR, VT, Expand);
221   }
222
223   // AArch64 doesn't have {U|S}MUL_LOHI.
224   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226
227
228   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229   // counterparts, which AArch64 supports directly.
230   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234
235   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237
238   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
240   for (MVT VT : MVT::vector_valuetypes()) {
241     setOperationAction(ISD::SDIVREM, VT, Expand);
242     setOperationAction(ISD::UDIVREM, VT, Expand);
243   }
244   setOperationAction(ISD::SREM, MVT::i32, Expand);
245   setOperationAction(ISD::SREM, MVT::i64, Expand);
246   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248   setOperationAction(ISD::UREM, MVT::i32, Expand);
249   setOperationAction(ISD::UREM, MVT::i64, Expand);
250
251   // Custom lower Add/Sub/Mul with overflow.
252   setOperationAction(ISD::SADDO, MVT::i32, Custom);
253   setOperationAction(ISD::SADDO, MVT::i64, Custom);
254   setOperationAction(ISD::UADDO, MVT::i32, Custom);
255   setOperationAction(ISD::UADDO, MVT::i64, Custom);
256   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258   setOperationAction(ISD::USUBO, MVT::i32, Custom);
259   setOperationAction(ISD::USUBO, MVT::i64, Custom);
260   setOperationAction(ISD::SMULO, MVT::i32, Custom);
261   setOperationAction(ISD::SMULO, MVT::i64, Custom);
262   setOperationAction(ISD::UMULO, MVT::i32, Custom);
263   setOperationAction(ISD::UMULO, MVT::i64, Custom);
264
265   setOperationAction(ISD::FSIN, MVT::f32, Expand);
266   setOperationAction(ISD::FSIN, MVT::f64, Expand);
267   setOperationAction(ISD::FCOS, MVT::f32, Expand);
268   setOperationAction(ISD::FCOS, MVT::f64, Expand);
269   setOperationAction(ISD::FPOW, MVT::f32, Expand);
270   setOperationAction(ISD::FPOW, MVT::f64, Expand);
271   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
273
274   // f16 is a storage-only type, always promote it to f32.
275   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
276   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
277   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
278   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
279   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
280   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
281   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
282   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
283   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
284   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
285   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
286   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
287   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
288   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
289   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
290   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
291   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
292   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
293   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
294   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
295   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
296   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
297   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
298   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
299   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
300   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
301   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
302   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
303   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
304   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
305   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
306   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
307   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
308   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
309
310   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
311   // known to be safe.
312   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
324
325   // Expand all other v4f16 operations.
326   // FIXME: We could generate better code by promoting some operations to
327   // a pair of v4f32s
328   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
354
355
356   // v8f16 is also a storage-only type, so expand it.
357   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
388
389   // AArch64 has implementations of a lot of rounding-like FP operations.
390   for (MVT Ty : {MVT::f32, MVT::f64}) {
391     setOperationAction(ISD::FFLOOR, Ty, Legal);
392     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393     setOperationAction(ISD::FCEIL, Ty, Legal);
394     setOperationAction(ISD::FRINT, Ty, Legal);
395     setOperationAction(ISD::FTRUNC, Ty, Legal);
396     setOperationAction(ISD::FROUND, Ty, Legal);
397     setOperationAction(ISD::FMINNUM, Ty, Legal);
398     setOperationAction(ISD::FMAXNUM, Ty, Legal);
399     setOperationAction(ISD::FMINNAN, Ty, Legal);
400     setOperationAction(ISD::FMAXNAN, Ty, Legal);
401   }
402
403   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
404
405   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406   // This requires the Performance Monitors extension.
407   if (Subtarget->hasPerfMon())
408     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
409
410   if (Subtarget->isTargetMachO()) {
411     // For iOS, we don't want to the normal expansion of a libcall to
412     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413     // traffic.
414     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416   } else {
417     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
419   }
420
421   // Make floating-point constants legal for the large code model, so they don't
422   // become loads from the constant pool.
423   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
426   }
427
428   // AArch64 does not have floating-point extending loads, i1 sign-extending
429   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
430   for (MVT VT : MVT::fp_valuetypes()) {
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435   }
436   for (MVT VT : MVT::integer_valuetypes())
437     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438
439   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
446
447   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449
450   // Indexed loads and stores are supported.
451   for (unsigned im = (unsigned)ISD::PRE_INC;
452        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453     setIndexedLoadAction(im, MVT::i8, Legal);
454     setIndexedLoadAction(im, MVT::i16, Legal);
455     setIndexedLoadAction(im, MVT::i32, Legal);
456     setIndexedLoadAction(im, MVT::i64, Legal);
457     setIndexedLoadAction(im, MVT::f64, Legal);
458     setIndexedLoadAction(im, MVT::f32, Legal);
459     setIndexedLoadAction(im, MVT::f16, Legal);
460     setIndexedStoreAction(im, MVT::i8, Legal);
461     setIndexedStoreAction(im, MVT::i16, Legal);
462     setIndexedStoreAction(im, MVT::i32, Legal);
463     setIndexedStoreAction(im, MVT::i64, Legal);
464     setIndexedStoreAction(im, MVT::f64, Legal);
465     setIndexedStoreAction(im, MVT::f32, Legal);
466     setIndexedStoreAction(im, MVT::f16, Legal);
467   }
468
469   // Trap.
470   setOperationAction(ISD::TRAP, MVT::Other, Legal);
471
472   // We combine OR nodes for bitfield operations.
473   setTargetDAGCombine(ISD::OR);
474
475   // Vector add and sub nodes may conceal a high-half opportunity.
476   // Also, try to fold ADD into CSINC/CSINV..
477   setTargetDAGCombine(ISD::ADD);
478   setTargetDAGCombine(ISD::SUB);
479
480   setTargetDAGCombine(ISD::XOR);
481   setTargetDAGCombine(ISD::SINT_TO_FP);
482   setTargetDAGCombine(ISD::UINT_TO_FP);
483
484   setTargetDAGCombine(ISD::FP_TO_SINT);
485   setTargetDAGCombine(ISD::FP_TO_UINT);
486   setTargetDAGCombine(ISD::FDIV);
487
488   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
489
490   setTargetDAGCombine(ISD::ANY_EXTEND);
491   setTargetDAGCombine(ISD::ZERO_EXTEND);
492   setTargetDAGCombine(ISD::SIGN_EXTEND);
493   setTargetDAGCombine(ISD::BITCAST);
494   setTargetDAGCombine(ISD::CONCAT_VECTORS);
495   setTargetDAGCombine(ISD::STORE);
496   if (Subtarget->supportsAddressTopByteIgnored())
497     setTargetDAGCombine(ISD::LOAD);
498
499   setTargetDAGCombine(ISD::MUL);
500
501   setTargetDAGCombine(ISD::SELECT);
502   setTargetDAGCombine(ISD::VSELECT);
503
504   setTargetDAGCombine(ISD::INTRINSIC_VOID);
505   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
507   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
508
509   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
512
513   setStackPointerRegisterToSaveRestore(AArch64::SP);
514
515   setSchedulingPreference(Sched::Hybrid);
516
517   // Enable TBZ/TBNZ
518   MaskAndBranchFoldingIsLegal = true;
519   EnableExtLdPromotion = true;
520
521   setMinFunctionAlignment(2);
522
523   setHasExtractBitsInsn(true);
524
525   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526
527   if (Subtarget->hasNEON()) {
528     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529     // silliness like this:
530     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555
556     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561
562     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563
564     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565     // elements smaller than i32, so promote the input to i32 first.
566     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
570     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571     // -> v8f16 conversions.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
576     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
581     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
582     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
585
586     // AArch64 doesn't have MUL.2d:
587     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
588     // Custom handling for some quad-vector types to detect MULL.
589     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
592
593     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595     // Likewise, narrowing and extending vector loads/stores aren't handled
596     // directly.
597     for (MVT VT : MVT::vector_valuetypes()) {
598       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
599
600       setOperationAction(ISD::MULHS, VT, Expand);
601       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602       setOperationAction(ISD::MULHU, VT, Expand);
603       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
604
605       setOperationAction(ISD::BSWAP, VT, Expand);
606
607       for (MVT InnerVT : MVT::vector_valuetypes()) {
608         setTruncStoreAction(VT, InnerVT, Expand);
609         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
612       }
613     }
614
615     // AArch64 has implementations of a lot of rounding-like FP operations.
616     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
617       setOperationAction(ISD::FFLOOR, Ty, Legal);
618       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619       setOperationAction(ISD::FCEIL, Ty, Legal);
620       setOperationAction(ISD::FRINT, Ty, Legal);
621       setOperationAction(ISD::FTRUNC, Ty, Legal);
622       setOperationAction(ISD::FROUND, Ty, Legal);
623     }
624   }
625
626   // Prefer likely predicted branches to selects on out-of-order cores.
627   if (Subtarget->isCortexA57())
628     PredictableSelectIsExpensive = true;
629 }
630
631 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
632   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
633     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
635
636     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
638   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
639     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
641
642     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
644   }
645
646   // Mark vector float intrinsics as expand.
647   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
657
658     // But we do support custom-lowering for FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
660   }
661
662   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
674
675   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
678   for (MVT InnerVT : MVT::all_valuetypes())
679     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
680
681   // CNT supports only B element sizes.
682   if (VT != MVT::v8i8 && VT != MVT::v16i8)
683     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
684
685   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
690
691   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
693
694   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
695   // i64.
696   if (!VT.isFloatingPoint() &&
697       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
698     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
699                             ISD::SABSDIFF, ISD::UABSDIFF})
700       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
701
702   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
703   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
704     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
705                             ISD::FMINNUM, ISD::FMAXNUM})
706       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
707
708   if (Subtarget->isLittleEndian()) {
709     for (unsigned im = (unsigned)ISD::PRE_INC;
710          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
711       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
712       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
713     }
714   }
715 }
716
717 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
718   addRegisterClass(VT, &AArch64::FPR64RegClass);
719   addTypeForNEON(VT, MVT::v2i32);
720 }
721
722 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
723   addRegisterClass(VT, &AArch64::FPR128RegClass);
724   addTypeForNEON(VT, MVT::v4i32);
725 }
726
727 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
728                                               EVT VT) const {
729   if (!VT.isVector())
730     return MVT::i32;
731   return VT.changeVectorElementTypeToInteger();
732 }
733
734 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
735 /// Mask are known to be either zero or one and return them in the
736 /// KnownZero/KnownOne bitsets.
737 void AArch64TargetLowering::computeKnownBitsForTargetNode(
738     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
739     const SelectionDAG &DAG, unsigned Depth) const {
740   switch (Op.getOpcode()) {
741   default:
742     break;
743   case AArch64ISD::CSEL: {
744     APInt KnownZero2, KnownOne2;
745     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
746     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
747     KnownZero &= KnownZero2;
748     KnownOne &= KnownOne2;
749     break;
750   }
751   case ISD::INTRINSIC_W_CHAIN: {
752     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
753     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
754     switch (IntID) {
755     default: return;
756     case Intrinsic::aarch64_ldaxr:
757     case Intrinsic::aarch64_ldxr: {
758       unsigned BitWidth = KnownOne.getBitWidth();
759       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
760       unsigned MemBits = VT.getScalarType().getSizeInBits();
761       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
762       return;
763     }
764     }
765     break;
766   }
767   case ISD::INTRINSIC_WO_CHAIN:
768   case ISD::INTRINSIC_VOID: {
769     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
770     switch (IntNo) {
771     default:
772       break;
773     case Intrinsic::aarch64_neon_umaxv:
774     case Intrinsic::aarch64_neon_uminv: {
775       // Figure out the datatype of the vector operand. The UMINV instruction
776       // will zero extend the result, so we can mark as known zero all the
777       // bits larger than the element datatype. 32-bit or larget doesn't need
778       // this as those are legal types and will be handled by isel directly.
779       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
780       unsigned BitWidth = KnownZero.getBitWidth();
781       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
782         assert(BitWidth >= 8 && "Unexpected width!");
783         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
784         KnownZero |= Mask;
785       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
786         assert(BitWidth >= 16 && "Unexpected width!");
787         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
788         KnownZero |= Mask;
789       }
790       break;
791     } break;
792     }
793   }
794   }
795 }
796
797 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
798                                                   EVT) const {
799   return MVT::i64;
800 }
801
802 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
803                                                            unsigned AddrSpace,
804                                                            unsigned Align,
805                                                            bool *Fast) const {
806   if (Subtarget->requiresStrictAlign())
807     return false;
808
809   // FIXME: This is mostly true for Cyclone, but not necessarily others.
810   if (Fast) {
811     // FIXME: Define an attribute for slow unaligned accesses instead of
812     // relying on the CPU type as a proxy.
813     // On Cyclone, unaligned 128-bit stores are slow.
814     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
815             // See comments in performSTORECombine() for more details about
816             // these conditions.
817
818             // Code that uses clang vector extensions can mark that it
819             // wants unaligned accesses to be treated as fast by
820             // underspecifying alignment to be 1 or 2.
821             Align <= 2 ||
822
823             // Disregard v2i64. Memcpy lowering produces those and splitting
824             // them regresses performance on micro-benchmarks and olden/bh.
825             VT == MVT::v2i64;
826   }
827   return true;
828 }
829
830 FastISel *
831 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
832                                       const TargetLibraryInfo *libInfo) const {
833   return AArch64::createFastISel(funcInfo, libInfo);
834 }
835
836 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
837   switch ((AArch64ISD::NodeType)Opcode) {
838   case AArch64ISD::FIRST_NUMBER:      break;
839   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
840   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
841   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
842   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
843   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
844   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
845   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
846   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
847   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
848   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
849   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
850   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
851   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
852   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
853   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
854   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
855   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
856   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
857   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
858   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
859   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
860   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
861   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
862   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
863   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
864   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
865   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
866   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
867   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
868   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
869   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
870   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
871   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
872   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
873   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
874   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
875   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
876   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
877   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
878   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
879   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
880   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
881   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
882   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
883   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
884   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
885   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
886   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
887   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
888   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
889   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
890   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
891   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
892   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
893   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
894   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
895   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
896   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
897   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
898   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
899   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
900   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
901   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
902   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
903   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
904   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
905   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
906   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
907   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
908   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
909   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
910   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
911   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
912   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
913   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
914   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
915   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
916   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
917   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
918   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
919   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
920   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
921   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
922   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
923   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
924   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
925   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
926   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
927   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
928   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
929   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
930   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
931   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
932   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
933   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
934   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
935   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
936   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
937   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
938   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
939   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
940   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
941   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
942   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
943   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
944   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
945   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
946   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
947   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
948   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
949   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
950   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
951   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
952   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
953   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
954   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
955   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
956   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
957   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
958   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
959   }
960   return nullptr;
961 }
962
963 MachineBasicBlock *
964 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
965                                     MachineBasicBlock *MBB) const {
966   // We materialise the F128CSEL pseudo-instruction as some control flow and a
967   // phi node:
968
969   // OrigBB:
970   //     [... previous instrs leading to comparison ...]
971   //     b.ne TrueBB
972   //     b EndBB
973   // TrueBB:
974   //     ; Fallthrough
975   // EndBB:
976   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
977
978   MachineFunction *MF = MBB->getParent();
979   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
980   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
981   DebugLoc DL = MI->getDebugLoc();
982   MachineFunction::iterator It = ++MBB->getIterator();
983
984   unsigned DestReg = MI->getOperand(0).getReg();
985   unsigned IfTrueReg = MI->getOperand(1).getReg();
986   unsigned IfFalseReg = MI->getOperand(2).getReg();
987   unsigned CondCode = MI->getOperand(3).getImm();
988   bool NZCVKilled = MI->getOperand(4).isKill();
989
990   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
991   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
992   MF->insert(It, TrueBB);
993   MF->insert(It, EndBB);
994
995   // Transfer rest of current basic-block to EndBB
996   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
997                 MBB->end());
998   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
999
1000   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1001   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1002   MBB->addSuccessor(TrueBB);
1003   MBB->addSuccessor(EndBB);
1004
1005   // TrueBB falls through to the end.
1006   TrueBB->addSuccessor(EndBB);
1007
1008   if (!NZCVKilled) {
1009     TrueBB->addLiveIn(AArch64::NZCV);
1010     EndBB->addLiveIn(AArch64::NZCV);
1011   }
1012
1013   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1014       .addReg(IfTrueReg)
1015       .addMBB(TrueBB)
1016       .addReg(IfFalseReg)
1017       .addMBB(MBB);
1018
1019   MI->eraseFromParent();
1020   return EndBB;
1021 }
1022
1023 MachineBasicBlock *
1024 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1025                                                  MachineBasicBlock *BB) const {
1026   switch (MI->getOpcode()) {
1027   default:
1028 #ifndef NDEBUG
1029     MI->dump();
1030 #endif
1031     llvm_unreachable("Unexpected instruction for custom inserter!");
1032
1033   case AArch64::F128CSEL:
1034     return EmitF128CSEL(MI, BB);
1035
1036   case TargetOpcode::STACKMAP:
1037   case TargetOpcode::PATCHPOINT:
1038     return emitPatchPoint(MI, BB);
1039   }
1040 }
1041
1042 //===----------------------------------------------------------------------===//
1043 // AArch64 Lowering private implementation.
1044 //===----------------------------------------------------------------------===//
1045
1046 //===----------------------------------------------------------------------===//
1047 // Lowering Code
1048 //===----------------------------------------------------------------------===//
1049
1050 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1051 /// CC
1052 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1053   switch (CC) {
1054   default:
1055     llvm_unreachable("Unknown condition code!");
1056   case ISD::SETNE:
1057     return AArch64CC::NE;
1058   case ISD::SETEQ:
1059     return AArch64CC::EQ;
1060   case ISD::SETGT:
1061     return AArch64CC::GT;
1062   case ISD::SETGE:
1063     return AArch64CC::GE;
1064   case ISD::SETLT:
1065     return AArch64CC::LT;
1066   case ISD::SETLE:
1067     return AArch64CC::LE;
1068   case ISD::SETUGT:
1069     return AArch64CC::HI;
1070   case ISD::SETUGE:
1071     return AArch64CC::HS;
1072   case ISD::SETULT:
1073     return AArch64CC::LO;
1074   case ISD::SETULE:
1075     return AArch64CC::LS;
1076   }
1077 }
1078
1079 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1080 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1081                                   AArch64CC::CondCode &CondCode,
1082                                   AArch64CC::CondCode &CondCode2) {
1083   CondCode2 = AArch64CC::AL;
1084   switch (CC) {
1085   default:
1086     llvm_unreachable("Unknown FP condition!");
1087   case ISD::SETEQ:
1088   case ISD::SETOEQ:
1089     CondCode = AArch64CC::EQ;
1090     break;
1091   case ISD::SETGT:
1092   case ISD::SETOGT:
1093     CondCode = AArch64CC::GT;
1094     break;
1095   case ISD::SETGE:
1096   case ISD::SETOGE:
1097     CondCode = AArch64CC::GE;
1098     break;
1099   case ISD::SETOLT:
1100     CondCode = AArch64CC::MI;
1101     break;
1102   case ISD::SETOLE:
1103     CondCode = AArch64CC::LS;
1104     break;
1105   case ISD::SETONE:
1106     CondCode = AArch64CC::MI;
1107     CondCode2 = AArch64CC::GT;
1108     break;
1109   case ISD::SETO:
1110     CondCode = AArch64CC::VC;
1111     break;
1112   case ISD::SETUO:
1113     CondCode = AArch64CC::VS;
1114     break;
1115   case ISD::SETUEQ:
1116     CondCode = AArch64CC::EQ;
1117     CondCode2 = AArch64CC::VS;
1118     break;
1119   case ISD::SETUGT:
1120     CondCode = AArch64CC::HI;
1121     break;
1122   case ISD::SETUGE:
1123     CondCode = AArch64CC::PL;
1124     break;
1125   case ISD::SETLT:
1126   case ISD::SETULT:
1127     CondCode = AArch64CC::LT;
1128     break;
1129   case ISD::SETLE:
1130   case ISD::SETULE:
1131     CondCode = AArch64CC::LE;
1132     break;
1133   case ISD::SETNE:
1134   case ISD::SETUNE:
1135     CondCode = AArch64CC::NE;
1136     break;
1137   }
1138 }
1139
1140 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1141 /// CC usable with the vector instructions. Fewer operations are available
1142 /// without a real NZCV register, so we have to use less efficient combinations
1143 /// to get the same effect.
1144 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1145                                         AArch64CC::CondCode &CondCode,
1146                                         AArch64CC::CondCode &CondCode2,
1147                                         bool &Invert) {
1148   Invert = false;
1149   switch (CC) {
1150   default:
1151     // Mostly the scalar mappings work fine.
1152     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1153     break;
1154   case ISD::SETUO:
1155     Invert = true; // Fallthrough
1156   case ISD::SETO:
1157     CondCode = AArch64CC::MI;
1158     CondCode2 = AArch64CC::GE;
1159     break;
1160   case ISD::SETUEQ:
1161   case ISD::SETULT:
1162   case ISD::SETULE:
1163   case ISD::SETUGT:
1164   case ISD::SETUGE:
1165     // All of the compare-mask comparisons are ordered, but we can switch
1166     // between the two by a double inversion. E.g. ULE == !OGT.
1167     Invert = true;
1168     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1169     break;
1170   }
1171 }
1172
1173 static bool isLegalArithImmed(uint64_t C) {
1174   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1175   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1176 }
1177
1178 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1179                               SDLoc dl, SelectionDAG &DAG) {
1180   EVT VT = LHS.getValueType();
1181
1182   if (VT.isFloatingPoint())
1183     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1184
1185   // The CMP instruction is just an alias for SUBS, and representing it as
1186   // SUBS means that it's possible to get CSE with subtract operations.
1187   // A later phase can perform the optimization of setting the destination
1188   // register to WZR/XZR if it ends up being unused.
1189   unsigned Opcode = AArch64ISD::SUBS;
1190
1191   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1192       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1193     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1194     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1195     // can be set differently by this operation. It comes down to whether
1196     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1197     // everything is fine. If not then the optimization is wrong. Thus general
1198     // comparisons are only valid if op2 != 0.
1199
1200     // So, finally, the only LLVM-native comparisons that don't mention C and V
1201     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1202     // the absence of information about op2.
1203     Opcode = AArch64ISD::ADDS;
1204     RHS = RHS.getOperand(1);
1205   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1206              !isUnsignedIntSetCC(CC)) {
1207     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1208     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1209     // of the signed comparisons.
1210     Opcode = AArch64ISD::ANDS;
1211     RHS = LHS.getOperand(1);
1212     LHS = LHS.getOperand(0);
1213   }
1214
1215   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1216       .getValue(1);
1217 }
1218
1219 /// \defgroup AArch64CCMP CMP;CCMP matching
1220 ///
1221 /// These functions deal with the formation of CMP;CCMP;... sequences.
1222 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1223 /// a comparison. They set the NZCV flags to a predefined value if their
1224 /// predicate is false. This allows to express arbitrary conjunctions, for
1225 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1226 /// expressed as:
1227 ///   cmp A
1228 ///   ccmp B, inv(CB), CA
1229 ///   check for CB flags
1230 ///
1231 /// In general we can create code for arbitrary "... (and (and A B) C)"
1232 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1233 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1234 /// negation operations:
1235 /// We can negate the results of a single comparison by inverting the flags
1236 /// used when the predicate fails and inverting the flags tested in the next
1237 /// instruction; We can also negate the results of the whole previous
1238 /// conditional compare sequence by inverting the flags tested in the next
1239 /// instruction. However there is no way to negate the result of a partial
1240 /// sequence.
1241 ///
1242 /// Therefore on encountering an "or" expression we can negate the subtree on
1243 /// one side and have to be able to push the negate to the leafs of the subtree
1244 /// on the other side (see also the comments in code). As complete example:
1245 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1246 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1247 /// is transformed to
1248 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1249 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1250 /// and implemented as:
1251 ///   cmp C
1252 ///   ccmp D, inv(CD), CC
1253 ///   ccmp A, CA, inv(CD)
1254 ///   ccmp B, CB, inv(CA)
1255 ///   check for CB flags
1256 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1257 /// by conditional compare sequences.
1258 /// @{
1259
1260 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1261 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1262                                          ISD::CondCode CC, SDValue CCOp,
1263                                          SDValue Condition, unsigned NZCV,
1264                                          SDLoc DL, SelectionDAG &DAG) {
1265   unsigned Opcode = 0;
1266   if (LHS.getValueType().isFloatingPoint())
1267     Opcode = AArch64ISD::FCCMP;
1268   else if (RHS.getOpcode() == ISD::SUB) {
1269     SDValue SubOp0 = RHS.getOperand(0);
1270     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1271         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1272         Opcode = AArch64ISD::CCMN;
1273         RHS = RHS.getOperand(1);
1274       }
1275   }
1276   if (Opcode == 0)
1277     Opcode = AArch64ISD::CCMP;
1278
1279   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1280   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1281 }
1282
1283 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1284 /// CanPushNegate is set to true if we can push a negate operation through
1285 /// the tree in a was that we are left with AND operations and negate operations
1286 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1287 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1288 /// brought into such a form.
1289 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1290                                          unsigned Depth = 0) {
1291   if (!Val.hasOneUse())
1292     return false;
1293   unsigned Opcode = Val->getOpcode();
1294   if (Opcode == ISD::SETCC) {
1295     CanPushNegate = true;
1296     return true;
1297   }
1298   // Protect against stack overflow.
1299   if (Depth > 15)
1300     return false;
1301   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1302     SDValue O0 = Val->getOperand(0);
1303     SDValue O1 = Val->getOperand(1);
1304     bool CanPushNegateL;
1305     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1306       return false;
1307     bool CanPushNegateR;
1308     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1309       return false;
1310     // We cannot push a negate through an AND operation (it would become an OR),
1311     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1312     // push the negate through the x/y subtrees.
1313     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1314     return true;
1315   }
1316   return false;
1317 }
1318
1319 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1320 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1321 /// Tries to transform the given i1 producing node @p Val to a series compare
1322 /// and conditional compare operations. @returns an NZCV flags producing node
1323 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1324 /// transformation was not possible.
1325 /// On recursive invocations @p PushNegate may be set to true to have negation
1326 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1327 /// for the comparisons in the current subtree; @p Depth limits the search
1328 /// depth to avoid stack overflow.
1329 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1330     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1331     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1332     unsigned Depth = 0) {
1333   // We're at a tree leaf, produce a conditional comparison operation.
1334   unsigned Opcode = Val->getOpcode();
1335   if (Opcode == ISD::SETCC) {
1336     SDValue LHS = Val->getOperand(0);
1337     SDValue RHS = Val->getOperand(1);
1338     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1339     bool isInteger = LHS.getValueType().isInteger();
1340     if (PushNegate)
1341       CC = getSetCCInverse(CC, isInteger);
1342     SDLoc DL(Val);
1343     // Determine OutCC and handle FP special case.
1344     if (isInteger) {
1345       OutCC = changeIntCCToAArch64CC(CC);
1346     } else {
1347       assert(LHS.getValueType().isFloatingPoint());
1348       AArch64CC::CondCode ExtraCC;
1349       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1350       // Surpisingly some floating point conditions can't be tested with a
1351       // single condition code. Construct an additional comparison in this case.
1352       // See comment below on how we deal with OR conditions.
1353       if (ExtraCC != AArch64CC::AL) {
1354         SDValue ExtraCmp;
1355         if (!CCOp.getNode())
1356           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1357         else {
1358           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1359           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1360           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1361           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1362                                                NZCV, DL, DAG);
1363         }
1364         CCOp = ExtraCmp;
1365         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1366         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1367       }
1368     }
1369
1370     // Produce a normal comparison if we are first in the chain
1371     if (!CCOp.getNode())
1372       return emitComparison(LHS, RHS, CC, DL, DAG);
1373     // Otherwise produce a ccmp.
1374     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1375     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1376     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1377     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1378                                      DAG);
1379   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1380     return SDValue();
1381
1382   assert((Opcode == ISD::OR || !PushNegate)
1383          && "Can only push negate through OR operation");
1384
1385   // Check if both sides can be transformed.
1386   SDValue LHS = Val->getOperand(0);
1387   SDValue RHS = Val->getOperand(1);
1388   bool CanPushNegateL;
1389   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1390     return SDValue();
1391   bool CanPushNegateR;
1392   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1393     return SDValue();
1394
1395   // Do we need to negate our operands?
1396   bool NegateOperands = Opcode == ISD::OR;
1397   // We can negate the results of all previous operations by inverting the
1398   // predicate flags giving us a free negation for one side. For the other side
1399   // we need to be able to push the negation to the leafs of the tree.
1400   if (NegateOperands) {
1401     if (!CanPushNegateL && !CanPushNegateR)
1402       return SDValue();
1403     // Order the side where we can push the negate through to LHS.
1404     if (!CanPushNegateL && CanPushNegateR)
1405       std::swap(LHS, RHS);
1406   } else {
1407     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1408     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1409     if (NeedsNegOutL && NeedsNegOutR)
1410       return SDValue();
1411     // Order the side where we need to negate the output flags to RHS so it
1412     // gets emitted first.
1413     if (NeedsNegOutL)
1414       std::swap(LHS, RHS);
1415   }
1416
1417   // Emit RHS. If we want to negate the tree we only need to push a negate
1418   // through if we are already in a PushNegate case, otherwise we can negate
1419   // the "flags to test" afterwards.
1420   AArch64CC::CondCode RHSCC;
1421   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1422                                                 CCOp, Predicate, Depth+1);
1423   if (NegateOperands && !PushNegate)
1424     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1425   // Emit LHS. We must push the negate through if we need to negate it.
1426   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1427                                                 CmpR, RHSCC, Depth+1);
1428   // If we transformed an OR to and AND then we have to negate the result
1429   // (or absorb a PushNegate resulting in a double negation).
1430   if (Opcode == ISD::OR && !PushNegate)
1431     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1432   return CmpL;
1433 }
1434
1435 /// @}
1436
1437 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1438                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1439   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1440     EVT VT = RHS.getValueType();
1441     uint64_t C = RHSC->getZExtValue();
1442     if (!isLegalArithImmed(C)) {
1443       // Constant does not fit, try adjusting it by one?
1444       switch (CC) {
1445       default:
1446         break;
1447       case ISD::SETLT:
1448       case ISD::SETGE:
1449         if ((VT == MVT::i32 && C != 0x80000000 &&
1450              isLegalArithImmed((uint32_t)(C - 1))) ||
1451             (VT == MVT::i64 && C != 0x80000000ULL &&
1452              isLegalArithImmed(C - 1ULL))) {
1453           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1454           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1455           RHS = DAG.getConstant(C, dl, VT);
1456         }
1457         break;
1458       case ISD::SETULT:
1459       case ISD::SETUGE:
1460         if ((VT == MVT::i32 && C != 0 &&
1461              isLegalArithImmed((uint32_t)(C - 1))) ||
1462             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1463           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1464           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1465           RHS = DAG.getConstant(C, dl, VT);
1466         }
1467         break;
1468       case ISD::SETLE:
1469       case ISD::SETGT:
1470         if ((VT == MVT::i32 && C != INT32_MAX &&
1471              isLegalArithImmed((uint32_t)(C + 1))) ||
1472             (VT == MVT::i64 && C != INT64_MAX &&
1473              isLegalArithImmed(C + 1ULL))) {
1474           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1475           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1476           RHS = DAG.getConstant(C, dl, VT);
1477         }
1478         break;
1479       case ISD::SETULE:
1480       case ISD::SETUGT:
1481         if ((VT == MVT::i32 && C != UINT32_MAX &&
1482              isLegalArithImmed((uint32_t)(C + 1))) ||
1483             (VT == MVT::i64 && C != UINT64_MAX &&
1484              isLegalArithImmed(C + 1ULL))) {
1485           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1486           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1487           RHS = DAG.getConstant(C, dl, VT);
1488         }
1489         break;
1490       }
1491     }
1492   }
1493   SDValue Cmp;
1494   AArch64CC::CondCode AArch64CC;
1495   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1496     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1497
1498     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1499     // For the i8 operand, the largest immediate is 255, so this can be easily
1500     // encoded in the compare instruction. For the i16 operand, however, the
1501     // largest immediate cannot be encoded in the compare.
1502     // Therefore, use a sign extending load and cmn to avoid materializing the
1503     // -1 constant. For example,
1504     // movz w1, #65535
1505     // ldrh w0, [x0, #0]
1506     // cmp w0, w1
1507     // >
1508     // ldrsh w0, [x0, #0]
1509     // cmn w0, #1
1510     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1511     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1512     // ensure both the LHS and RHS are truly zero extended and to make sure the
1513     // transformation is profitable.
1514     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1515         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1516         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1517         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1518       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1519       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1520         SDValue SExt =
1521             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1522                         DAG.getValueType(MVT::i16));
1523         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1524                                                    RHS.getValueType()),
1525                              CC, dl, DAG);
1526         AArch64CC = changeIntCCToAArch64CC(CC);
1527       }
1528     }
1529
1530     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1531       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1532         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1533           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1534       }
1535     }
1536   }
1537
1538   if (!Cmp) {
1539     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1540     AArch64CC = changeIntCCToAArch64CC(CC);
1541   }
1542   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1543   return Cmp;
1544 }
1545
1546 static std::pair<SDValue, SDValue>
1547 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1548   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1549          "Unsupported value type");
1550   SDValue Value, Overflow;
1551   SDLoc DL(Op);
1552   SDValue LHS = Op.getOperand(0);
1553   SDValue RHS = Op.getOperand(1);
1554   unsigned Opc = 0;
1555   switch (Op.getOpcode()) {
1556   default:
1557     llvm_unreachable("Unknown overflow instruction!");
1558   case ISD::SADDO:
1559     Opc = AArch64ISD::ADDS;
1560     CC = AArch64CC::VS;
1561     break;
1562   case ISD::UADDO:
1563     Opc = AArch64ISD::ADDS;
1564     CC = AArch64CC::HS;
1565     break;
1566   case ISD::SSUBO:
1567     Opc = AArch64ISD::SUBS;
1568     CC = AArch64CC::VS;
1569     break;
1570   case ISD::USUBO:
1571     Opc = AArch64ISD::SUBS;
1572     CC = AArch64CC::LO;
1573     break;
1574   // Multiply needs a little bit extra work.
1575   case ISD::SMULO:
1576   case ISD::UMULO: {
1577     CC = AArch64CC::NE;
1578     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1579     if (Op.getValueType() == MVT::i32) {
1580       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1581       // For a 32 bit multiply with overflow check we want the instruction
1582       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1583       // need to generate the following pattern:
1584       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1585       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1586       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1587       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1588       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1589                                 DAG.getConstant(0, DL, MVT::i64));
1590       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1591       // operation. We need to clear out the upper 32 bits, because we used a
1592       // widening multiply that wrote all 64 bits. In the end this should be a
1593       // noop.
1594       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1595       if (IsSigned) {
1596         // The signed overflow check requires more than just a simple check for
1597         // any bit set in the upper 32 bits of the result. These bits could be
1598         // just the sign bits of a negative number. To perform the overflow
1599         // check we have to arithmetic shift right the 32nd bit of the result by
1600         // 31 bits. Then we compare the result to the upper 32 bits.
1601         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1602                                         DAG.getConstant(32, DL, MVT::i64));
1603         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1604         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1605                                         DAG.getConstant(31, DL, MVT::i64));
1606         // It is important that LowerBits is last, otherwise the arithmetic
1607         // shift will not be folded into the compare (SUBS).
1608         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1609         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1610                        .getValue(1);
1611       } else {
1612         // The overflow check for unsigned multiply is easy. We only need to
1613         // check if any of the upper 32 bits are set. This can be done with a
1614         // CMP (shifted register). For that we need to generate the following
1615         // pattern:
1616         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1617         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1618                                         DAG.getConstant(32, DL, MVT::i64));
1619         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1620         Overflow =
1621             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1622                         DAG.getConstant(0, DL, MVT::i64),
1623                         UpperBits).getValue(1);
1624       }
1625       break;
1626     }
1627     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1628     // For the 64 bit multiply
1629     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1630     if (IsSigned) {
1631       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1632       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1633                                       DAG.getConstant(63, DL, MVT::i64));
1634       // It is important that LowerBits is last, otherwise the arithmetic
1635       // shift will not be folded into the compare (SUBS).
1636       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1637       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1638                      .getValue(1);
1639     } else {
1640       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1641       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1642       Overflow =
1643           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1644                       DAG.getConstant(0, DL, MVT::i64),
1645                       UpperBits).getValue(1);
1646     }
1647     break;
1648   }
1649   } // switch (...)
1650
1651   if (Opc) {
1652     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1653
1654     // Emit the AArch64 operation with overflow check.
1655     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1656     Overflow = Value.getValue(1);
1657   }
1658   return std::make_pair(Value, Overflow);
1659 }
1660
1661 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1662                                              RTLIB::Libcall Call) const {
1663   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1664   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1665 }
1666
1667 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1668   SDValue Sel = Op.getOperand(0);
1669   SDValue Other = Op.getOperand(1);
1670
1671   // If neither operand is a SELECT_CC, give up.
1672   if (Sel.getOpcode() != ISD::SELECT_CC)
1673     std::swap(Sel, Other);
1674   if (Sel.getOpcode() != ISD::SELECT_CC)
1675     return Op;
1676
1677   // The folding we want to perform is:
1678   // (xor x, (select_cc a, b, cc, 0, -1) )
1679   //   -->
1680   // (csel x, (xor x, -1), cc ...)
1681   //
1682   // The latter will get matched to a CSINV instruction.
1683
1684   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1685   SDValue LHS = Sel.getOperand(0);
1686   SDValue RHS = Sel.getOperand(1);
1687   SDValue TVal = Sel.getOperand(2);
1688   SDValue FVal = Sel.getOperand(3);
1689   SDLoc dl(Sel);
1690
1691   // FIXME: This could be generalized to non-integer comparisons.
1692   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1693     return Op;
1694
1695   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1696   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1697
1698   // The values aren't constants, this isn't the pattern we're looking for.
1699   if (!CFVal || !CTVal)
1700     return Op;
1701
1702   // We can commute the SELECT_CC by inverting the condition.  This
1703   // might be needed to make this fit into a CSINV pattern.
1704   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1705     std::swap(TVal, FVal);
1706     std::swap(CTVal, CFVal);
1707     CC = ISD::getSetCCInverse(CC, true);
1708   }
1709
1710   // If the constants line up, perform the transform!
1711   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1712     SDValue CCVal;
1713     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1714
1715     FVal = Other;
1716     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1717                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1718
1719     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1720                        CCVal, Cmp);
1721   }
1722
1723   return Op;
1724 }
1725
1726 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1727   EVT VT = Op.getValueType();
1728
1729   // Let legalize expand this if it isn't a legal type yet.
1730   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1731     return SDValue();
1732
1733   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1734
1735   unsigned Opc;
1736   bool ExtraOp = false;
1737   switch (Op.getOpcode()) {
1738   default:
1739     llvm_unreachable("Invalid code");
1740   case ISD::ADDC:
1741     Opc = AArch64ISD::ADDS;
1742     break;
1743   case ISD::SUBC:
1744     Opc = AArch64ISD::SUBS;
1745     break;
1746   case ISD::ADDE:
1747     Opc = AArch64ISD::ADCS;
1748     ExtraOp = true;
1749     break;
1750   case ISD::SUBE:
1751     Opc = AArch64ISD::SBCS;
1752     ExtraOp = true;
1753     break;
1754   }
1755
1756   if (!ExtraOp)
1757     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1758   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1759                      Op.getOperand(2));
1760 }
1761
1762 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1763   // Let legalize expand this if it isn't a legal type yet.
1764   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1765     return SDValue();
1766
1767   SDLoc dl(Op);
1768   AArch64CC::CondCode CC;
1769   // The actual operation that sets the overflow or carry flag.
1770   SDValue Value, Overflow;
1771   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1772
1773   // We use 0 and 1 as false and true values.
1774   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1775   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1776
1777   // We use an inverted condition, because the conditional select is inverted
1778   // too. This will allow it to be selected to a single instruction:
1779   // CSINC Wd, WZR, WZR, invert(cond).
1780   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1781   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1782                          CCVal, Overflow);
1783
1784   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1785   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1786 }
1787
1788 // Prefetch operands are:
1789 // 1: Address to prefetch
1790 // 2: bool isWrite
1791 // 3: int locality (0 = no locality ... 3 = extreme locality)
1792 // 4: bool isDataCache
1793 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1794   SDLoc DL(Op);
1795   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1796   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1797   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1798
1799   bool IsStream = !Locality;
1800   // When the locality number is set
1801   if (Locality) {
1802     // The front-end should have filtered out the out-of-range values
1803     assert(Locality <= 3 && "Prefetch locality out-of-range");
1804     // The locality degree is the opposite of the cache speed.
1805     // Put the number the other way around.
1806     // The encoding starts at 0 for level 1
1807     Locality = 3 - Locality;
1808   }
1809
1810   // built the mask value encoding the expected behavior.
1811   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1812                    (!IsData << 3) |     // IsDataCache bit
1813                    (Locality << 1) |    // Cache level bits
1814                    (unsigned)IsStream;  // Stream bit
1815   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1816                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1817 }
1818
1819 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1820                                               SelectionDAG &DAG) const {
1821   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1822
1823   RTLIB::Libcall LC;
1824   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1825
1826   return LowerF128Call(Op, DAG, LC);
1827 }
1828
1829 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1830                                              SelectionDAG &DAG) const {
1831   if (Op.getOperand(0).getValueType() != MVT::f128) {
1832     // It's legal except when f128 is involved
1833     return Op;
1834   }
1835
1836   RTLIB::Libcall LC;
1837   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1838
1839   // FP_ROUND node has a second operand indicating whether it is known to be
1840   // precise. That doesn't take part in the LibCall so we can't directly use
1841   // LowerF128Call.
1842   SDValue SrcVal = Op.getOperand(0);
1843   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1844                      SDLoc(Op)).first;
1845 }
1846
1847 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1848   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1849   // Any additional optimization in this function should be recorded
1850   // in the cost tables.
1851   EVT InVT = Op.getOperand(0).getValueType();
1852   EVT VT = Op.getValueType();
1853   unsigned NumElts = InVT.getVectorNumElements();
1854
1855   // f16 vectors are promoted to f32 before a conversion.
1856   if (InVT.getVectorElementType() == MVT::f16) {
1857     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1858     SDLoc dl(Op);
1859     return DAG.getNode(
1860         Op.getOpcode(), dl, Op.getValueType(),
1861         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1862   }
1863
1864   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1865     SDLoc dl(Op);
1866     SDValue Cv =
1867         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1868                     Op.getOperand(0));
1869     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1870   }
1871
1872   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1873     SDLoc dl(Op);
1874     MVT ExtVT =
1875         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1876                          VT.getVectorNumElements());
1877     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1878     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1879   }
1880
1881   // Type changing conversions are illegal.
1882   return Op;
1883 }
1884
1885 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1886                                               SelectionDAG &DAG) const {
1887   if (Op.getOperand(0).getValueType().isVector())
1888     return LowerVectorFP_TO_INT(Op, DAG);
1889
1890   // f16 conversions are promoted to f32.
1891   if (Op.getOperand(0).getValueType() == MVT::f16) {
1892     SDLoc dl(Op);
1893     return DAG.getNode(
1894         Op.getOpcode(), dl, Op.getValueType(),
1895         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1896   }
1897
1898   if (Op.getOperand(0).getValueType() != MVT::f128) {
1899     // It's legal except when f128 is involved
1900     return Op;
1901   }
1902
1903   RTLIB::Libcall LC;
1904   if (Op.getOpcode() == ISD::FP_TO_SINT)
1905     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1906   else
1907     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1908
1909   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1910   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1911 }
1912
1913 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1914   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1915   // Any additional optimization in this function should be recorded
1916   // in the cost tables.
1917   EVT VT = Op.getValueType();
1918   SDLoc dl(Op);
1919   SDValue In = Op.getOperand(0);
1920   EVT InVT = In.getValueType();
1921
1922   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1923     MVT CastVT =
1924         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1925                          InVT.getVectorNumElements());
1926     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1927     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1928   }
1929
1930   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1931     unsigned CastOpc =
1932         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1933     EVT CastVT = VT.changeVectorElementTypeToInteger();
1934     In = DAG.getNode(CastOpc, dl, CastVT, In);
1935     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1936   }
1937
1938   return Op;
1939 }
1940
1941 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1942                                             SelectionDAG &DAG) const {
1943   if (Op.getValueType().isVector())
1944     return LowerVectorINT_TO_FP(Op, DAG);
1945
1946   // f16 conversions are promoted to f32.
1947   if (Op.getValueType() == MVT::f16) {
1948     SDLoc dl(Op);
1949     return DAG.getNode(
1950         ISD::FP_ROUND, dl, MVT::f16,
1951         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1952         DAG.getIntPtrConstant(0, dl));
1953   }
1954
1955   // i128 conversions are libcalls.
1956   if (Op.getOperand(0).getValueType() == MVT::i128)
1957     return SDValue();
1958
1959   // Other conversions are legal, unless it's to the completely software-based
1960   // fp128.
1961   if (Op.getValueType() != MVT::f128)
1962     return Op;
1963
1964   RTLIB::Libcall LC;
1965   if (Op.getOpcode() == ISD::SINT_TO_FP)
1966     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1967   else
1968     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1969
1970   return LowerF128Call(Op, DAG, LC);
1971 }
1972
1973 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1974                                             SelectionDAG &DAG) const {
1975   // For iOS, we want to call an alternative entry point: __sincos_stret,
1976   // which returns the values in two S / D registers.
1977   SDLoc dl(Op);
1978   SDValue Arg = Op.getOperand(0);
1979   EVT ArgVT = Arg.getValueType();
1980   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1981
1982   ArgListTy Args;
1983   ArgListEntry Entry;
1984
1985   Entry.Node = Arg;
1986   Entry.Ty = ArgTy;
1987   Entry.isSExt = false;
1988   Entry.isZExt = false;
1989   Args.push_back(Entry);
1990
1991   const char *LibcallName =
1992       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1993   SDValue Callee =
1994       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1995
1996   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1997   TargetLowering::CallLoweringInfo CLI(DAG);
1998   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1999     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
2000
2001   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2002   return CallResult.first;
2003 }
2004
2005 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2006   if (Op.getValueType() != MVT::f16)
2007     return SDValue();
2008
2009   assert(Op.getOperand(0).getValueType() == MVT::i16);
2010   SDLoc DL(Op);
2011
2012   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2013   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2014   return SDValue(
2015       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2016                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2017       0);
2018 }
2019
2020 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2021   if (OrigVT.getSizeInBits() >= 64)
2022     return OrigVT;
2023
2024   assert(OrigVT.isSimple() && "Expecting a simple value type");
2025
2026   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2027   switch (OrigSimpleTy) {
2028   default: llvm_unreachable("Unexpected Vector Type");
2029   case MVT::v2i8:
2030   case MVT::v2i16:
2031      return MVT::v2i32;
2032   case MVT::v4i8:
2033     return  MVT::v4i16;
2034   }
2035 }
2036
2037 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2038                                                  const EVT &OrigTy,
2039                                                  const EVT &ExtTy,
2040                                                  unsigned ExtOpcode) {
2041   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2042   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2043   // 64-bits we need to insert a new extension so that it will be 64-bits.
2044   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2045   if (OrigTy.getSizeInBits() >= 64)
2046     return N;
2047
2048   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2049   EVT NewVT = getExtensionTo64Bits(OrigTy);
2050
2051   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2052 }
2053
2054 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2055                                    bool isSigned) {
2056   EVT VT = N->getValueType(0);
2057
2058   if (N->getOpcode() != ISD::BUILD_VECTOR)
2059     return false;
2060
2061   for (const SDValue &Elt : N->op_values()) {
2062     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2063       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2064       unsigned HalfSize = EltSize / 2;
2065       if (isSigned) {
2066         if (!isIntN(HalfSize, C->getSExtValue()))
2067           return false;
2068       } else {
2069         if (!isUIntN(HalfSize, C->getZExtValue()))
2070           return false;
2071       }
2072       continue;
2073     }
2074     return false;
2075   }
2076
2077   return true;
2078 }
2079
2080 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2081   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2082     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2083                                              N->getOperand(0)->getValueType(0),
2084                                              N->getValueType(0),
2085                                              N->getOpcode());
2086
2087   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2088   EVT VT = N->getValueType(0);
2089   SDLoc dl(N);
2090   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2091   unsigned NumElts = VT.getVectorNumElements();
2092   MVT TruncVT = MVT::getIntegerVT(EltSize);
2093   SmallVector<SDValue, 8> Ops;
2094   for (unsigned i = 0; i != NumElts; ++i) {
2095     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2096     const APInt &CInt = C->getAPIntValue();
2097     // Element types smaller than 32 bits are not legal, so use i32 elements.
2098     // The values are implicitly truncated so sext vs. zext doesn't matter.
2099     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2100   }
2101   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2102                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2103 }
2104
2105 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2106   if (N->getOpcode() == ISD::SIGN_EXTEND)
2107     return true;
2108   if (isExtendedBUILD_VECTOR(N, DAG, true))
2109     return true;
2110   return false;
2111 }
2112
2113 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2114   if (N->getOpcode() == ISD::ZERO_EXTEND)
2115     return true;
2116   if (isExtendedBUILD_VECTOR(N, DAG, false))
2117     return true;
2118   return false;
2119 }
2120
2121 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2122   unsigned Opcode = N->getOpcode();
2123   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2124     SDNode *N0 = N->getOperand(0).getNode();
2125     SDNode *N1 = N->getOperand(1).getNode();
2126     return N0->hasOneUse() && N1->hasOneUse() &&
2127       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2128   }
2129   return false;
2130 }
2131
2132 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2133   unsigned Opcode = N->getOpcode();
2134   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2135     SDNode *N0 = N->getOperand(0).getNode();
2136     SDNode *N1 = N->getOperand(1).getNode();
2137     return N0->hasOneUse() && N1->hasOneUse() &&
2138       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2139   }
2140   return false;
2141 }
2142
2143 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2144   // Multiplications are only custom-lowered for 128-bit vectors so that
2145   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2146   EVT VT = Op.getValueType();
2147   assert(VT.is128BitVector() && VT.isInteger() &&
2148          "unexpected type for custom-lowering ISD::MUL");
2149   SDNode *N0 = Op.getOperand(0).getNode();
2150   SDNode *N1 = Op.getOperand(1).getNode();
2151   unsigned NewOpc = 0;
2152   bool isMLA = false;
2153   bool isN0SExt = isSignExtended(N0, DAG);
2154   bool isN1SExt = isSignExtended(N1, DAG);
2155   if (isN0SExt && isN1SExt)
2156     NewOpc = AArch64ISD::SMULL;
2157   else {
2158     bool isN0ZExt = isZeroExtended(N0, DAG);
2159     bool isN1ZExt = isZeroExtended(N1, DAG);
2160     if (isN0ZExt && isN1ZExt)
2161       NewOpc = AArch64ISD::UMULL;
2162     else if (isN1SExt || isN1ZExt) {
2163       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2164       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2165       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2166         NewOpc = AArch64ISD::SMULL;
2167         isMLA = true;
2168       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2169         NewOpc =  AArch64ISD::UMULL;
2170         isMLA = true;
2171       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2172         std::swap(N0, N1);
2173         NewOpc =  AArch64ISD::UMULL;
2174         isMLA = true;
2175       }
2176     }
2177
2178     if (!NewOpc) {
2179       if (VT == MVT::v2i64)
2180         // Fall through to expand this.  It is not legal.
2181         return SDValue();
2182       else
2183         // Other vector multiplications are legal.
2184         return Op;
2185     }
2186   }
2187
2188   // Legalize to a S/UMULL instruction
2189   SDLoc DL(Op);
2190   SDValue Op0;
2191   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2192   if (!isMLA) {
2193     Op0 = skipExtensionForVectorMULL(N0, DAG);
2194     assert(Op0.getValueType().is64BitVector() &&
2195            Op1.getValueType().is64BitVector() &&
2196            "unexpected types for extended operands to VMULL");
2197     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2198   }
2199   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2200   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2201   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2202   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2203   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2204   EVT Op1VT = Op1.getValueType();
2205   return DAG.getNode(N0->getOpcode(), DL, VT,
2206                      DAG.getNode(NewOpc, DL, VT,
2207                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2208                      DAG.getNode(NewOpc, DL, VT,
2209                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2210 }
2211
2212 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2213                                                      SelectionDAG &DAG) const {
2214   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2215   SDLoc dl(Op);
2216   switch (IntNo) {
2217   default: return SDValue();    // Don't custom lower most intrinsics.
2218   case Intrinsic::aarch64_thread_pointer: {
2219     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2220     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2221   }
2222   case Intrinsic::aarch64_neon_smax:
2223     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2224                        Op.getOperand(1), Op.getOperand(2));
2225   case Intrinsic::aarch64_neon_umax:
2226     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2227                        Op.getOperand(1), Op.getOperand(2));
2228   case Intrinsic::aarch64_neon_smin:
2229     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2230                        Op.getOperand(1), Op.getOperand(2));
2231   case Intrinsic::aarch64_neon_umin:
2232     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2233                        Op.getOperand(1), Op.getOperand(2));
2234   }
2235 }
2236
2237 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2238                                               SelectionDAG &DAG) const {
2239   switch (Op.getOpcode()) {
2240   default:
2241     llvm_unreachable("unimplemented operand");
2242     return SDValue();
2243   case ISD::BITCAST:
2244     return LowerBITCAST(Op, DAG);
2245   case ISD::GlobalAddress:
2246     return LowerGlobalAddress(Op, DAG);
2247   case ISD::GlobalTLSAddress:
2248     return LowerGlobalTLSAddress(Op, DAG);
2249   case ISD::SETCC:
2250     return LowerSETCC(Op, DAG);
2251   case ISD::BR_CC:
2252     return LowerBR_CC(Op, DAG);
2253   case ISD::SELECT:
2254     return LowerSELECT(Op, DAG);
2255   case ISD::SELECT_CC:
2256     return LowerSELECT_CC(Op, DAG);
2257   case ISD::JumpTable:
2258     return LowerJumpTable(Op, DAG);
2259   case ISD::ConstantPool:
2260     return LowerConstantPool(Op, DAG);
2261   case ISD::BlockAddress:
2262     return LowerBlockAddress(Op, DAG);
2263   case ISD::VASTART:
2264     return LowerVASTART(Op, DAG);
2265   case ISD::VACOPY:
2266     return LowerVACOPY(Op, DAG);
2267   case ISD::VAARG:
2268     return LowerVAARG(Op, DAG);
2269   case ISD::ADDC:
2270   case ISD::ADDE:
2271   case ISD::SUBC:
2272   case ISD::SUBE:
2273     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2274   case ISD::SADDO:
2275   case ISD::UADDO:
2276   case ISD::SSUBO:
2277   case ISD::USUBO:
2278   case ISD::SMULO:
2279   case ISD::UMULO:
2280     return LowerXALUO(Op, DAG);
2281   case ISD::FADD:
2282     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2283   case ISD::FSUB:
2284     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2285   case ISD::FMUL:
2286     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2287   case ISD::FDIV:
2288     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2289   case ISD::FP_ROUND:
2290     return LowerFP_ROUND(Op, DAG);
2291   case ISD::FP_EXTEND:
2292     return LowerFP_EXTEND(Op, DAG);
2293   case ISD::FRAMEADDR:
2294     return LowerFRAMEADDR(Op, DAG);
2295   case ISD::RETURNADDR:
2296     return LowerRETURNADDR(Op, DAG);
2297   case ISD::INSERT_VECTOR_ELT:
2298     return LowerINSERT_VECTOR_ELT(Op, DAG);
2299   case ISD::EXTRACT_VECTOR_ELT:
2300     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2301   case ISD::BUILD_VECTOR:
2302     return LowerBUILD_VECTOR(Op, DAG);
2303   case ISD::VECTOR_SHUFFLE:
2304     return LowerVECTOR_SHUFFLE(Op, DAG);
2305   case ISD::EXTRACT_SUBVECTOR:
2306     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2307   case ISD::SRA:
2308   case ISD::SRL:
2309   case ISD::SHL:
2310     return LowerVectorSRA_SRL_SHL(Op, DAG);
2311   case ISD::SHL_PARTS:
2312     return LowerShiftLeftParts(Op, DAG);
2313   case ISD::SRL_PARTS:
2314   case ISD::SRA_PARTS:
2315     return LowerShiftRightParts(Op, DAG);
2316   case ISD::CTPOP:
2317     return LowerCTPOP(Op, DAG);
2318   case ISD::FCOPYSIGN:
2319     return LowerFCOPYSIGN(Op, DAG);
2320   case ISD::AND:
2321     return LowerVectorAND(Op, DAG);
2322   case ISD::OR:
2323     return LowerVectorOR(Op, DAG);
2324   case ISD::XOR:
2325     return LowerXOR(Op, DAG);
2326   case ISD::PREFETCH:
2327     return LowerPREFETCH(Op, DAG);
2328   case ISD::SINT_TO_FP:
2329   case ISD::UINT_TO_FP:
2330     return LowerINT_TO_FP(Op, DAG);
2331   case ISD::FP_TO_SINT:
2332   case ISD::FP_TO_UINT:
2333     return LowerFP_TO_INT(Op, DAG);
2334   case ISD::FSINCOS:
2335     return LowerFSINCOS(Op, DAG);
2336   case ISD::MUL:
2337     return LowerMUL(Op, DAG);
2338   case ISD::INTRINSIC_WO_CHAIN:
2339     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2340   }
2341 }
2342
2343 /// getFunctionAlignment - Return the Log2 alignment of this function.
2344 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2345   return 2;
2346 }
2347
2348 //===----------------------------------------------------------------------===//
2349 //                      Calling Convention Implementation
2350 //===----------------------------------------------------------------------===//
2351
2352 #include "AArch64GenCallingConv.inc"
2353
2354 /// Selects the correct CCAssignFn for a given CallingConvention value.
2355 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2356                                                      bool IsVarArg) const {
2357   switch (CC) {
2358   default:
2359     llvm_unreachable("Unsupported calling convention.");
2360   case CallingConv::WebKit_JS:
2361     return CC_AArch64_WebKit_JS;
2362   case CallingConv::GHC:
2363     return CC_AArch64_GHC;
2364   case CallingConv::C:
2365   case CallingConv::Fast:
2366     if (!Subtarget->isTargetDarwin())
2367       return CC_AArch64_AAPCS;
2368     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2369   }
2370 }
2371
2372 SDValue AArch64TargetLowering::LowerFormalArguments(
2373     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2374     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2375     SmallVectorImpl<SDValue> &InVals) const {
2376   MachineFunction &MF = DAG.getMachineFunction();
2377   MachineFrameInfo *MFI = MF.getFrameInfo();
2378
2379   // Assign locations to all of the incoming arguments.
2380   SmallVector<CCValAssign, 16> ArgLocs;
2381   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2382                  *DAG.getContext());
2383
2384   // At this point, Ins[].VT may already be promoted to i32. To correctly
2385   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2386   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2387   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2388   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2389   // LocVT.
2390   unsigned NumArgs = Ins.size();
2391   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2392   unsigned CurArgIdx = 0;
2393   for (unsigned i = 0; i != NumArgs; ++i) {
2394     MVT ValVT = Ins[i].VT;
2395     if (Ins[i].isOrigArg()) {
2396       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2397       CurArgIdx = Ins[i].getOrigArgIndex();
2398
2399       // Get type of the original argument.
2400       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2401                                   /*AllowUnknown*/ true);
2402       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2403       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2404       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2405         ValVT = MVT::i8;
2406       else if (ActualMVT == MVT::i16)
2407         ValVT = MVT::i16;
2408     }
2409     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2410     bool Res =
2411         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2412     assert(!Res && "Call operand has unhandled type");
2413     (void)Res;
2414   }
2415   assert(ArgLocs.size() == Ins.size());
2416   SmallVector<SDValue, 16> ArgValues;
2417   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2418     CCValAssign &VA = ArgLocs[i];
2419
2420     if (Ins[i].Flags.isByVal()) {
2421       // Byval is used for HFAs in the PCS, but the system should work in a
2422       // non-compliant manner for larger structs.
2423       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2424       int Size = Ins[i].Flags.getByValSize();
2425       unsigned NumRegs = (Size + 7) / 8;
2426
2427       // FIXME: This works on big-endian for composite byvals, which are the common
2428       // case. It should also work for fundamental types too.
2429       unsigned FrameIdx =
2430         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2431       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2432       InVals.push_back(FrameIdxN);
2433
2434       continue;
2435     }
2436     
2437     if (VA.isRegLoc()) {
2438       // Arguments stored in registers.
2439       EVT RegVT = VA.getLocVT();
2440
2441       SDValue ArgValue;
2442       const TargetRegisterClass *RC;
2443
2444       if (RegVT == MVT::i32)
2445         RC = &AArch64::GPR32RegClass;
2446       else if (RegVT == MVT::i64)
2447         RC = &AArch64::GPR64RegClass;
2448       else if (RegVT == MVT::f16)
2449         RC = &AArch64::FPR16RegClass;
2450       else if (RegVT == MVT::f32)
2451         RC = &AArch64::FPR32RegClass;
2452       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2453         RC = &AArch64::FPR64RegClass;
2454       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2455         RC = &AArch64::FPR128RegClass;
2456       else
2457         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2458
2459       // Transform the arguments in physical registers into virtual ones.
2460       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2461       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2462
2463       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2464       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2465       // truncate to the right size.
2466       switch (VA.getLocInfo()) {
2467       default:
2468         llvm_unreachable("Unknown loc info!");
2469       case CCValAssign::Full:
2470         break;
2471       case CCValAssign::BCvt:
2472         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2473         break;
2474       case CCValAssign::AExt:
2475       case CCValAssign::SExt:
2476       case CCValAssign::ZExt:
2477         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2478         // nodes after our lowering.
2479         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2480         break;
2481       }
2482
2483       InVals.push_back(ArgValue);
2484
2485     } else { // VA.isRegLoc()
2486       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2487       unsigned ArgOffset = VA.getLocMemOffset();
2488       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2489
2490       uint32_t BEAlign = 0;
2491       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2492           !Ins[i].Flags.isInConsecutiveRegs())
2493         BEAlign = 8 - ArgSize;
2494
2495       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2496
2497       // Create load nodes to retrieve arguments from the stack.
2498       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2499       SDValue ArgValue;
2500
2501       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2502       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2503       MVT MemVT = VA.getValVT();
2504
2505       switch (VA.getLocInfo()) {
2506       default:
2507         break;
2508       case CCValAssign::BCvt:
2509         MemVT = VA.getLocVT();
2510         break;
2511       case CCValAssign::SExt:
2512         ExtType = ISD::SEXTLOAD;
2513         break;
2514       case CCValAssign::ZExt:
2515         ExtType = ISD::ZEXTLOAD;
2516         break;
2517       case CCValAssign::AExt:
2518         ExtType = ISD::EXTLOAD;
2519         break;
2520       }
2521
2522       ArgValue = DAG.getExtLoad(
2523           ExtType, DL, VA.getLocVT(), Chain, FIN,
2524           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2525           MemVT, false, false, false, 0);
2526
2527       InVals.push_back(ArgValue);
2528     }
2529   }
2530
2531   // varargs
2532   if (isVarArg) {
2533     if (!Subtarget->isTargetDarwin()) {
2534       // The AAPCS variadic function ABI is identical to the non-variadic
2535       // one. As a result there may be more arguments in registers and we should
2536       // save them for future reference.
2537       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2538     }
2539
2540     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2541     // This will point to the next argument passed via stack.
2542     unsigned StackOffset = CCInfo.getNextStackOffset();
2543     // We currently pass all varargs at 8-byte alignment.
2544     StackOffset = ((StackOffset + 7) & ~7);
2545     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2546   }
2547
2548   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2549   unsigned StackArgSize = CCInfo.getNextStackOffset();
2550   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2551   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2552     // This is a non-standard ABI so by fiat I say we're allowed to make full
2553     // use of the stack area to be popped, which must be aligned to 16 bytes in
2554     // any case:
2555     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2556
2557     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2558     // a multiple of 16.
2559     FuncInfo->setArgumentStackToRestore(StackArgSize);
2560
2561     // This realignment carries over to the available bytes below. Our own
2562     // callers will guarantee the space is free by giving an aligned value to
2563     // CALLSEQ_START.
2564   }
2565   // Even if we're not expected to free up the space, it's useful to know how
2566   // much is there while considering tail calls (because we can reuse it).
2567   FuncInfo->setBytesInStackArgArea(StackArgSize);
2568
2569   return Chain;
2570 }
2571
2572 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2573                                                 SelectionDAG &DAG, SDLoc DL,
2574                                                 SDValue &Chain) const {
2575   MachineFunction &MF = DAG.getMachineFunction();
2576   MachineFrameInfo *MFI = MF.getFrameInfo();
2577   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2578   auto PtrVT = getPointerTy(DAG.getDataLayout());
2579
2580   SmallVector<SDValue, 8> MemOps;
2581
2582   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2583                                           AArch64::X3, AArch64::X4, AArch64::X5,
2584                                           AArch64::X6, AArch64::X7 };
2585   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2586   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2587
2588   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2589   int GPRIdx = 0;
2590   if (GPRSaveSize != 0) {
2591     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2592
2593     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2594
2595     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2596       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2597       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2598       SDValue Store = DAG.getStore(
2599           Val.getValue(1), DL, Val, FIN,
2600           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2601           false, 0);
2602       MemOps.push_back(Store);
2603       FIN =
2604           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2605     }
2606   }
2607   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2608   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2609
2610   if (Subtarget->hasFPARMv8()) {
2611     static const MCPhysReg FPRArgRegs[] = {
2612         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2613         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2614     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2615     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2616
2617     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2618     int FPRIdx = 0;
2619     if (FPRSaveSize != 0) {
2620       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2621
2622       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2623
2624       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2625         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2626         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2627
2628         SDValue Store = DAG.getStore(
2629             Val.getValue(1), DL, Val, FIN,
2630             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2631             false, false, 0);
2632         MemOps.push_back(Store);
2633         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2634                           DAG.getConstant(16, DL, PtrVT));
2635       }
2636     }
2637     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2638     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2639   }
2640
2641   if (!MemOps.empty()) {
2642     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2643   }
2644 }
2645
2646 /// LowerCallResult - Lower the result values of a call into the
2647 /// appropriate copies out of appropriate physical registers.
2648 SDValue AArch64TargetLowering::LowerCallResult(
2649     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2650     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2651     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2652     SDValue ThisVal) const {
2653   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2654                           ? RetCC_AArch64_WebKit_JS
2655                           : RetCC_AArch64_AAPCS;
2656   // Assign locations to each value returned by this call.
2657   SmallVector<CCValAssign, 16> RVLocs;
2658   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2659                  *DAG.getContext());
2660   CCInfo.AnalyzeCallResult(Ins, RetCC);
2661
2662   // Copy all of the result registers out of their specified physreg.
2663   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2664     CCValAssign VA = RVLocs[i];
2665
2666     // Pass 'this' value directly from the argument to return value, to avoid
2667     // reg unit interference
2668     if (i == 0 && isThisReturn) {
2669       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2670              "unexpected return calling convention register assignment");
2671       InVals.push_back(ThisVal);
2672       continue;
2673     }
2674
2675     SDValue Val =
2676         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2677     Chain = Val.getValue(1);
2678     InFlag = Val.getValue(2);
2679
2680     switch (VA.getLocInfo()) {
2681     default:
2682       llvm_unreachable("Unknown loc info!");
2683     case CCValAssign::Full:
2684       break;
2685     case CCValAssign::BCvt:
2686       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2687       break;
2688     }
2689
2690     InVals.push_back(Val);
2691   }
2692
2693   return Chain;
2694 }
2695
2696 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2697     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2698     bool isCalleeStructRet, bool isCallerStructRet,
2699     const SmallVectorImpl<ISD::OutputArg> &Outs,
2700     const SmallVectorImpl<SDValue> &OutVals,
2701     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2702   // For CallingConv::C this function knows whether the ABI needs
2703   // changing. That's not true for other conventions so they will have to opt in
2704   // manually.
2705   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2706     return false;
2707
2708   const MachineFunction &MF = DAG.getMachineFunction();
2709   const Function *CallerF = MF.getFunction();
2710   CallingConv::ID CallerCC = CallerF->getCallingConv();
2711   bool CCMatch = CallerCC == CalleeCC;
2712
2713   // Byval parameters hand the function a pointer directly into the stack area
2714   // we want to reuse during a tail call. Working around this *is* possible (see
2715   // X86) but less efficient and uglier in LowerCall.
2716   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2717                                     e = CallerF->arg_end();
2718        i != e; ++i)
2719     if (i->hasByValAttr())
2720       return false;
2721
2722   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2723     if (IsTailCallConvention(CalleeCC) && CCMatch)
2724       return true;
2725     return false;
2726   }
2727
2728   // Externally-defined functions with weak linkage should not be
2729   // tail-called on AArch64 when the OS does not support dynamic
2730   // pre-emption of symbols, as the AAELF spec requires normal calls
2731   // to undefined weak functions to be replaced with a NOP or jump to the
2732   // next instruction. The behaviour of branch instructions in this
2733   // situation (as used for tail calls) is implementation-defined, so we
2734   // cannot rely on the linker replacing the tail call with a return.
2735   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2736     const GlobalValue *GV = G->getGlobal();
2737     const Triple &TT = getTargetMachine().getTargetTriple();
2738     if (GV->hasExternalWeakLinkage() &&
2739         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2740       return false;
2741   }
2742
2743   // Now we search for cases where we can use a tail call without changing the
2744   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2745   // concept.
2746
2747   // I want anyone implementing a new calling convention to think long and hard
2748   // about this assert.
2749   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2750          "Unexpected variadic calling convention");
2751
2752   if (isVarArg && !Outs.empty()) {
2753     // At least two cases here: if caller is fastcc then we can't have any
2754     // memory arguments (we'd be expected to clean up the stack afterwards). If
2755     // caller is C then we could potentially use its argument area.
2756
2757     // FIXME: for now we take the most conservative of these in both cases:
2758     // disallow all variadic memory operands.
2759     SmallVector<CCValAssign, 16> ArgLocs;
2760     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2761                    *DAG.getContext());
2762
2763     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2764     for (const CCValAssign &ArgLoc : ArgLocs)
2765       if (!ArgLoc.isRegLoc())
2766         return false;
2767   }
2768
2769   // If the calling conventions do not match, then we'd better make sure the
2770   // results are returned in the same way as what the caller expects.
2771   if (!CCMatch) {
2772     SmallVector<CCValAssign, 16> RVLocs1;
2773     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2774                     *DAG.getContext());
2775     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2776
2777     SmallVector<CCValAssign, 16> RVLocs2;
2778     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2779                     *DAG.getContext());
2780     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2781
2782     if (RVLocs1.size() != RVLocs2.size())
2783       return false;
2784     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2785       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2786         return false;
2787       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2788         return false;
2789       if (RVLocs1[i].isRegLoc()) {
2790         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2791           return false;
2792       } else {
2793         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2794           return false;
2795       }
2796     }
2797   }
2798
2799   // Nothing more to check if the callee is taking no arguments
2800   if (Outs.empty())
2801     return true;
2802
2803   SmallVector<CCValAssign, 16> ArgLocs;
2804   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2805                  *DAG.getContext());
2806
2807   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2808
2809   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2810
2811   // If the stack arguments for this call would fit into our own save area then
2812   // the call can be made tail.
2813   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2814 }
2815
2816 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2817                                                    SelectionDAG &DAG,
2818                                                    MachineFrameInfo *MFI,
2819                                                    int ClobberedFI) const {
2820   SmallVector<SDValue, 8> ArgChains;
2821   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2822   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2823
2824   // Include the original chain at the beginning of the list. When this is
2825   // used by target LowerCall hooks, this helps legalize find the
2826   // CALLSEQ_BEGIN node.
2827   ArgChains.push_back(Chain);
2828
2829   // Add a chain value for each stack argument corresponding
2830   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2831                             UE = DAG.getEntryNode().getNode()->use_end();
2832        U != UE; ++U)
2833     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2834       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2835         if (FI->getIndex() < 0) {
2836           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2837           int64_t InLastByte = InFirstByte;
2838           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2839
2840           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2841               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2842             ArgChains.push_back(SDValue(L, 1));
2843         }
2844
2845   // Build a tokenfactor for all the chains.
2846   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2847 }
2848
2849 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2850                                                    bool TailCallOpt) const {
2851   return CallCC == CallingConv::Fast && TailCallOpt;
2852 }
2853
2854 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2855   return CallCC == CallingConv::Fast;
2856 }
2857
2858 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2859 /// and add input and output parameter nodes.
2860 SDValue
2861 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2862                                  SmallVectorImpl<SDValue> &InVals) const {
2863   SelectionDAG &DAG = CLI.DAG;
2864   SDLoc &DL = CLI.DL;
2865   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2866   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2867   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2868   SDValue Chain = CLI.Chain;
2869   SDValue Callee = CLI.Callee;
2870   bool &IsTailCall = CLI.IsTailCall;
2871   CallingConv::ID CallConv = CLI.CallConv;
2872   bool IsVarArg = CLI.IsVarArg;
2873
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2876   bool IsThisReturn = false;
2877
2878   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2879   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2880   bool IsSibCall = false;
2881
2882   if (IsTailCall) {
2883     // Check if it's really possible to do a tail call.
2884     IsTailCall = isEligibleForTailCallOptimization(
2885         Callee, CallConv, IsVarArg, IsStructRet,
2886         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2887     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2888       report_fatal_error("failed to perform tail call elimination on a call "
2889                          "site marked musttail");
2890
2891     // A sibling call is one where we're under the usual C ABI and not planning
2892     // to change that but can still do a tail call:
2893     if (!TailCallOpt && IsTailCall)
2894       IsSibCall = true;
2895
2896     if (IsTailCall)
2897       ++NumTailCalls;
2898   }
2899
2900   // Analyze operands of the call, assigning locations to each operand.
2901   SmallVector<CCValAssign, 16> ArgLocs;
2902   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2903                  *DAG.getContext());
2904
2905   if (IsVarArg) {
2906     // Handle fixed and variable vector arguments differently.
2907     // Variable vector arguments always go into memory.
2908     unsigned NumArgs = Outs.size();
2909
2910     for (unsigned i = 0; i != NumArgs; ++i) {
2911       MVT ArgVT = Outs[i].VT;
2912       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2913       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2914                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2915       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2916       assert(!Res && "Call operand has unhandled type");
2917       (void)Res;
2918     }
2919   } else {
2920     // At this point, Outs[].VT may already be promoted to i32. To correctly
2921     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2922     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2923     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2924     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2925     // LocVT.
2926     unsigned NumArgs = Outs.size();
2927     for (unsigned i = 0; i != NumArgs; ++i) {
2928       MVT ValVT = Outs[i].VT;
2929       // Get type of the original argument.
2930       EVT ActualVT = getValueType(DAG.getDataLayout(),
2931                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2932                                   /*AllowUnknown*/ true);
2933       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2934       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2935       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2936       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2937         ValVT = MVT::i8;
2938       else if (ActualMVT == MVT::i16)
2939         ValVT = MVT::i16;
2940
2941       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2942       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2943       assert(!Res && "Call operand has unhandled type");
2944       (void)Res;
2945     }
2946   }
2947
2948   // Get a count of how many bytes are to be pushed on the stack.
2949   unsigned NumBytes = CCInfo.getNextStackOffset();
2950
2951   if (IsSibCall) {
2952     // Since we're not changing the ABI to make this a tail call, the memory
2953     // operands are already available in the caller's incoming argument space.
2954     NumBytes = 0;
2955   }
2956
2957   // FPDiff is the byte offset of the call's argument area from the callee's.
2958   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2959   // by this amount for a tail call. In a sibling call it must be 0 because the
2960   // caller will deallocate the entire stack and the callee still expects its
2961   // arguments to begin at SP+0. Completely unused for non-tail calls.
2962   int FPDiff = 0;
2963
2964   if (IsTailCall && !IsSibCall) {
2965     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2966
2967     // Since callee will pop argument stack as a tail call, we must keep the
2968     // popped size 16-byte aligned.
2969     NumBytes = RoundUpToAlignment(NumBytes, 16);
2970
2971     // FPDiff will be negative if this tail call requires more space than we
2972     // would automatically have in our incoming argument space. Positive if we
2973     // can actually shrink the stack.
2974     FPDiff = NumReusableBytes - NumBytes;
2975
2976     // The stack pointer must be 16-byte aligned at all times it's used for a
2977     // memory operation, which in practice means at *all* times and in
2978     // particular across call boundaries. Therefore our own arguments started at
2979     // a 16-byte aligned SP and the delta applied for the tail call should
2980     // satisfy the same constraint.
2981     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2982   }
2983
2984   // Adjust the stack pointer for the new arguments...
2985   // These operations are automatically eliminated by the prolog/epilog pass
2986   if (!IsSibCall)
2987     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2988                                                               true),
2989                                  DL);
2990
2991   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2992                                         getPointerTy(DAG.getDataLayout()));
2993
2994   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2995   SmallVector<SDValue, 8> MemOpChains;
2996   auto PtrVT = getPointerTy(DAG.getDataLayout());
2997
2998   // Walk the register/memloc assignments, inserting copies/loads.
2999   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3000        ++i, ++realArgIdx) {
3001     CCValAssign &VA = ArgLocs[i];
3002     SDValue Arg = OutVals[realArgIdx];
3003     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3004
3005     // Promote the value if needed.
3006     switch (VA.getLocInfo()) {
3007     default:
3008       llvm_unreachable("Unknown loc info!");
3009     case CCValAssign::Full:
3010       break;
3011     case CCValAssign::SExt:
3012       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3013       break;
3014     case CCValAssign::ZExt:
3015       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3016       break;
3017     case CCValAssign::AExt:
3018       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3019         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3020         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3021         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3022       }
3023       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3024       break;
3025     case CCValAssign::BCvt:
3026       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3027       break;
3028     case CCValAssign::FPExt:
3029       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3030       break;
3031     }
3032
3033     if (VA.isRegLoc()) {
3034       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3035         assert(VA.getLocVT() == MVT::i64 &&
3036                "unexpected calling convention register assignment");
3037         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3038                "unexpected use of 'returned'");
3039         IsThisReturn = true;
3040       }
3041       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3042     } else {
3043       assert(VA.isMemLoc());
3044
3045       SDValue DstAddr;
3046       MachinePointerInfo DstInfo;
3047
3048       // FIXME: This works on big-endian for composite byvals, which are the
3049       // common case. It should also work for fundamental types too.
3050       uint32_t BEAlign = 0;
3051       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3052                                         : VA.getValVT().getSizeInBits();
3053       OpSize = (OpSize + 7) / 8;
3054       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3055           !Flags.isInConsecutiveRegs()) {
3056         if (OpSize < 8)
3057           BEAlign = 8 - OpSize;
3058       }
3059       unsigned LocMemOffset = VA.getLocMemOffset();
3060       int32_t Offset = LocMemOffset + BEAlign;
3061       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3062       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3063
3064       if (IsTailCall) {
3065         Offset = Offset + FPDiff;
3066         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3067
3068         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3069         DstInfo =
3070             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3071
3072         // Make sure any stack arguments overlapping with where we're storing
3073         // are loaded before this eventual operation. Otherwise they'll be
3074         // clobbered.
3075         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3076       } else {
3077         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3078
3079         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3080         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3081                                                LocMemOffset);
3082       }
3083
3084       if (Outs[i].Flags.isByVal()) {
3085         SDValue SizeNode =
3086             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3087         SDValue Cpy = DAG.getMemcpy(
3088             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3089             /*isVol = */ false, /*AlwaysInline = */ false,
3090             /*isTailCall = */ false,
3091             DstInfo, MachinePointerInfo());
3092
3093         MemOpChains.push_back(Cpy);
3094       } else {
3095         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3096         // promoted to a legal register type i32, we should truncate Arg back to
3097         // i1/i8/i16.
3098         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3099             VA.getValVT() == MVT::i16)
3100           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3101
3102         SDValue Store =
3103             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3104         MemOpChains.push_back(Store);
3105       }
3106     }
3107   }
3108
3109   if (!MemOpChains.empty())
3110     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3111
3112   // Build a sequence of copy-to-reg nodes chained together with token chain
3113   // and flag operands which copy the outgoing args into the appropriate regs.
3114   SDValue InFlag;
3115   for (auto &RegToPass : RegsToPass) {
3116     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3117                              RegToPass.second, InFlag);
3118     InFlag = Chain.getValue(1);
3119   }
3120
3121   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3122   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3123   // node so that legalize doesn't hack it.
3124   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3125       Subtarget->isTargetMachO()) {
3126     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3127       const GlobalValue *GV = G->getGlobal();
3128       bool InternalLinkage = GV->hasInternalLinkage();
3129       if (InternalLinkage)
3130         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3131       else {
3132         Callee =
3133             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3134         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3135       }
3136     } else if (ExternalSymbolSDNode *S =
3137                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3138       const char *Sym = S->getSymbol();
3139       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3140       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3141     }
3142   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3143     const GlobalValue *GV = G->getGlobal();
3144     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3145   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3146     const char *Sym = S->getSymbol();
3147     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3148   }
3149
3150   // We don't usually want to end the call-sequence here because we would tidy
3151   // the frame up *after* the call, however in the ABI-changing tail-call case
3152   // we've carefully laid out the parameters so that when sp is reset they'll be
3153   // in the correct location.
3154   if (IsTailCall && !IsSibCall) {
3155     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3156                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3157     InFlag = Chain.getValue(1);
3158   }
3159
3160   std::vector<SDValue> Ops;
3161   Ops.push_back(Chain);
3162   Ops.push_back(Callee);
3163
3164   if (IsTailCall) {
3165     // Each tail call may have to adjust the stack by a different amount, so
3166     // this information must travel along with the operation for eventual
3167     // consumption by emitEpilogue.
3168     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3169   }
3170
3171   // Add argument registers to the end of the list so that they are known live
3172   // into the call.
3173   for (auto &RegToPass : RegsToPass)
3174     Ops.push_back(DAG.getRegister(RegToPass.first,
3175                                   RegToPass.second.getValueType()));
3176
3177   // Add a register mask operand representing the call-preserved registers.
3178   const uint32_t *Mask;
3179   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3180   if (IsThisReturn) {
3181     // For 'this' returns, use the X0-preserving mask if applicable
3182     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3183     if (!Mask) {
3184       IsThisReturn = false;
3185       Mask = TRI->getCallPreservedMask(MF, CallConv);
3186     }
3187   } else
3188     Mask = TRI->getCallPreservedMask(MF, CallConv);
3189
3190   assert(Mask && "Missing call preserved mask for calling convention");
3191   Ops.push_back(DAG.getRegisterMask(Mask));
3192
3193   if (InFlag.getNode())
3194     Ops.push_back(InFlag);
3195
3196   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3197
3198   // If we're doing a tall call, use a TC_RETURN here rather than an
3199   // actual call instruction.
3200   if (IsTailCall) {
3201     MF.getFrameInfo()->setHasTailCall();
3202     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3203   }
3204
3205   // Returns a chain and a flag for retval copy to use.
3206   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3207   InFlag = Chain.getValue(1);
3208
3209   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3210                                 ? RoundUpToAlignment(NumBytes, 16)
3211                                 : 0;
3212
3213   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3214                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3215                              InFlag, DL);
3216   if (!Ins.empty())
3217     InFlag = Chain.getValue(1);
3218
3219   // Handle result values, copying them out of physregs into vregs that we
3220   // return.
3221   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3222                          InVals, IsThisReturn,
3223                          IsThisReturn ? OutVals[0] : SDValue());
3224 }
3225
3226 bool AArch64TargetLowering::CanLowerReturn(
3227     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3228     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3229   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3230                           ? RetCC_AArch64_WebKit_JS
3231                           : RetCC_AArch64_AAPCS;
3232   SmallVector<CCValAssign, 16> RVLocs;
3233   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3234   return CCInfo.CheckReturn(Outs, RetCC);
3235 }
3236
3237 SDValue
3238 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3239                                    bool isVarArg,
3240                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3241                                    const SmallVectorImpl<SDValue> &OutVals,
3242                                    SDLoc DL, SelectionDAG &DAG) const {
3243   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3244                           ? RetCC_AArch64_WebKit_JS
3245                           : RetCC_AArch64_AAPCS;
3246   SmallVector<CCValAssign, 16> RVLocs;
3247   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3248                  *DAG.getContext());
3249   CCInfo.AnalyzeReturn(Outs, RetCC);
3250
3251   // Copy the result values into the output registers.
3252   SDValue Flag;
3253   SmallVector<SDValue, 4> RetOps(1, Chain);
3254   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3255        ++i, ++realRVLocIdx) {
3256     CCValAssign &VA = RVLocs[i];
3257     assert(VA.isRegLoc() && "Can only return in registers!");
3258     SDValue Arg = OutVals[realRVLocIdx];
3259
3260     switch (VA.getLocInfo()) {
3261     default:
3262       llvm_unreachable("Unknown loc info!");
3263     case CCValAssign::Full:
3264       if (Outs[i].ArgVT == MVT::i1) {
3265         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3266         // value. This is strictly redundant on Darwin (which uses "zeroext
3267         // i1"), but will be optimised out before ISel.
3268         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3269         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3270       }
3271       break;
3272     case CCValAssign::BCvt:
3273       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3274       break;
3275     }
3276
3277     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3278     Flag = Chain.getValue(1);
3279     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3280   }
3281
3282   RetOps[0] = Chain; // Update chain.
3283
3284   // Add the flag if we have it.
3285   if (Flag.getNode())
3286     RetOps.push_back(Flag);
3287
3288   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3289 }
3290
3291 //===----------------------------------------------------------------------===//
3292 //  Other Lowering Code
3293 //===----------------------------------------------------------------------===//
3294
3295 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3296                                                   SelectionDAG &DAG) const {
3297   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3298   SDLoc DL(Op);
3299   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3300   const GlobalValue *GV = GN->getGlobal();
3301   unsigned char OpFlags =
3302       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3303
3304   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3305          "unexpected offset in global node");
3306
3307   // This also catched the large code model case for Darwin.
3308   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3309     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3310     // FIXME: Once remat is capable of dealing with instructions with register
3311     // operands, expand this into two nodes instead of using a wrapper node.
3312     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3313   }
3314
3315   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3316     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3317            "use of MO_CONSTPOOL only supported on small model");
3318     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3319     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3320     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3321     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3322     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3323     SDValue GlobalAddr = DAG.getLoad(
3324         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3325         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3326         /*isVolatile=*/false,
3327         /*isNonTemporal=*/true,
3328         /*isInvariant=*/true, 8);
3329     if (GN->getOffset() != 0)
3330       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3331                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3332     return GlobalAddr;
3333   }
3334
3335   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3336     const unsigned char MO_NC = AArch64II::MO_NC;
3337     return DAG.getNode(
3338         AArch64ISD::WrapperLarge, DL, PtrVT,
3339         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3340         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3341         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3342         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3343   } else {
3344     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3345     // the only correct model on Darwin.
3346     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3347                                             OpFlags | AArch64II::MO_PAGE);
3348     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3349     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3350
3351     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3352     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3353   }
3354 }
3355
3356 /// \brief Convert a TLS address reference into the correct sequence of loads
3357 /// and calls to compute the variable's address (for Darwin, currently) and
3358 /// return an SDValue containing the final node.
3359
3360 /// Darwin only has one TLS scheme which must be capable of dealing with the
3361 /// fully general situation, in the worst case. This means:
3362 ///     + "extern __thread" declaration.
3363 ///     + Defined in a possibly unknown dynamic library.
3364 ///
3365 /// The general system is that each __thread variable has a [3 x i64] descriptor
3366 /// which contains information used by the runtime to calculate the address. The
3367 /// only part of this the compiler needs to know about is the first xword, which
3368 /// contains a function pointer that must be called with the address of the
3369 /// entire descriptor in "x0".
3370 ///
3371 /// Since this descriptor may be in a different unit, in general even the
3372 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3373 /// is:
3374 ///     adrp x0, _var@TLVPPAGE
3375 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3376 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3377 ///                                      ; the function pointer
3378 ///     blr x1                           ; Uses descriptor address in x0
3379 ///     ; Address of _var is now in x0.
3380 ///
3381 /// If the address of _var's descriptor *is* known to the linker, then it can
3382 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3383 /// a slight efficiency gain.
3384 SDValue
3385 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3386                                                    SelectionDAG &DAG) const {
3387   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3388
3389   SDLoc DL(Op);
3390   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3391   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3392
3393   SDValue TLVPAddr =
3394       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3395   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3396
3397   // The first entry in the descriptor is a function pointer that we must call
3398   // to obtain the address of the variable.
3399   SDValue Chain = DAG.getEntryNode();
3400   SDValue FuncTLVGet =
3401       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3402                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3403                   true, true, 8);
3404   Chain = FuncTLVGet.getValue(1);
3405
3406   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3407   MFI->setAdjustsStack(true);
3408
3409   // TLS calls preserve all registers except those that absolutely must be
3410   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3411   // silly).
3412   const uint32_t *Mask =
3413       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3414
3415   // Finally, we can make the call. This is just a degenerate version of a
3416   // normal AArch64 call node: x0 takes the address of the descriptor, and
3417   // returns the address of the variable in this thread.
3418   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3419   Chain =
3420       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3421                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3422                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3423   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3424 }
3425
3426 /// When accessing thread-local variables under either the general-dynamic or
3427 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3428 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3429 /// is a function pointer to carry out the resolution.
3430 ///
3431 /// The sequence is:
3432 ///    adrp  x0, :tlsdesc:var
3433 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3434 ///    add   x0, x0, #:tlsdesc_lo12:var
3435 ///    .tlsdesccall var
3436 ///    blr   x1
3437 ///    (TPIDR_EL0 offset now in x0)
3438 ///
3439 ///  The above sequence must be produced unscheduled, to enable the linker to
3440 ///  optimize/relax this sequence.
3441 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3442 ///  above sequence, and expanded really late in the compilation flow, to ensure
3443 ///  the sequence is produced as per above.
3444 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3445                                                       SelectionDAG &DAG) const {
3446   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3447
3448   SDValue Chain = DAG.getEntryNode();
3449   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3450
3451   SmallVector<SDValue, 2> Ops;
3452   Ops.push_back(Chain);
3453   Ops.push_back(SymAddr);
3454
3455   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3456   SDValue Glue = Chain.getValue(1);
3457
3458   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3459 }
3460
3461 SDValue
3462 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3463                                                 SelectionDAG &DAG) const {
3464   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3465   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3466          "ELF TLS only supported in small memory model");
3467   // Different choices can be made for the maximum size of the TLS area for a
3468   // module. For the small address model, the default TLS size is 16MiB and the
3469   // maximum TLS size is 4GiB.
3470   // FIXME: add -mtls-size command line option and make it control the 16MiB
3471   // vs. 4GiB code sequence generation.
3472   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3473
3474   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3475
3476   if (DAG.getTarget().Options.EmulatedTLS)
3477     return LowerToTLSEmulatedModel(GA, DAG);
3478
3479   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3480     if (Model == TLSModel::LocalDynamic)
3481       Model = TLSModel::GeneralDynamic;
3482   }
3483
3484   SDValue TPOff;
3485   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3486   SDLoc DL(Op);
3487   const GlobalValue *GV = GA->getGlobal();
3488
3489   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3490
3491   if (Model == TLSModel::LocalExec) {
3492     SDValue HiVar = DAG.getTargetGlobalAddress(
3493         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3494     SDValue LoVar = DAG.getTargetGlobalAddress(
3495         GV, DL, PtrVT, 0,
3496         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3497
3498     SDValue TPWithOff_lo =
3499         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3500                                    HiVar,
3501                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3502                 0);
3503     SDValue TPWithOff =
3504         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3505                                    LoVar,
3506                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3507                 0);
3508     return TPWithOff;
3509   } else if (Model == TLSModel::InitialExec) {
3510     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3511     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3512   } else if (Model == TLSModel::LocalDynamic) {
3513     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3514     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3515     // the beginning of the module's TLS region, followed by a DTPREL offset
3516     // calculation.
3517
3518     // These accesses will need deduplicating if there's more than one.
3519     AArch64FunctionInfo *MFI =
3520         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3521     MFI->incNumLocalDynamicTLSAccesses();
3522
3523     // The call needs a relocation too for linker relaxation. It doesn't make
3524     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3525     // the address.
3526     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3527                                                   AArch64II::MO_TLS);
3528
3529     // Now we can calculate the offset from TPIDR_EL0 to this module's
3530     // thread-local area.
3531     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3532
3533     // Now use :dtprel_whatever: operations to calculate this variable's offset
3534     // in its thread-storage area.
3535     SDValue HiVar = DAG.getTargetGlobalAddress(
3536         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3537     SDValue LoVar = DAG.getTargetGlobalAddress(
3538         GV, DL, MVT::i64, 0,
3539         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3540
3541     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3542                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3543                     0);
3544     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3545                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3546                     0);
3547   } else if (Model == TLSModel::GeneralDynamic) {
3548     // The call needs a relocation too for linker relaxation. It doesn't make
3549     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3550     // the address.
3551     SDValue SymAddr =
3552         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3553
3554     // Finally we can make a call to calculate the offset from tpidr_el0.
3555     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3556   } else
3557     llvm_unreachable("Unsupported ELF TLS access model");
3558
3559   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3560 }
3561
3562 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3563                                                      SelectionDAG &DAG) const {
3564   if (Subtarget->isTargetDarwin())
3565     return LowerDarwinGlobalTLSAddress(Op, DAG);
3566   else if (Subtarget->isTargetELF())
3567     return LowerELFGlobalTLSAddress(Op, DAG);
3568
3569   llvm_unreachable("Unexpected platform trying to use TLS");
3570 }
3571 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3572   SDValue Chain = Op.getOperand(0);
3573   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3574   SDValue LHS = Op.getOperand(2);
3575   SDValue RHS = Op.getOperand(3);
3576   SDValue Dest = Op.getOperand(4);
3577   SDLoc dl(Op);
3578
3579   // Handle f128 first, since lowering it will result in comparing the return
3580   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3581   // is expecting to deal with.
3582   if (LHS.getValueType() == MVT::f128) {
3583     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3584
3585     // If softenSetCCOperands returned a scalar, we need to compare the result
3586     // against zero to select between true and false values.
3587     if (!RHS.getNode()) {
3588       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3589       CC = ISD::SETNE;
3590     }
3591   }
3592
3593   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3594   // instruction.
3595   unsigned Opc = LHS.getOpcode();
3596   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3597       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3598        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3599     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3600            "Unexpected condition code.");
3601     // Only lower legal XALUO ops.
3602     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3603       return SDValue();
3604
3605     // The actual operation with overflow check.
3606     AArch64CC::CondCode OFCC;
3607     SDValue Value, Overflow;
3608     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3609
3610     if (CC == ISD::SETNE)
3611       OFCC = getInvertedCondCode(OFCC);
3612     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3613
3614     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3615                        Overflow);
3616   }
3617
3618   if (LHS.getValueType().isInteger()) {
3619     assert((LHS.getValueType() == RHS.getValueType()) &&
3620            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3621
3622     // If the RHS of the comparison is zero, we can potentially fold this
3623     // to a specialized branch.
3624     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3625     if (RHSC && RHSC->getZExtValue() == 0) {
3626       if (CC == ISD::SETEQ) {
3627         // See if we can use a TBZ to fold in an AND as well.
3628         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3629         // out of bounds, a late MI-layer pass rewrites branches.
3630         // 403.gcc is an example that hits this case.
3631         if (LHS.getOpcode() == ISD::AND &&
3632             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3633             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3634           SDValue Test = LHS.getOperand(0);
3635           uint64_t Mask = LHS.getConstantOperandVal(1);
3636           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3637                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3638                              Dest);
3639         }
3640
3641         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3642       } else if (CC == ISD::SETNE) {
3643         // See if we can use a TBZ to fold in an AND as well.
3644         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3645         // out of bounds, a late MI-layer pass rewrites branches.
3646         // 403.gcc is an example that hits this case.
3647         if (LHS.getOpcode() == ISD::AND &&
3648             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3649             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3650           SDValue Test = LHS.getOperand(0);
3651           uint64_t Mask = LHS.getConstantOperandVal(1);
3652           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3653                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3654                              Dest);
3655         }
3656
3657         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3658       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3659         // Don't combine AND since emitComparison converts the AND to an ANDS
3660         // (a.k.a. TST) and the test in the test bit and branch instruction
3661         // becomes redundant.  This would also increase register pressure.
3662         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3663         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3664                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3665       }
3666     }
3667     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3668         LHS.getOpcode() != ISD::AND) {
3669       // Don't combine AND since emitComparison converts the AND to an ANDS
3670       // (a.k.a. TST) and the test in the test bit and branch instruction
3671       // becomes redundant.  This would also increase register pressure.
3672       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3673       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3674                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3675     }
3676
3677     SDValue CCVal;
3678     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3679     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3680                        Cmp);
3681   }
3682
3683   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3684
3685   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3686   // clean.  Some of them require two branches to implement.
3687   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3688   AArch64CC::CondCode CC1, CC2;
3689   changeFPCCToAArch64CC(CC, CC1, CC2);
3690   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3691   SDValue BR1 =
3692       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3693   if (CC2 != AArch64CC::AL) {
3694     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3695     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3696                        Cmp);
3697   }
3698
3699   return BR1;
3700 }
3701
3702 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3703                                               SelectionDAG &DAG) const {
3704   EVT VT = Op.getValueType();
3705   SDLoc DL(Op);
3706
3707   SDValue In1 = Op.getOperand(0);
3708   SDValue In2 = Op.getOperand(1);
3709   EVT SrcVT = In2.getValueType();
3710
3711   if (SrcVT.bitsLT(VT))
3712     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3713   else if (SrcVT.bitsGT(VT))
3714     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3715
3716   EVT VecVT;
3717   EVT EltVT;
3718   uint64_t EltMask;
3719   SDValue VecVal1, VecVal2;
3720   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3721     EltVT = MVT::i32;
3722     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3723     EltMask = 0x80000000ULL;
3724
3725     if (!VT.isVector()) {
3726       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3727                                           DAG.getUNDEF(VecVT), In1);
3728       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3729                                           DAG.getUNDEF(VecVT), In2);
3730     } else {
3731       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3732       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3733     }
3734   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3735     EltVT = MVT::i64;
3736     VecVT = MVT::v2i64;
3737
3738     // We want to materialize a mask with the high bit set, but the AdvSIMD
3739     // immediate moves cannot materialize that in a single instruction for
3740     // 64-bit elements. Instead, materialize zero and then negate it.
3741     EltMask = 0;
3742
3743     if (!VT.isVector()) {
3744       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3745                                           DAG.getUNDEF(VecVT), In1);
3746       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3747                                           DAG.getUNDEF(VecVT), In2);
3748     } else {
3749       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3750       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3751     }
3752   } else {
3753     llvm_unreachable("Invalid type for copysign!");
3754   }
3755
3756   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3757
3758   // If we couldn't materialize the mask above, then the mask vector will be
3759   // the zero vector, and we need to negate it here.
3760   if (VT == MVT::f64 || VT == MVT::v2f64) {
3761     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3762     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3763     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3764   }
3765
3766   SDValue Sel =
3767       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3768
3769   if (VT == MVT::f32)
3770     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3771   else if (VT == MVT::f64)
3772     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3773   else
3774     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3775 }
3776
3777 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3778   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3779           Attribute::NoImplicitFloat))
3780     return SDValue();
3781
3782   if (!Subtarget->hasNEON())
3783     return SDValue();
3784
3785   // While there is no integer popcount instruction, it can
3786   // be more efficiently lowered to the following sequence that uses
3787   // AdvSIMD registers/instructions as long as the copies to/from
3788   // the AdvSIMD registers are cheap.
3789   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3790   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3791   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3792   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3793   SDValue Val = Op.getOperand(0);
3794   SDLoc DL(Op);
3795   EVT VT = Op.getValueType();
3796
3797   if (VT == MVT::i32)
3798     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3799   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3800
3801   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3802   SDValue UaddLV = DAG.getNode(
3803       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3804       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3805
3806   if (VT == MVT::i64)
3807     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3808   return UaddLV;
3809 }
3810
3811 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3812
3813   if (Op.getValueType().isVector())
3814     return LowerVSETCC(Op, DAG);
3815
3816   SDValue LHS = Op.getOperand(0);
3817   SDValue RHS = Op.getOperand(1);
3818   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3819   SDLoc dl(Op);
3820
3821   // We chose ZeroOrOneBooleanContents, so use zero and one.
3822   EVT VT = Op.getValueType();
3823   SDValue TVal = DAG.getConstant(1, dl, VT);
3824   SDValue FVal = DAG.getConstant(0, dl, VT);
3825
3826   // Handle f128 first, since one possible outcome is a normal integer
3827   // comparison which gets picked up by the next if statement.
3828   if (LHS.getValueType() == MVT::f128) {
3829     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3830
3831     // If softenSetCCOperands returned a scalar, use it.
3832     if (!RHS.getNode()) {
3833       assert(LHS.getValueType() == Op.getValueType() &&
3834              "Unexpected setcc expansion!");
3835       return LHS;
3836     }
3837   }
3838
3839   if (LHS.getValueType().isInteger()) {
3840     SDValue CCVal;
3841     SDValue Cmp =
3842         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3843
3844     // Note that we inverted the condition above, so we reverse the order of
3845     // the true and false operands here.  This will allow the setcc to be
3846     // matched to a single CSINC instruction.
3847     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3848   }
3849
3850   // Now we know we're dealing with FP values.
3851   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3852
3853   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3854   // and do the comparison.
3855   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3856
3857   AArch64CC::CondCode CC1, CC2;
3858   changeFPCCToAArch64CC(CC, CC1, CC2);
3859   if (CC2 == AArch64CC::AL) {
3860     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3861     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3862
3863     // Note that we inverted the condition above, so we reverse the order of
3864     // the true and false operands here.  This will allow the setcc to be
3865     // matched to a single CSINC instruction.
3866     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3867   } else {
3868     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3869     // totally clean.  Some of them require two CSELs to implement.  As is in
3870     // this case, we emit the first CSEL and then emit a second using the output
3871     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3872
3873     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3874     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3875     SDValue CS1 =
3876         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3877
3878     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3879     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3880   }
3881 }
3882
3883 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3884                                               SDValue RHS, SDValue TVal,
3885                                               SDValue FVal, SDLoc dl,
3886                                               SelectionDAG &DAG) const {
3887   // Handle f128 first, because it will result in a comparison of some RTLIB
3888   // call result against zero.
3889   if (LHS.getValueType() == MVT::f128) {
3890     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3891
3892     // If softenSetCCOperands returned a scalar, we need to compare the result
3893     // against zero to select between true and false values.
3894     if (!RHS.getNode()) {
3895       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3896       CC = ISD::SETNE;
3897     }
3898   }
3899
3900   // Also handle f16, for which we need to do a f32 comparison.
3901   if (LHS.getValueType() == MVT::f16) {
3902     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3903     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3904   }
3905
3906   // Next, handle integers.
3907   if (LHS.getValueType().isInteger()) {
3908     assert((LHS.getValueType() == RHS.getValueType()) &&
3909            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3910
3911     unsigned Opcode = AArch64ISD::CSEL;
3912
3913     // If both the TVal and the FVal are constants, see if we can swap them in
3914     // order to for a CSINV or CSINC out of them.
3915     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3916     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3917
3918     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3919       std::swap(TVal, FVal);
3920       std::swap(CTVal, CFVal);
3921       CC = ISD::getSetCCInverse(CC, true);
3922     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3923       std::swap(TVal, FVal);
3924       std::swap(CTVal, CFVal);
3925       CC = ISD::getSetCCInverse(CC, true);
3926     } else if (TVal.getOpcode() == ISD::XOR) {
3927       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3928       // with a CSINV rather than a CSEL.
3929       if (isAllOnesConstant(TVal.getOperand(1))) {
3930         std::swap(TVal, FVal);
3931         std::swap(CTVal, CFVal);
3932         CC = ISD::getSetCCInverse(CC, true);
3933       }
3934     } else if (TVal.getOpcode() == ISD::SUB) {
3935       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3936       // that we can match with a CSNEG rather than a CSEL.
3937       if (isNullConstant(TVal.getOperand(0))) {
3938         std::swap(TVal, FVal);
3939         std::swap(CTVal, CFVal);
3940         CC = ISD::getSetCCInverse(CC, true);
3941       }
3942     } else if (CTVal && CFVal) {
3943       const int64_t TrueVal = CTVal->getSExtValue();
3944       const int64_t FalseVal = CFVal->getSExtValue();
3945       bool Swap = false;
3946
3947       // If both TVal and FVal are constants, see if FVal is the
3948       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3949       // instead of a CSEL in that case.
3950       if (TrueVal == ~FalseVal) {
3951         Opcode = AArch64ISD::CSINV;
3952       } else if (TrueVal == -FalseVal) {
3953         Opcode = AArch64ISD::CSNEG;
3954       } else if (TVal.getValueType() == MVT::i32) {
3955         // If our operands are only 32-bit wide, make sure we use 32-bit
3956         // arithmetic for the check whether we can use CSINC. This ensures that
3957         // the addition in the check will wrap around properly in case there is
3958         // an overflow (which would not be the case if we do the check with
3959         // 64-bit arithmetic).
3960         const uint32_t TrueVal32 = CTVal->getZExtValue();
3961         const uint32_t FalseVal32 = CFVal->getZExtValue();
3962
3963         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3964           Opcode = AArch64ISD::CSINC;
3965
3966           if (TrueVal32 > FalseVal32) {
3967             Swap = true;
3968           }
3969         }
3970         // 64-bit check whether we can use CSINC.
3971       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3972         Opcode = AArch64ISD::CSINC;
3973
3974         if (TrueVal > FalseVal) {
3975           Swap = true;
3976         }
3977       }
3978
3979       // Swap TVal and FVal if necessary.
3980       if (Swap) {
3981         std::swap(TVal, FVal);
3982         std::swap(CTVal, CFVal);
3983         CC = ISD::getSetCCInverse(CC, true);
3984       }
3985
3986       if (Opcode != AArch64ISD::CSEL) {
3987         // Drop FVal since we can get its value by simply inverting/negating
3988         // TVal.
3989         FVal = TVal;
3990       }
3991     }
3992
3993     SDValue CCVal;
3994     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3995
3996     EVT VT = TVal.getValueType();
3997     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3998   }
3999
4000   // Now we know we're dealing with FP values.
4001   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4002   assert(LHS.getValueType() == RHS.getValueType());
4003   EVT VT = TVal.getValueType();
4004   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4005
4006   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4007   // clean.  Some of them require two CSELs to implement.
4008   AArch64CC::CondCode CC1, CC2;
4009   changeFPCCToAArch64CC(CC, CC1, CC2);
4010   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4011   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4012
4013   // If we need a second CSEL, emit it, using the output of the first as the
4014   // RHS.  We're effectively OR'ing the two CC's together.
4015   if (CC2 != AArch64CC::AL) {
4016     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4017     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4018   }
4019
4020   // Otherwise, return the output of the first CSEL.
4021   return CS1;
4022 }
4023
4024 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4025                                               SelectionDAG &DAG) const {
4026   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4027   SDValue LHS = Op.getOperand(0);
4028   SDValue RHS = Op.getOperand(1);
4029   SDValue TVal = Op.getOperand(2);
4030   SDValue FVal = Op.getOperand(3);
4031   SDLoc DL(Op);
4032   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4033 }
4034
4035 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4036                                            SelectionDAG &DAG) const {
4037   SDValue CCVal = Op->getOperand(0);
4038   SDValue TVal = Op->getOperand(1);
4039   SDValue FVal = Op->getOperand(2);
4040   SDLoc DL(Op);
4041
4042   unsigned Opc = CCVal.getOpcode();
4043   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4044   // instruction.
4045   if (CCVal.getResNo() == 1 &&
4046       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4047        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4048     // Only lower legal XALUO ops.
4049     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4050       return SDValue();
4051
4052     AArch64CC::CondCode OFCC;
4053     SDValue Value, Overflow;
4054     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4055     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4056
4057     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4058                        CCVal, Overflow);
4059   }
4060
4061   // Lower it the same way as we would lower a SELECT_CC node.
4062   ISD::CondCode CC;
4063   SDValue LHS, RHS;
4064   if (CCVal.getOpcode() == ISD::SETCC) {
4065     LHS = CCVal.getOperand(0);
4066     RHS = CCVal.getOperand(1);
4067     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4068   } else {
4069     LHS = CCVal;
4070     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4071     CC = ISD::SETNE;
4072   }
4073   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4074 }
4075
4076 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4077                                               SelectionDAG &DAG) const {
4078   // Jump table entries as PC relative offsets. No additional tweaking
4079   // is necessary here. Just get the address of the jump table.
4080   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4081   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4082   SDLoc DL(Op);
4083
4084   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4085       !Subtarget->isTargetMachO()) {
4086     const unsigned char MO_NC = AArch64II::MO_NC;
4087     return DAG.getNode(
4088         AArch64ISD::WrapperLarge, DL, PtrVT,
4089         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4090         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4091         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4092         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4093                                AArch64II::MO_G0 | MO_NC));
4094   }
4095
4096   SDValue Hi =
4097       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4098   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4099                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4100   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4101   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4102 }
4103
4104 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4105                                                  SelectionDAG &DAG) const {
4106   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4107   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4108   SDLoc DL(Op);
4109
4110   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4111     // Use the GOT for the large code model on iOS.
4112     if (Subtarget->isTargetMachO()) {
4113       SDValue GotAddr = DAG.getTargetConstantPool(
4114           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4115           AArch64II::MO_GOT);
4116       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4117     }
4118
4119     const unsigned char MO_NC = AArch64II::MO_NC;
4120     return DAG.getNode(
4121         AArch64ISD::WrapperLarge, DL, PtrVT,
4122         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4123                                   CP->getOffset(), AArch64II::MO_G3),
4124         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4125                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4126         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4127                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4128         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4129                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4130   } else {
4131     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4132     // ELF, the only valid one on Darwin.
4133     SDValue Hi =
4134         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4135                                   CP->getOffset(), AArch64II::MO_PAGE);
4136     SDValue Lo = DAG.getTargetConstantPool(
4137         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4138         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4139
4140     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4141     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4142   }
4143 }
4144
4145 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4146                                                SelectionDAG &DAG) const {
4147   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4148   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4149   SDLoc DL(Op);
4150   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4151       !Subtarget->isTargetMachO()) {
4152     const unsigned char MO_NC = AArch64II::MO_NC;
4153     return DAG.getNode(
4154         AArch64ISD::WrapperLarge, DL, PtrVT,
4155         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4156         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4157         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4158         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4159   } else {
4160     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4161     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4162                                                              AArch64II::MO_NC);
4163     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4164     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4165   }
4166 }
4167
4168 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4169                                                  SelectionDAG &DAG) const {
4170   AArch64FunctionInfo *FuncInfo =
4171       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4172
4173   SDLoc DL(Op);
4174   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4175                                  getPointerTy(DAG.getDataLayout()));
4176   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4177   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4178                       MachinePointerInfo(SV), false, false, 0);
4179 }
4180
4181 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4182                                                 SelectionDAG &DAG) const {
4183   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4184   // Standard, section B.3.
4185   MachineFunction &MF = DAG.getMachineFunction();
4186   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4187   auto PtrVT = getPointerTy(DAG.getDataLayout());
4188   SDLoc DL(Op);
4189
4190   SDValue Chain = Op.getOperand(0);
4191   SDValue VAList = Op.getOperand(1);
4192   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4193   SmallVector<SDValue, 4> MemOps;
4194
4195   // void *__stack at offset 0
4196   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4197   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4198                                 MachinePointerInfo(SV), false, false, 8));
4199
4200   // void *__gr_top at offset 8
4201   int GPRSize = FuncInfo->getVarArgsGPRSize();
4202   if (GPRSize > 0) {
4203     SDValue GRTop, GRTopAddr;
4204
4205     GRTopAddr =
4206         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4207
4208     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4209     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4210                         DAG.getConstant(GPRSize, DL, PtrVT));
4211
4212     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4213                                   MachinePointerInfo(SV, 8), false, false, 8));
4214   }
4215
4216   // void *__vr_top at offset 16
4217   int FPRSize = FuncInfo->getVarArgsFPRSize();
4218   if (FPRSize > 0) {
4219     SDValue VRTop, VRTopAddr;
4220     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4221                             DAG.getConstant(16, DL, PtrVT));
4222
4223     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4224     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4225                         DAG.getConstant(FPRSize, DL, PtrVT));
4226
4227     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4228                                   MachinePointerInfo(SV, 16), false, false, 8));
4229   }
4230
4231   // int __gr_offs at offset 24
4232   SDValue GROffsAddr =
4233       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4234   MemOps.push_back(DAG.getStore(Chain, DL,
4235                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4236                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4237                                 false, 4));
4238
4239   // int __vr_offs at offset 28
4240   SDValue VROffsAddr =
4241       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4242   MemOps.push_back(DAG.getStore(Chain, DL,
4243                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4244                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4245                                 false, 4));
4246
4247   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4248 }
4249
4250 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4251                                             SelectionDAG &DAG) const {
4252   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4253                                      : LowerAAPCS_VASTART(Op, DAG);
4254 }
4255
4256 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4257                                            SelectionDAG &DAG) const {
4258   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4259   // pointer.
4260   SDLoc DL(Op);
4261   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4262   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4263   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4264
4265   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4266                        Op.getOperand(2),
4267                        DAG.getConstant(VaListSize, DL, MVT::i32),
4268                        8, false, false, false, MachinePointerInfo(DestSV),
4269                        MachinePointerInfo(SrcSV));
4270 }
4271
4272 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4273   assert(Subtarget->isTargetDarwin() &&
4274          "automatic va_arg instruction only works on Darwin");
4275
4276   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4277   EVT VT = Op.getValueType();
4278   SDLoc DL(Op);
4279   SDValue Chain = Op.getOperand(0);
4280   SDValue Addr = Op.getOperand(1);
4281   unsigned Align = Op.getConstantOperandVal(3);
4282   auto PtrVT = getPointerTy(DAG.getDataLayout());
4283
4284   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4285                                false, false, false, 0);
4286   Chain = VAList.getValue(1);
4287
4288   if (Align > 8) {
4289     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4290     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4291                          DAG.getConstant(Align - 1, DL, PtrVT));
4292     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4293                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4294   }
4295
4296   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4297   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4298
4299   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4300   // up to 64 bits.  At the very least, we have to increase the striding of the
4301   // vaargs list to match this, and for FP values we need to introduce
4302   // FP_ROUND nodes as well.
4303   if (VT.isInteger() && !VT.isVector())
4304     ArgSize = 8;
4305   bool NeedFPTrunc = false;
4306   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4307     ArgSize = 8;
4308     NeedFPTrunc = true;
4309   }
4310
4311   // Increment the pointer, VAList, to the next vaarg
4312   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4313                                DAG.getConstant(ArgSize, DL, PtrVT));
4314   // Store the incremented VAList to the legalized pointer
4315   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4316                                  false, false, 0);
4317
4318   // Load the actual argument out of the pointer VAList
4319   if (NeedFPTrunc) {
4320     // Load the value as an f64.
4321     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4322                                  MachinePointerInfo(), false, false, false, 0);
4323     // Round the value down to an f32.
4324     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4325                                    DAG.getIntPtrConstant(1, DL));
4326     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4327     // Merge the rounded value with the chain output of the load.
4328     return DAG.getMergeValues(Ops, DL);
4329   }
4330
4331   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4332                      false, false, 0);
4333 }
4334
4335 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4336                                               SelectionDAG &DAG) const {
4337   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4338   MFI->setFrameAddressIsTaken(true);
4339
4340   EVT VT = Op.getValueType();
4341   SDLoc DL(Op);
4342   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4343   SDValue FrameAddr =
4344       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4345   while (Depth--)
4346     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4347                             MachinePointerInfo(), false, false, false, 0);
4348   return FrameAddr;
4349 }
4350
4351 // FIXME? Maybe this could be a TableGen attribute on some registers and
4352 // this table could be generated automatically from RegInfo.
4353 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4354                                                   SelectionDAG &DAG) const {
4355   unsigned Reg = StringSwitch<unsigned>(RegName)
4356                        .Case("sp", AArch64::SP)
4357                        .Default(0);
4358   if (Reg)
4359     return Reg;
4360   report_fatal_error(Twine("Invalid register name \""
4361                               + StringRef(RegName)  + "\"."));
4362 }
4363
4364 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4365                                                SelectionDAG &DAG) const {
4366   MachineFunction &MF = DAG.getMachineFunction();
4367   MachineFrameInfo *MFI = MF.getFrameInfo();
4368   MFI->setReturnAddressIsTaken(true);
4369
4370   EVT VT = Op.getValueType();
4371   SDLoc DL(Op);
4372   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4373   if (Depth) {
4374     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4375     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4376     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4377                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4378                        MachinePointerInfo(), false, false, false, 0);
4379   }
4380
4381   // Return LR, which contains the return address. Mark it an implicit live-in.
4382   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4383   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4384 }
4385
4386 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4387 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4388 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4389                                                     SelectionDAG &DAG) const {
4390   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4391   EVT VT = Op.getValueType();
4392   unsigned VTBits = VT.getSizeInBits();
4393   SDLoc dl(Op);
4394   SDValue ShOpLo = Op.getOperand(0);
4395   SDValue ShOpHi = Op.getOperand(1);
4396   SDValue ShAmt = Op.getOperand(2);
4397   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4398
4399   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4400
4401   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4402                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4403   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4404
4405   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4406   // is "undef". We wanted 0, so CSEL it directly.
4407   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4408                                ISD::SETEQ, dl, DAG);
4409   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4410   HiBitsForLo =
4411       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4412                   HiBitsForLo, CCVal, Cmp);
4413
4414   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4415                                    DAG.getConstant(VTBits, dl, MVT::i64));
4416
4417   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4418   SDValue LoForNormalShift =
4419       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4420
4421   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4422                        dl, DAG);
4423   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4424   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4425   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4426                            LoForNormalShift, CCVal, Cmp);
4427
4428   // AArch64 shifts larger than the register width are wrapped rather than
4429   // clamped, so we can't just emit "hi >> x".
4430   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4431   SDValue HiForBigShift =
4432       Opc == ISD::SRA
4433           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4434                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4435           : DAG.getConstant(0, dl, VT);
4436   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4437                            HiForNormalShift, CCVal, Cmp);
4438
4439   SDValue Ops[2] = { Lo, Hi };
4440   return DAG.getMergeValues(Ops, dl);
4441 }
4442
4443
4444 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4445 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4446 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4447                                                    SelectionDAG &DAG) const {
4448   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4449   EVT VT = Op.getValueType();
4450   unsigned VTBits = VT.getSizeInBits();
4451   SDLoc dl(Op);
4452   SDValue ShOpLo = Op.getOperand(0);
4453   SDValue ShOpHi = Op.getOperand(1);
4454   SDValue ShAmt = Op.getOperand(2);
4455
4456   assert(Op.getOpcode() == ISD::SHL_PARTS);
4457   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4458                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4459   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4460
4461   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4462   // is "undef". We wanted 0, so CSEL it directly.
4463   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4464                                ISD::SETEQ, dl, DAG);
4465   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4466   LoBitsForHi =
4467       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4468                   LoBitsForHi, CCVal, Cmp);
4469
4470   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4471                                    DAG.getConstant(VTBits, dl, MVT::i64));
4472   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4473   SDValue HiForNormalShift =
4474       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4475
4476   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4477
4478   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4479                        dl, DAG);
4480   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4481   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4482                            HiForNormalShift, CCVal, Cmp);
4483
4484   // AArch64 shifts of larger than register sizes are wrapped rather than
4485   // clamped, so we can't just emit "lo << a" if a is too big.
4486   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4487   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4488   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4489                            LoForNormalShift, CCVal, Cmp);
4490
4491   SDValue Ops[2] = { Lo, Hi };
4492   return DAG.getMergeValues(Ops, dl);
4493 }
4494
4495 bool AArch64TargetLowering::isOffsetFoldingLegal(
4496     const GlobalAddressSDNode *GA) const {
4497   // The AArch64 target doesn't support folding offsets into global addresses.
4498   return false;
4499 }
4500
4501 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4502   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4503   // FIXME: We should be able to handle f128 as well with a clever lowering.
4504   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4505     return true;
4506
4507   if (VT == MVT::f64)
4508     return AArch64_AM::getFP64Imm(Imm) != -1;
4509   else if (VT == MVT::f32)
4510     return AArch64_AM::getFP32Imm(Imm) != -1;
4511   return false;
4512 }
4513
4514 //===----------------------------------------------------------------------===//
4515 //                          AArch64 Optimization Hooks
4516 //===----------------------------------------------------------------------===//
4517
4518 //===----------------------------------------------------------------------===//
4519 //                          AArch64 Inline Assembly Support
4520 //===----------------------------------------------------------------------===//
4521
4522 // Table of Constraints
4523 // TODO: This is the current set of constraints supported by ARM for the
4524 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4525 //
4526 // r - A general register
4527 // w - An FP/SIMD register of some size in the range v0-v31
4528 // x - An FP/SIMD register of some size in the range v0-v15
4529 // I - Constant that can be used with an ADD instruction
4530 // J - Constant that can be used with a SUB instruction
4531 // K - Constant that can be used with a 32-bit logical instruction
4532 // L - Constant that can be used with a 64-bit logical instruction
4533 // M - Constant that can be used as a 32-bit MOV immediate
4534 // N - Constant that can be used as a 64-bit MOV immediate
4535 // Q - A memory reference with base register and no offset
4536 // S - A symbolic address
4537 // Y - Floating point constant zero
4538 // Z - Integer constant zero
4539 //
4540 //   Note that general register operands will be output using their 64-bit x
4541 // register name, whatever the size of the variable, unless the asm operand
4542 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4543 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4544 // %q modifier.
4545
4546 /// getConstraintType - Given a constraint letter, return the type of
4547 /// constraint it is for this target.
4548 AArch64TargetLowering::ConstraintType
4549 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4550   if (Constraint.size() == 1) {
4551     switch (Constraint[0]) {
4552     default:
4553       break;
4554     case 'z':
4555       return C_Other;
4556     case 'x':
4557     case 'w':
4558       return C_RegisterClass;
4559     // An address with a single base register. Due to the way we
4560     // currently handle addresses it is the same as 'r'.
4561     case 'Q':
4562       return C_Memory;
4563     }
4564   }
4565   return TargetLowering::getConstraintType(Constraint);
4566 }
4567
4568 /// Examine constraint type and operand type and determine a weight value.
4569 /// This object must already have been set up with the operand type
4570 /// and the current alternative constraint selected.
4571 TargetLowering::ConstraintWeight
4572 AArch64TargetLowering::getSingleConstraintMatchWeight(
4573     AsmOperandInfo &info, const char *constraint) const {
4574   ConstraintWeight weight = CW_Invalid;
4575   Value *CallOperandVal = info.CallOperandVal;
4576   // If we don't have a value, we can't do a match,
4577   // but allow it at the lowest weight.
4578   if (!CallOperandVal)
4579     return CW_Default;
4580   Type *type = CallOperandVal->getType();
4581   // Look at the constraint type.
4582   switch (*constraint) {
4583   default:
4584     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4585     break;
4586   case 'x':
4587   case 'w':
4588     if (type->isFloatingPointTy() || type->isVectorTy())
4589       weight = CW_Register;
4590     break;
4591   case 'z':
4592     weight = CW_Constant;
4593     break;
4594   }
4595   return weight;
4596 }
4597
4598 std::pair<unsigned, const TargetRegisterClass *>
4599 AArch64TargetLowering::getRegForInlineAsmConstraint(
4600     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4601   if (Constraint.size() == 1) {
4602     switch (Constraint[0]) {
4603     case 'r':
4604       if (VT.getSizeInBits() == 64)
4605         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4606       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4607     case 'w':
4608       if (VT == MVT::f32)
4609         return std::make_pair(0U, &AArch64::FPR32RegClass);
4610       if (VT.getSizeInBits() == 64)
4611         return std::make_pair(0U, &AArch64::FPR64RegClass);
4612       if (VT.getSizeInBits() == 128)
4613         return std::make_pair(0U, &AArch64::FPR128RegClass);
4614       break;
4615     // The instructions that this constraint is designed for can
4616     // only take 128-bit registers so just use that regclass.
4617     case 'x':
4618       if (VT.getSizeInBits() == 128)
4619         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4620       break;
4621     }
4622   }
4623   if (StringRef("{cc}").equals_lower(Constraint))
4624     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4625
4626   // Use the default implementation in TargetLowering to convert the register
4627   // constraint into a member of a register class.
4628   std::pair<unsigned, const TargetRegisterClass *> Res;
4629   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4630
4631   // Not found as a standard register?
4632   if (!Res.second) {
4633     unsigned Size = Constraint.size();
4634     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4635         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4636       int RegNo;
4637       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4638       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4639         // v0 - v31 are aliases of q0 - q31.
4640         // By default we'll emit v0-v31 for this unless there's a modifier where
4641         // we'll emit the correct register as well.
4642         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4643         Res.second = &AArch64::FPR128RegClass;
4644       }
4645     }
4646   }
4647
4648   return Res;
4649 }
4650
4651 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4652 /// vector.  If it is invalid, don't add anything to Ops.
4653 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4654     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4655     SelectionDAG &DAG) const {
4656   SDValue Result;
4657
4658   // Currently only support length 1 constraints.
4659   if (Constraint.length() != 1)
4660     return;
4661
4662   char ConstraintLetter = Constraint[0];
4663   switch (ConstraintLetter) {
4664   default:
4665     break;
4666
4667   // This set of constraints deal with valid constants for various instructions.
4668   // Validate and return a target constant for them if we can.
4669   case 'z': {
4670     // 'z' maps to xzr or wzr so it needs an input of 0.
4671     if (!isNullConstant(Op))
4672       return;
4673
4674     if (Op.getValueType() == MVT::i64)
4675       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4676     else
4677       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4678     break;
4679   }
4680
4681   case 'I':
4682   case 'J':
4683   case 'K':
4684   case 'L':
4685   case 'M':
4686   case 'N':
4687     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4688     if (!C)
4689       return;
4690
4691     // Grab the value and do some validation.
4692     uint64_t CVal = C->getZExtValue();
4693     switch (ConstraintLetter) {
4694     // The I constraint applies only to simple ADD or SUB immediate operands:
4695     // i.e. 0 to 4095 with optional shift by 12
4696     // The J constraint applies only to ADD or SUB immediates that would be
4697     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4698     // instruction [or vice versa], in other words -1 to -4095 with optional
4699     // left shift by 12.
4700     case 'I':
4701       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4702         break;
4703       return;
4704     case 'J': {
4705       uint64_t NVal = -C->getSExtValue();
4706       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4707         CVal = C->getSExtValue();
4708         break;
4709       }
4710       return;
4711     }
4712     // The K and L constraints apply *only* to logical immediates, including
4713     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4714     // been removed and MOV should be used). So these constraints have to
4715     // distinguish between bit patterns that are valid 32-bit or 64-bit
4716     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4717     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4718     // versa.
4719     case 'K':
4720       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4721         break;
4722       return;
4723     case 'L':
4724       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4725         break;
4726       return;
4727     // The M and N constraints are a superset of K and L respectively, for use
4728     // with the MOV (immediate) alias. As well as the logical immediates they
4729     // also match 32 or 64-bit immediates that can be loaded either using a
4730     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4731     // (M) or 64-bit 0x1234000000000000 (N) etc.
4732     // As a note some of this code is liberally stolen from the asm parser.
4733     case 'M': {
4734       if (!isUInt<32>(CVal))
4735         return;
4736       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4737         break;
4738       if ((CVal & 0xFFFF) == CVal)
4739         break;
4740       if ((CVal & 0xFFFF0000ULL) == CVal)
4741         break;
4742       uint64_t NCVal = ~(uint32_t)CVal;
4743       if ((NCVal & 0xFFFFULL) == NCVal)
4744         break;
4745       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4746         break;
4747       return;
4748     }
4749     case 'N': {
4750       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4751         break;
4752       if ((CVal & 0xFFFFULL) == CVal)
4753         break;
4754       if ((CVal & 0xFFFF0000ULL) == CVal)
4755         break;
4756       if ((CVal & 0xFFFF00000000ULL) == CVal)
4757         break;
4758       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4759         break;
4760       uint64_t NCVal = ~CVal;
4761       if ((NCVal & 0xFFFFULL) == NCVal)
4762         break;
4763       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4764         break;
4765       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4766         break;
4767       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4768         break;
4769       return;
4770     }
4771     default:
4772       return;
4773     }
4774
4775     // All assembler immediates are 64-bit integers.
4776     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4777     break;
4778   }
4779
4780   if (Result.getNode()) {
4781     Ops.push_back(Result);
4782     return;
4783   }
4784
4785   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4786 }
4787
4788 //===----------------------------------------------------------------------===//
4789 //                     AArch64 Advanced SIMD Support
4790 //===----------------------------------------------------------------------===//
4791
4792 /// WidenVector - Given a value in the V64 register class, produce the
4793 /// equivalent value in the V128 register class.
4794 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4795   EVT VT = V64Reg.getValueType();
4796   unsigned NarrowSize = VT.getVectorNumElements();
4797   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4798   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4799   SDLoc DL(V64Reg);
4800
4801   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4802                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4803 }
4804
4805 /// getExtFactor - Determine the adjustment factor for the position when
4806 /// generating an "extract from vector registers" instruction.
4807 static unsigned getExtFactor(SDValue &V) {
4808   EVT EltType = V.getValueType().getVectorElementType();
4809   return EltType.getSizeInBits() / 8;
4810 }
4811
4812 /// NarrowVector - Given a value in the V128 register class, produce the
4813 /// equivalent value in the V64 register class.
4814 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4815   EVT VT = V128Reg.getValueType();
4816   unsigned WideSize = VT.getVectorNumElements();
4817   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4818   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4819   SDLoc DL(V128Reg);
4820
4821   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4822 }
4823
4824 // Gather data to see if the operation can be modelled as a
4825 // shuffle in combination with VEXTs.
4826 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4827                                                   SelectionDAG &DAG) const {
4828   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4829   SDLoc dl(Op);
4830   EVT VT = Op.getValueType();
4831   unsigned NumElts = VT.getVectorNumElements();
4832
4833   struct ShuffleSourceInfo {
4834     SDValue Vec;
4835     unsigned MinElt;
4836     unsigned MaxElt;
4837
4838     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4839     // be compatible with the shuffle we intend to construct. As a result
4840     // ShuffleVec will be some sliding window into the original Vec.
4841     SDValue ShuffleVec;
4842
4843     // Code should guarantee that element i in Vec starts at element "WindowBase
4844     // + i * WindowScale in ShuffleVec".
4845     int WindowBase;
4846     int WindowScale;
4847
4848     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4849     ShuffleSourceInfo(SDValue Vec)
4850         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4851           WindowScale(1) {}
4852   };
4853
4854   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4855   // node.
4856   SmallVector<ShuffleSourceInfo, 2> Sources;
4857   for (unsigned i = 0; i < NumElts; ++i) {
4858     SDValue V = Op.getOperand(i);
4859     if (V.getOpcode() == ISD::UNDEF)
4860       continue;
4861     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4862       // A shuffle can only come from building a vector from various
4863       // elements of other vectors.
4864       return SDValue();
4865     }
4866
4867     // Add this element source to the list if it's not already there.
4868     SDValue SourceVec = V.getOperand(0);
4869     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4870     if (Source == Sources.end())
4871       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4872
4873     // Update the minimum and maximum lane number seen.
4874     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4875     Source->MinElt = std::min(Source->MinElt, EltNo);
4876     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4877   }
4878
4879   // Currently only do something sane when at most two source vectors
4880   // are involved.
4881   if (Sources.size() > 2)
4882     return SDValue();
4883
4884   // Find out the smallest element size among result and two sources, and use
4885   // it as element size to build the shuffle_vector.
4886   EVT SmallestEltTy = VT.getVectorElementType();
4887   for (auto &Source : Sources) {
4888     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4889     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4890       SmallestEltTy = SrcEltTy;
4891     }
4892   }
4893   unsigned ResMultiplier =
4894       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4895   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4896   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4897
4898   // If the source vector is too wide or too narrow, we may nevertheless be able
4899   // to construct a compatible shuffle either by concatenating it with UNDEF or
4900   // extracting a suitable range of elements.
4901   for (auto &Src : Sources) {
4902     EVT SrcVT = Src.ShuffleVec.getValueType();
4903
4904     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4905       continue;
4906
4907     // This stage of the search produces a source with the same element type as
4908     // the original, but with a total width matching the BUILD_VECTOR output.
4909     EVT EltVT = SrcVT.getVectorElementType();
4910     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4911     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4912
4913     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4914       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4915       // We can pad out the smaller vector for free, so if it's part of a
4916       // shuffle...
4917       Src.ShuffleVec =
4918           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4919                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4920       continue;
4921     }
4922
4923     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4924
4925     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4926       // Span too large for a VEXT to cope
4927       return SDValue();
4928     }
4929
4930     if (Src.MinElt >= NumSrcElts) {
4931       // The extraction can just take the second half
4932       Src.ShuffleVec =
4933           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4934                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4935       Src.WindowBase = -NumSrcElts;
4936     } else if (Src.MaxElt < NumSrcElts) {
4937       // The extraction can just take the first half
4938       Src.ShuffleVec =
4939           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4940                       DAG.getConstant(0, dl, MVT::i64));
4941     } else {
4942       // An actual VEXT is needed
4943       SDValue VEXTSrc1 =
4944           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4945                       DAG.getConstant(0, dl, MVT::i64));
4946       SDValue VEXTSrc2 =
4947           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4948                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4949       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4950
4951       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4952                                    VEXTSrc2,
4953                                    DAG.getConstant(Imm, dl, MVT::i32));
4954       Src.WindowBase = -Src.MinElt;
4955     }
4956   }
4957
4958   // Another possible incompatibility occurs from the vector element types. We
4959   // can fix this by bitcasting the source vectors to the same type we intend
4960   // for the shuffle.
4961   for (auto &Src : Sources) {
4962     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4963     if (SrcEltTy == SmallestEltTy)
4964       continue;
4965     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4966     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4967     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4968     Src.WindowBase *= Src.WindowScale;
4969   }
4970
4971   // Final sanity check before we try to actually produce a shuffle.
4972   DEBUG(
4973     for (auto Src : Sources)
4974       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4975   );
4976
4977   // The stars all align, our next step is to produce the mask for the shuffle.
4978   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4979   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4980   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4981     SDValue Entry = Op.getOperand(i);
4982     if (Entry.getOpcode() == ISD::UNDEF)
4983       continue;
4984
4985     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4986     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4987
4988     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4989     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4990     // segment.
4991     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4992     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4993                                VT.getVectorElementType().getSizeInBits());
4994     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4995
4996     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4997     // starting at the appropriate offset.
4998     int *LaneMask = &Mask[i * ResMultiplier];
4999
5000     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5001     ExtractBase += NumElts * (Src - Sources.begin());
5002     for (int j = 0; j < LanesDefined; ++j)
5003       LaneMask[j] = ExtractBase + j;
5004   }
5005
5006   // Final check before we try to produce nonsense...
5007   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5008     return SDValue();
5009
5010   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5011   for (unsigned i = 0; i < Sources.size(); ++i)
5012     ShuffleOps[i] = Sources[i].ShuffleVec;
5013
5014   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5015                                          ShuffleOps[1], &Mask[0]);
5016   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5017 }
5018
5019 // check if an EXT instruction can handle the shuffle mask when the
5020 // vector sources of the shuffle are the same.
5021 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5022   unsigned NumElts = VT.getVectorNumElements();
5023
5024   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5025   if (M[0] < 0)
5026     return false;
5027
5028   Imm = M[0];
5029
5030   // If this is a VEXT shuffle, the immediate value is the index of the first
5031   // element.  The other shuffle indices must be the successive elements after
5032   // the first one.
5033   unsigned ExpectedElt = Imm;
5034   for (unsigned i = 1; i < NumElts; ++i) {
5035     // Increment the expected index.  If it wraps around, just follow it
5036     // back to index zero and keep going.
5037     ++ExpectedElt;
5038     if (ExpectedElt == NumElts)
5039       ExpectedElt = 0;
5040
5041     if (M[i] < 0)
5042       continue; // ignore UNDEF indices
5043     if (ExpectedElt != static_cast<unsigned>(M[i]))
5044       return false;
5045   }
5046
5047   return true;
5048 }
5049
5050 // check if an EXT instruction can handle the shuffle mask when the
5051 // vector sources of the shuffle are different.
5052 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5053                       unsigned &Imm) {
5054   // Look for the first non-undef element.
5055   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5056       [](int Elt) {return Elt >= 0;});
5057
5058   // Benefit form APInt to handle overflow when calculating expected element.
5059   unsigned NumElts = VT.getVectorNumElements();
5060   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5061   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5062   // The following shuffle indices must be the successive elements after the
5063   // first real element.
5064   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5065       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5066   if (FirstWrongElt != M.end())
5067     return false;
5068
5069   // The index of an EXT is the first element if it is not UNDEF.
5070   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5071   // value of the first element.  E.g. 
5072   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5073   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5074   // ExpectedElt is the last mask index plus 1.
5075   Imm = ExpectedElt.getZExtValue();
5076
5077   // There are two difference cases requiring to reverse input vectors.
5078   // For example, for vector <4 x i32> we have the following cases,
5079   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5080   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5081   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5082   // to reverse two input vectors.
5083   if (Imm < NumElts)
5084     ReverseEXT = true;
5085   else
5086     Imm -= NumElts;
5087
5088   return true;
5089 }
5090
5091 /// isREVMask - Check if a vector shuffle corresponds to a REV
5092 /// instruction with the specified blocksize.  (The order of the elements
5093 /// within each block of the vector is reversed.)
5094 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5095   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5096          "Only possible block sizes for REV are: 16, 32, 64");
5097
5098   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5099   if (EltSz == 64)
5100     return false;
5101
5102   unsigned NumElts = VT.getVectorNumElements();
5103   unsigned BlockElts = M[0] + 1;
5104   // If the first shuffle index is UNDEF, be optimistic.
5105   if (M[0] < 0)
5106     BlockElts = BlockSize / EltSz;
5107
5108   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5109     return false;
5110
5111   for (unsigned i = 0; i < NumElts; ++i) {
5112     if (M[i] < 0)
5113       continue; // ignore UNDEF indices
5114     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5115       return false;
5116   }
5117
5118   return true;
5119 }
5120
5121 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5122   unsigned NumElts = VT.getVectorNumElements();
5123   WhichResult = (M[0] == 0 ? 0 : 1);
5124   unsigned Idx = WhichResult * NumElts / 2;
5125   for (unsigned i = 0; i != NumElts; i += 2) {
5126     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5127         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5128       return false;
5129     Idx += 1;
5130   }
5131
5132   return true;
5133 }
5134
5135 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5136   unsigned NumElts = VT.getVectorNumElements();
5137   WhichResult = (M[0] == 0 ? 0 : 1);
5138   for (unsigned i = 0; i != NumElts; ++i) {
5139     if (M[i] < 0)
5140       continue; // ignore UNDEF indices
5141     if ((unsigned)M[i] != 2 * i + WhichResult)
5142       return false;
5143   }
5144
5145   return true;
5146 }
5147
5148 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5149   unsigned NumElts = VT.getVectorNumElements();
5150   WhichResult = (M[0] == 0 ? 0 : 1);
5151   for (unsigned i = 0; i < NumElts; i += 2) {
5152     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5153         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5154       return false;
5155   }
5156   return true;
5157 }
5158
5159 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5160 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5161 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5162 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5163   unsigned NumElts = VT.getVectorNumElements();
5164   WhichResult = (M[0] == 0 ? 0 : 1);
5165   unsigned Idx = WhichResult * NumElts / 2;
5166   for (unsigned i = 0; i != NumElts; i += 2) {
5167     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5168         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5169       return false;
5170     Idx += 1;
5171   }
5172
5173   return true;
5174 }
5175
5176 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5177 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5178 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5179 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5180   unsigned Half = VT.getVectorNumElements() / 2;
5181   WhichResult = (M[0] == 0 ? 0 : 1);
5182   for (unsigned j = 0; j != 2; ++j) {
5183     unsigned Idx = WhichResult;
5184     for (unsigned i = 0; i != Half; ++i) {
5185       int MIdx = M[i + j * Half];
5186       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5187         return false;
5188       Idx += 2;
5189     }
5190   }
5191
5192   return true;
5193 }
5194
5195 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5196 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5197 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5198 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5199   unsigned NumElts = VT.getVectorNumElements();
5200   WhichResult = (M[0] == 0 ? 0 : 1);
5201   for (unsigned i = 0; i < NumElts; i += 2) {
5202     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5203         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5204       return false;
5205   }
5206   return true;
5207 }
5208
5209 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5210                       bool &DstIsLeft, int &Anomaly) {
5211   if (M.size() != static_cast<size_t>(NumInputElements))
5212     return false;
5213
5214   int NumLHSMatch = 0, NumRHSMatch = 0;
5215   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5216
5217   for (int i = 0; i < NumInputElements; ++i) {
5218     if (M[i] == -1) {
5219       ++NumLHSMatch;
5220       ++NumRHSMatch;
5221       continue;
5222     }
5223
5224     if (M[i] == i)
5225       ++NumLHSMatch;
5226     else
5227       LastLHSMismatch = i;
5228
5229     if (M[i] == i + NumInputElements)
5230       ++NumRHSMatch;
5231     else
5232       LastRHSMismatch = i;
5233   }
5234
5235   if (NumLHSMatch == NumInputElements - 1) {
5236     DstIsLeft = true;
5237     Anomaly = LastLHSMismatch;
5238     return true;
5239   } else if (NumRHSMatch == NumInputElements - 1) {
5240     DstIsLeft = false;
5241     Anomaly = LastRHSMismatch;
5242     return true;
5243   }
5244
5245   return false;
5246 }
5247
5248 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5249   if (VT.getSizeInBits() != 128)
5250     return false;
5251
5252   unsigned NumElts = VT.getVectorNumElements();
5253
5254   for (int I = 0, E = NumElts / 2; I != E; I++) {
5255     if (Mask[I] != I)
5256       return false;
5257   }
5258
5259   int Offset = NumElts / 2;
5260   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5261     if (Mask[I] != I + SplitLHS * Offset)
5262       return false;
5263   }
5264
5265   return true;
5266 }
5267
5268 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5269   SDLoc DL(Op);
5270   EVT VT = Op.getValueType();
5271   SDValue V0 = Op.getOperand(0);
5272   SDValue V1 = Op.getOperand(1);
5273   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5274
5275   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5276       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5277     return SDValue();
5278
5279   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5280
5281   if (!isConcatMask(Mask, VT, SplitV0))
5282     return SDValue();
5283
5284   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5285                                 VT.getVectorNumElements() / 2);
5286   if (SplitV0) {
5287     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5288                      DAG.getConstant(0, DL, MVT::i64));
5289   }
5290   if (V1.getValueType().getSizeInBits() == 128) {
5291     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5292                      DAG.getConstant(0, DL, MVT::i64));
5293   }
5294   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5295 }
5296
5297 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5298 /// the specified operations to build the shuffle.
5299 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5300                                       SDValue RHS, SelectionDAG &DAG,
5301                                       SDLoc dl) {
5302   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5303   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5304   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5305
5306   enum {
5307     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5308     OP_VREV,
5309     OP_VDUP0,
5310     OP_VDUP1,
5311     OP_VDUP2,
5312     OP_VDUP3,
5313     OP_VEXT1,
5314     OP_VEXT2,
5315     OP_VEXT3,
5316     OP_VUZPL, // VUZP, left result
5317     OP_VUZPR, // VUZP, right result
5318     OP_VZIPL, // VZIP, left result
5319     OP_VZIPR, // VZIP, right result
5320     OP_VTRNL, // VTRN, left result
5321     OP_VTRNR  // VTRN, right result
5322   };
5323
5324   if (OpNum == OP_COPY) {
5325     if (LHSID == (1 * 9 + 2) * 9 + 3)
5326       return LHS;
5327     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5328     return RHS;
5329   }
5330
5331   SDValue OpLHS, OpRHS;
5332   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5333   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5334   EVT VT = OpLHS.getValueType();
5335
5336   switch (OpNum) {
5337   default:
5338     llvm_unreachable("Unknown shuffle opcode!");
5339   case OP_VREV:
5340     // VREV divides the vector in half and swaps within the half.
5341     if (VT.getVectorElementType() == MVT::i32 ||
5342         VT.getVectorElementType() == MVT::f32)
5343       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5344     // vrev <4 x i16> -> REV32
5345     if (VT.getVectorElementType() == MVT::i16 ||
5346         VT.getVectorElementType() == MVT::f16)
5347       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5348     // vrev <4 x i8> -> REV16
5349     assert(VT.getVectorElementType() == MVT::i8);
5350     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5351   case OP_VDUP0:
5352   case OP_VDUP1:
5353   case OP_VDUP2:
5354   case OP_VDUP3: {
5355     EVT EltTy = VT.getVectorElementType();
5356     unsigned Opcode;
5357     if (EltTy == MVT::i8)
5358       Opcode = AArch64ISD::DUPLANE8;
5359     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5360       Opcode = AArch64ISD::DUPLANE16;
5361     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5362       Opcode = AArch64ISD::DUPLANE32;
5363     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5364       Opcode = AArch64ISD::DUPLANE64;
5365     else
5366       llvm_unreachable("Invalid vector element type?");
5367
5368     if (VT.getSizeInBits() == 64)
5369       OpLHS = WidenVector(OpLHS, DAG);
5370     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5371     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5372   }
5373   case OP_VEXT1:
5374   case OP_VEXT2:
5375   case OP_VEXT3: {
5376     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5377     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5378                        DAG.getConstant(Imm, dl, MVT::i32));
5379   }
5380   case OP_VUZPL:
5381     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5382                        OpRHS);
5383   case OP_VUZPR:
5384     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5385                        OpRHS);
5386   case OP_VZIPL:
5387     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5388                        OpRHS);
5389   case OP_VZIPR:
5390     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5391                        OpRHS);
5392   case OP_VTRNL:
5393     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5394                        OpRHS);
5395   case OP_VTRNR:
5396     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5397                        OpRHS);
5398   }
5399 }
5400
5401 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5402                            SelectionDAG &DAG) {
5403   // Check to see if we can use the TBL instruction.
5404   SDValue V1 = Op.getOperand(0);
5405   SDValue V2 = Op.getOperand(1);
5406   SDLoc DL(Op);
5407
5408   EVT EltVT = Op.getValueType().getVectorElementType();
5409   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5410
5411   SmallVector<SDValue, 8> TBLMask;
5412   for (int Val : ShuffleMask) {
5413     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5414       unsigned Offset = Byte + Val * BytesPerElt;
5415       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5416     }
5417   }
5418
5419   MVT IndexVT = MVT::v8i8;
5420   unsigned IndexLen = 8;
5421   if (Op.getValueType().getSizeInBits() == 128) {
5422     IndexVT = MVT::v16i8;
5423     IndexLen = 16;
5424   }
5425
5426   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5427   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5428
5429   SDValue Shuffle;
5430   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5431     if (IndexLen == 8)
5432       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5433     Shuffle = DAG.getNode(
5434         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5435         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5436         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5437                     makeArrayRef(TBLMask.data(), IndexLen)));
5438   } else {
5439     if (IndexLen == 8) {
5440       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5441       Shuffle = DAG.getNode(
5442           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5443           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5444           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5445                       makeArrayRef(TBLMask.data(), IndexLen)));
5446     } else {
5447       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5448       // cannot currently represent the register constraints on the input
5449       // table registers.
5450       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5451       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5452       //                               &TBLMask[0], IndexLen));
5453       Shuffle = DAG.getNode(
5454           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5455           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5456           V1Cst, V2Cst,
5457           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5458                       makeArrayRef(TBLMask.data(), IndexLen)));
5459     }
5460   }
5461   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5462 }
5463
5464 static unsigned getDUPLANEOp(EVT EltType) {
5465   if (EltType == MVT::i8)
5466     return AArch64ISD::DUPLANE8;
5467   if (EltType == MVT::i16 || EltType == MVT::f16)
5468     return AArch64ISD::DUPLANE16;
5469   if (EltType == MVT::i32 || EltType == MVT::f32)
5470     return AArch64ISD::DUPLANE32;
5471   if (EltType == MVT::i64 || EltType == MVT::f64)
5472     return AArch64ISD::DUPLANE64;
5473
5474   llvm_unreachable("Invalid vector element type?");
5475 }
5476
5477 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5478                                                    SelectionDAG &DAG) const {
5479   SDLoc dl(Op);
5480   EVT VT = Op.getValueType();
5481
5482   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5483
5484   // Convert shuffles that are directly supported on NEON to target-specific
5485   // DAG nodes, instead of keeping them as shuffles and matching them again
5486   // during code selection.  This is more efficient and avoids the possibility
5487   // of inconsistencies between legalization and selection.
5488   ArrayRef<int> ShuffleMask = SVN->getMask();
5489
5490   SDValue V1 = Op.getOperand(0);
5491   SDValue V2 = Op.getOperand(1);
5492
5493   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5494                                        V1.getValueType().getSimpleVT())) {
5495     int Lane = SVN->getSplatIndex();
5496     // If this is undef splat, generate it via "just" vdup, if possible.
5497     if (Lane == -1)
5498       Lane = 0;
5499
5500     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5501       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5502                          V1.getOperand(0));
5503     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5504     // constant. If so, we can just reference the lane's definition directly.
5505     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5506         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5507       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5508
5509     // Otherwise, duplicate from the lane of the input vector.
5510     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5511
5512     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5513     // to make a vector of the same size as this SHUFFLE. We can ignore the
5514     // extract entirely, and canonicalise the concat using WidenVector.
5515     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5516       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5517       V1 = V1.getOperand(0);
5518     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5519       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5520       Lane -= Idx * VT.getVectorNumElements() / 2;
5521       V1 = WidenVector(V1.getOperand(Idx), DAG);
5522     } else if (VT.getSizeInBits() == 64)
5523       V1 = WidenVector(V1, DAG);
5524
5525     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5526   }
5527
5528   if (isREVMask(ShuffleMask, VT, 64))
5529     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5530   if (isREVMask(ShuffleMask, VT, 32))
5531     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5532   if (isREVMask(ShuffleMask, VT, 16))
5533     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5534
5535   bool ReverseEXT = false;
5536   unsigned Imm;
5537   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5538     if (ReverseEXT)
5539       std::swap(V1, V2);
5540     Imm *= getExtFactor(V1);
5541     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5542                        DAG.getConstant(Imm, dl, MVT::i32));
5543   } else if (V2->getOpcode() == ISD::UNDEF &&
5544              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5545     Imm *= getExtFactor(V1);
5546     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5547                        DAG.getConstant(Imm, dl, MVT::i32));
5548   }
5549
5550   unsigned WhichResult;
5551   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5552     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5553     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5554   }
5555   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5556     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5557     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5558   }
5559   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5560     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5561     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5562   }
5563
5564   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5565     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5566     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5567   }
5568   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5569     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5570     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5571   }
5572   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5573     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5574     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5575   }
5576
5577   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5578   if (Concat.getNode())
5579     return Concat;
5580
5581   bool DstIsLeft;
5582   int Anomaly;
5583   int NumInputElements = V1.getValueType().getVectorNumElements();
5584   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5585     SDValue DstVec = DstIsLeft ? V1 : V2;
5586     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5587
5588     SDValue SrcVec = V1;
5589     int SrcLane = ShuffleMask[Anomaly];
5590     if (SrcLane >= NumInputElements) {
5591       SrcVec = V2;
5592       SrcLane -= VT.getVectorNumElements();
5593     }
5594     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5595
5596     EVT ScalarVT = VT.getVectorElementType();
5597
5598     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5599       ScalarVT = MVT::i32;
5600
5601     return DAG.getNode(
5602         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5603         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5604         DstLaneV);
5605   }
5606
5607   // If the shuffle is not directly supported and it has 4 elements, use
5608   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5609   unsigned NumElts = VT.getVectorNumElements();
5610   if (NumElts == 4) {
5611     unsigned PFIndexes[4];
5612     for (unsigned i = 0; i != 4; ++i) {
5613       if (ShuffleMask[i] < 0)
5614         PFIndexes[i] = 8;
5615       else
5616         PFIndexes[i] = ShuffleMask[i];
5617     }
5618
5619     // Compute the index in the perfect shuffle table.
5620     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5621                             PFIndexes[2] * 9 + PFIndexes[3];
5622     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5623     unsigned Cost = (PFEntry >> 30);
5624
5625     if (Cost <= 4)
5626       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5627   }
5628
5629   return GenerateTBL(Op, ShuffleMask, DAG);
5630 }
5631
5632 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5633                                APInt &UndefBits) {
5634   EVT VT = BVN->getValueType(0);
5635   APInt SplatBits, SplatUndef;
5636   unsigned SplatBitSize;
5637   bool HasAnyUndefs;
5638   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5639     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5640
5641     for (unsigned i = 0; i < NumSplats; ++i) {
5642       CnstBits <<= SplatBitSize;
5643       UndefBits <<= SplatBitSize;
5644       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5645       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5646     }
5647
5648     return true;
5649   }
5650
5651   return false;
5652 }
5653
5654 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5655                                               SelectionDAG &DAG) const {
5656   BuildVectorSDNode *BVN =
5657       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5658   SDValue LHS = Op.getOperand(0);
5659   SDLoc dl(Op);
5660   EVT VT = Op.getValueType();
5661
5662   if (!BVN)
5663     return Op;
5664
5665   APInt CnstBits(VT.getSizeInBits(), 0);
5666   APInt UndefBits(VT.getSizeInBits(), 0);
5667   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5668     // We only have BIC vector immediate instruction, which is and-not.
5669     CnstBits = ~CnstBits;
5670
5671     // We make use of a little bit of goto ickiness in order to avoid having to
5672     // duplicate the immediate matching logic for the undef toggled case.
5673     bool SecondTry = false;
5674   AttemptModImm:
5675
5676     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5677       CnstBits = CnstBits.zextOrTrunc(64);
5678       uint64_t CnstVal = CnstBits.getZExtValue();
5679
5680       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5681         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5682         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5683         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5684                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5685                                   DAG.getConstant(0, dl, MVT::i32));
5686         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5687       }
5688
5689       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5690         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5691         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5692         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5693                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5694                                   DAG.getConstant(8, dl, MVT::i32));
5695         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5696       }
5697
5698       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5699         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5700         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5701         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5702                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5703                                   DAG.getConstant(16, dl, MVT::i32));
5704         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5705       }
5706
5707       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5708         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5709         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5710         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5711                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5712                                   DAG.getConstant(24, dl, MVT::i32));
5713         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5714       }
5715
5716       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5717         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5718         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5719         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5720                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5721                                   DAG.getConstant(0, dl, MVT::i32));
5722         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5723       }
5724
5725       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5726         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5727         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5728         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5729                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5730                                   DAG.getConstant(8, dl, MVT::i32));
5731         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5732       }
5733     }
5734
5735     if (SecondTry)
5736       goto FailedModImm;
5737     SecondTry = true;
5738     CnstBits = ~UndefBits;
5739     goto AttemptModImm;
5740   }
5741
5742 // We can always fall back to a non-immediate AND.
5743 FailedModImm:
5744   return Op;
5745 }
5746
5747 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5748 // consists of only the same constant int value, returned in reference arg
5749 // ConstVal
5750 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5751                                      uint64_t &ConstVal) {
5752   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5753   if (!Bvec)
5754     return false;
5755   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5756   if (!FirstElt)
5757     return false;
5758   EVT VT = Bvec->getValueType(0);
5759   unsigned NumElts = VT.getVectorNumElements();
5760   for (unsigned i = 1; i < NumElts; ++i)
5761     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5762       return false;
5763   ConstVal = FirstElt->getZExtValue();
5764   return true;
5765 }
5766
5767 static unsigned getIntrinsicID(const SDNode *N) {
5768   unsigned Opcode = N->getOpcode();
5769   switch (Opcode) {
5770   default:
5771     return Intrinsic::not_intrinsic;
5772   case ISD::INTRINSIC_WO_CHAIN: {
5773     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5774     if (IID < Intrinsic::num_intrinsics)
5775       return IID;
5776     return Intrinsic::not_intrinsic;
5777   }
5778   }
5779 }
5780
5781 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5782 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5783 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5784 // Also, logical shift right -> sri, with the same structure.
5785 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5786   EVT VT = N->getValueType(0);
5787
5788   if (!VT.isVector())
5789     return SDValue();
5790
5791   SDLoc DL(N);
5792
5793   // Is the first op an AND?
5794   const SDValue And = N->getOperand(0);
5795   if (And.getOpcode() != ISD::AND)
5796     return SDValue();
5797
5798   // Is the second op an shl or lshr?
5799   SDValue Shift = N->getOperand(1);
5800   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5801   // or AArch64ISD::VLSHR vector, #shift
5802   unsigned ShiftOpc = Shift.getOpcode();
5803   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5804     return SDValue();
5805   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5806
5807   // Is the shift amount constant?
5808   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5809   if (!C2node)
5810     return SDValue();
5811
5812   // Is the and mask vector all constant?
5813   uint64_t C1;
5814   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5815     return SDValue();
5816
5817   // Is C1 == ~C2, taking into account how much one can shift elements of a
5818   // particular size?
5819   uint64_t C2 = C2node->getZExtValue();
5820   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5821   if (C2 > ElemSizeInBits)
5822     return SDValue();
5823   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5824   if ((C1 & ElemMask) != (~C2 & ElemMask))
5825     return SDValue();
5826
5827   SDValue X = And.getOperand(0);
5828   SDValue Y = Shift.getOperand(0);
5829
5830   unsigned Intrin =
5831       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5832   SDValue ResultSLI =
5833       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5834                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5835                   Shift.getOperand(1));
5836
5837   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5838   DEBUG(N->dump(&DAG));
5839   DEBUG(dbgs() << "into: \n");
5840   DEBUG(ResultSLI->dump(&DAG));
5841
5842   ++NumShiftInserts;
5843   return ResultSLI;
5844 }
5845
5846 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5847                                              SelectionDAG &DAG) const {
5848   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5849   if (EnableAArch64SlrGeneration) {
5850     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5851     if (Res.getNode())
5852       return Res;
5853   }
5854
5855   BuildVectorSDNode *BVN =
5856       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5857   SDValue LHS = Op.getOperand(1);
5858   SDLoc dl(Op);
5859   EVT VT = Op.getValueType();
5860
5861   // OR commutes, so try swapping the operands.
5862   if (!BVN) {
5863     LHS = Op.getOperand(0);
5864     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5865   }
5866   if (!BVN)
5867     return Op;
5868
5869   APInt CnstBits(VT.getSizeInBits(), 0);
5870   APInt UndefBits(VT.getSizeInBits(), 0);
5871   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5872     // We make use of a little bit of goto ickiness in order to avoid having to
5873     // duplicate the immediate matching logic for the undef toggled case.
5874     bool SecondTry = false;
5875   AttemptModImm:
5876
5877     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5878       CnstBits = CnstBits.zextOrTrunc(64);
5879       uint64_t CnstVal = CnstBits.getZExtValue();
5880
5881       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5882         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5883         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5884         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5885                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5886                                   DAG.getConstant(0, dl, MVT::i32));
5887         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5888       }
5889
5890       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5891         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5892         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5893         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5894                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5895                                   DAG.getConstant(8, dl, MVT::i32));
5896         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5897       }
5898
5899       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5900         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5901         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5902         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5903                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5904                                   DAG.getConstant(16, dl, MVT::i32));
5905         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5906       }
5907
5908       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5909         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5910         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5911         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5912                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5913                                   DAG.getConstant(24, dl, MVT::i32));
5914         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5915       }
5916
5917       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5918         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5919         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5920         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5921                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5922                                   DAG.getConstant(0, dl, MVT::i32));
5923         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5924       }
5925
5926       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5927         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5928         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5929         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5930                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5931                                   DAG.getConstant(8, dl, MVT::i32));
5932         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5933       }
5934     }
5935
5936     if (SecondTry)
5937       goto FailedModImm;
5938     SecondTry = true;
5939     CnstBits = UndefBits;
5940     goto AttemptModImm;
5941   }
5942
5943 // We can always fall back to a non-immediate OR.
5944 FailedModImm:
5945   return Op;
5946 }
5947
5948 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5949 // be truncated to fit element width.
5950 static SDValue NormalizeBuildVector(SDValue Op,
5951                                     SelectionDAG &DAG) {
5952   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5953   SDLoc dl(Op);
5954   EVT VT = Op.getValueType();
5955   EVT EltTy= VT.getVectorElementType();
5956
5957   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5958     return Op;
5959
5960   SmallVector<SDValue, 16> Ops;
5961   for (SDValue Lane : Op->ops()) {
5962     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5963       APInt LowBits(EltTy.getSizeInBits(),
5964                     CstLane->getZExtValue());
5965       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5966     }
5967     Ops.push_back(Lane);
5968   }
5969   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5970 }
5971
5972 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5973                                                  SelectionDAG &DAG) const {
5974   SDLoc dl(Op);
5975   EVT VT = Op.getValueType();
5976   Op = NormalizeBuildVector(Op, DAG);
5977   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5978
5979   APInt CnstBits(VT.getSizeInBits(), 0);
5980   APInt UndefBits(VT.getSizeInBits(), 0);
5981   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5982     // We make use of a little bit of goto ickiness in order to avoid having to
5983     // duplicate the immediate matching logic for the undef toggled case.
5984     bool SecondTry = false;
5985   AttemptModImm:
5986
5987     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5988       CnstBits = CnstBits.zextOrTrunc(64);
5989       uint64_t CnstVal = CnstBits.getZExtValue();
5990
5991       // Certain magic vector constants (used to express things like NOT
5992       // and NEG) are passed through unmodified.  This allows codegen patterns
5993       // for these operations to match.  Special-purpose patterns will lower
5994       // these immediates to MOVIs if it proves necessary.
5995       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5996         return Op;
5997
5998       // The many faces of MOVI...
5999       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6000         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6001         if (VT.getSizeInBits() == 128) {
6002           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6003                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6004           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6005         }
6006
6007         // Support the V64 version via subregister insertion.
6008         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6009                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6010         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6011       }
6012
6013       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6014         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6015         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6016         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6017                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6018                                   DAG.getConstant(0, dl, MVT::i32));
6019         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6020       }
6021
6022       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6023         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6024         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6025         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6026                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6027                                   DAG.getConstant(8, dl, MVT::i32));
6028         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6029       }
6030
6031       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6032         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6033         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6034         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6035                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6036                                   DAG.getConstant(16, dl, MVT::i32));
6037         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6038       }
6039
6040       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6041         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6042         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6043         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6044                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6045                                   DAG.getConstant(24, dl, MVT::i32));
6046         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6047       }
6048
6049       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6050         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6051         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6052         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6053                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6054                                   DAG.getConstant(0, dl, MVT::i32));
6055         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6056       }
6057
6058       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6059         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6060         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6061         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6062                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6063                                   DAG.getConstant(8, dl, MVT::i32));
6064         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6065       }
6066
6067       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6068         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6069         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6070         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6071                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6072                                   DAG.getConstant(264, dl, MVT::i32));
6073         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6074       }
6075
6076       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6077         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6078         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6079         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6080                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6081                                   DAG.getConstant(272, dl, MVT::i32));
6082         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6083       }
6084
6085       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6086         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6087         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6088         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6089                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6090         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6091       }
6092
6093       // The few faces of FMOV...
6094       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6095         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6096         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6097         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6098                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6099         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6100       }
6101
6102       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6103           VT.getSizeInBits() == 128) {
6104         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6105         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6106                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6107         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6108       }
6109
6110       // The many faces of MVNI...
6111       CnstVal = ~CnstVal;
6112       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6113         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6114         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6115         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6116                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6117                                   DAG.getConstant(0, dl, MVT::i32));
6118         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6119       }
6120
6121       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6122         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6123         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6124         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6125                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6126                                   DAG.getConstant(8, dl, MVT::i32));
6127         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6128       }
6129
6130       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6131         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6132         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6133         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6134                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6135                                   DAG.getConstant(16, dl, MVT::i32));
6136         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6137       }
6138
6139       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6140         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6141         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6142         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6143                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6144                                   DAG.getConstant(24, dl, MVT::i32));
6145         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6146       }
6147
6148       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6149         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6150         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6151         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6152                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6153                                   DAG.getConstant(0, dl, MVT::i32));
6154         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6155       }
6156
6157       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6158         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6159         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6160         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6161                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6162                                   DAG.getConstant(8, dl, MVT::i32));
6163         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6164       }
6165
6166       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6167         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6168         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6169         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6170                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6171                                   DAG.getConstant(264, dl, MVT::i32));
6172         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6173       }
6174
6175       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6176         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6177         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6178         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6179                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6180                                   DAG.getConstant(272, dl, MVT::i32));
6181         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6182       }
6183     }
6184
6185     if (SecondTry)
6186       goto FailedModImm;
6187     SecondTry = true;
6188     CnstBits = UndefBits;
6189     goto AttemptModImm;
6190   }
6191 FailedModImm:
6192
6193   // Scan through the operands to find some interesting properties we can
6194   // exploit:
6195   //   1) If only one value is used, we can use a DUP, or
6196   //   2) if only the low element is not undef, we can just insert that, or
6197   //   3) if only one constant value is used (w/ some non-constant lanes),
6198   //      we can splat the constant value into the whole vector then fill
6199   //      in the non-constant lanes.
6200   //   4) FIXME: If different constant values are used, but we can intelligently
6201   //             select the values we'll be overwriting for the non-constant
6202   //             lanes such that we can directly materialize the vector
6203   //             some other way (MOVI, e.g.), we can be sneaky.
6204   unsigned NumElts = VT.getVectorNumElements();
6205   bool isOnlyLowElement = true;
6206   bool usesOnlyOneValue = true;
6207   bool usesOnlyOneConstantValue = true;
6208   bool isConstant = true;
6209   unsigned NumConstantLanes = 0;
6210   SDValue Value;
6211   SDValue ConstantValue;
6212   for (unsigned i = 0; i < NumElts; ++i) {
6213     SDValue V = Op.getOperand(i);
6214     if (V.getOpcode() == ISD::UNDEF)
6215       continue;
6216     if (i > 0)
6217       isOnlyLowElement = false;
6218     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6219       isConstant = false;
6220
6221     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6222       ++NumConstantLanes;
6223       if (!ConstantValue.getNode())
6224         ConstantValue = V;
6225       else if (ConstantValue != V)
6226         usesOnlyOneConstantValue = false;
6227     }
6228
6229     if (!Value.getNode())
6230       Value = V;
6231     else if (V != Value)
6232       usesOnlyOneValue = false;
6233   }
6234
6235   if (!Value.getNode())
6236     return DAG.getUNDEF(VT);
6237
6238   if (isOnlyLowElement)
6239     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6240
6241   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6242   // i32 and try again.
6243   if (usesOnlyOneValue) {
6244     if (!isConstant) {
6245       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6246           Value.getValueType() != VT)
6247         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6248
6249       // This is actually a DUPLANExx operation, which keeps everything vectory.
6250
6251       // DUPLANE works on 128-bit vectors, widen it if necessary.
6252       SDValue Lane = Value.getOperand(1);
6253       Value = Value.getOperand(0);
6254       if (Value.getValueType().getSizeInBits() == 64)
6255         Value = WidenVector(Value, DAG);
6256
6257       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6258       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6259     }
6260
6261     if (VT.getVectorElementType().isFloatingPoint()) {
6262       SmallVector<SDValue, 8> Ops;
6263       EVT EltTy = VT.getVectorElementType();
6264       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6265               "Unsupported floating-point vector type");
6266       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6267       for (unsigned i = 0; i < NumElts; ++i)
6268         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6269       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6270       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6271       Val = LowerBUILD_VECTOR(Val, DAG);
6272       if (Val.getNode())
6273         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6274     }
6275   }
6276
6277   // If there was only one constant value used and for more than one lane,
6278   // start by splatting that value, then replace the non-constant lanes. This
6279   // is better than the default, which will perform a separate initialization
6280   // for each lane.
6281   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6282     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6283     // Now insert the non-constant lanes.
6284     for (unsigned i = 0; i < NumElts; ++i) {
6285       SDValue V = Op.getOperand(i);
6286       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6287       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6288         // Note that type legalization likely mucked about with the VT of the
6289         // source operand, so we may have to convert it here before inserting.
6290         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6291       }
6292     }
6293     return Val;
6294   }
6295
6296   // If all elements are constants and the case above didn't get hit, fall back
6297   // to the default expansion, which will generate a load from the constant
6298   // pool.
6299   if (isConstant)
6300     return SDValue();
6301
6302   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6303   if (NumElts >= 4) {
6304     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6305       return shuffle;
6306   }
6307
6308   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6309   // know the default expansion would otherwise fall back on something even
6310   // worse. For a vector with one or two non-undef values, that's
6311   // scalar_to_vector for the elements followed by a shuffle (provided the
6312   // shuffle is valid for the target) and materialization element by element
6313   // on the stack followed by a load for everything else.
6314   if (!isConstant && !usesOnlyOneValue) {
6315     SDValue Vec = DAG.getUNDEF(VT);
6316     SDValue Op0 = Op.getOperand(0);
6317     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6318     unsigned i = 0;
6319     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6320     // a) Avoid a RMW dependency on the full vector register, and
6321     // b) Allow the register coalescer to fold away the copy if the
6322     //    value is already in an S or D register.
6323     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6324     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6325     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6326         (ElemSize == 32 || ElemSize == 64)) {
6327       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6328       MachineSDNode *N =
6329           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6330                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6331       Vec = SDValue(N, 0);
6332       ++i;
6333     }
6334     for (; i < NumElts; ++i) {
6335       SDValue V = Op.getOperand(i);
6336       if (V.getOpcode() == ISD::UNDEF)
6337         continue;
6338       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6339       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6340     }
6341     return Vec;
6342   }
6343
6344   // Just use the default expansion. We failed to find a better alternative.
6345   return SDValue();
6346 }
6347
6348 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6349                                                       SelectionDAG &DAG) const {
6350   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6351
6352   // Check for non-constant or out of range lane.
6353   EVT VT = Op.getOperand(0).getValueType();
6354   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6355   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6356     return SDValue();
6357
6358
6359   // Insertion/extraction are legal for V128 types.
6360   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6361       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6362       VT == MVT::v8f16)
6363     return Op;
6364
6365   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6366       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6367     return SDValue();
6368
6369   // For V64 types, we perform insertion by expanding the value
6370   // to a V128 type and perform the insertion on that.
6371   SDLoc DL(Op);
6372   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6373   EVT WideTy = WideVec.getValueType();
6374
6375   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6376                              Op.getOperand(1), Op.getOperand(2));
6377   // Re-narrow the resultant vector.
6378   return NarrowVector(Node, DAG);
6379 }
6380
6381 SDValue
6382 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6383                                                SelectionDAG &DAG) const {
6384   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6385
6386   // Check for non-constant or out of range lane.
6387   EVT VT = Op.getOperand(0).getValueType();
6388   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6389   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6390     return SDValue();
6391
6392
6393   // Insertion/extraction are legal for V128 types.
6394   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6395       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6396       VT == MVT::v8f16)
6397     return Op;
6398
6399   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6400       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6401     return SDValue();
6402
6403   // For V64 types, we perform extraction by expanding the value
6404   // to a V128 type and perform the extraction on that.
6405   SDLoc DL(Op);
6406   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6407   EVT WideTy = WideVec.getValueType();
6408
6409   EVT ExtrTy = WideTy.getVectorElementType();
6410   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6411     ExtrTy = MVT::i32;
6412
6413   // For extractions, we just return the result directly.
6414   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6415                      Op.getOperand(1));
6416 }
6417
6418 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6419                                                       SelectionDAG &DAG) const {
6420   EVT VT = Op.getOperand(0).getValueType();
6421   SDLoc dl(Op);
6422   // Just in case...
6423   if (!VT.isVector())
6424     return SDValue();
6425
6426   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6427   if (!Cst)
6428     return SDValue();
6429   unsigned Val = Cst->getZExtValue();
6430
6431   unsigned Size = Op.getValueType().getSizeInBits();
6432
6433   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6434   if (Val == 0)
6435     return Op;
6436
6437   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6438   // that directly.
6439   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6440     return Op;
6441
6442   return SDValue();
6443 }
6444
6445 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6446                                                EVT VT) const {
6447   if (VT.getVectorNumElements() == 4 &&
6448       (VT.is128BitVector() || VT.is64BitVector())) {
6449     unsigned PFIndexes[4];
6450     for (unsigned i = 0; i != 4; ++i) {
6451       if (M[i] < 0)
6452         PFIndexes[i] = 8;
6453       else
6454         PFIndexes[i] = M[i];
6455     }
6456
6457     // Compute the index in the perfect shuffle table.
6458     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6459                             PFIndexes[2] * 9 + PFIndexes[3];
6460     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6461     unsigned Cost = (PFEntry >> 30);
6462
6463     if (Cost <= 4)
6464       return true;
6465   }
6466
6467   bool DummyBool;
6468   int DummyInt;
6469   unsigned DummyUnsigned;
6470
6471   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6472           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6473           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6474           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6475           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6476           isZIPMask(M, VT, DummyUnsigned) ||
6477           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6478           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6479           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6480           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6481           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6482 }
6483
6484 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6485 /// operand of a vector shift operation, where all the elements of the
6486 /// build_vector must have the same constant integer value.
6487 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6488   // Ignore bit_converts.
6489   while (Op.getOpcode() == ISD::BITCAST)
6490     Op = Op.getOperand(0);
6491   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6492   APInt SplatBits, SplatUndef;
6493   unsigned SplatBitSize;
6494   bool HasAnyUndefs;
6495   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6496                                     HasAnyUndefs, ElementBits) ||
6497       SplatBitSize > ElementBits)
6498     return false;
6499   Cnt = SplatBits.getSExtValue();
6500   return true;
6501 }
6502
6503 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6504 /// operand of a vector shift left operation.  That value must be in the range:
6505 ///   0 <= Value < ElementBits for a left shift; or
6506 ///   0 <= Value <= ElementBits for a long left shift.
6507 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6508   assert(VT.isVector() && "vector shift count is not a vector type");
6509   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6510   if (!getVShiftImm(Op, ElementBits, Cnt))
6511     return false;
6512   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6513 }
6514
6515 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6516 /// operand of a vector shift right operation. The value must be in the range:
6517 ///   1 <= Value <= ElementBits for a right shift; or
6518 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6519   assert(VT.isVector() && "vector shift count is not a vector type");
6520   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6521   if (!getVShiftImm(Op, ElementBits, Cnt))
6522     return false;
6523   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6524 }
6525
6526 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6527                                                       SelectionDAG &DAG) const {
6528   EVT VT = Op.getValueType();
6529   SDLoc DL(Op);
6530   int64_t Cnt;
6531
6532   if (!Op.getOperand(1).getValueType().isVector())
6533     return Op;
6534   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6535
6536   switch (Op.getOpcode()) {
6537   default:
6538     llvm_unreachable("unexpected shift opcode");
6539
6540   case ISD::SHL:
6541     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6542       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6543                          DAG.getConstant(Cnt, DL, MVT::i32));
6544     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6545                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6546                                        MVT::i32),
6547                        Op.getOperand(0), Op.getOperand(1));
6548   case ISD::SRA:
6549   case ISD::SRL:
6550     // Right shift immediate
6551     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6552       unsigned Opc =
6553           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6554       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6555                          DAG.getConstant(Cnt, DL, MVT::i32));
6556     }
6557
6558     // Right shift register.  Note, there is not a shift right register
6559     // instruction, but the shift left register instruction takes a signed
6560     // value, where negative numbers specify a right shift.
6561     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6562                                                 : Intrinsic::aarch64_neon_ushl;
6563     // negate the shift amount
6564     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6565     SDValue NegShiftLeft =
6566         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6567                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6568                     NegShift);
6569     return NegShiftLeft;
6570   }
6571
6572   return SDValue();
6573 }
6574
6575 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6576                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6577                                     SDLoc dl, SelectionDAG &DAG) {
6578   EVT SrcVT = LHS.getValueType();
6579   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6580          "function only supposed to emit natural comparisons");
6581
6582   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6583   APInt CnstBits(VT.getSizeInBits(), 0);
6584   APInt UndefBits(VT.getSizeInBits(), 0);
6585   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6586   bool IsZero = IsCnst && (CnstBits == 0);
6587
6588   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6589     switch (CC) {
6590     default:
6591       return SDValue();
6592     case AArch64CC::NE: {
6593       SDValue Fcmeq;
6594       if (IsZero)
6595         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6596       else
6597         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6598       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6599     }
6600     case AArch64CC::EQ:
6601       if (IsZero)
6602         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6603       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6604     case AArch64CC::GE:
6605       if (IsZero)
6606         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6607       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6608     case AArch64CC::GT:
6609       if (IsZero)
6610         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6611       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6612     case AArch64CC::LS:
6613       if (IsZero)
6614         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6615       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6616     case AArch64CC::LT:
6617       if (!NoNans)
6618         return SDValue();
6619     // If we ignore NaNs then we can use to the MI implementation.
6620     // Fallthrough.
6621     case AArch64CC::MI:
6622       if (IsZero)
6623         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6624       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6625     }
6626   }
6627
6628   switch (CC) {
6629   default:
6630     return SDValue();
6631   case AArch64CC::NE: {
6632     SDValue Cmeq;
6633     if (IsZero)
6634       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6635     else
6636       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6637     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6638   }
6639   case AArch64CC::EQ:
6640     if (IsZero)
6641       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6642     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6643   case AArch64CC::GE:
6644     if (IsZero)
6645       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6646     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6647   case AArch64CC::GT:
6648     if (IsZero)
6649       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6650     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6651   case AArch64CC::LE:
6652     if (IsZero)
6653       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6654     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6655   case AArch64CC::LS:
6656     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6657   case AArch64CC::LO:
6658     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6659   case AArch64CC::LT:
6660     if (IsZero)
6661       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6662     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6663   case AArch64CC::HI:
6664     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6665   case AArch64CC::HS:
6666     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6667   }
6668 }
6669
6670 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6671                                            SelectionDAG &DAG) const {
6672   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6673   SDValue LHS = Op.getOperand(0);
6674   SDValue RHS = Op.getOperand(1);
6675   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6676   SDLoc dl(Op);
6677
6678   if (LHS.getValueType().getVectorElementType().isInteger()) {
6679     assert(LHS.getValueType() == RHS.getValueType());
6680     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6681     SDValue Cmp =
6682         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6683     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6684   }
6685
6686   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6687          LHS.getValueType().getVectorElementType() == MVT::f64);
6688
6689   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6690   // clean.  Some of them require two branches to implement.
6691   AArch64CC::CondCode CC1, CC2;
6692   bool ShouldInvert;
6693   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6694
6695   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6696   SDValue Cmp =
6697       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6698   if (!Cmp.getNode())
6699     return SDValue();
6700
6701   if (CC2 != AArch64CC::AL) {
6702     SDValue Cmp2 =
6703         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6704     if (!Cmp2.getNode())
6705       return SDValue();
6706
6707     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6708   }
6709
6710   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6711
6712   if (ShouldInvert)
6713     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6714
6715   return Cmp;
6716 }
6717
6718 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6719 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6720 /// specified in the intrinsic calls.
6721 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6722                                                const CallInst &I,
6723                                                unsigned Intrinsic) const {
6724   auto &DL = I.getModule()->getDataLayout();
6725   switch (Intrinsic) {
6726   case Intrinsic::aarch64_neon_ld2:
6727   case Intrinsic::aarch64_neon_ld3:
6728   case Intrinsic::aarch64_neon_ld4:
6729   case Intrinsic::aarch64_neon_ld1x2:
6730   case Intrinsic::aarch64_neon_ld1x3:
6731   case Intrinsic::aarch64_neon_ld1x4:
6732   case Intrinsic::aarch64_neon_ld2lane:
6733   case Intrinsic::aarch64_neon_ld3lane:
6734   case Intrinsic::aarch64_neon_ld4lane:
6735   case Intrinsic::aarch64_neon_ld2r:
6736   case Intrinsic::aarch64_neon_ld3r:
6737   case Intrinsic::aarch64_neon_ld4r: {
6738     Info.opc = ISD::INTRINSIC_W_CHAIN;
6739     // Conservatively set memVT to the entire set of vectors loaded.
6740     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6741     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6742     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6743     Info.offset = 0;
6744     Info.align = 0;
6745     Info.vol = false; // volatile loads with NEON intrinsics not supported
6746     Info.readMem = true;
6747     Info.writeMem = false;
6748     return true;
6749   }
6750   case Intrinsic::aarch64_neon_st2:
6751   case Intrinsic::aarch64_neon_st3:
6752   case Intrinsic::aarch64_neon_st4:
6753   case Intrinsic::aarch64_neon_st1x2:
6754   case Intrinsic::aarch64_neon_st1x3:
6755   case Intrinsic::aarch64_neon_st1x4:
6756   case Intrinsic::aarch64_neon_st2lane:
6757   case Intrinsic::aarch64_neon_st3lane:
6758   case Intrinsic::aarch64_neon_st4lane: {
6759     Info.opc = ISD::INTRINSIC_VOID;
6760     // Conservatively set memVT to the entire set of vectors stored.
6761     unsigned NumElts = 0;
6762     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6763       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6764       if (!ArgTy->isVectorTy())
6765         break;
6766       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6767     }
6768     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6769     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6770     Info.offset = 0;
6771     Info.align = 0;
6772     Info.vol = false; // volatile stores with NEON intrinsics not supported
6773     Info.readMem = false;
6774     Info.writeMem = true;
6775     return true;
6776   }
6777   case Intrinsic::aarch64_ldaxr:
6778   case Intrinsic::aarch64_ldxr: {
6779     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6780     Info.opc = ISD::INTRINSIC_W_CHAIN;
6781     Info.memVT = MVT::getVT(PtrTy->getElementType());
6782     Info.ptrVal = I.getArgOperand(0);
6783     Info.offset = 0;
6784     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6785     Info.vol = true;
6786     Info.readMem = true;
6787     Info.writeMem = false;
6788     return true;
6789   }
6790   case Intrinsic::aarch64_stlxr:
6791   case Intrinsic::aarch64_stxr: {
6792     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6793     Info.opc = ISD::INTRINSIC_W_CHAIN;
6794     Info.memVT = MVT::getVT(PtrTy->getElementType());
6795     Info.ptrVal = I.getArgOperand(1);
6796     Info.offset = 0;
6797     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6798     Info.vol = true;
6799     Info.readMem = false;
6800     Info.writeMem = true;
6801     return true;
6802   }
6803   case Intrinsic::aarch64_ldaxp:
6804   case Intrinsic::aarch64_ldxp: {
6805     Info.opc = ISD::INTRINSIC_W_CHAIN;
6806     Info.memVT = MVT::i128;
6807     Info.ptrVal = I.getArgOperand(0);
6808     Info.offset = 0;
6809     Info.align = 16;
6810     Info.vol = true;
6811     Info.readMem = true;
6812     Info.writeMem = false;
6813     return true;
6814   }
6815   case Intrinsic::aarch64_stlxp:
6816   case Intrinsic::aarch64_stxp: {
6817     Info.opc = ISD::INTRINSIC_W_CHAIN;
6818     Info.memVT = MVT::i128;
6819     Info.ptrVal = I.getArgOperand(2);
6820     Info.offset = 0;
6821     Info.align = 16;
6822     Info.vol = true;
6823     Info.readMem = false;
6824     Info.writeMem = true;
6825     return true;
6826   }
6827   default:
6828     break;
6829   }
6830
6831   return false;
6832 }
6833
6834 // Truncations from 64-bit GPR to 32-bit GPR is free.
6835 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6836   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6837     return false;
6838   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6839   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6840   return NumBits1 > NumBits2;
6841 }
6842 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6843   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6844     return false;
6845   unsigned NumBits1 = VT1.getSizeInBits();
6846   unsigned NumBits2 = VT2.getSizeInBits();
6847   return NumBits1 > NumBits2;
6848 }
6849
6850 /// Check if it is profitable to hoist instruction in then/else to if.
6851 /// Not profitable if I and it's user can form a FMA instruction
6852 /// because we prefer FMSUB/FMADD.
6853 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6854   if (I->getOpcode() != Instruction::FMul)
6855     return true;
6856
6857   if (I->getNumUses() != 1)
6858     return true;
6859
6860   Instruction *User = I->user_back();
6861
6862   if (User &&
6863       !(User->getOpcode() == Instruction::FSub ||
6864         User->getOpcode() == Instruction::FAdd))
6865     return true;
6866
6867   const TargetOptions &Options = getTargetMachine().Options;
6868   const DataLayout &DL = I->getModule()->getDataLayout();
6869   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6870
6871   if (isFMAFasterThanFMulAndFAdd(VT) &&
6872       isOperationLegalOrCustom(ISD::FMA, VT) &&
6873       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6874     return false;
6875
6876   return true;
6877 }
6878
6879 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6880 // 64-bit GPR.
6881 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6882   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6883     return false;
6884   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6885   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6886   return NumBits1 == 32 && NumBits2 == 64;
6887 }
6888 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6889   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6890     return false;
6891   unsigned NumBits1 = VT1.getSizeInBits();
6892   unsigned NumBits2 = VT2.getSizeInBits();
6893   return NumBits1 == 32 && NumBits2 == 64;
6894 }
6895
6896 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6897   EVT VT1 = Val.getValueType();
6898   if (isZExtFree(VT1, VT2)) {
6899     return true;
6900   }
6901
6902   if (Val.getOpcode() != ISD::LOAD)
6903     return false;
6904
6905   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6906   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6907           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6908           VT1.getSizeInBits() <= 32);
6909 }
6910
6911 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6912   if (isa<FPExtInst>(Ext))
6913     return false;
6914
6915   // Vector types are next free.
6916   if (Ext->getType()->isVectorTy())
6917     return false;
6918
6919   for (const Use &U : Ext->uses()) {
6920     // The extension is free if we can fold it with a left shift in an
6921     // addressing mode or an arithmetic operation: add, sub, and cmp.
6922
6923     // Is there a shift?
6924     const Instruction *Instr = cast<Instruction>(U.getUser());
6925
6926     // Is this a constant shift?
6927     switch (Instr->getOpcode()) {
6928     case Instruction::Shl:
6929       if (!isa<ConstantInt>(Instr->getOperand(1)))
6930         return false;
6931       break;
6932     case Instruction::GetElementPtr: {
6933       gep_type_iterator GTI = gep_type_begin(Instr);
6934       auto &DL = Ext->getModule()->getDataLayout();
6935       std::advance(GTI, U.getOperandNo());
6936       Type *IdxTy = *GTI;
6937       // This extension will end up with a shift because of the scaling factor.
6938       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6939       // Get the shift amount based on the scaling factor:
6940       // log2(sizeof(IdxTy)) - log2(8).
6941       uint64_t ShiftAmt =
6942           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6943       // Is the constant foldable in the shift of the addressing mode?
6944       // I.e., shift amount is between 1 and 4 inclusive.
6945       if (ShiftAmt == 0 || ShiftAmt > 4)
6946         return false;
6947       break;
6948     }
6949     case Instruction::Trunc:
6950       // Check if this is a noop.
6951       // trunc(sext ty1 to ty2) to ty1.
6952       if (Instr->getType() == Ext->getOperand(0)->getType())
6953         continue;
6954     // FALL THROUGH.
6955     default:
6956       return false;
6957     }
6958
6959     // At this point we can use the bfm family, so this extension is free
6960     // for that use.
6961   }
6962   return true;
6963 }
6964
6965 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6966                                           unsigned &RequiredAligment) const {
6967   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6968     return false;
6969   // Cyclone supports unaligned accesses.
6970   RequiredAligment = 0;
6971   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6972   return NumBits == 32 || NumBits == 64;
6973 }
6974
6975 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6976                                           unsigned &RequiredAligment) const {
6977   if (!LoadedType.isSimple() ||
6978       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6979     return false;
6980   // Cyclone supports unaligned accesses.
6981   RequiredAligment = 0;
6982   unsigned NumBits = LoadedType.getSizeInBits();
6983   return NumBits == 32 || NumBits == 64;
6984 }
6985
6986 /// \brief Lower an interleaved load into a ldN intrinsic.
6987 ///
6988 /// E.g. Lower an interleaved load (Factor = 2):
6989 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6990 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6991 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6992 ///
6993 ///      Into:
6994 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6995 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6996 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6997 bool AArch64TargetLowering::lowerInterleavedLoad(
6998     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6999     ArrayRef<unsigned> Indices, unsigned Factor) const {
7000   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7001          "Invalid interleave factor");
7002   assert(!Shuffles.empty() && "Empty shufflevector input");
7003   assert(Shuffles.size() == Indices.size() &&
7004          "Unmatched number of shufflevectors and indices");
7005
7006   const DataLayout &DL = LI->getModule()->getDataLayout();
7007
7008   VectorType *VecTy = Shuffles[0]->getType();
7009   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7010
7011   // Skip if we do not have NEON and skip illegal vector types.
7012   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7013     return false;
7014
7015   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7016   // load integer vectors first and then convert to pointer vectors.
7017   Type *EltTy = VecTy->getVectorElementType();
7018   if (EltTy->isPointerTy())
7019     VecTy =
7020         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7021
7022   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7023   Type *Tys[2] = {VecTy, PtrTy};
7024   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7025                                             Intrinsic::aarch64_neon_ld3,
7026                                             Intrinsic::aarch64_neon_ld4};
7027   Function *LdNFunc =
7028       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7029
7030   IRBuilder<> Builder(LI);
7031   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7032
7033   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7034
7035   // Replace uses of each shufflevector with the corresponding vector loaded
7036   // by ldN.
7037   for (unsigned i = 0; i < Shuffles.size(); i++) {
7038     ShuffleVectorInst *SVI = Shuffles[i];
7039     unsigned Index = Indices[i];
7040
7041     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7042
7043     // Convert the integer vector to pointer vector if the element is pointer.
7044     if (EltTy->isPointerTy())
7045       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7046
7047     SVI->replaceAllUsesWith(SubVec);
7048   }
7049
7050   return true;
7051 }
7052
7053 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7054 ///
7055 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7056 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7057                                    unsigned NumElts) {
7058   SmallVector<Constant *, 16> Mask;
7059   for (unsigned i = 0; i < NumElts; i++)
7060     Mask.push_back(Builder.getInt32(Start + i));
7061
7062   return ConstantVector::get(Mask);
7063 }
7064
7065 /// \brief Lower an interleaved store into a stN intrinsic.
7066 ///
7067 /// E.g. Lower an interleaved store (Factor = 3):
7068 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7069 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7070 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7071 ///
7072 ///      Into:
7073 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7074 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7075 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7076 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7077 ///
7078 /// Note that the new shufflevectors will be removed and we'll only generate one
7079 /// st3 instruction in CodeGen.
7080 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7081                                                   ShuffleVectorInst *SVI,
7082                                                   unsigned Factor) const {
7083   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7084          "Invalid interleave factor");
7085
7086   VectorType *VecTy = SVI->getType();
7087   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7088          "Invalid interleaved store");
7089
7090   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7091   Type *EltTy = VecTy->getVectorElementType();
7092   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7093
7094   const DataLayout &DL = SI->getModule()->getDataLayout();
7095   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7096
7097   // Skip if we do not have NEON and skip illegal vector types.
7098   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7099     return false;
7100
7101   Value *Op0 = SVI->getOperand(0);
7102   Value *Op1 = SVI->getOperand(1);
7103   IRBuilder<> Builder(SI);
7104
7105   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7106   // vectors to integer vectors.
7107   if (EltTy->isPointerTy()) {
7108     Type *IntTy = DL.getIntPtrType(EltTy);
7109     unsigned NumOpElts =
7110         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7111
7112     // Convert to the corresponding integer vector.
7113     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7114     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7115     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7116
7117     SubVecTy = VectorType::get(IntTy, NumSubElts);
7118   }
7119
7120   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7121   Type *Tys[2] = {SubVecTy, PtrTy};
7122   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7123                                              Intrinsic::aarch64_neon_st3,
7124                                              Intrinsic::aarch64_neon_st4};
7125   Function *StNFunc =
7126       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7127
7128   SmallVector<Value *, 5> Ops;
7129
7130   // Split the shufflevector operands into sub vectors for the new stN call.
7131   for (unsigned i = 0; i < Factor; i++)
7132     Ops.push_back(Builder.CreateShuffleVector(
7133         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7134
7135   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7136   Builder.CreateCall(StNFunc, Ops);
7137   return true;
7138 }
7139
7140 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7141                        unsigned AlignCheck) {
7142   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7143           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7144 }
7145
7146 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7147                                                unsigned SrcAlign, bool IsMemset,
7148                                                bool ZeroMemset,
7149                                                bool MemcpyStrSrc,
7150                                                MachineFunction &MF) const {
7151   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7152   // instruction to materialize the v2i64 zero and one store (with restrictive
7153   // addressing mode). Just do two i64 store of zero-registers.
7154   bool Fast;
7155   const Function *F = MF.getFunction();
7156   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7157       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7158       (memOpAlign(SrcAlign, DstAlign, 16) ||
7159        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7160     return MVT::f128;
7161
7162   if (Size >= 8 &&
7163       (memOpAlign(SrcAlign, DstAlign, 8) ||
7164        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7165     return MVT::i64;
7166
7167   if (Size >= 4 &&
7168       (memOpAlign(SrcAlign, DstAlign, 4) ||
7169        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7170     return MVT::i32;
7171
7172   return MVT::Other;
7173 }
7174
7175 // 12-bit optionally shifted immediates are legal for adds.
7176 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7177   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7178     return true;
7179   return false;
7180 }
7181
7182 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7183 // immediates is the same as for an add or a sub.
7184 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7185   if (Immed < 0)
7186     Immed *= -1;
7187   return isLegalAddImmediate(Immed);
7188 }
7189
7190 /// isLegalAddressingMode - Return true if the addressing mode represented
7191 /// by AM is legal for this target, for a load/store of the specified type.
7192 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7193                                                   const AddrMode &AM, Type *Ty,
7194                                                   unsigned AS) const {
7195   // AArch64 has five basic addressing modes:
7196   //  reg
7197   //  reg + 9-bit signed offset
7198   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7199   //  reg1 + reg2
7200   //  reg + SIZE_IN_BYTES * reg
7201
7202   // No global is ever allowed as a base.
7203   if (AM.BaseGV)
7204     return false;
7205
7206   // No reg+reg+imm addressing.
7207   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7208     return false;
7209
7210   // check reg + imm case:
7211   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7212   uint64_t NumBytes = 0;
7213   if (Ty->isSized()) {
7214     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7215     NumBytes = NumBits / 8;
7216     if (!isPowerOf2_64(NumBits))
7217       NumBytes = 0;
7218   }
7219
7220   if (!AM.Scale) {
7221     int64_t Offset = AM.BaseOffs;
7222
7223     // 9-bit signed offset
7224     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7225       return true;
7226
7227     // 12-bit unsigned offset
7228     unsigned shift = Log2_64(NumBytes);
7229     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7230         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7231         (Offset >> shift) << shift == Offset)
7232       return true;
7233     return false;
7234   }
7235
7236   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7237
7238   if (!AM.Scale || AM.Scale == 1 ||
7239       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7240     return true;
7241   return false;
7242 }
7243
7244 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7245                                                 const AddrMode &AM, Type *Ty,
7246                                                 unsigned AS) const {
7247   // Scaling factors are not free at all.
7248   // Operands                     | Rt Latency
7249   // -------------------------------------------
7250   // Rt, [Xn, Xm]                 | 4
7251   // -------------------------------------------
7252   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7253   // Rt, [Xn, Wm, <extend> #imm]  |
7254   if (isLegalAddressingMode(DL, AM, Ty, AS))
7255     // Scale represents reg2 * scale, thus account for 1 if
7256     // it is not equal to 0 or 1.
7257     return AM.Scale != 0 && AM.Scale != 1;
7258   return -1;
7259 }
7260
7261 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7262   VT = VT.getScalarType();
7263
7264   if (!VT.isSimple())
7265     return false;
7266
7267   switch (VT.getSimpleVT().SimpleTy) {
7268   case MVT::f32:
7269   case MVT::f64:
7270     return true;
7271   default:
7272     break;
7273   }
7274
7275   return false;
7276 }
7277
7278 const MCPhysReg *
7279 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7280   // LR is a callee-save register, but we must treat it as clobbered by any call
7281   // site. Hence we include LR in the scratch registers, which are in turn added
7282   // as implicit-defs for stackmaps and patchpoints.
7283   static const MCPhysReg ScratchRegs[] = {
7284     AArch64::X16, AArch64::X17, AArch64::LR, 0
7285   };
7286   return ScratchRegs;
7287 }
7288
7289 bool
7290 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7291   EVT VT = N->getValueType(0);
7292     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7293     // it with shift to let it be lowered to UBFX.
7294   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7295       isa<ConstantSDNode>(N->getOperand(1))) {
7296     uint64_t TruncMask = N->getConstantOperandVal(1);
7297     if (isMask_64(TruncMask) &&
7298       N->getOperand(0).getOpcode() == ISD::SRL &&
7299       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7300       return false;
7301   }
7302   return true;
7303 }
7304
7305 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7306                                                               Type *Ty) const {
7307   assert(Ty->isIntegerTy());
7308
7309   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7310   if (BitSize == 0)
7311     return false;
7312
7313   int64_t Val = Imm.getSExtValue();
7314   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7315     return true;
7316
7317   if ((int64_t)Val < 0)
7318     Val = ~Val;
7319   if (BitSize == 32)
7320     Val &= (1LL << 32) - 1;
7321
7322   unsigned LZ = countLeadingZeros((uint64_t)Val);
7323   unsigned Shift = (63 - LZ) / 16;
7324   // MOVZ is free so return true for one or fewer MOVK.
7325   return Shift < 3;
7326 }
7327
7328 // Generate SUBS and CSEL for integer abs.
7329 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7330   EVT VT = N->getValueType(0);
7331
7332   SDValue N0 = N->getOperand(0);
7333   SDValue N1 = N->getOperand(1);
7334   SDLoc DL(N);
7335
7336   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7337   // and change it to SUB and CSEL.
7338   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7339       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7340       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7341     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7342       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7343         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7344                                   N0.getOperand(0));
7345         // Generate SUBS & CSEL.
7346         SDValue Cmp =
7347             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7348                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7349         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7350                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7351                            SDValue(Cmp.getNode(), 1));
7352       }
7353   return SDValue();
7354 }
7355
7356 // performXorCombine - Attempts to handle integer ABS.
7357 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7358                                  TargetLowering::DAGCombinerInfo &DCI,
7359                                  const AArch64Subtarget *Subtarget) {
7360   if (DCI.isBeforeLegalizeOps())
7361     return SDValue();
7362
7363   return performIntegerAbsCombine(N, DAG);
7364 }
7365
7366 SDValue
7367 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7368                                      SelectionDAG &DAG,
7369                                      std::vector<SDNode *> *Created) const {
7370   // fold (sdiv X, pow2)
7371   EVT VT = N->getValueType(0);
7372   if ((VT != MVT::i32 && VT != MVT::i64) ||
7373       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7374     return SDValue();
7375
7376   SDLoc DL(N);
7377   SDValue N0 = N->getOperand(0);
7378   unsigned Lg2 = Divisor.countTrailingZeros();
7379   SDValue Zero = DAG.getConstant(0, DL, VT);
7380   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7381
7382   // Add (N0 < 0) ? Pow2 - 1 : 0;
7383   SDValue CCVal;
7384   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7385   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7386   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7387
7388   if (Created) {
7389     Created->push_back(Cmp.getNode());
7390     Created->push_back(Add.getNode());
7391     Created->push_back(CSel.getNode());
7392   }
7393
7394   // Divide by pow2.
7395   SDValue SRA =
7396       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7397
7398   // If we're dividing by a positive value, we're done.  Otherwise, we must
7399   // negate the result.
7400   if (Divisor.isNonNegative())
7401     return SRA;
7402
7403   if (Created)
7404     Created->push_back(SRA.getNode());
7405   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7406 }
7407
7408 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7409                                  TargetLowering::DAGCombinerInfo &DCI,
7410                                  const AArch64Subtarget *Subtarget) {
7411   if (DCI.isBeforeLegalizeOps())
7412     return SDValue();
7413
7414   // Multiplication of a power of two plus/minus one can be done more
7415   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7416   // future CPUs have a cheaper MADD instruction, this may need to be
7417   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7418   // 64-bit is 5 cycles, so this is always a win.
7419   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7420     APInt Value = C->getAPIntValue();
7421     EVT VT = N->getValueType(0);
7422     SDLoc DL(N);
7423     if (Value.isNonNegative()) {
7424       // (mul x, 2^N + 1) => (add (shl x, N), x)
7425       APInt VM1 = Value - 1;
7426       if (VM1.isPowerOf2()) {
7427         SDValue ShiftedVal =
7428             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7429                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7430         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7431                            N->getOperand(0));
7432       }
7433       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7434       APInt VP1 = Value + 1;
7435       if (VP1.isPowerOf2()) {
7436         SDValue ShiftedVal =
7437             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7438                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7439         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7440                            N->getOperand(0));
7441       }
7442     } else {
7443       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7444       APInt VNP1 = -Value + 1;
7445       if (VNP1.isPowerOf2()) {
7446         SDValue ShiftedVal =
7447             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7448                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7449         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7450                            ShiftedVal);
7451       }
7452       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7453       APInt VNM1 = -Value - 1;
7454       if (VNM1.isPowerOf2()) {
7455         SDValue ShiftedVal =
7456             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7457                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7458         SDValue Add =
7459             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7460         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7461       }
7462     }
7463   }
7464   return SDValue();
7465 }
7466
7467 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7468                                                          SelectionDAG &DAG) {
7469   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7470   // optimize away operation when it's from a constant.
7471   //
7472   // The general transformation is:
7473   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7474   //       AND(VECTOR_CMP(x,y), constant2)
7475   //    constant2 = UNARYOP(constant)
7476
7477   // Early exit if this isn't a vector operation, the operand of the
7478   // unary operation isn't a bitwise AND, or if the sizes of the operations
7479   // aren't the same.
7480   EVT VT = N->getValueType(0);
7481   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7482       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7483       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7484     return SDValue();
7485
7486   // Now check that the other operand of the AND is a constant. We could
7487   // make the transformation for non-constant splats as well, but it's unclear
7488   // that would be a benefit as it would not eliminate any operations, just
7489   // perform one more step in scalar code before moving to the vector unit.
7490   if (BuildVectorSDNode *BV =
7491           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7492     // Bail out if the vector isn't a constant.
7493     if (!BV->isConstant())
7494       return SDValue();
7495
7496     // Everything checks out. Build up the new and improved node.
7497     SDLoc DL(N);
7498     EVT IntVT = BV->getValueType(0);
7499     // Create a new constant of the appropriate type for the transformed
7500     // DAG.
7501     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7502     // The AND node needs bitcasts to/from an integer vector type around it.
7503     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7504     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7505                                  N->getOperand(0)->getOperand(0), MaskConst);
7506     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7507     return Res;
7508   }
7509
7510   return SDValue();
7511 }
7512
7513 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7514                                      const AArch64Subtarget *Subtarget) {
7515   // First try to optimize away the conversion when it's conditionally from
7516   // a constant. Vectors only.
7517   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7518     return Res;
7519
7520   EVT VT = N->getValueType(0);
7521   if (VT != MVT::f32 && VT != MVT::f64)
7522     return SDValue();
7523
7524   // Only optimize when the source and destination types have the same width.
7525   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7526     return SDValue();
7527
7528   // If the result of an integer load is only used by an integer-to-float
7529   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7530   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7531   SDValue N0 = N->getOperand(0);
7532   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7533       // Do not change the width of a volatile load.
7534       !cast<LoadSDNode>(N0)->isVolatile()) {
7535     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7536     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7537                                LN0->getPointerInfo(), LN0->isVolatile(),
7538                                LN0->isNonTemporal(), LN0->isInvariant(),
7539                                LN0->getAlignment());
7540
7541     // Make sure successors of the original load stay after it by updating them
7542     // to use the new Chain.
7543     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7544
7545     unsigned Opcode =
7546         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7547     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7548   }
7549
7550   return SDValue();
7551 }
7552
7553 /// Fold a floating-point multiply by power of two into floating-point to
7554 /// fixed-point conversion.
7555 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7556                                      const AArch64Subtarget *Subtarget) {
7557   if (!Subtarget->hasNEON())
7558     return SDValue();
7559
7560   SDValue Op = N->getOperand(0);
7561   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7562     return SDValue();
7563
7564   SDValue ConstVec = Op->getOperand(1);
7565   if (!isa<BuildVectorSDNode>(ConstVec))
7566     return SDValue();
7567
7568   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7569   uint32_t FloatBits = FloatTy.getSizeInBits();
7570   if (FloatBits != 32 && FloatBits != 64)
7571     return SDValue();
7572
7573   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7574   uint32_t IntBits = IntTy.getSizeInBits();
7575   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7576     return SDValue();
7577
7578   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7579   if (IntBits > FloatBits)
7580     return SDValue();
7581
7582   BitVector UndefElements;
7583   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7584   int32_t Bits = IntBits == 64 ? 64 : 32;
7585   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7586   if (C == -1 || C == 0 || C > Bits)
7587     return SDValue();
7588
7589   MVT ResTy;
7590   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7591   switch (NumLanes) {
7592   default:
7593     return SDValue();
7594   case 2:
7595     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7596     break;
7597   case 4:
7598     ResTy = MVT::v4i32;
7599     break;
7600   }
7601
7602   SDLoc DL(N);
7603   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7604   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7605                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7606   SDValue FixConv =
7607       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7608                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7609                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7610   // We can handle smaller integers by generating an extra trunc.
7611   if (IntBits < FloatBits)
7612     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7613
7614   return FixConv;
7615 }
7616
7617 /// Fold a floating-point divide by power of two into fixed-point to
7618 /// floating-point conversion.
7619 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7620                                   const AArch64Subtarget *Subtarget) {
7621   if (!Subtarget->hasNEON())
7622     return SDValue();
7623
7624   SDValue Op = N->getOperand(0);
7625   unsigned Opc = Op->getOpcode();
7626   if (!Op.getValueType().isVector() ||
7627       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7628     return SDValue();
7629
7630   SDValue ConstVec = N->getOperand(1);
7631   if (!isa<BuildVectorSDNode>(ConstVec))
7632     return SDValue();
7633
7634   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7635   int32_t IntBits = IntTy.getSizeInBits();
7636   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7637     return SDValue();
7638
7639   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7640   int32_t FloatBits = FloatTy.getSizeInBits();
7641   if (FloatBits != 32 && FloatBits != 64)
7642     return SDValue();
7643
7644   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7645   if (IntBits > FloatBits)
7646     return SDValue();
7647
7648   BitVector UndefElements;
7649   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7650   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7651   if (C == -1 || C == 0 || C > FloatBits)
7652     return SDValue();
7653
7654   MVT ResTy;
7655   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7656   switch (NumLanes) {
7657   default:
7658     return SDValue();
7659   case 2:
7660     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7661     break;
7662   case 4:
7663     ResTy = MVT::v4i32;
7664     break;
7665   }
7666
7667   SDLoc DL(N);
7668   SDValue ConvInput = Op.getOperand(0);
7669   bool IsSigned = Opc == ISD::SINT_TO_FP;
7670   if (IntBits < FloatBits)
7671     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7672                             ResTy, ConvInput);
7673
7674   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7675                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7676   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7677                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7678                      DAG.getConstant(C, DL, MVT::i32));
7679 }
7680
7681 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7682 /// searches for and classifies those shifts.
7683 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7684                          bool &FromHi) {
7685   if (N.getOpcode() == ISD::SHL)
7686     FromHi = false;
7687   else if (N.getOpcode() == ISD::SRL)
7688     FromHi = true;
7689   else
7690     return false;
7691
7692   if (!isa<ConstantSDNode>(N.getOperand(1)))
7693     return false;
7694
7695   ShiftAmount = N->getConstantOperandVal(1);
7696   Src = N->getOperand(0);
7697   return true;
7698 }
7699
7700 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7701 /// registers viewed as a high/low pair. This function looks for the pattern:
7702 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7703 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7704 /// independent.
7705 static SDValue tryCombineToEXTR(SDNode *N,
7706                                 TargetLowering::DAGCombinerInfo &DCI) {
7707   SelectionDAG &DAG = DCI.DAG;
7708   SDLoc DL(N);
7709   EVT VT = N->getValueType(0);
7710
7711   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7712
7713   if (VT != MVT::i32 && VT != MVT::i64)
7714     return SDValue();
7715
7716   SDValue LHS;
7717   uint32_t ShiftLHS = 0;
7718   bool LHSFromHi = 0;
7719   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7720     return SDValue();
7721
7722   SDValue RHS;
7723   uint32_t ShiftRHS = 0;
7724   bool RHSFromHi = 0;
7725   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7726     return SDValue();
7727
7728   // If they're both trying to come from the high part of the register, they're
7729   // not really an EXTR.
7730   if (LHSFromHi == RHSFromHi)
7731     return SDValue();
7732
7733   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7734     return SDValue();
7735
7736   if (LHSFromHi) {
7737     std::swap(LHS, RHS);
7738     std::swap(ShiftLHS, ShiftRHS);
7739   }
7740
7741   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7742                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7743 }
7744
7745 static SDValue tryCombineToBSL(SDNode *N,
7746                                 TargetLowering::DAGCombinerInfo &DCI) {
7747   EVT VT = N->getValueType(0);
7748   SelectionDAG &DAG = DCI.DAG;
7749   SDLoc DL(N);
7750
7751   if (!VT.isVector())
7752     return SDValue();
7753
7754   SDValue N0 = N->getOperand(0);
7755   if (N0.getOpcode() != ISD::AND)
7756     return SDValue();
7757
7758   SDValue N1 = N->getOperand(1);
7759   if (N1.getOpcode() != ISD::AND)
7760     return SDValue();
7761
7762   // We only have to look for constant vectors here since the general, variable
7763   // case can be handled in TableGen.
7764   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7765   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7766   for (int i = 1; i >= 0; --i)
7767     for (int j = 1; j >= 0; --j) {
7768       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7769       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7770       if (!BVN0 || !BVN1)
7771         continue;
7772
7773       bool FoundMatch = true;
7774       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7775         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7776         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7777         if (!CN0 || !CN1 ||
7778             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7779           FoundMatch = false;
7780           break;
7781         }
7782       }
7783
7784       if (FoundMatch)
7785         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7786                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7787     }
7788
7789   return SDValue();
7790 }
7791
7792 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7793                                 const AArch64Subtarget *Subtarget) {
7794   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7795   if (!EnableAArch64ExtrGeneration)
7796     return SDValue();
7797   SelectionDAG &DAG = DCI.DAG;
7798   EVT VT = N->getValueType(0);
7799
7800   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7801     return SDValue();
7802
7803   SDValue Res = tryCombineToEXTR(N, DCI);
7804   if (Res.getNode())
7805     return Res;
7806
7807   Res = tryCombineToBSL(N, DCI);
7808   if (Res.getNode())
7809     return Res;
7810
7811   return SDValue();
7812 }
7813
7814 static SDValue performBitcastCombine(SDNode *N,
7815                                      TargetLowering::DAGCombinerInfo &DCI,
7816                                      SelectionDAG &DAG) {
7817   // Wait 'til after everything is legalized to try this. That way we have
7818   // legal vector types and such.
7819   if (DCI.isBeforeLegalizeOps())
7820     return SDValue();
7821
7822   // Remove extraneous bitcasts around an extract_subvector.
7823   // For example,
7824   //    (v4i16 (bitconvert
7825   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7826   //  becomes
7827   //    (extract_subvector ((v8i16 ...), (i64 4)))
7828
7829   // Only interested in 64-bit vectors as the ultimate result.
7830   EVT VT = N->getValueType(0);
7831   if (!VT.isVector())
7832     return SDValue();
7833   if (VT.getSimpleVT().getSizeInBits() != 64)
7834     return SDValue();
7835   // Is the operand an extract_subvector starting at the beginning or halfway
7836   // point of the vector? A low half may also come through as an
7837   // EXTRACT_SUBREG, so look for that, too.
7838   SDValue Op0 = N->getOperand(0);
7839   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7840       !(Op0->isMachineOpcode() &&
7841         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7842     return SDValue();
7843   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7844   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7845     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7846       return SDValue();
7847   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7848     if (idx != AArch64::dsub)
7849       return SDValue();
7850     // The dsub reference is equivalent to a lane zero subvector reference.
7851     idx = 0;
7852   }
7853   // Look through the bitcast of the input to the extract.
7854   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7855     return SDValue();
7856   SDValue Source = Op0->getOperand(0)->getOperand(0);
7857   // If the source type has twice the number of elements as our destination
7858   // type, we know this is an extract of the high or low half of the vector.
7859   EVT SVT = Source->getValueType(0);
7860   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7861     return SDValue();
7862
7863   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7864
7865   // Create the simplified form to just extract the low or high half of the
7866   // vector directly rather than bothering with the bitcasts.
7867   SDLoc dl(N);
7868   unsigned NumElements = VT.getVectorNumElements();
7869   if (idx) {
7870     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7871     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7872   } else {
7873     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7874     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7875                                       Source, SubReg),
7876                    0);
7877   }
7878 }
7879
7880 static SDValue performConcatVectorsCombine(SDNode *N,
7881                                            TargetLowering::DAGCombinerInfo &DCI,
7882                                            SelectionDAG &DAG) {
7883   SDLoc dl(N);
7884   EVT VT = N->getValueType(0);
7885   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7886
7887   // Optimize concat_vectors of truncated vectors, where the intermediate
7888   // type is illegal, to avoid said illegality,  e.g.,
7889   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7890   //                          (v2i16 (truncate (v2i64)))))
7891   // ->
7892   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7893   //                                    (v4i32 (bitcast (v2i64))),
7894   //                                    <0, 2, 4, 6>)))
7895   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7896   // on both input and result type, so we might generate worse code.
7897   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7898   if (N->getNumOperands() == 2 &&
7899       N0->getOpcode() == ISD::TRUNCATE &&
7900       N1->getOpcode() == ISD::TRUNCATE) {
7901     SDValue N00 = N0->getOperand(0);
7902     SDValue N10 = N1->getOperand(0);
7903     EVT N00VT = N00.getValueType();
7904
7905     if (N00VT == N10.getValueType() &&
7906         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7907         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7908       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7909       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7910       for (size_t i = 0; i < Mask.size(); ++i)
7911         Mask[i] = i * 2;
7912       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7913                          DAG.getVectorShuffle(
7914                              MidVT, dl,
7915                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7916                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7917     }
7918   }
7919
7920   // Wait 'til after everything is legalized to try this. That way we have
7921   // legal vector types and such.
7922   if (DCI.isBeforeLegalizeOps())
7923     return SDValue();
7924
7925   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7926   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7927   // canonicalise to that.
7928   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7929     assert(VT.getVectorElementType().getSizeInBits() == 64);
7930     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7931                        DAG.getConstant(0, dl, MVT::i64));
7932   }
7933
7934   // Canonicalise concat_vectors so that the right-hand vector has as few
7935   // bit-casts as possible before its real operation. The primary matching
7936   // destination for these operations will be the narrowing "2" instructions,
7937   // which depend on the operation being performed on this right-hand vector.
7938   // For example,
7939   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7940   // becomes
7941   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7942
7943   if (N1->getOpcode() != ISD::BITCAST)
7944     return SDValue();
7945   SDValue RHS = N1->getOperand(0);
7946   MVT RHSTy = RHS.getValueType().getSimpleVT();
7947   // If the RHS is not a vector, this is not the pattern we're looking for.
7948   if (!RHSTy.isVector())
7949     return SDValue();
7950
7951   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7952
7953   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7954                                   RHSTy.getVectorNumElements() * 2);
7955   return DAG.getNode(ISD::BITCAST, dl, VT,
7956                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7957                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7958                                  RHS));
7959 }
7960
7961 static SDValue tryCombineFixedPointConvert(SDNode *N,
7962                                            TargetLowering::DAGCombinerInfo &DCI,
7963                                            SelectionDAG &DAG) {
7964   // Wait 'til after everything is legalized to try this. That way we have
7965   // legal vector types and such.
7966   if (DCI.isBeforeLegalizeOps())
7967     return SDValue();
7968   // Transform a scalar conversion of a value from a lane extract into a
7969   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7970   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7971   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7972   //
7973   // The second form interacts better with instruction selection and the
7974   // register allocator to avoid cross-class register copies that aren't
7975   // coalescable due to a lane reference.
7976
7977   // Check the operand and see if it originates from a lane extract.
7978   SDValue Op1 = N->getOperand(1);
7979   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7980     // Yep, no additional predication needed. Perform the transform.
7981     SDValue IID = N->getOperand(0);
7982     SDValue Shift = N->getOperand(2);
7983     SDValue Vec = Op1.getOperand(0);
7984     SDValue Lane = Op1.getOperand(1);
7985     EVT ResTy = N->getValueType(0);
7986     EVT VecResTy;
7987     SDLoc DL(N);
7988
7989     // The vector width should be 128 bits by the time we get here, even
7990     // if it started as 64 bits (the extract_vector handling will have
7991     // done so).
7992     assert(Vec.getValueType().getSizeInBits() == 128 &&
7993            "unexpected vector size on extract_vector_elt!");
7994     if (Vec.getValueType() == MVT::v4i32)
7995       VecResTy = MVT::v4f32;
7996     else if (Vec.getValueType() == MVT::v2i64)
7997       VecResTy = MVT::v2f64;
7998     else
7999       llvm_unreachable("unexpected vector type!");
8000
8001     SDValue Convert =
8002         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8003     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8004   }
8005   return SDValue();
8006 }
8007
8008 // AArch64 high-vector "long" operations are formed by performing the non-high
8009 // version on an extract_subvector of each operand which gets the high half:
8010 //
8011 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8012 //
8013 // However, there are cases which don't have an extract_high explicitly, but
8014 // have another operation that can be made compatible with one for free. For
8015 // example:
8016 //
8017 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8018 //
8019 // This routine does the actual conversion of such DUPs, once outer routines
8020 // have determined that everything else is in order.
8021 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8022 // similarly here.
8023 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8024   switch (N.getOpcode()) {
8025   case AArch64ISD::DUP:
8026   case AArch64ISD::DUPLANE8:
8027   case AArch64ISD::DUPLANE16:
8028   case AArch64ISD::DUPLANE32:
8029   case AArch64ISD::DUPLANE64:
8030   case AArch64ISD::MOVI:
8031   case AArch64ISD::MOVIshift:
8032   case AArch64ISD::MOVIedit:
8033   case AArch64ISD::MOVImsl:
8034   case AArch64ISD::MVNIshift:
8035   case AArch64ISD::MVNImsl:
8036     break;
8037   default:
8038     // FMOV could be supported, but isn't very useful, as it would only occur
8039     // if you passed a bitcast' floating point immediate to an eligible long
8040     // integer op (addl, smull, ...).
8041     return SDValue();
8042   }
8043
8044   MVT NarrowTy = N.getSimpleValueType();
8045   if (!NarrowTy.is64BitVector())
8046     return SDValue();
8047
8048   MVT ElementTy = NarrowTy.getVectorElementType();
8049   unsigned NumElems = NarrowTy.getVectorNumElements();
8050   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8051
8052   SDLoc dl(N);
8053   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8054                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8055                      DAG.getConstant(NumElems, dl, MVT::i64));
8056 }
8057
8058 static bool isEssentiallyExtractSubvector(SDValue N) {
8059   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8060     return true;
8061
8062   return N.getOpcode() == ISD::BITCAST &&
8063          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8064 }
8065
8066 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8067 struct GenericSetCCInfo {
8068   const SDValue *Opnd0;
8069   const SDValue *Opnd1;
8070   ISD::CondCode CC;
8071 };
8072
8073 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8074 struct AArch64SetCCInfo {
8075   const SDValue *Cmp;
8076   AArch64CC::CondCode CC;
8077 };
8078
8079 /// \brief Helper structure to keep track of SetCC information.
8080 union SetCCInfo {
8081   GenericSetCCInfo Generic;
8082   AArch64SetCCInfo AArch64;
8083 };
8084
8085 /// \brief Helper structure to be able to read SetCC information.  If set to
8086 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8087 /// GenericSetCCInfo.
8088 struct SetCCInfoAndKind {
8089   SetCCInfo Info;
8090   bool IsAArch64;
8091 };
8092
8093 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8094 /// an
8095 /// AArch64 lowered one.
8096 /// \p SetCCInfo is filled accordingly.
8097 /// \post SetCCInfo is meanginfull only when this function returns true.
8098 /// \return True when Op is a kind of SET_CC operation.
8099 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8100   // If this is a setcc, this is straight forward.
8101   if (Op.getOpcode() == ISD::SETCC) {
8102     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8103     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8104     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8105     SetCCInfo.IsAArch64 = false;
8106     return true;
8107   }
8108   // Otherwise, check if this is a matching csel instruction.
8109   // In other words:
8110   // - csel 1, 0, cc
8111   // - csel 0, 1, !cc
8112   if (Op.getOpcode() != AArch64ISD::CSEL)
8113     return false;
8114   // Set the information about the operands.
8115   // TODO: we want the operands of the Cmp not the csel
8116   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8117   SetCCInfo.IsAArch64 = true;
8118   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8119       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8120
8121   // Check that the operands matches the constraints:
8122   // (1) Both operands must be constants.
8123   // (2) One must be 1 and the other must be 0.
8124   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8125   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8126
8127   // Check (1).
8128   if (!TValue || !FValue)
8129     return false;
8130
8131   // Check (2).
8132   if (!TValue->isOne()) {
8133     // Update the comparison when we are interested in !cc.
8134     std::swap(TValue, FValue);
8135     SetCCInfo.Info.AArch64.CC =
8136         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8137   }
8138   return TValue->isOne() && FValue->isNullValue();
8139 }
8140
8141 // Returns true if Op is setcc or zext of setcc.
8142 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8143   if (isSetCC(Op, Info))
8144     return true;
8145   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8146     isSetCC(Op->getOperand(0), Info));
8147 }
8148
8149 // The folding we want to perform is:
8150 // (add x, [zext] (setcc cc ...) )
8151 //   -->
8152 // (csel x, (add x, 1), !cc ...)
8153 //
8154 // The latter will get matched to a CSINC instruction.
8155 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8156   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8157   SDValue LHS = Op->getOperand(0);
8158   SDValue RHS = Op->getOperand(1);
8159   SetCCInfoAndKind InfoAndKind;
8160
8161   // If neither operand is a SET_CC, give up.
8162   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8163     std::swap(LHS, RHS);
8164     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8165       return SDValue();
8166   }
8167
8168   // FIXME: This could be generatized to work for FP comparisons.
8169   EVT CmpVT = InfoAndKind.IsAArch64
8170                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8171                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8172   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8173     return SDValue();
8174
8175   SDValue CCVal;
8176   SDValue Cmp;
8177   SDLoc dl(Op);
8178   if (InfoAndKind.IsAArch64) {
8179     CCVal = DAG.getConstant(
8180         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8181         MVT::i32);
8182     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8183   } else
8184     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8185                       *InfoAndKind.Info.Generic.Opnd1,
8186                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8187                       CCVal, DAG, dl);
8188
8189   EVT VT = Op->getValueType(0);
8190   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8191   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8192 }
8193
8194 // The basic add/sub long vector instructions have variants with "2" on the end
8195 // which act on the high-half of their inputs. They are normally matched by
8196 // patterns like:
8197 //
8198 // (add (zeroext (extract_high LHS)),
8199 //      (zeroext (extract_high RHS)))
8200 // -> uaddl2 vD, vN, vM
8201 //
8202 // However, if one of the extracts is something like a duplicate, this
8203 // instruction can still be used profitably. This function puts the DAG into a
8204 // more appropriate form for those patterns to trigger.
8205 static SDValue performAddSubLongCombine(SDNode *N,
8206                                         TargetLowering::DAGCombinerInfo &DCI,
8207                                         SelectionDAG &DAG) {
8208   if (DCI.isBeforeLegalizeOps())
8209     return SDValue();
8210
8211   MVT VT = N->getSimpleValueType(0);
8212   if (!VT.is128BitVector()) {
8213     if (N->getOpcode() == ISD::ADD)
8214       return performSetccAddFolding(N, DAG);
8215     return SDValue();
8216   }
8217
8218   // Make sure both branches are extended in the same way.
8219   SDValue LHS = N->getOperand(0);
8220   SDValue RHS = N->getOperand(1);
8221   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8222        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8223       LHS.getOpcode() != RHS.getOpcode())
8224     return SDValue();
8225
8226   unsigned ExtType = LHS.getOpcode();
8227
8228   // It's not worth doing if at least one of the inputs isn't already an
8229   // extract, but we don't know which it'll be so we have to try both.
8230   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8231     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8232     if (!RHS.getNode())
8233       return SDValue();
8234
8235     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8236   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8237     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8238     if (!LHS.getNode())
8239       return SDValue();
8240
8241     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8242   }
8243
8244   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8245 }
8246
8247 // Massage DAGs which we can use the high-half "long" operations on into
8248 // something isel will recognize better. E.g.
8249 //
8250 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8251 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8252 //                     (extract_high (v2i64 (dup128 scalar)))))
8253 //
8254 static SDValue tryCombineLongOpWithDup(SDNode *N,
8255                                        TargetLowering::DAGCombinerInfo &DCI,
8256                                        SelectionDAG &DAG) {
8257   if (DCI.isBeforeLegalizeOps())
8258     return SDValue();
8259
8260   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8261   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8262   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8263   assert(LHS.getValueType().is64BitVector() &&
8264          RHS.getValueType().is64BitVector() &&
8265          "unexpected shape for long operation");
8266
8267   // Either node could be a DUP, but it's not worth doing both of them (you'd
8268   // just as well use the non-high version) so look for a corresponding extract
8269   // operation on the other "wing".
8270   if (isEssentiallyExtractSubvector(LHS)) {
8271     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8272     if (!RHS.getNode())
8273       return SDValue();
8274   } else if (isEssentiallyExtractSubvector(RHS)) {
8275     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8276     if (!LHS.getNode())
8277       return SDValue();
8278   }
8279
8280   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8281   if (IsIntrinsic)
8282     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8283                        N->getOperand(0), LHS, RHS);
8284   else
8285     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8286                        LHS, RHS);
8287 }
8288
8289 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8290   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8291   unsigned ElemBits = ElemTy.getSizeInBits();
8292
8293   int64_t ShiftAmount;
8294   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8295     APInt SplatValue, SplatUndef;
8296     unsigned SplatBitSize;
8297     bool HasAnyUndefs;
8298     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8299                               HasAnyUndefs, ElemBits) ||
8300         SplatBitSize != ElemBits)
8301       return SDValue();
8302
8303     ShiftAmount = SplatValue.getSExtValue();
8304   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8305     ShiftAmount = CVN->getSExtValue();
8306   } else
8307     return SDValue();
8308
8309   unsigned Opcode;
8310   bool IsRightShift;
8311   switch (IID) {
8312   default:
8313     llvm_unreachable("Unknown shift intrinsic");
8314   case Intrinsic::aarch64_neon_sqshl:
8315     Opcode = AArch64ISD::SQSHL_I;
8316     IsRightShift = false;
8317     break;
8318   case Intrinsic::aarch64_neon_uqshl:
8319     Opcode = AArch64ISD::UQSHL_I;
8320     IsRightShift = false;
8321     break;
8322   case Intrinsic::aarch64_neon_srshl:
8323     Opcode = AArch64ISD::SRSHR_I;
8324     IsRightShift = true;
8325     break;
8326   case Intrinsic::aarch64_neon_urshl:
8327     Opcode = AArch64ISD::URSHR_I;
8328     IsRightShift = true;
8329     break;
8330   case Intrinsic::aarch64_neon_sqshlu:
8331     Opcode = AArch64ISD::SQSHLU_I;
8332     IsRightShift = false;
8333     break;
8334   }
8335
8336   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8337     SDLoc dl(N);
8338     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8339                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8340   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8341     SDLoc dl(N);
8342     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8343                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8344   }
8345
8346   return SDValue();
8347 }
8348
8349 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8350 // the intrinsics must be legal and take an i32, this means there's almost
8351 // certainly going to be a zext in the DAG which we can eliminate.
8352 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8353   SDValue AndN = N->getOperand(2);
8354   if (AndN.getOpcode() != ISD::AND)
8355     return SDValue();
8356
8357   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8358   if (!CMask || CMask->getZExtValue() != Mask)
8359     return SDValue();
8360
8361   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8362                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8363 }
8364
8365 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8366                                            SelectionDAG &DAG) {
8367   SDLoc dl(N);
8368   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8369                      DAG.getNode(Opc, dl,
8370                                  N->getOperand(1).getSimpleValueType(),
8371                                  N->getOperand(1)),
8372                      DAG.getConstant(0, dl, MVT::i64));
8373 }
8374
8375 static SDValue performIntrinsicCombine(SDNode *N,
8376                                        TargetLowering::DAGCombinerInfo &DCI,
8377                                        const AArch64Subtarget *Subtarget) {
8378   SelectionDAG &DAG = DCI.DAG;
8379   unsigned IID = getIntrinsicID(N);
8380   switch (IID) {
8381   default:
8382     break;
8383   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8384   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8385     return tryCombineFixedPointConvert(N, DCI, DAG);
8386   case Intrinsic::aarch64_neon_saddv:
8387     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8388   case Intrinsic::aarch64_neon_uaddv:
8389     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8390   case Intrinsic::aarch64_neon_sminv:
8391     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8392   case Intrinsic::aarch64_neon_uminv:
8393     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8394   case Intrinsic::aarch64_neon_smaxv:
8395     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8396   case Intrinsic::aarch64_neon_umaxv:
8397     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8398   case Intrinsic::aarch64_neon_fmax:
8399     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8400                        N->getOperand(1), N->getOperand(2));
8401   case Intrinsic::aarch64_neon_fmin:
8402     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8403                        N->getOperand(1), N->getOperand(2));
8404   case Intrinsic::aarch64_neon_sabd:
8405     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8406                        N->getOperand(1), N->getOperand(2));
8407   case Intrinsic::aarch64_neon_uabd:
8408     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8409                        N->getOperand(1), N->getOperand(2));
8410   case Intrinsic::aarch64_neon_fmaxnm:
8411     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8412                        N->getOperand(1), N->getOperand(2));
8413   case Intrinsic::aarch64_neon_fminnm:
8414     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8415                        N->getOperand(1), N->getOperand(2));
8416   case Intrinsic::aarch64_neon_smull:
8417   case Intrinsic::aarch64_neon_umull:
8418   case Intrinsic::aarch64_neon_pmull:
8419   case Intrinsic::aarch64_neon_sqdmull:
8420     return tryCombineLongOpWithDup(N, DCI, DAG);
8421   case Intrinsic::aarch64_neon_sqshl:
8422   case Intrinsic::aarch64_neon_uqshl:
8423   case Intrinsic::aarch64_neon_sqshlu:
8424   case Intrinsic::aarch64_neon_srshl:
8425   case Intrinsic::aarch64_neon_urshl:
8426     return tryCombineShiftImm(IID, N, DAG);
8427   case Intrinsic::aarch64_crc32b:
8428   case Intrinsic::aarch64_crc32cb:
8429     return tryCombineCRC32(0xff, N, DAG);
8430   case Intrinsic::aarch64_crc32h:
8431   case Intrinsic::aarch64_crc32ch:
8432     return tryCombineCRC32(0xffff, N, DAG);
8433   }
8434   return SDValue();
8435 }
8436
8437 static SDValue performExtendCombine(SDNode *N,
8438                                     TargetLowering::DAGCombinerInfo &DCI,
8439                                     SelectionDAG &DAG) {
8440   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8441   // we can convert that DUP into another extract_high (of a bigger DUP), which
8442   // helps the backend to decide that an sabdl2 would be useful, saving a real
8443   // extract_high operation.
8444   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8445       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8446        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8447     SDNode *ABDNode = N->getOperand(0).getNode();
8448     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8449     if (!NewABD.getNode())
8450       return SDValue();
8451
8452     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8453                        NewABD);
8454   }
8455
8456   // This is effectively a custom type legalization for AArch64.
8457   //
8458   // Type legalization will split an extend of a small, legal, type to a larger
8459   // illegal type by first splitting the destination type, often creating
8460   // illegal source types, which then get legalized in isel-confusing ways,
8461   // leading to really terrible codegen. E.g.,
8462   //   %result = v8i32 sext v8i8 %value
8463   // becomes
8464   //   %losrc = extract_subreg %value, ...
8465   //   %hisrc = extract_subreg %value, ...
8466   //   %lo = v4i32 sext v4i8 %losrc
8467   //   %hi = v4i32 sext v4i8 %hisrc
8468   // Things go rapidly downhill from there.
8469   //
8470   // For AArch64, the [sz]ext vector instructions can only go up one element
8471   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8472   // take two instructions.
8473   //
8474   // This implies that the most efficient way to do the extend from v8i8
8475   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8476   // the normal splitting to happen for the v8i16->v8i32.
8477
8478   // This is pre-legalization to catch some cases where the default
8479   // type legalization will create ill-tempered code.
8480   if (!DCI.isBeforeLegalizeOps())
8481     return SDValue();
8482
8483   // We're only interested in cleaning things up for non-legal vector types
8484   // here. If both the source and destination are legal, things will just
8485   // work naturally without any fiddling.
8486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8487   EVT ResVT = N->getValueType(0);
8488   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8489     return SDValue();
8490   // If the vector type isn't a simple VT, it's beyond the scope of what
8491   // we're  worried about here. Let legalization do its thing and hope for
8492   // the best.
8493   SDValue Src = N->getOperand(0);
8494   EVT SrcVT = Src->getValueType(0);
8495   if (!ResVT.isSimple() || !SrcVT.isSimple())
8496     return SDValue();
8497
8498   // If the source VT is a 64-bit vector, we can play games and get the
8499   // better results we want.
8500   if (SrcVT.getSizeInBits() != 64)
8501     return SDValue();
8502
8503   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8504   unsigned ElementCount = SrcVT.getVectorNumElements();
8505   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8506   SDLoc DL(N);
8507   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8508
8509   // Now split the rest of the operation into two halves, each with a 64
8510   // bit source.
8511   EVT LoVT, HiVT;
8512   SDValue Lo, Hi;
8513   unsigned NumElements = ResVT.getVectorNumElements();
8514   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8515   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8516                                  ResVT.getVectorElementType(), NumElements / 2);
8517
8518   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8519                                LoVT.getVectorNumElements());
8520   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8521                    DAG.getConstant(0, DL, MVT::i64));
8522   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8523                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8524   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8525   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8526
8527   // Now combine the parts back together so we still have a single result
8528   // like the combiner expects.
8529   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8530 }
8531
8532 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8533 /// value. The load store optimizer pass will merge them to store pair stores.
8534 /// This has better performance than a splat of the scalar followed by a split
8535 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8536 /// followed by an ext.b and two stores.
8537 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8538   SDValue StVal = St->getValue();
8539   EVT VT = StVal.getValueType();
8540
8541   // Don't replace floating point stores, they possibly won't be transformed to
8542   // stp because of the store pair suppress pass.
8543   if (VT.isFloatingPoint())
8544     return SDValue();
8545
8546   // Check for insert vector elements.
8547   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8548     return SDValue();
8549
8550   // We can express a splat as store pair(s) for 2 or 4 elements.
8551   unsigned NumVecElts = VT.getVectorNumElements();
8552   if (NumVecElts != 4 && NumVecElts != 2)
8553     return SDValue();
8554   SDValue SplatVal = StVal.getOperand(1);
8555   unsigned RemainInsertElts = NumVecElts - 1;
8556
8557   // Check that this is a splat.
8558   while (--RemainInsertElts) {
8559     SDValue NextInsertElt = StVal.getOperand(0);
8560     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8561       return SDValue();
8562     if (NextInsertElt.getOperand(1) != SplatVal)
8563       return SDValue();
8564     StVal = NextInsertElt;
8565   }
8566   unsigned OrigAlignment = St->getAlignment();
8567   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8568   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8569
8570   // Create scalar stores. This is at least as good as the code sequence for a
8571   // split unaligned store which is a dup.s, ext.b, and two stores.
8572   // Most of the time the three stores should be replaced by store pair
8573   // instructions (stp).
8574   SDLoc DL(St);
8575   SDValue BasePtr = St->getBasePtr();
8576   SDValue NewST1 =
8577       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8578                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8579
8580   unsigned Offset = EltOffset;
8581   while (--NumVecElts) {
8582     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8583                                     DAG.getConstant(Offset, DL, MVT::i64));
8584     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8585                           St->getPointerInfo(), St->isVolatile(),
8586                           St->isNonTemporal(), Alignment);
8587     Offset += EltOffset;
8588   }
8589   return NewST1;
8590 }
8591
8592 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8593                               SelectionDAG &DAG,
8594                               const AArch64Subtarget *Subtarget) {
8595   if (!DCI.isBeforeLegalize())
8596     return SDValue();
8597
8598   StoreSDNode *S = cast<StoreSDNode>(N);
8599   if (S->isVolatile())
8600     return SDValue();
8601
8602   // FIXME: The logic for deciding if an unaligned store should be split should
8603   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8604   // a call to that function here.
8605
8606   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8607   // page boundaries. We want to split such stores.
8608   if (!Subtarget->isCyclone())
8609     return SDValue();
8610
8611   // Don't split at -Oz.
8612   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8613     return SDValue();
8614
8615   SDValue StVal = S->getValue();
8616   EVT VT = StVal.getValueType();
8617
8618   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8619   // those up regresses performance on micro-benchmarks and olden/bh.
8620   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8621     return SDValue();
8622
8623   // Split unaligned 16B stores. They are terrible for performance.
8624   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8625   // extensions can use this to mark that it does not want splitting to happen
8626   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8627   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8628   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8629       S->getAlignment() <= 2)
8630     return SDValue();
8631
8632   // If we get a splat of a scalar convert this vector store to a store of
8633   // scalars. They will be merged into store pairs thereby removing two
8634   // instructions.
8635   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8636     return ReplacedSplat;
8637
8638   SDLoc DL(S);
8639   unsigned NumElts = VT.getVectorNumElements() / 2;
8640   // Split VT into two.
8641   EVT HalfVT =
8642       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8643   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8644                                    DAG.getConstant(0, DL, MVT::i64));
8645   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8646                                    DAG.getConstant(NumElts, DL, MVT::i64));
8647   SDValue BasePtr = S->getBasePtr();
8648   SDValue NewST1 =
8649       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8650                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8651   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8652                                   DAG.getConstant(8, DL, MVT::i64));
8653   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8654                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8655                       S->getAlignment());
8656 }
8657
8658 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8659 /// post-increment LD1R.
8660 static SDValue performPostLD1Combine(SDNode *N,
8661                                      TargetLowering::DAGCombinerInfo &DCI,
8662                                      bool IsLaneOp) {
8663   if (DCI.isBeforeLegalizeOps())
8664     return SDValue();
8665
8666   SelectionDAG &DAG = DCI.DAG;
8667   EVT VT = N->getValueType(0);
8668
8669   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8670   SDNode *LD = N->getOperand(LoadIdx).getNode();
8671   // If it is not LOAD, can not do such combine.
8672   if (LD->getOpcode() != ISD::LOAD)
8673     return SDValue();
8674
8675   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8676   EVT MemVT = LoadSDN->getMemoryVT();
8677   // Check if memory operand is the same type as the vector element.
8678   if (MemVT != VT.getVectorElementType())
8679     return SDValue();
8680
8681   // Check if there are other uses. If so, do not combine as it will introduce
8682   // an extra load.
8683   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8684        ++UI) {
8685     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8686       continue;
8687     if (*UI != N)
8688       return SDValue();
8689   }
8690
8691   SDValue Addr = LD->getOperand(1);
8692   SDValue Vector = N->getOperand(0);
8693   // Search for a use of the address operand that is an increment.
8694   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8695        Addr.getNode()->use_end(); UI != UE; ++UI) {
8696     SDNode *User = *UI;
8697     if (User->getOpcode() != ISD::ADD
8698         || UI.getUse().getResNo() != Addr.getResNo())
8699       continue;
8700
8701     // Check that the add is independent of the load.  Otherwise, folding it
8702     // would create a cycle.
8703     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8704       continue;
8705     // Also check that add is not used in the vector operand.  This would also
8706     // create a cycle.
8707     if (User->isPredecessorOf(Vector.getNode()))
8708       continue;
8709
8710     // If the increment is a constant, it must match the memory ref size.
8711     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8712     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8713       uint32_t IncVal = CInc->getZExtValue();
8714       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8715       if (IncVal != NumBytes)
8716         continue;
8717       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8718     }
8719
8720     // Finally, check that the vector doesn't depend on the load.
8721     // Again, this would create a cycle.
8722     // The load depending on the vector is fine, as that's the case for the
8723     // LD1*post we'll eventually generate anyway.
8724     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8725       continue;
8726
8727     SmallVector<SDValue, 8> Ops;
8728     Ops.push_back(LD->getOperand(0));  // Chain
8729     if (IsLaneOp) {
8730       Ops.push_back(Vector);           // The vector to be inserted
8731       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8732     }
8733     Ops.push_back(Addr);
8734     Ops.push_back(Inc);
8735
8736     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8737     SDVTList SDTys = DAG.getVTList(Tys);
8738     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8739     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8740                                            MemVT,
8741                                            LoadSDN->getMemOperand());
8742
8743     // Update the uses.
8744     SmallVector<SDValue, 2> NewResults;
8745     NewResults.push_back(SDValue(LD, 0));             // The result of load
8746     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8747     DCI.CombineTo(LD, NewResults);
8748     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8749     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8750
8751     break;
8752   }
8753   return SDValue();
8754 }
8755
8756 /// Simplify \Addr given that the top byte of it is ignored by HW during
8757 /// address translation.
8758 static bool performTBISimplification(SDValue Addr,
8759                                      TargetLowering::DAGCombinerInfo &DCI,
8760                                      SelectionDAG &DAG) {
8761   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8762   APInt KnownZero, KnownOne;
8763   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8764                                         DCI.isBeforeLegalizeOps());
8765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8766   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8767     DCI.CommitTargetLoweringOpt(TLO);
8768     return true;
8769   }
8770   return false;
8771 }
8772
8773 static SDValue performSTORECombine(SDNode *N,
8774                                    TargetLowering::DAGCombinerInfo &DCI,
8775                                    SelectionDAG &DAG,
8776                                    const AArch64Subtarget *Subtarget) {
8777   SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8778   if (Split.getNode())
8779     return Split;
8780
8781   if (Subtarget->supportsAddressTopByteIgnored() &&
8782       performTBISimplification(N->getOperand(2), DCI, DAG))
8783     return SDValue(N, 0);
8784
8785   return SDValue();
8786 }
8787
8788   /// This function handles the log2-shuffle pattern produced by the
8789 /// LoopVectorizer for the across vector reduction. It consists of
8790 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8791 /// are reduced, where s is an induction variable from 0 to
8792 /// log2(NumVectorElements).
8793 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8794                                                      unsigned Op,
8795                                                      SelectionDAG &DAG) {
8796   EVT VTy = OpV->getOperand(0).getValueType();
8797   if (!VTy.isVector())
8798     return SDValue();
8799
8800   int NumVecElts = VTy.getVectorNumElements();
8801   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8802     if (NumVecElts != 4)
8803       return SDValue();
8804   } else {
8805     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8806       return SDValue();
8807   }
8808
8809   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8810   SDValue PreOp = OpV;
8811   // Iterate over each step of the across vector reduction.
8812   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8813     SDValue CurOp = PreOp.getOperand(0);
8814     SDValue Shuffle = PreOp.getOperand(1);
8815     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8816       // Try to swap the 1st and 2nd operand as add and min/max instructions
8817       // are commutative.
8818       CurOp = PreOp.getOperand(1);
8819       Shuffle = PreOp.getOperand(0);
8820       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8821         return SDValue();
8822     }
8823
8824     // Check if the input vector is fed by the operator we want to handle,
8825     // except the last step; the very first input vector is not necessarily
8826     // the same operator we are handling.
8827     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8828       return SDValue();
8829
8830     // Check if it forms one step of the across vector reduction.
8831     // E.g.,
8832     //   %cur = add %1, %0
8833     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8834     //   %pre = add %cur, %shuffle
8835     if (Shuffle.getOperand(0) != CurOp)
8836       return SDValue();
8837
8838     int NumMaskElts = 1 << CurStep;
8839     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8840     // Check mask values in each step.
8841     // We expect the shuffle mask in each step follows a specific pattern
8842     // denoted here by the <M, U> form, where M is a sequence of integers
8843     // starting from NumMaskElts, increasing by 1, and the number integers
8844     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8845     // of undef in U should be NumVecElts - NumMaskElts.
8846     // E.g., for <8 x i16>, mask values in each step should be :
8847     //   step 0 : <1,u,u,u,u,u,u,u>
8848     //   step 1 : <2,3,u,u,u,u,u,u>
8849     //   step 2 : <4,5,6,7,u,u,u,u>
8850     for (int i = 0; i < NumVecElts; ++i)
8851       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8852           (i >= NumMaskElts && !(Mask[i] < 0)))
8853         return SDValue();
8854
8855     PreOp = CurOp;
8856   }
8857   unsigned Opcode;
8858   bool IsIntrinsic = false;
8859
8860   switch (Op) {
8861   default:
8862     llvm_unreachable("Unexpected operator for across vector reduction");
8863   case ISD::ADD:
8864     Opcode = AArch64ISD::UADDV;
8865     break;
8866   case ISD::SMAX:
8867     Opcode = AArch64ISD::SMAXV;
8868     break;
8869   case ISD::UMAX:
8870     Opcode = AArch64ISD::UMAXV;
8871     break;
8872   case ISD::SMIN:
8873     Opcode = AArch64ISD::SMINV;
8874     break;
8875   case ISD::UMIN:
8876     Opcode = AArch64ISD::UMINV;
8877     break;
8878   case ISD::FMAXNUM:
8879     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8880     IsIntrinsic = true;
8881     break;
8882   case ISD::FMINNUM:
8883     Opcode = Intrinsic::aarch64_neon_fminnmv;
8884     IsIntrinsic = true;
8885     break;
8886   }
8887   SDLoc DL(N);
8888
8889   return IsIntrinsic
8890              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8891                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8892              : DAG.getNode(
8893                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8894                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8895                    DAG.getConstant(0, DL, MVT::i64));
8896 }
8897
8898 /// Target-specific DAG combine for the across vector min/max reductions.
8899 /// This function specifically handles the final clean-up step of the vector
8900 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8901 /// pattern, which narrows down and finds the final min/max value from all
8902 /// elements of the vector.
8903 /// For example, for a <16 x i8> vector :
8904 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8905 ///   %smax0 = smax %arr, svn0
8906 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8907 ///   %smax1 = smax %smax0, %svn1
8908 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8909 ///   %smax2 = smax %smax1, svn2
8910 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8911 ///   %sc = setcc %smax2, %svn3, gt
8912 ///   %n0 = extract_vector_elt %sc, #0
8913 ///   %n1 = extract_vector_elt %smax2, #0
8914 ///   %n2 = extract_vector_elt $smax2, #1
8915 ///   %result = select %n0, %n1, n2
8916 ///     becomes :
8917 ///   %1 = smaxv %0
8918 ///   %result = extract_vector_elt %1, 0
8919 static SDValue
8920 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8921                                         const AArch64Subtarget *Subtarget) {
8922   if (!Subtarget->hasNEON())
8923     return SDValue();
8924
8925   SDValue N0 = N->getOperand(0);
8926   SDValue IfTrue = N->getOperand(1);
8927   SDValue IfFalse = N->getOperand(2);
8928
8929   // Check if the SELECT merges up the final result of the min/max
8930   // from a vector.
8931   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8932       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8933       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8934     return SDValue();
8935
8936   // Expect N0 is fed by SETCC.
8937   SDValue SetCC = N0.getOperand(0);
8938   EVT SetCCVT = SetCC.getValueType();
8939   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8940       SetCCVT.getVectorElementType() != MVT::i1)
8941     return SDValue();
8942
8943   SDValue VectorOp = SetCC.getOperand(0);
8944   unsigned Op = VectorOp->getOpcode();
8945   // Check if the input vector is fed by the operator we want to handle.
8946   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8947       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8948     return SDValue();
8949
8950   EVT VTy = VectorOp.getValueType();
8951   if (!VTy.isVector())
8952     return SDValue();
8953
8954   if (VTy.getSizeInBits() < 64)
8955     return SDValue();
8956
8957   EVT EltTy = VTy.getVectorElementType();
8958   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8959     if (EltTy != MVT::f32)
8960       return SDValue();
8961   } else {
8962     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8963       return SDValue();
8964   }
8965
8966   // Check if extracting from the same vector.
8967   // For example,
8968   //   %sc = setcc %vector, %svn1, gt
8969   //   %n0 = extract_vector_elt %sc, #0
8970   //   %n1 = extract_vector_elt %vector, #0
8971   //   %n2 = extract_vector_elt $vector, #1
8972   if (!(VectorOp == IfTrue->getOperand(0) &&
8973         VectorOp == IfFalse->getOperand(0)))
8974     return SDValue();
8975
8976   // Check if the condition code is matched with the operator type.
8977   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8978   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8979       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8980       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8981       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8982       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8983        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8984        CC != ISD::SETGE) ||
8985       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8986        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8987        CC != ISD::SETLE))
8988     return SDValue();
8989
8990   // Expect to check only lane 0 from the vector SETCC.
8991   if (!isNullConstant(N0.getOperand(1)))
8992     return SDValue();
8993
8994   // Expect to extract the true value from lane 0.
8995   if (!isNullConstant(IfTrue.getOperand(1)))
8996     return SDValue();
8997
8998   // Expect to extract the false value from lane 1.
8999   if (!isOneConstant(IfFalse.getOperand(1)))
9000     return SDValue();
9001
9002   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9003 }
9004
9005 /// Target-specific DAG combine for the across vector add reduction.
9006 /// This function specifically handles the final clean-up step of the vector
9007 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9008 /// pattern, which adds all elements of a vector together.
9009 /// For example, for a <4 x i32> vector :
9010 ///   %1 = vector_shuffle %0, <2,3,u,u>
9011 ///   %2 = add %0, %1
9012 ///   %3 = vector_shuffle %2, <1,u,u,u>
9013 ///   %4 = add %2, %3
9014 ///   %result = extract_vector_elt %4, 0
9015 /// becomes :
9016 ///   %0 = uaddv %0
9017 ///   %result = extract_vector_elt %0, 0
9018 static SDValue
9019 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9020                                      const AArch64Subtarget *Subtarget) {
9021   if (!Subtarget->hasNEON())
9022     return SDValue();
9023   SDValue N0 = N->getOperand(0);
9024   SDValue N1 = N->getOperand(1);
9025
9026   // Check if the input vector is fed by the ADD.
9027   if (N0->getOpcode() != ISD::ADD)
9028     return SDValue();
9029
9030   // The vector extract idx must constant zero because we only expect the final
9031   // result of the reduction is placed in lane 0.
9032   if (!isNullConstant(N1))
9033     return SDValue();
9034
9035   EVT VTy = N0.getValueType();
9036   if (!VTy.isVector())
9037     return SDValue();
9038
9039   EVT EltTy = VTy.getVectorElementType();
9040   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9041     return SDValue();
9042
9043   if (VTy.getSizeInBits() < 64)
9044     return SDValue();
9045
9046   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9047 }
9048
9049 /// Target-specific DAG combine function for NEON load/store intrinsics
9050 /// to merge base address updates.
9051 static SDValue performNEONPostLDSTCombine(SDNode *N,
9052                                           TargetLowering::DAGCombinerInfo &DCI,
9053                                           SelectionDAG &DAG) {
9054   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9055     return SDValue();
9056
9057   unsigned AddrOpIdx = N->getNumOperands() - 1;
9058   SDValue Addr = N->getOperand(AddrOpIdx);
9059
9060   // Search for a use of the address operand that is an increment.
9061   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9062        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9063     SDNode *User = *UI;
9064     if (User->getOpcode() != ISD::ADD ||
9065         UI.getUse().getResNo() != Addr.getResNo())
9066       continue;
9067
9068     // Check that the add is independent of the load/store.  Otherwise, folding
9069     // it would create a cycle.
9070     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9071       continue;
9072
9073     // Find the new opcode for the updating load/store.
9074     bool IsStore = false;
9075     bool IsLaneOp = false;
9076     bool IsDupOp = false;
9077     unsigned NewOpc = 0;
9078     unsigned NumVecs = 0;
9079     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9080     switch (IntNo) {
9081     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9082     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9083       NumVecs = 2; break;
9084     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9085       NumVecs = 3; break;
9086     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9087       NumVecs = 4; break;
9088     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9089       NumVecs = 2; IsStore = true; break;
9090     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9091       NumVecs = 3; IsStore = true; break;
9092     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9093       NumVecs = 4; IsStore = true; break;
9094     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9095       NumVecs = 2; break;
9096     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9097       NumVecs = 3; break;
9098     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9099       NumVecs = 4; break;
9100     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9101       NumVecs = 2; IsStore = true; break;
9102     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9103       NumVecs = 3; IsStore = true; break;
9104     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9105       NumVecs = 4; IsStore = true; break;
9106     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9107       NumVecs = 2; IsDupOp = true; break;
9108     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9109       NumVecs = 3; IsDupOp = true; break;
9110     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9111       NumVecs = 4; IsDupOp = true; break;
9112     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9113       NumVecs = 2; IsLaneOp = true; break;
9114     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9115       NumVecs = 3; IsLaneOp = true; break;
9116     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9117       NumVecs = 4; IsLaneOp = true; break;
9118     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9119       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9120     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9121       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9122     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9123       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9124     }
9125
9126     EVT VecTy;
9127     if (IsStore)
9128       VecTy = N->getOperand(2).getValueType();
9129     else
9130       VecTy = N->getValueType(0);
9131
9132     // If the increment is a constant, it must match the memory ref size.
9133     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9134     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9135       uint32_t IncVal = CInc->getZExtValue();
9136       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9137       if (IsLaneOp || IsDupOp)
9138         NumBytes /= VecTy.getVectorNumElements();
9139       if (IncVal != NumBytes)
9140         continue;
9141       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9142     }
9143     SmallVector<SDValue, 8> Ops;
9144     Ops.push_back(N->getOperand(0)); // Incoming chain
9145     // Load lane and store have vector list as input.
9146     if (IsLaneOp || IsStore)
9147       for (unsigned i = 2; i < AddrOpIdx; ++i)
9148         Ops.push_back(N->getOperand(i));
9149     Ops.push_back(Addr); // Base register
9150     Ops.push_back(Inc);
9151
9152     // Return Types.
9153     EVT Tys[6];
9154     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9155     unsigned n;
9156     for (n = 0; n < NumResultVecs; ++n)
9157       Tys[n] = VecTy;
9158     Tys[n++] = MVT::i64;  // Type of write back register
9159     Tys[n] = MVT::Other;  // Type of the chain
9160     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9161
9162     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9163     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9164                                            MemInt->getMemoryVT(),
9165                                            MemInt->getMemOperand());
9166
9167     // Update the uses.
9168     std::vector<SDValue> NewResults;
9169     for (unsigned i = 0; i < NumResultVecs; ++i) {
9170       NewResults.push_back(SDValue(UpdN.getNode(), i));
9171     }
9172     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9173     DCI.CombineTo(N, NewResults);
9174     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9175
9176     break;
9177   }
9178   return SDValue();
9179 }
9180
9181 // Checks to see if the value is the prescribed width and returns information
9182 // about its extension mode.
9183 static
9184 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9185   ExtType = ISD::NON_EXTLOAD;
9186   switch(V.getNode()->getOpcode()) {
9187   default:
9188     return false;
9189   case ISD::LOAD: {
9190     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9191     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9192        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9193       ExtType = LoadNode->getExtensionType();
9194       return true;
9195     }
9196     return false;
9197   }
9198   case ISD::AssertSext: {
9199     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9200     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9201        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9202       ExtType = ISD::SEXTLOAD;
9203       return true;
9204     }
9205     return false;
9206   }
9207   case ISD::AssertZext: {
9208     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9209     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9210        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9211       ExtType = ISD::ZEXTLOAD;
9212       return true;
9213     }
9214     return false;
9215   }
9216   case ISD::Constant:
9217   case ISD::TargetConstant: {
9218     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9219         1LL << (width - 1))
9220       return true;
9221     return false;
9222   }
9223   }
9224
9225   return true;
9226 }
9227
9228 // This function does a whole lot of voodoo to determine if the tests are
9229 // equivalent without and with a mask. Essentially what happens is that given a
9230 // DAG resembling:
9231 //
9232 //  +-------------+ +-------------+ +-------------+ +-------------+
9233 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9234 //  +-------------+ +-------------+ +-------------+ +-------------+
9235 //           |           |           |               |
9236 //           V           V           |    +----------+
9237 //          +-------------+  +----+  |    |
9238 //          |     ADD     |  |0xff|  |    |
9239 //          +-------------+  +----+  |    |
9240 //                  |           |    |    |
9241 //                  V           V    |    |
9242 //                 +-------------+   |    |
9243 //                 |     AND     |   |    |
9244 //                 +-------------+   |    |
9245 //                      |            |    |
9246 //                      +-----+      |    |
9247 //                            |      |    |
9248 //                            V      V    V
9249 //                           +-------------+
9250 //                           |     CMP     |
9251 //                           +-------------+
9252 //
9253 // The AND node may be safely removed for some combinations of inputs. In
9254 // particular we need to take into account the extension type of the Input,
9255 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9256 // width of the input (this can work for any width inputs, the above graph is
9257 // specific to 8 bits.
9258 //
9259 // The specific equations were worked out by generating output tables for each
9260 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9261 // problem was simplified by working with 4 bit inputs, which means we only
9262 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9263 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9264 // patterns present in both extensions (0,7). For every distinct set of
9265 // AddConstant and CompConstants bit patterns we can consider the masked and
9266 // unmasked versions to be equivalent if the result of this function is true for
9267 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9268 //
9269 //   sub      w8, w0, w1
9270 //   and      w10, w8, #0x0f
9271 //   cmp      w8, w2
9272 //   cset     w9, AArch64CC
9273 //   cmp      w10, w2
9274 //   cset     w11, AArch64CC
9275 //   cmp      w9, w11
9276 //   cset     w0, eq
9277 //   ret
9278 //
9279 // Since the above function shows when the outputs are equivalent it defines
9280 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9281 // would be expensive to run during compiles. The equations below were written
9282 // in a test harness that confirmed they gave equivalent outputs to the above
9283 // for all inputs function, so they can be used determine if the removal is
9284 // legal instead.
9285 //
9286 // isEquivalentMaskless() is the code for testing if the AND can be removed
9287 // factored out of the DAG recognition as the DAG can take several forms.
9288
9289 static
9290 bool isEquivalentMaskless(unsigned CC, unsigned width,
9291                           ISD::LoadExtType ExtType, signed AddConstant,
9292                           signed CompConstant) {
9293   // By being careful about our equations and only writing the in term
9294   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9295   // make them generally applicable to all bit widths.
9296   signed MaxUInt = (1 << width);
9297
9298   // For the purposes of these comparisons sign extending the type is
9299   // equivalent to zero extending the add and displacing it by half the integer
9300   // width. Provided we are careful and make sure our equations are valid over
9301   // the whole range we can just adjust the input and avoid writing equations
9302   // for sign extended inputs.
9303   if (ExtType == ISD::SEXTLOAD)
9304     AddConstant -= (1 << (width-1));
9305
9306   switch(CC) {
9307   case AArch64CC::LE:
9308   case AArch64CC::GT: {
9309     if ((AddConstant == 0) ||
9310         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9311         (AddConstant >= 0 && CompConstant < 0) ||
9312         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9313       return true;
9314   } break;
9315   case AArch64CC::LT:
9316   case AArch64CC::GE: {
9317     if ((AddConstant == 0) ||
9318         (AddConstant >= 0 && CompConstant <= 0) ||
9319         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9320       return true;
9321   } break;
9322   case AArch64CC::HI:
9323   case AArch64CC::LS: {
9324     if ((AddConstant >= 0 && CompConstant < 0) ||
9325        (AddConstant <= 0 && CompConstant >= -1 &&
9326         CompConstant < AddConstant + MaxUInt))
9327       return true;
9328   } break;
9329   case AArch64CC::PL:
9330   case AArch64CC::MI: {
9331     if ((AddConstant == 0) ||
9332         (AddConstant > 0 && CompConstant <= 0) ||
9333         (AddConstant < 0 && CompConstant <= AddConstant))
9334       return true;
9335   } break;
9336   case AArch64CC::LO:
9337   case AArch64CC::HS: {
9338     if ((AddConstant >= 0 && CompConstant <= 0) ||
9339         (AddConstant <= 0 && CompConstant >= 0 &&
9340          CompConstant <= AddConstant + MaxUInt))
9341       return true;
9342   } break;
9343   case AArch64CC::EQ:
9344   case AArch64CC::NE: {
9345     if ((AddConstant > 0 && CompConstant < 0) ||
9346         (AddConstant < 0 && CompConstant >= 0 &&
9347          CompConstant < AddConstant + MaxUInt) ||
9348         (AddConstant >= 0 && CompConstant >= 0 &&
9349          CompConstant >= AddConstant) ||
9350         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9351
9352       return true;
9353   } break;
9354   case AArch64CC::VS:
9355   case AArch64CC::VC:
9356   case AArch64CC::AL:
9357   case AArch64CC::NV:
9358     return true;
9359   case AArch64CC::Invalid:
9360     break;
9361   }
9362
9363   return false;
9364 }
9365
9366 static
9367 SDValue performCONDCombine(SDNode *N,
9368                            TargetLowering::DAGCombinerInfo &DCI,
9369                            SelectionDAG &DAG, unsigned CCIndex,
9370                            unsigned CmpIndex) {
9371   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9372   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9373   unsigned CondOpcode = SubsNode->getOpcode();
9374
9375   if (CondOpcode != AArch64ISD::SUBS)
9376     return SDValue();
9377
9378   // There is a SUBS feeding this condition. Is it fed by a mask we can
9379   // use?
9380
9381   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9382   unsigned MaskBits = 0;
9383
9384   if (AndNode->getOpcode() != ISD::AND)
9385     return SDValue();
9386
9387   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9388     uint32_t CNV = CN->getZExtValue();
9389     if (CNV == 255)
9390       MaskBits = 8;
9391     else if (CNV == 65535)
9392       MaskBits = 16;
9393   }
9394
9395   if (!MaskBits)
9396     return SDValue();
9397
9398   SDValue AddValue = AndNode->getOperand(0);
9399
9400   if (AddValue.getOpcode() != ISD::ADD)
9401     return SDValue();
9402
9403   // The basic dag structure is correct, grab the inputs and validate them.
9404
9405   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9406   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9407   SDValue SubsInputValue = SubsNode->getOperand(1);
9408
9409   // The mask is present and the provenance of all the values is a smaller type,
9410   // lets see if the mask is superfluous.
9411
9412   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9413       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9414     return SDValue();
9415
9416   ISD::LoadExtType ExtType;
9417
9418   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9419       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9420       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9421     return SDValue();
9422
9423   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9424                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9425                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9426     return SDValue();
9427
9428   // The AND is not necessary, remove it.
9429
9430   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9431                                SubsNode->getValueType(1));
9432   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9433
9434   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9435   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9436
9437   return SDValue(N, 0);
9438 }
9439
9440 // Optimize compare with zero and branch.
9441 static SDValue performBRCONDCombine(SDNode *N,
9442                                     TargetLowering::DAGCombinerInfo &DCI,
9443                                     SelectionDAG &DAG) {
9444   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9445   if (NV.getNode())
9446     N = NV.getNode();
9447   SDValue Chain = N->getOperand(0);
9448   SDValue Dest = N->getOperand(1);
9449   SDValue CCVal = N->getOperand(2);
9450   SDValue Cmp = N->getOperand(3);
9451
9452   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9453   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9454   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9455     return SDValue();
9456
9457   unsigned CmpOpc = Cmp.getOpcode();
9458   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9459     return SDValue();
9460
9461   // Only attempt folding if there is only one use of the flag and no use of the
9462   // value.
9463   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9464     return SDValue();
9465
9466   SDValue LHS = Cmp.getOperand(0);
9467   SDValue RHS = Cmp.getOperand(1);
9468
9469   assert(LHS.getValueType() == RHS.getValueType() &&
9470          "Expected the value type to be the same for both operands!");
9471   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9472     return SDValue();
9473
9474   if (isNullConstant(LHS))
9475     std::swap(LHS, RHS);
9476
9477   if (!isNullConstant(RHS))
9478     return SDValue();
9479
9480   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9481       LHS.getOpcode() == ISD::SRL)
9482     return SDValue();
9483
9484   // Fold the compare into the branch instruction.
9485   SDValue BR;
9486   if (CC == AArch64CC::EQ)
9487     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9488   else
9489     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9490
9491   // Do not add new nodes to DAG combiner worklist.
9492   DCI.CombineTo(N, BR, false);
9493
9494   return SDValue();
9495 }
9496
9497 // vselect (v1i1 setcc) ->
9498 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9499 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9500 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9501 // such VSELECT.
9502 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9503   SDValue N0 = N->getOperand(0);
9504   EVT CCVT = N0.getValueType();
9505
9506   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9507       CCVT.getVectorElementType() != MVT::i1)
9508     return SDValue();
9509
9510   EVT ResVT = N->getValueType(0);
9511   EVT CmpVT = N0.getOperand(0).getValueType();
9512   // Only combine when the result type is of the same size as the compared
9513   // operands.
9514   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9515     return SDValue();
9516
9517   SDValue IfTrue = N->getOperand(1);
9518   SDValue IfFalse = N->getOperand(2);
9519   SDValue SetCC =
9520       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9521                    N0.getOperand(0), N0.getOperand(1),
9522                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9523   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9524                      IfTrue, IfFalse);
9525 }
9526
9527 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9528 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9529 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9530 /// with a vector one followed by a DUP shuffle on the result.
9531 static SDValue performSelectCombine(SDNode *N,
9532                                     TargetLowering::DAGCombinerInfo &DCI) {
9533   SelectionDAG &DAG = DCI.DAG;
9534   SDValue N0 = N->getOperand(0);
9535   EVT ResVT = N->getValueType(0);
9536
9537   if (N0.getOpcode() != ISD::SETCC)
9538     return SDValue();
9539
9540   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9541   // scalar SetCCResultType. We also don't expect vectors, because we assume
9542   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9543   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9544          "Scalar-SETCC feeding SELECT has unexpected result type!");
9545
9546   // If NumMaskElts == 0, the comparison is larger than select result. The
9547   // largest real NEON comparison is 64-bits per lane, which means the result is
9548   // at most 32-bits and an illegal vector. Just bail out for now.
9549   EVT SrcVT = N0.getOperand(0).getValueType();
9550
9551   // Don't try to do this optimization when the setcc itself has i1 operands.
9552   // There are no legal vectors of i1, so this would be pointless.
9553   if (SrcVT == MVT::i1)
9554     return SDValue();
9555
9556   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9557   if (!ResVT.isVector() || NumMaskElts == 0)
9558     return SDValue();
9559
9560   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9561   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9562
9563   // Also bail out if the vector CCVT isn't the same size as ResVT.
9564   // This can happen if the SETCC operand size doesn't divide the ResVT size
9565   // (e.g., f64 vs v3f32).
9566   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9567     return SDValue();
9568
9569   // Make sure we didn't create illegal types, if we're not supposed to.
9570   assert(DCI.isBeforeLegalize() ||
9571          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9572
9573   // First perform a vector comparison, where lane 0 is the one we're interested
9574   // in.
9575   SDLoc DL(N0);
9576   SDValue LHS =
9577       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9578   SDValue RHS =
9579       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9580   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9581
9582   // Now duplicate the comparison mask we want across all other lanes.
9583   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9584   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9585   Mask = DAG.getNode(ISD::BITCAST, DL,
9586                      ResVT.changeVectorElementTypeToInteger(), Mask);
9587
9588   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9589 }
9590
9591 /// Get rid of unnecessary NVCASTs (that don't change the type).
9592 static SDValue performNVCASTCombine(SDNode *N) {
9593   if (N->getValueType(0) == N->getOperand(0).getValueType())
9594     return N->getOperand(0);
9595
9596   return SDValue();
9597 }
9598
9599 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9600                                                  DAGCombinerInfo &DCI) const {
9601   SelectionDAG &DAG = DCI.DAG;
9602   switch (N->getOpcode()) {
9603   default:
9604     break;
9605   case ISD::ADD:
9606   case ISD::SUB:
9607     return performAddSubLongCombine(N, DCI, DAG);
9608   case ISD::XOR:
9609     return performXorCombine(N, DAG, DCI, Subtarget);
9610   case ISD::MUL:
9611     return performMulCombine(N, DAG, DCI, Subtarget);
9612   case ISD::SINT_TO_FP:
9613   case ISD::UINT_TO_FP:
9614     return performIntToFpCombine(N, DAG, Subtarget);
9615   case ISD::FP_TO_SINT:
9616   case ISD::FP_TO_UINT:
9617     return performFpToIntCombine(N, DAG, Subtarget);
9618   case ISD::FDIV:
9619     return performFDivCombine(N, DAG, Subtarget);
9620   case ISD::OR:
9621     return performORCombine(N, DCI, Subtarget);
9622   case ISD::INTRINSIC_WO_CHAIN:
9623     return performIntrinsicCombine(N, DCI, Subtarget);
9624   case ISD::ANY_EXTEND:
9625   case ISD::ZERO_EXTEND:
9626   case ISD::SIGN_EXTEND:
9627     return performExtendCombine(N, DCI, DAG);
9628   case ISD::BITCAST:
9629     return performBitcastCombine(N, DCI, DAG);
9630   case ISD::CONCAT_VECTORS:
9631     return performConcatVectorsCombine(N, DCI, DAG);
9632   case ISD::SELECT: {
9633     SDValue RV = performSelectCombine(N, DCI);
9634     if (!RV.getNode())
9635       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9636     return RV;
9637   }
9638   case ISD::VSELECT:
9639     return performVSelectCombine(N, DCI.DAG);
9640   case ISD::LOAD:
9641     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9642       return SDValue(N, 0);
9643     break;
9644   case ISD::STORE:
9645     return performSTORECombine(N, DCI, DAG, Subtarget);
9646   case AArch64ISD::BRCOND:
9647     return performBRCONDCombine(N, DCI, DAG);
9648   case AArch64ISD::CSEL:
9649     return performCONDCombine(N, DCI, DAG, 2, 3);
9650   case AArch64ISD::DUP:
9651     return performPostLD1Combine(N, DCI, false);
9652   case AArch64ISD::NVCAST:
9653     return performNVCASTCombine(N);
9654   case ISD::INSERT_VECTOR_ELT:
9655     return performPostLD1Combine(N, DCI, true);
9656   case ISD::EXTRACT_VECTOR_ELT:
9657     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9658   case ISD::INTRINSIC_VOID:
9659   case ISD::INTRINSIC_W_CHAIN:
9660     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9661     case Intrinsic::aarch64_neon_ld2:
9662     case Intrinsic::aarch64_neon_ld3:
9663     case Intrinsic::aarch64_neon_ld4:
9664     case Intrinsic::aarch64_neon_ld1x2:
9665     case Intrinsic::aarch64_neon_ld1x3:
9666     case Intrinsic::aarch64_neon_ld1x4:
9667     case Intrinsic::aarch64_neon_ld2lane:
9668     case Intrinsic::aarch64_neon_ld3lane:
9669     case Intrinsic::aarch64_neon_ld4lane:
9670     case Intrinsic::aarch64_neon_ld2r:
9671     case Intrinsic::aarch64_neon_ld3r:
9672     case Intrinsic::aarch64_neon_ld4r:
9673     case Intrinsic::aarch64_neon_st2:
9674     case Intrinsic::aarch64_neon_st3:
9675     case Intrinsic::aarch64_neon_st4:
9676     case Intrinsic::aarch64_neon_st1x2:
9677     case Intrinsic::aarch64_neon_st1x3:
9678     case Intrinsic::aarch64_neon_st1x4:
9679     case Intrinsic::aarch64_neon_st2lane:
9680     case Intrinsic::aarch64_neon_st3lane:
9681     case Intrinsic::aarch64_neon_st4lane:
9682       return performNEONPostLDSTCombine(N, DCI, DAG);
9683     default:
9684       break;
9685     }
9686   }
9687   return SDValue();
9688 }
9689
9690 // Check if the return value is used as only a return value, as otherwise
9691 // we can't perform a tail-call. In particular, we need to check for
9692 // target ISD nodes that are returns and any other "odd" constructs
9693 // that the generic analysis code won't necessarily catch.
9694 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9695                                                SDValue &Chain) const {
9696   if (N->getNumValues() != 1)
9697     return false;
9698   if (!N->hasNUsesOfValue(1, 0))
9699     return false;
9700
9701   SDValue TCChain = Chain;
9702   SDNode *Copy = *N->use_begin();
9703   if (Copy->getOpcode() == ISD::CopyToReg) {
9704     // If the copy has a glue operand, we conservatively assume it isn't safe to
9705     // perform a tail call.
9706     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9707         MVT::Glue)
9708       return false;
9709     TCChain = Copy->getOperand(0);
9710   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9711     return false;
9712
9713   bool HasRet = false;
9714   for (SDNode *Node : Copy->uses()) {
9715     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9716       return false;
9717     HasRet = true;
9718   }
9719
9720   if (!HasRet)
9721     return false;
9722
9723   Chain = TCChain;
9724   return true;
9725 }
9726
9727 // Return whether the an instruction can potentially be optimized to a tail
9728 // call. This will cause the optimizers to attempt to move, or duplicate,
9729 // return instructions to help enable tail call optimizations for this
9730 // instruction.
9731 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9732   if (!CI->isTailCall())
9733     return false;
9734
9735   return true;
9736 }
9737
9738 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9739                                                    SDValue &Offset,
9740                                                    ISD::MemIndexedMode &AM,
9741                                                    bool &IsInc,
9742                                                    SelectionDAG &DAG) const {
9743   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9744     return false;
9745
9746   Base = Op->getOperand(0);
9747   // All of the indexed addressing mode instructions take a signed
9748   // 9 bit immediate offset.
9749   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9750     int64_t RHSC = (int64_t)RHS->getZExtValue();
9751     if (RHSC >= 256 || RHSC <= -256)
9752       return false;
9753     IsInc = (Op->getOpcode() == ISD::ADD);
9754     Offset = Op->getOperand(1);
9755     return true;
9756   }
9757   return false;
9758 }
9759
9760 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9761                                                       SDValue &Offset,
9762                                                       ISD::MemIndexedMode &AM,
9763                                                       SelectionDAG &DAG) const {
9764   EVT VT;
9765   SDValue Ptr;
9766   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9767     VT = LD->getMemoryVT();
9768     Ptr = LD->getBasePtr();
9769   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9770     VT = ST->getMemoryVT();
9771     Ptr = ST->getBasePtr();
9772   } else
9773     return false;
9774
9775   bool IsInc;
9776   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9777     return false;
9778   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9779   return true;
9780 }
9781
9782 bool AArch64TargetLowering::getPostIndexedAddressParts(
9783     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9784     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9785   EVT VT;
9786   SDValue Ptr;
9787   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9788     VT = LD->getMemoryVT();
9789     Ptr = LD->getBasePtr();
9790   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9791     VT = ST->getMemoryVT();
9792     Ptr = ST->getBasePtr();
9793   } else
9794     return false;
9795
9796   bool IsInc;
9797   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9798     return false;
9799   // Post-indexing updates the base, so it's not a valid transform
9800   // if that's not the same as the load's pointer.
9801   if (Ptr != Base)
9802     return false;
9803   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9804   return true;
9805 }
9806
9807 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9808                                   SelectionDAG &DAG) {
9809   SDLoc DL(N);
9810   SDValue Op = N->getOperand(0);
9811
9812   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9813     return;
9814
9815   Op = SDValue(
9816       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9817                          DAG.getUNDEF(MVT::i32), Op,
9818                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9819       0);
9820   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9821   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9822 }
9823
9824 static void ReplaceReductionResults(SDNode *N,
9825                                     SmallVectorImpl<SDValue> &Results,
9826                                     SelectionDAG &DAG, unsigned InterOp,
9827                                     unsigned AcrossOp) {
9828   EVT LoVT, HiVT;
9829   SDValue Lo, Hi;
9830   SDLoc dl(N);
9831   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9832   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9833   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9834   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9835   Results.push_back(SplitVal);
9836 }
9837
9838 void AArch64TargetLowering::ReplaceNodeResults(
9839     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9840   switch (N->getOpcode()) {
9841   default:
9842     llvm_unreachable("Don't know how to custom expand this");
9843   case ISD::BITCAST:
9844     ReplaceBITCASTResults(N, Results, DAG);
9845     return;
9846   case AArch64ISD::SADDV:
9847     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9848     return;
9849   case AArch64ISD::UADDV:
9850     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9851     return;
9852   case AArch64ISD::SMINV:
9853     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9854     return;
9855   case AArch64ISD::UMINV:
9856     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9857     return;
9858   case AArch64ISD::SMAXV:
9859     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9860     return;
9861   case AArch64ISD::UMAXV:
9862     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9863     return;
9864   case ISD::FP_TO_UINT:
9865   case ISD::FP_TO_SINT:
9866     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9867     // Let normal code take care of it by not adding anything to Results.
9868     return;
9869   }
9870 }
9871
9872 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9873   return true;
9874 }
9875
9876 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9877   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9878   // reciprocal if there are three or more FDIVs.
9879   return 3;
9880 }
9881
9882 TargetLoweringBase::LegalizeTypeAction
9883 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9884   MVT SVT = VT.getSimpleVT();
9885   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9886   // v4i16, v2i32 instead of to promote.
9887   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9888       || SVT == MVT::v1f32)
9889     return TypeWidenVector;
9890
9891   return TargetLoweringBase::getPreferredVectorAction(VT);
9892 }
9893
9894 // Loads and stores less than 128-bits are already atomic; ones above that
9895 // are doomed anyway, so defer to the default libcall and blame the OS when
9896 // things go wrong.
9897 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9898   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9899   return Size == 128;
9900 }
9901
9902 // Loads and stores less than 128-bits are already atomic; ones above that
9903 // are doomed anyway, so defer to the default libcall and blame the OS when
9904 // things go wrong.
9905 TargetLowering::AtomicExpansionKind
9906 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9907   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9908   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9909 }
9910
9911 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9912 TargetLowering::AtomicExpansionKind
9913 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9914   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9915   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9916 }
9917
9918 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9919     AtomicCmpXchgInst *AI) const {
9920   return true;
9921 }
9922
9923 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9924                                              AtomicOrdering Ord) const {
9925   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9926   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9927   bool IsAcquire = isAtLeastAcquire(Ord);
9928
9929   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9930   // intrinsic must return {i64, i64} and we have to recombine them into a
9931   // single i128 here.
9932   if (ValTy->getPrimitiveSizeInBits() == 128) {
9933     Intrinsic::ID Int =
9934         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9935     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9936
9937     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9938     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9939
9940     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9941     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9942     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9943     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9944     return Builder.CreateOr(
9945         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9946   }
9947
9948   Type *Tys[] = { Addr->getType() };
9949   Intrinsic::ID Int =
9950       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9951   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9952
9953   return Builder.CreateTruncOrBitCast(
9954       Builder.CreateCall(Ldxr, Addr),
9955       cast<PointerType>(Addr->getType())->getElementType());
9956 }
9957
9958 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9959     IRBuilder<> &Builder) const {
9960   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9961   Builder.CreateCall(
9962       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9963 }
9964
9965 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9966                                                    Value *Val, Value *Addr,
9967                                                    AtomicOrdering Ord) const {
9968   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9969   bool IsRelease = isAtLeastRelease(Ord);
9970
9971   // Since the intrinsics must have legal type, the i128 intrinsics take two
9972   // parameters: "i64, i64". We must marshal Val into the appropriate form
9973   // before the call.
9974   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9975     Intrinsic::ID Int =
9976         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9977     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9978     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9979
9980     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9981     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9982     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9983     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9984   }
9985
9986   Intrinsic::ID Int =
9987       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9988   Type *Tys[] = { Addr->getType() };
9989   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9990
9991   return Builder.CreateCall(Stxr,
9992                             {Builder.CreateZExtOrBitCast(
9993                                  Val, Stxr->getFunctionType()->getParamType(0)),
9994                              Addr});
9995 }
9996
9997 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9998     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9999   return Ty->isArrayTy();
10000 }
10001
10002 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10003                                                             EVT) const {
10004   return false;
10005 }
10006
10007 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10008   if (!Subtarget->isTargetAndroid())
10009     return TargetLowering::getSafeStackPointerLocation(IRB);
10010
10011   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10012   // definition of TLS_SLOT_SAFESTACK in
10013   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10014   const unsigned TlsOffset = 0x48;
10015   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10016   Function *ThreadPointerFunc =
10017       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10018   return IRB.CreatePointerCast(
10019       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10020       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10021 }