[AArch64] Lower READCYCLECOUNTER using MRS PMCCTNR_EL0.
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 #define DEBUG_TYPE "aarch64-lower"
39
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
43 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147   // Virtually no operation on f128 is legal, but LLVM can't expand them when
148   // there's a valid register class, so we need custom operations in most cases.
149   setOperationAction(ISD::FABS, MVT::f128, Expand);
150   setOperationAction(ISD::FADD, MVT::f128, Custom);
151   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152   setOperationAction(ISD::FCOS, MVT::f128, Expand);
153   setOperationAction(ISD::FDIV, MVT::f128, Custom);
154   setOperationAction(ISD::FMA, MVT::f128, Expand);
155   setOperationAction(ISD::FMUL, MVT::f128, Custom);
156   setOperationAction(ISD::FNEG, MVT::f128, Expand);
157   setOperationAction(ISD::FPOW, MVT::f128, Expand);
158   setOperationAction(ISD::FREM, MVT::f128, Expand);
159   setOperationAction(ISD::FRINT, MVT::f128, Expand);
160   setOperationAction(ISD::FSIN, MVT::f128, Expand);
161   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163   setOperationAction(ISD::FSUB, MVT::f128, Custom);
164   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165   setOperationAction(ISD::SETCC, MVT::f128, Custom);
166   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167   setOperationAction(ISD::SELECT, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171   // Lowering for many of the conversions is actually specified by the non-f128
172   // type. The LowerXXX function will be trivial when f128 isn't involved.
173   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188   // Variable arguments.
189   setOperationAction(ISD::VASTART, MVT::Other, Custom);
190   setOperationAction(ISD::VAARG, MVT::Other, Custom);
191   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192   setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194   // Variable-sized objects.
195   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
199   // Exception handling.
200   // FIXME: These are guesses. Has this been defined yet?
201   setExceptionPointerRegister(AArch64::X0);
202   setExceptionSelectorRegister(AArch64::X1);
203
204   // Constant pool entries
205   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
206
207   // BlockAddress
208   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
209
210   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211   setOperationAction(ISD::ADDC, MVT::i32, Custom);
212   setOperationAction(ISD::ADDE, MVT::i32, Custom);
213   setOperationAction(ISD::SUBC, MVT::i32, Custom);
214   setOperationAction(ISD::SUBE, MVT::i32, Custom);
215   setOperationAction(ISD::ADDC, MVT::i64, Custom);
216   setOperationAction(ISD::ADDE, MVT::i64, Custom);
217   setOperationAction(ISD::SUBC, MVT::i64, Custom);
218   setOperationAction(ISD::SUBE, MVT::i64, Custom);
219
220   // AArch64 lacks both left-rotate and popcount instructions.
221   setOperationAction(ISD::ROTL, MVT::i32, Expand);
222   setOperationAction(ISD::ROTL, MVT::i64, Expand);
223
224   // AArch64 doesn't have {U|S}MUL_LOHI.
225   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
227
228
229   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230   // counterparts, which AArch64 supports directly.
231   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
235
236   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
238
239   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241   setOperationAction(ISD::SREM, MVT::i32, Expand);
242   setOperationAction(ISD::SREM, MVT::i64, Expand);
243   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245   setOperationAction(ISD::UREM, MVT::i32, Expand);
246   setOperationAction(ISD::UREM, MVT::i64, Expand);
247
248   // Custom lower Add/Sub/Mul with overflow.
249   setOperationAction(ISD::SADDO, MVT::i32, Custom);
250   setOperationAction(ISD::SADDO, MVT::i64, Custom);
251   setOperationAction(ISD::UADDO, MVT::i32, Custom);
252   setOperationAction(ISD::UADDO, MVT::i64, Custom);
253   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255   setOperationAction(ISD::USUBO, MVT::i32, Custom);
256   setOperationAction(ISD::USUBO, MVT::i64, Custom);
257   setOperationAction(ISD::SMULO, MVT::i32, Custom);
258   setOperationAction(ISD::SMULO, MVT::i64, Custom);
259   setOperationAction(ISD::UMULO, MVT::i32, Custom);
260   setOperationAction(ISD::UMULO, MVT::i64, Custom);
261
262   setOperationAction(ISD::FSIN, MVT::f32, Expand);
263   setOperationAction(ISD::FSIN, MVT::f64, Expand);
264   setOperationAction(ISD::FCOS, MVT::f32, Expand);
265   setOperationAction(ISD::FCOS, MVT::f64, Expand);
266   setOperationAction(ISD::FPOW, MVT::f32, Expand);
267   setOperationAction(ISD::FPOW, MVT::f64, Expand);
268   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
270
271   // f16 is a storage-only type, always promote it to f32.
272   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
273   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
274   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
275   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
276   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
277   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
278   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
279   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
280   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
281   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
282   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
283   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
284   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
285   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
286   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
287   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
288   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
289   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
290   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
291   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
292   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
293   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
294   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
295   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
296   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
297   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
298   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
299   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
300   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
301   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
302   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
303   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
304   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
305   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
306
307   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
308   // known to be safe.
309   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
321
322   // Expand all other v4f16 operations.
323   // FIXME: We could generate better code by promoting some operations to
324   // a pair of v4f32s
325   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
351
352
353   // v8f16 is also a storage-only type, so expand it.
354   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
385
386   // AArch64 has implementations of a lot of rounding-like FP operations.
387   for (MVT Ty : {MVT::f32, MVT::f64}) {
388     setOperationAction(ISD::FFLOOR, Ty, Legal);
389     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390     setOperationAction(ISD::FCEIL, Ty, Legal);
391     setOperationAction(ISD::FRINT, Ty, Legal);
392     setOperationAction(ISD::FTRUNC, Ty, Legal);
393     setOperationAction(ISD::FROUND, Ty, Legal);
394     setOperationAction(ISD::FMINNUM, Ty, Legal);
395     setOperationAction(ISD::FMAXNUM, Ty, Legal);
396     setOperationAction(ISD::FMINNAN, Ty, Legal);
397     setOperationAction(ISD::FMAXNAN, Ty, Legal);
398   }
399
400   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
401
402   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
403   // This requires the Performance Monitors extension.
404   if (Subtarget->hasPerfMon())
405     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
406
407   if (Subtarget->isTargetMachO()) {
408     // For iOS, we don't want to the normal expansion of a libcall to
409     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
410     // traffic.
411     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
412     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
413   } else {
414     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
415     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
416   }
417
418   // Make floating-point constants legal for the large code model, so they don't
419   // become loads from the constant pool.
420   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
421     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
422     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
423   }
424
425   // AArch64 does not have floating-point extending loads, i1 sign-extending
426   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
427   for (MVT VT : MVT::fp_valuetypes()) {
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
432   }
433   for (MVT VT : MVT::integer_valuetypes())
434     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
435
436   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
443
444   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
445   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
446
447   // Indexed loads and stores are supported.
448   for (unsigned im = (unsigned)ISD::PRE_INC;
449        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
450     setIndexedLoadAction(im, MVT::i8, Legal);
451     setIndexedLoadAction(im, MVT::i16, Legal);
452     setIndexedLoadAction(im, MVT::i32, Legal);
453     setIndexedLoadAction(im, MVT::i64, Legal);
454     setIndexedLoadAction(im, MVT::f64, Legal);
455     setIndexedLoadAction(im, MVT::f32, Legal);
456     setIndexedLoadAction(im, MVT::f16, Legal);
457     setIndexedStoreAction(im, MVT::i8, Legal);
458     setIndexedStoreAction(im, MVT::i16, Legal);
459     setIndexedStoreAction(im, MVT::i32, Legal);
460     setIndexedStoreAction(im, MVT::i64, Legal);
461     setIndexedStoreAction(im, MVT::f64, Legal);
462     setIndexedStoreAction(im, MVT::f32, Legal);
463     setIndexedStoreAction(im, MVT::f16, Legal);
464   }
465
466   // Trap.
467   setOperationAction(ISD::TRAP, MVT::Other, Legal);
468
469   // We combine OR nodes for bitfield operations.
470   setTargetDAGCombine(ISD::OR);
471
472   // Vector add and sub nodes may conceal a high-half opportunity.
473   // Also, try to fold ADD into CSINC/CSINV..
474   setTargetDAGCombine(ISD::ADD);
475   setTargetDAGCombine(ISD::SUB);
476
477   setTargetDAGCombine(ISD::XOR);
478   setTargetDAGCombine(ISD::SINT_TO_FP);
479   setTargetDAGCombine(ISD::UINT_TO_FP);
480
481   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
482
483   setTargetDAGCombine(ISD::ANY_EXTEND);
484   setTargetDAGCombine(ISD::ZERO_EXTEND);
485   setTargetDAGCombine(ISD::SIGN_EXTEND);
486   setTargetDAGCombine(ISD::BITCAST);
487   setTargetDAGCombine(ISD::CONCAT_VECTORS);
488   setTargetDAGCombine(ISD::STORE);
489
490   setTargetDAGCombine(ISD::MUL);
491
492   setTargetDAGCombine(ISD::SELECT);
493   setTargetDAGCombine(ISD::VSELECT);
494
495   setTargetDAGCombine(ISD::INTRINSIC_VOID);
496   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
498
499   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
500   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
501   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
502
503   setStackPointerRegisterToSaveRestore(AArch64::SP);
504
505   setSchedulingPreference(Sched::Hybrid);
506
507   // Enable TBZ/TBNZ
508   MaskAndBranchFoldingIsLegal = true;
509   EnableExtLdPromotion = true;
510
511   setMinFunctionAlignment(2);
512
513   setHasExtractBitsInsn(true);
514
515   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
516
517   if (Subtarget->hasNEON()) {
518     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
519     // silliness like this:
520     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
521     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
523     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
524     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
525     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
527     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
528     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
529     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
530     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
531     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
532     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
533     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
534     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
535     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
536     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
537     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
538     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
539     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
540     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
541     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
542     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
543     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
544     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
545
546     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
547     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
548     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
549     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
550     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
551
552     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
553
554     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
555     // elements smaller than i32, so promote the input to i32 first.
556     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
557     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
560     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
561     // -> v8f16 conversions.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
564     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
565     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
566     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
571     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
572     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
573     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
575
576     // AArch64 doesn't have MUL.2d:
577     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
578     // Custom handling for some quad-vector types to detect MULL.
579     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
580     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
581     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
582
583     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
584     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
585     // Likewise, narrowing and extending vector loads/stores aren't handled
586     // directly.
587     for (MVT VT : MVT::vector_valuetypes()) {
588       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
589
590       setOperationAction(ISD::MULHS, VT, Expand);
591       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
592       setOperationAction(ISD::MULHU, VT, Expand);
593       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
594
595       setOperationAction(ISD::BSWAP, VT, Expand);
596
597       for (MVT InnerVT : MVT::vector_valuetypes()) {
598         setTruncStoreAction(VT, InnerVT, Expand);
599         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
601         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
602       }
603     }
604
605     // AArch64 has implementations of a lot of rounding-like FP operations.
606     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
607       setOperationAction(ISD::FFLOOR, Ty, Legal);
608       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
609       setOperationAction(ISD::FCEIL, Ty, Legal);
610       setOperationAction(ISD::FRINT, Ty, Legal);
611       setOperationAction(ISD::FTRUNC, Ty, Legal);
612       setOperationAction(ISD::FROUND, Ty, Legal);
613     }
614   }
615
616   // Prefer likely predicted branches to selects on out-of-order cores.
617   if (Subtarget->isCortexA57())
618     PredictableSelectIsExpensive = true;
619 }
620
621 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
622   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
623     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
624     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
625
626     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
627     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
628   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
629     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
631
632     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
634   }
635
636   // Mark vector float intrinsics as expand.
637   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
638     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
639     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
640     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
641     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
642     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
643     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
647
648     // But we do support custom-lowering for FCOPYSIGN.
649     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
650   }
651
652   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
653   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
654   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
655   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
656   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
657   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
661   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
662   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
663   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
664
665   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
666   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
667   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
668   for (MVT InnerVT : MVT::all_valuetypes())
669     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
670
671   // CNT supports only B element sizes.
672   if (VT != MVT::v8i8 && VT != MVT::v16i8)
673     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
674
675   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
676   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
677   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
678   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
679   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
680
681   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
682   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
683
684   // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
685   // i64.
686   if (!VT.isFloatingPoint() &&
687       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
688     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
689                             ISD::SABSDIFF, ISD::UABSDIFF})
690       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
691
692   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
693   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
694     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
695                             ISD::FMINNUM, ISD::FMAXNUM})
696       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
697
698   if (Subtarget->isLittleEndian()) {
699     for (unsigned im = (unsigned)ISD::PRE_INC;
700          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
701       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
702       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
703     }
704   }
705 }
706
707 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
708   addRegisterClass(VT, &AArch64::FPR64RegClass);
709   addTypeForNEON(VT, MVT::v2i32);
710 }
711
712 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
713   addRegisterClass(VT, &AArch64::FPR128RegClass);
714   addTypeForNEON(VT, MVT::v4i32);
715 }
716
717 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
718                                               EVT VT) const {
719   if (!VT.isVector())
720     return MVT::i32;
721   return VT.changeVectorElementTypeToInteger();
722 }
723
724 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
725 /// Mask are known to be either zero or one and return them in the
726 /// KnownZero/KnownOne bitsets.
727 void AArch64TargetLowering::computeKnownBitsForTargetNode(
728     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
729     const SelectionDAG &DAG, unsigned Depth) const {
730   switch (Op.getOpcode()) {
731   default:
732     break;
733   case AArch64ISD::CSEL: {
734     APInt KnownZero2, KnownOne2;
735     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
736     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
737     KnownZero &= KnownZero2;
738     KnownOne &= KnownOne2;
739     break;
740   }
741   case ISD::INTRINSIC_W_CHAIN: {
742    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
743     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
744     switch (IntID) {
745     default: return;
746     case Intrinsic::aarch64_ldaxr:
747     case Intrinsic::aarch64_ldxr: {
748       unsigned BitWidth = KnownOne.getBitWidth();
749       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
750       unsigned MemBits = VT.getScalarType().getSizeInBits();
751       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
752       return;
753     }
754     }
755     break;
756   }
757   case ISD::INTRINSIC_WO_CHAIN:
758   case ISD::INTRINSIC_VOID: {
759     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
760     switch (IntNo) {
761     default:
762       break;
763     case Intrinsic::aarch64_neon_umaxv:
764     case Intrinsic::aarch64_neon_uminv: {
765       // Figure out the datatype of the vector operand. The UMINV instruction
766       // will zero extend the result, so we can mark as known zero all the
767       // bits larger than the element datatype. 32-bit or larget doesn't need
768       // this as those are legal types and will be handled by isel directly.
769       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
770       unsigned BitWidth = KnownZero.getBitWidth();
771       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
772         assert(BitWidth >= 8 && "Unexpected width!");
773         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
774         KnownZero |= Mask;
775       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
776         assert(BitWidth >= 16 && "Unexpected width!");
777         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
778         KnownZero |= Mask;
779       }
780       break;
781     } break;
782     }
783   }
784   }
785 }
786
787 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
788                                                   EVT) const {
789   return MVT::i64;
790 }
791
792 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
793                                                            unsigned AddrSpace,
794                                                            unsigned Align,
795                                                            bool *Fast) const {
796   if (Subtarget->requiresStrictAlign())
797     return false;
798   // FIXME: True for Cyclone, but not necessary others.
799   if (Fast)
800     *Fast = true;
801   return true;
802 }
803
804 FastISel *
805 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
806                                       const TargetLibraryInfo *libInfo) const {
807   return AArch64::createFastISel(funcInfo, libInfo);
808 }
809
810 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
811   switch ((AArch64ISD::NodeType)Opcode) {
812   case AArch64ISD::FIRST_NUMBER:      break;
813   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
814   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
815   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
816   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
817   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
818   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
819   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
820   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
821   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
822   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
823   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
824   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
825   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
826   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
827   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
828   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
829   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
830   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
831   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
832   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
833   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
834   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
835   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
836   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
837   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
838   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
839   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
840   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
841   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
842   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
843   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
844   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
845   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
846   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
847   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
848   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
849   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
850   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
851   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
852   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
853   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
854   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
855   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
856   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
857   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
858   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
859   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
860   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
861   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
862   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
863   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
864   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
865   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
866   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
867   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
868   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
869   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
870   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
871   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
872   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
873   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
874   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
875   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
876   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
877   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
878   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
879   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
880   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
881   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
882   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
883   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
884   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
885   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
886   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
887   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
888   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
889   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
890   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
891   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
892   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
893   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
894   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
895   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
896   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
897   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
898   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
899   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
900   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
901   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
902   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
903   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
904   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
905   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
906   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
907   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
908   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
909   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
910   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
911   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
912   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
913   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
914   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
915   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
916   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
917   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
918   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
919   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
920   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
921   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
922   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
923   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
924   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
925   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
926   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
927   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
928   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
929   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
930   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
931   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
932   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
933   }
934   return nullptr;
935 }
936
937 MachineBasicBlock *
938 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
939                                     MachineBasicBlock *MBB) const {
940   // We materialise the F128CSEL pseudo-instruction as some control flow and a
941   // phi node:
942
943   // OrigBB:
944   //     [... previous instrs leading to comparison ...]
945   //     b.ne TrueBB
946   //     b EndBB
947   // TrueBB:
948   //     ; Fallthrough
949   // EndBB:
950   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
951
952   MachineFunction *MF = MBB->getParent();
953   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
954   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
955   DebugLoc DL = MI->getDebugLoc();
956   MachineFunction::iterator It = MBB;
957   ++It;
958
959   unsigned DestReg = MI->getOperand(0).getReg();
960   unsigned IfTrueReg = MI->getOperand(1).getReg();
961   unsigned IfFalseReg = MI->getOperand(2).getReg();
962   unsigned CondCode = MI->getOperand(3).getImm();
963   bool NZCVKilled = MI->getOperand(4).isKill();
964
965   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
966   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
967   MF->insert(It, TrueBB);
968   MF->insert(It, EndBB);
969
970   // Transfer rest of current basic-block to EndBB
971   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
972                 MBB->end());
973   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
974
975   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
976   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
977   MBB->addSuccessor(TrueBB);
978   MBB->addSuccessor(EndBB);
979
980   // TrueBB falls through to the end.
981   TrueBB->addSuccessor(EndBB);
982
983   if (!NZCVKilled) {
984     TrueBB->addLiveIn(AArch64::NZCV);
985     EndBB->addLiveIn(AArch64::NZCV);
986   }
987
988   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
989       .addReg(IfTrueReg)
990       .addMBB(TrueBB)
991       .addReg(IfFalseReg)
992       .addMBB(MBB);
993
994   MI->eraseFromParent();
995   return EndBB;
996 }
997
998 MachineBasicBlock *
999 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1000                                                  MachineBasicBlock *BB) const {
1001   switch (MI->getOpcode()) {
1002   default:
1003 #ifndef NDEBUG
1004     MI->dump();
1005 #endif
1006     llvm_unreachable("Unexpected instruction for custom inserter!");
1007
1008   case AArch64::F128CSEL:
1009     return EmitF128CSEL(MI, BB);
1010
1011   case TargetOpcode::STACKMAP:
1012   case TargetOpcode::PATCHPOINT:
1013     return emitPatchPoint(MI, BB);
1014   }
1015 }
1016
1017 //===----------------------------------------------------------------------===//
1018 // AArch64 Lowering private implementation.
1019 //===----------------------------------------------------------------------===//
1020
1021 //===----------------------------------------------------------------------===//
1022 // Lowering Code
1023 //===----------------------------------------------------------------------===//
1024
1025 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1026 /// CC
1027 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1028   switch (CC) {
1029   default:
1030     llvm_unreachable("Unknown condition code!");
1031   case ISD::SETNE:
1032     return AArch64CC::NE;
1033   case ISD::SETEQ:
1034     return AArch64CC::EQ;
1035   case ISD::SETGT:
1036     return AArch64CC::GT;
1037   case ISD::SETGE:
1038     return AArch64CC::GE;
1039   case ISD::SETLT:
1040     return AArch64CC::LT;
1041   case ISD::SETLE:
1042     return AArch64CC::LE;
1043   case ISD::SETUGT:
1044     return AArch64CC::HI;
1045   case ISD::SETUGE:
1046     return AArch64CC::HS;
1047   case ISD::SETULT:
1048     return AArch64CC::LO;
1049   case ISD::SETULE:
1050     return AArch64CC::LS;
1051   }
1052 }
1053
1054 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1055 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1056                                   AArch64CC::CondCode &CondCode,
1057                                   AArch64CC::CondCode &CondCode2) {
1058   CondCode2 = AArch64CC::AL;
1059   switch (CC) {
1060   default:
1061     llvm_unreachable("Unknown FP condition!");
1062   case ISD::SETEQ:
1063   case ISD::SETOEQ:
1064     CondCode = AArch64CC::EQ;
1065     break;
1066   case ISD::SETGT:
1067   case ISD::SETOGT:
1068     CondCode = AArch64CC::GT;
1069     break;
1070   case ISD::SETGE:
1071   case ISD::SETOGE:
1072     CondCode = AArch64CC::GE;
1073     break;
1074   case ISD::SETOLT:
1075     CondCode = AArch64CC::MI;
1076     break;
1077   case ISD::SETOLE:
1078     CondCode = AArch64CC::LS;
1079     break;
1080   case ISD::SETONE:
1081     CondCode = AArch64CC::MI;
1082     CondCode2 = AArch64CC::GT;
1083     break;
1084   case ISD::SETO:
1085     CondCode = AArch64CC::VC;
1086     break;
1087   case ISD::SETUO:
1088     CondCode = AArch64CC::VS;
1089     break;
1090   case ISD::SETUEQ:
1091     CondCode = AArch64CC::EQ;
1092     CondCode2 = AArch64CC::VS;
1093     break;
1094   case ISD::SETUGT:
1095     CondCode = AArch64CC::HI;
1096     break;
1097   case ISD::SETUGE:
1098     CondCode = AArch64CC::PL;
1099     break;
1100   case ISD::SETLT:
1101   case ISD::SETULT:
1102     CondCode = AArch64CC::LT;
1103     break;
1104   case ISD::SETLE:
1105   case ISD::SETULE:
1106     CondCode = AArch64CC::LE;
1107     break;
1108   case ISD::SETNE:
1109   case ISD::SETUNE:
1110     CondCode = AArch64CC::NE;
1111     break;
1112   }
1113 }
1114
1115 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1116 /// CC usable with the vector instructions. Fewer operations are available
1117 /// without a real NZCV register, so we have to use less efficient combinations
1118 /// to get the same effect.
1119 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1120                                         AArch64CC::CondCode &CondCode,
1121                                         AArch64CC::CondCode &CondCode2,
1122                                         bool &Invert) {
1123   Invert = false;
1124   switch (CC) {
1125   default:
1126     // Mostly the scalar mappings work fine.
1127     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1128     break;
1129   case ISD::SETUO:
1130     Invert = true; // Fallthrough
1131   case ISD::SETO:
1132     CondCode = AArch64CC::MI;
1133     CondCode2 = AArch64CC::GE;
1134     break;
1135   case ISD::SETUEQ:
1136   case ISD::SETULT:
1137   case ISD::SETULE:
1138   case ISD::SETUGT:
1139   case ISD::SETUGE:
1140     // All of the compare-mask comparisons are ordered, but we can switch
1141     // between the two by a double inversion. E.g. ULE == !OGT.
1142     Invert = true;
1143     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1144     break;
1145   }
1146 }
1147
1148 static bool isLegalArithImmed(uint64_t C) {
1149   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1150   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1151 }
1152
1153 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1154                               SDLoc dl, SelectionDAG &DAG) {
1155   EVT VT = LHS.getValueType();
1156
1157   if (VT.isFloatingPoint())
1158     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1159
1160   // The CMP instruction is just an alias for SUBS, and representing it as
1161   // SUBS means that it's possible to get CSE with subtract operations.
1162   // A later phase can perform the optimization of setting the destination
1163   // register to WZR/XZR if it ends up being unused.
1164   unsigned Opcode = AArch64ISD::SUBS;
1165
1166   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1167       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1168       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1169     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1170     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1171     // can be set differently by this operation. It comes down to whether
1172     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1173     // everything is fine. If not then the optimization is wrong. Thus general
1174     // comparisons are only valid if op2 != 0.
1175
1176     // So, finally, the only LLVM-native comparisons that don't mention C and V
1177     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1178     // the absence of information about op2.
1179     Opcode = AArch64ISD::ADDS;
1180     RHS = RHS.getOperand(1);
1181   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1182              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1183              !isUnsignedIntSetCC(CC)) {
1184     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1185     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1186     // of the signed comparisons.
1187     Opcode = AArch64ISD::ANDS;
1188     RHS = LHS.getOperand(1);
1189     LHS = LHS.getOperand(0);
1190   }
1191
1192   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1193       .getValue(1);
1194 }
1195
1196 /// \defgroup AArch64CCMP CMP;CCMP matching
1197 ///
1198 /// These functions deal with the formation of CMP;CCMP;... sequences.
1199 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1200 /// a comparison. They set the NZCV flags to a predefined value if their
1201 /// predicate is false. This allows to express arbitrary conjunctions, for
1202 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1203 /// expressed as:
1204 ///   cmp A
1205 ///   ccmp B, inv(CB), CA
1206 ///   check for CB flags
1207 ///
1208 /// In general we can create code for arbitrary "... (and (and A B) C)"
1209 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1210 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1211 /// negation operations:
1212 /// We can negate the results of a single comparison by inverting the flags
1213 /// used when the predicate fails and inverting the flags tested in the next
1214 /// instruction; We can also negate the results of the whole previous
1215 /// conditional compare sequence by inverting the flags tested in the next
1216 /// instruction. However there is no way to negate the result of a partial
1217 /// sequence.
1218 ///
1219 /// Therefore on encountering an "or" expression we can negate the subtree on
1220 /// one side and have to be able to push the negate to the leafs of the subtree
1221 /// on the other side (see also the comments in code). As complete example:
1222 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1223 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1224 /// is transformed to
1225 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1226 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1227 /// and implemented as:
1228 ///   cmp C
1229 ///   ccmp D, inv(CD), CC
1230 ///   ccmp A, CA, inv(CD)
1231 ///   ccmp B, CB, inv(CA)
1232 ///   check for CB flags
1233 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1234 /// by conditional compare sequences.
1235 /// @{
1236
1237 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1238 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1239                                          ISD::CondCode CC, SDValue CCOp,
1240                                          SDValue Condition, unsigned NZCV,
1241                                          SDLoc DL, SelectionDAG &DAG) {
1242   unsigned Opcode = 0;
1243   if (LHS.getValueType().isFloatingPoint())
1244     Opcode = AArch64ISD::FCCMP;
1245   else if (RHS.getOpcode() == ISD::SUB) {
1246     SDValue SubOp0 = RHS.getOperand(0);
1247     if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1248       if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1249         // See emitComparison() on why we can only do this for SETEQ and SETNE.
1250         Opcode = AArch64ISD::CCMN;
1251         RHS = RHS.getOperand(1);
1252       }
1253   }
1254   if (Opcode == 0)
1255     Opcode = AArch64ISD::CCMP;
1256
1257   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1258   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1259 }
1260
1261 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1262 /// CanPushNegate is set to true if we can push a negate operation through
1263 /// the tree in a was that we are left with AND operations and negate operations
1264 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1265 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1266 /// brought into such a form.
1267 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1268                                          unsigned Depth = 0) {
1269   if (!Val.hasOneUse())
1270     return false;
1271   unsigned Opcode = Val->getOpcode();
1272   if (Opcode == ISD::SETCC) {
1273     CanPushNegate = true;
1274     return true;
1275   }
1276   // Protect against stack overflow.
1277   if (Depth > 15)
1278     return false;
1279   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1280     SDValue O0 = Val->getOperand(0);
1281     SDValue O1 = Val->getOperand(1);
1282     bool CanPushNegateL;
1283     if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1284       return false;
1285     bool CanPushNegateR;
1286     if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1287       return false;
1288     // We cannot push a negate through an AND operation (it would become an OR),
1289     // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1290     // push the negate through the x/y subtrees.
1291     CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1292     return true;
1293   }
1294   return false;
1295 }
1296
1297 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1298 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1299 /// Tries to transform the given i1 producing node @p Val to a series compare
1300 /// and conditional compare operations. @returns an NZCV flags producing node
1301 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1302 /// transformation was not possible.
1303 /// On recursive invocations @p PushNegate may be set to true to have negation
1304 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1305 /// for the comparisons in the current subtree; @p Depth limits the search
1306 /// depth to avoid stack overflow.
1307 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1308     AArch64CC::CondCode &OutCC, bool PushNegate = false,
1309     SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1310     unsigned Depth = 0) {
1311   // We're at a tree leaf, produce a conditional comparison operation.
1312   unsigned Opcode = Val->getOpcode();
1313   if (Opcode == ISD::SETCC) {
1314     SDValue LHS = Val->getOperand(0);
1315     SDValue RHS = Val->getOperand(1);
1316     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1317     bool isInteger = LHS.getValueType().isInteger();
1318     if (PushNegate)
1319       CC = getSetCCInverse(CC, isInteger);
1320     SDLoc DL(Val);
1321     // Determine OutCC and handle FP special case.
1322     if (isInteger) {
1323       OutCC = changeIntCCToAArch64CC(CC);
1324     } else {
1325       assert(LHS.getValueType().isFloatingPoint());
1326       AArch64CC::CondCode ExtraCC;
1327       changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1328       // Surpisingly some floating point conditions can't be tested with a
1329       // single condition code. Construct an additional comparison in this case.
1330       // See comment below on how we deal with OR conditions.
1331       if (ExtraCC != AArch64CC::AL) {
1332         SDValue ExtraCmp;
1333         if (!CCOp.getNode())
1334           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1335         else {
1336           SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1337           // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1338           unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1339           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1340                                                NZCV, DL, DAG);
1341         }
1342         CCOp = ExtraCmp;
1343         Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1344         OutCC = AArch64CC::getInvertedCondCode(OutCC);
1345       }
1346     }
1347
1348     // Produce a normal comparison if we are first in the chain
1349     if (!CCOp.getNode())
1350       return emitComparison(LHS, RHS, CC, DL, DAG);
1351     // Otherwise produce a ccmp.
1352     SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1353     AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1354     unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1355     return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1356                                      DAG);
1357   } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1358     return SDValue();
1359
1360   assert((Opcode == ISD::OR || !PushNegate)
1361          && "Can only push negate through OR operation");
1362
1363   // Check if both sides can be transformed.
1364   SDValue LHS = Val->getOperand(0);
1365   SDValue RHS = Val->getOperand(1);
1366   bool CanPushNegateL;
1367   if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1368     return SDValue();
1369   bool CanPushNegateR;
1370   if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1371     return SDValue();
1372
1373   // Do we need to negate our operands?
1374   bool NegateOperands = Opcode == ISD::OR;
1375   // We can negate the results of all previous operations by inverting the
1376   // predicate flags giving us a free negation for one side. For the other side
1377   // we need to be able to push the negation to the leafs of the tree.
1378   if (NegateOperands) {
1379     if (!CanPushNegateL && !CanPushNegateR)
1380       return SDValue();
1381     // Order the side where we can push the negate through to LHS.
1382     if (!CanPushNegateL && CanPushNegateR)
1383       std::swap(LHS, RHS);
1384   } else {
1385     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1386     bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1387     if (NeedsNegOutL && NeedsNegOutR)
1388       return SDValue();
1389     // Order the side where we need to negate the output flags to RHS so it
1390     // gets emitted first.
1391     if (NeedsNegOutL)
1392       std::swap(LHS, RHS);
1393   }
1394
1395   // Emit RHS. If we want to negate the tree we only need to push a negate
1396   // through if we are already in a PushNegate case, otherwise we can negate
1397   // the "flags to test" afterwards.
1398   AArch64CC::CondCode RHSCC;
1399   SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1400                                                 CCOp, Predicate, Depth+1);
1401   if (NegateOperands && !PushNegate)
1402     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1403   // Emit LHS. We must push the negate through if we need to negate it.
1404   SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1405                                                 CmpR, RHSCC, Depth+1);
1406   // If we transformed an OR to and AND then we have to negate the result
1407   // (or absorb a PushNegate resulting in a double negation).
1408   if (Opcode == ISD::OR && !PushNegate)
1409     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1410   return CmpL;
1411 }
1412
1413 /// @}
1414
1415 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1416                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1417   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1418     EVT VT = RHS.getValueType();
1419     uint64_t C = RHSC->getZExtValue();
1420     if (!isLegalArithImmed(C)) {
1421       // Constant does not fit, try adjusting it by one?
1422       switch (CC) {
1423       default:
1424         break;
1425       case ISD::SETLT:
1426       case ISD::SETGE:
1427         if ((VT == MVT::i32 && C != 0x80000000 &&
1428              isLegalArithImmed((uint32_t)(C - 1))) ||
1429             (VT == MVT::i64 && C != 0x80000000ULL &&
1430              isLegalArithImmed(C - 1ULL))) {
1431           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1432           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1433           RHS = DAG.getConstant(C, dl, VT);
1434         }
1435         break;
1436       case ISD::SETULT:
1437       case ISD::SETUGE:
1438         if ((VT == MVT::i32 && C != 0 &&
1439              isLegalArithImmed((uint32_t)(C - 1))) ||
1440             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1441           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1442           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1443           RHS = DAG.getConstant(C, dl, VT);
1444         }
1445         break;
1446       case ISD::SETLE:
1447       case ISD::SETGT:
1448         if ((VT == MVT::i32 && C != INT32_MAX &&
1449              isLegalArithImmed((uint32_t)(C + 1))) ||
1450             (VT == MVT::i64 && C != INT64_MAX &&
1451              isLegalArithImmed(C + 1ULL))) {
1452           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1453           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1454           RHS = DAG.getConstant(C, dl, VT);
1455         }
1456         break;
1457       case ISD::SETULE:
1458       case ISD::SETUGT:
1459         if ((VT == MVT::i32 && C != UINT32_MAX &&
1460              isLegalArithImmed((uint32_t)(C + 1))) ||
1461             (VT == MVT::i64 && C != UINT64_MAX &&
1462              isLegalArithImmed(C + 1ULL))) {
1463           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1464           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1465           RHS = DAG.getConstant(C, dl, VT);
1466         }
1467         break;
1468       }
1469     }
1470   }
1471   SDValue Cmp;
1472   AArch64CC::CondCode AArch64CC;
1473   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1474     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1475
1476     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1477     // For the i8 operand, the largest immediate is 255, so this can be easily
1478     // encoded in the compare instruction. For the i16 operand, however, the
1479     // largest immediate cannot be encoded in the compare.
1480     // Therefore, use a sign extending load and cmn to avoid materializing the
1481     // -1 constant. For example,
1482     // movz w1, #65535
1483     // ldrh w0, [x0, #0]
1484     // cmp w0, w1
1485     // >
1486     // ldrsh w0, [x0, #0]
1487     // cmn w0, #1
1488     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1489     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1490     // ensure both the LHS and RHS are truly zero extended and to make sure the
1491     // transformation is profitable.
1492     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1493         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1494         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1495         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1496       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1497       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1498         SDValue SExt =
1499             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1500                         DAG.getValueType(MVT::i16));
1501         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1502                                                    RHS.getValueType()),
1503                              CC, dl, DAG);
1504         AArch64CC = changeIntCCToAArch64CC(CC);
1505       }
1506     }
1507
1508     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1509       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1510         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1511           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1512       }
1513     }
1514   }
1515
1516   if (!Cmp) {
1517     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1518     AArch64CC = changeIntCCToAArch64CC(CC);
1519   }
1520   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1521   return Cmp;
1522 }
1523
1524 static std::pair<SDValue, SDValue>
1525 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1526   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1527          "Unsupported value type");
1528   SDValue Value, Overflow;
1529   SDLoc DL(Op);
1530   SDValue LHS = Op.getOperand(0);
1531   SDValue RHS = Op.getOperand(1);
1532   unsigned Opc = 0;
1533   switch (Op.getOpcode()) {
1534   default:
1535     llvm_unreachable("Unknown overflow instruction!");
1536   case ISD::SADDO:
1537     Opc = AArch64ISD::ADDS;
1538     CC = AArch64CC::VS;
1539     break;
1540   case ISD::UADDO:
1541     Opc = AArch64ISD::ADDS;
1542     CC = AArch64CC::HS;
1543     break;
1544   case ISD::SSUBO:
1545     Opc = AArch64ISD::SUBS;
1546     CC = AArch64CC::VS;
1547     break;
1548   case ISD::USUBO:
1549     Opc = AArch64ISD::SUBS;
1550     CC = AArch64CC::LO;
1551     break;
1552   // Multiply needs a little bit extra work.
1553   case ISD::SMULO:
1554   case ISD::UMULO: {
1555     CC = AArch64CC::NE;
1556     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1557     if (Op.getValueType() == MVT::i32) {
1558       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1559       // For a 32 bit multiply with overflow check we want the instruction
1560       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1561       // need to generate the following pattern:
1562       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1563       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1564       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1565       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1566       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1567                                 DAG.getConstant(0, DL, MVT::i64));
1568       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1569       // operation. We need to clear out the upper 32 bits, because we used a
1570       // widening multiply that wrote all 64 bits. In the end this should be a
1571       // noop.
1572       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1573       if (IsSigned) {
1574         // The signed overflow check requires more than just a simple check for
1575         // any bit set in the upper 32 bits of the result. These bits could be
1576         // just the sign bits of a negative number. To perform the overflow
1577         // check we have to arithmetic shift right the 32nd bit of the result by
1578         // 31 bits. Then we compare the result to the upper 32 bits.
1579         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1580                                         DAG.getConstant(32, DL, MVT::i64));
1581         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1582         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1583                                         DAG.getConstant(31, DL, MVT::i64));
1584         // It is important that LowerBits is last, otherwise the arithmetic
1585         // shift will not be folded into the compare (SUBS).
1586         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1587         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1588                        .getValue(1);
1589       } else {
1590         // The overflow check for unsigned multiply is easy. We only need to
1591         // check if any of the upper 32 bits are set. This can be done with a
1592         // CMP (shifted register). For that we need to generate the following
1593         // pattern:
1594         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1595         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1596                                         DAG.getConstant(32, DL, MVT::i64));
1597         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1598         Overflow =
1599             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1600                         DAG.getConstant(0, DL, MVT::i64),
1601                         UpperBits).getValue(1);
1602       }
1603       break;
1604     }
1605     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1606     // For the 64 bit multiply
1607     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1608     if (IsSigned) {
1609       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1610       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1611                                       DAG.getConstant(63, DL, MVT::i64));
1612       // It is important that LowerBits is last, otherwise the arithmetic
1613       // shift will not be folded into the compare (SUBS).
1614       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1615       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1616                      .getValue(1);
1617     } else {
1618       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
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   } // switch (...)
1628
1629   if (Opc) {
1630     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1631
1632     // Emit the AArch64 operation with overflow check.
1633     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1634     Overflow = Value.getValue(1);
1635   }
1636   return std::make_pair(Value, Overflow);
1637 }
1638
1639 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1640                                              RTLIB::Libcall Call) const {
1641   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1642   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1643                      SDLoc(Op)).first;
1644 }
1645
1646 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1647   SDValue Sel = Op.getOperand(0);
1648   SDValue Other = Op.getOperand(1);
1649
1650   // If neither operand is a SELECT_CC, give up.
1651   if (Sel.getOpcode() != ISD::SELECT_CC)
1652     std::swap(Sel, Other);
1653   if (Sel.getOpcode() != ISD::SELECT_CC)
1654     return Op;
1655
1656   // The folding we want to perform is:
1657   // (xor x, (select_cc a, b, cc, 0, -1) )
1658   //   -->
1659   // (csel x, (xor x, -1), cc ...)
1660   //
1661   // The latter will get matched to a CSINV instruction.
1662
1663   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1664   SDValue LHS = Sel.getOperand(0);
1665   SDValue RHS = Sel.getOperand(1);
1666   SDValue TVal = Sel.getOperand(2);
1667   SDValue FVal = Sel.getOperand(3);
1668   SDLoc dl(Sel);
1669
1670   // FIXME: This could be generalized to non-integer comparisons.
1671   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1672     return Op;
1673
1674   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1675   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1676
1677   // The values aren't constants, this isn't the pattern we're looking for.
1678   if (!CFVal || !CTVal)
1679     return Op;
1680
1681   // We can commute the SELECT_CC by inverting the condition.  This
1682   // might be needed to make this fit into a CSINV pattern.
1683   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1684     std::swap(TVal, FVal);
1685     std::swap(CTVal, CFVal);
1686     CC = ISD::getSetCCInverse(CC, true);
1687   }
1688
1689   // If the constants line up, perform the transform!
1690   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1691     SDValue CCVal;
1692     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1693
1694     FVal = Other;
1695     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1696                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1697
1698     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1699                        CCVal, Cmp);
1700   }
1701
1702   return Op;
1703 }
1704
1705 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1706   EVT VT = Op.getValueType();
1707
1708   // Let legalize expand this if it isn't a legal type yet.
1709   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1710     return SDValue();
1711
1712   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1713
1714   unsigned Opc;
1715   bool ExtraOp = false;
1716   switch (Op.getOpcode()) {
1717   default:
1718     llvm_unreachable("Invalid code");
1719   case ISD::ADDC:
1720     Opc = AArch64ISD::ADDS;
1721     break;
1722   case ISD::SUBC:
1723     Opc = AArch64ISD::SUBS;
1724     break;
1725   case ISD::ADDE:
1726     Opc = AArch64ISD::ADCS;
1727     ExtraOp = true;
1728     break;
1729   case ISD::SUBE:
1730     Opc = AArch64ISD::SBCS;
1731     ExtraOp = true;
1732     break;
1733   }
1734
1735   if (!ExtraOp)
1736     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1737   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1738                      Op.getOperand(2));
1739 }
1740
1741 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1742   // Let legalize expand this if it isn't a legal type yet.
1743   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1744     return SDValue();
1745
1746   SDLoc dl(Op);
1747   AArch64CC::CondCode CC;
1748   // The actual operation that sets the overflow or carry flag.
1749   SDValue Value, Overflow;
1750   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1751
1752   // We use 0 and 1 as false and true values.
1753   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1754   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1755
1756   // We use an inverted condition, because the conditional select is inverted
1757   // too. This will allow it to be selected to a single instruction:
1758   // CSINC Wd, WZR, WZR, invert(cond).
1759   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1760   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1761                          CCVal, Overflow);
1762
1763   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1764   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1765 }
1766
1767 // Prefetch operands are:
1768 // 1: Address to prefetch
1769 // 2: bool isWrite
1770 // 3: int locality (0 = no locality ... 3 = extreme locality)
1771 // 4: bool isDataCache
1772 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1773   SDLoc DL(Op);
1774   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1775   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1776   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1777
1778   bool IsStream = !Locality;
1779   // When the locality number is set
1780   if (Locality) {
1781     // The front-end should have filtered out the out-of-range values
1782     assert(Locality <= 3 && "Prefetch locality out-of-range");
1783     // The locality degree is the opposite of the cache speed.
1784     // Put the number the other way around.
1785     // The encoding starts at 0 for level 1
1786     Locality = 3 - Locality;
1787   }
1788
1789   // built the mask value encoding the expected behavior.
1790   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1791                    (!IsData << 3) |     // IsDataCache bit
1792                    (Locality << 1) |    // Cache level bits
1793                    (unsigned)IsStream;  // Stream bit
1794   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1795                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1796 }
1797
1798 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1799                                               SelectionDAG &DAG) const {
1800   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1801
1802   RTLIB::Libcall LC;
1803   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1804
1805   return LowerF128Call(Op, DAG, LC);
1806 }
1807
1808 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1809                                              SelectionDAG &DAG) const {
1810   if (Op.getOperand(0).getValueType() != MVT::f128) {
1811     // It's legal except when f128 is involved
1812     return Op;
1813   }
1814
1815   RTLIB::Libcall LC;
1816   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1817
1818   // FP_ROUND node has a second operand indicating whether it is known to be
1819   // precise. That doesn't take part in the LibCall so we can't directly use
1820   // LowerF128Call.
1821   SDValue SrcVal = Op.getOperand(0);
1822   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1823                      /*isSigned*/ false, SDLoc(Op)).first;
1824 }
1825
1826 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1827   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1828   // Any additional optimization in this function should be recorded
1829   // in the cost tables.
1830   EVT InVT = Op.getOperand(0).getValueType();
1831   EVT VT = Op.getValueType();
1832
1833   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1834     SDLoc dl(Op);
1835     SDValue Cv =
1836         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1837                     Op.getOperand(0));
1838     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1839   }
1840
1841   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1842     SDLoc dl(Op);
1843     MVT ExtVT =
1844         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1845                          VT.getVectorNumElements());
1846     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1847     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1848   }
1849
1850   // Type changing conversions are illegal.
1851   return Op;
1852 }
1853
1854 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1855                                               SelectionDAG &DAG) const {
1856   if (Op.getOperand(0).getValueType().isVector())
1857     return LowerVectorFP_TO_INT(Op, DAG);
1858
1859   // f16 conversions are promoted to f32.
1860   if (Op.getOperand(0).getValueType() == MVT::f16) {
1861     SDLoc dl(Op);
1862     return DAG.getNode(
1863         Op.getOpcode(), dl, Op.getValueType(),
1864         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1865   }
1866
1867   if (Op.getOperand(0).getValueType() != MVT::f128) {
1868     // It's legal except when f128 is involved
1869     return Op;
1870   }
1871
1872   RTLIB::Libcall LC;
1873   if (Op.getOpcode() == ISD::FP_TO_SINT)
1874     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1875   else
1876     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1877
1878   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1879   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1880                      SDLoc(Op)).first;
1881 }
1882
1883 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1884   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1885   // Any additional optimization in this function should be recorded
1886   // in the cost tables.
1887   EVT VT = Op.getValueType();
1888   SDLoc dl(Op);
1889   SDValue In = Op.getOperand(0);
1890   EVT InVT = In.getValueType();
1891
1892   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1893     MVT CastVT =
1894         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1895                          InVT.getVectorNumElements());
1896     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1897     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1898   }
1899
1900   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1901     unsigned CastOpc =
1902         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1903     EVT CastVT = VT.changeVectorElementTypeToInteger();
1904     In = DAG.getNode(CastOpc, dl, CastVT, In);
1905     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1906   }
1907
1908   return Op;
1909 }
1910
1911 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1912                                             SelectionDAG &DAG) const {
1913   if (Op.getValueType().isVector())
1914     return LowerVectorINT_TO_FP(Op, DAG);
1915
1916   // f16 conversions are promoted to f32.
1917   if (Op.getValueType() == MVT::f16) {
1918     SDLoc dl(Op);
1919     return DAG.getNode(
1920         ISD::FP_ROUND, dl, MVT::f16,
1921         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1922         DAG.getIntPtrConstant(0, dl));
1923   }
1924
1925   // i128 conversions are libcalls.
1926   if (Op.getOperand(0).getValueType() == MVT::i128)
1927     return SDValue();
1928
1929   // Other conversions are legal, unless it's to the completely software-based
1930   // fp128.
1931   if (Op.getValueType() != MVT::f128)
1932     return Op;
1933
1934   RTLIB::Libcall LC;
1935   if (Op.getOpcode() == ISD::SINT_TO_FP)
1936     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1937   else
1938     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1939
1940   return LowerF128Call(Op, DAG, LC);
1941 }
1942
1943 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1944                                             SelectionDAG &DAG) const {
1945   // For iOS, we want to call an alternative entry point: __sincos_stret,
1946   // which returns the values in two S / D registers.
1947   SDLoc dl(Op);
1948   SDValue Arg = Op.getOperand(0);
1949   EVT ArgVT = Arg.getValueType();
1950   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1951
1952   ArgListTy Args;
1953   ArgListEntry Entry;
1954
1955   Entry.Node = Arg;
1956   Entry.Ty = ArgTy;
1957   Entry.isSExt = false;
1958   Entry.isZExt = false;
1959   Args.push_back(Entry);
1960
1961   const char *LibcallName =
1962       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1963   SDValue Callee =
1964       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1965
1966   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1967   TargetLowering::CallLoweringInfo CLI(DAG);
1968   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1969     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1970
1971   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1972   return CallResult.first;
1973 }
1974
1975 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1976   if (Op.getValueType() != MVT::f16)
1977     return SDValue();
1978
1979   assert(Op.getOperand(0).getValueType() == MVT::i16);
1980   SDLoc DL(Op);
1981
1982   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1983   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1984   return SDValue(
1985       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1986                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1987       0);
1988 }
1989
1990 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1991   if (OrigVT.getSizeInBits() >= 64)
1992     return OrigVT;
1993
1994   assert(OrigVT.isSimple() && "Expecting a simple value type");
1995
1996   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1997   switch (OrigSimpleTy) {
1998   default: llvm_unreachable("Unexpected Vector Type");
1999   case MVT::v2i8:
2000   case MVT::v2i16:
2001      return MVT::v2i32;
2002   case MVT::v4i8:
2003     return  MVT::v4i16;
2004   }
2005 }
2006
2007 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2008                                                  const EVT &OrigTy,
2009                                                  const EVT &ExtTy,
2010                                                  unsigned ExtOpcode) {
2011   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2012   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2013   // 64-bits we need to insert a new extension so that it will be 64-bits.
2014   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2015   if (OrigTy.getSizeInBits() >= 64)
2016     return N;
2017
2018   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2019   EVT NewVT = getExtensionTo64Bits(OrigTy);
2020
2021   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2022 }
2023
2024 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2025                                    bool isSigned) {
2026   EVT VT = N->getValueType(0);
2027
2028   if (N->getOpcode() != ISD::BUILD_VECTOR)
2029     return false;
2030
2031   for (const SDValue &Elt : N->op_values()) {
2032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2033       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2034       unsigned HalfSize = EltSize / 2;
2035       if (isSigned) {
2036         if (!isIntN(HalfSize, C->getSExtValue()))
2037           return false;
2038       } else {
2039         if (!isUIntN(HalfSize, C->getZExtValue()))
2040           return false;
2041       }
2042       continue;
2043     }
2044     return false;
2045   }
2046
2047   return true;
2048 }
2049
2050 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2051   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2052     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2053                                              N->getOperand(0)->getValueType(0),
2054                                              N->getValueType(0),
2055                                              N->getOpcode());
2056
2057   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2058   EVT VT = N->getValueType(0);
2059   SDLoc dl(N);
2060   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2061   unsigned NumElts = VT.getVectorNumElements();
2062   MVT TruncVT = MVT::getIntegerVT(EltSize);
2063   SmallVector<SDValue, 8> Ops;
2064   for (unsigned i = 0; i != NumElts; ++i) {
2065     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2066     const APInt &CInt = C->getAPIntValue();
2067     // Element types smaller than 32 bits are not legal, so use i32 elements.
2068     // The values are implicitly truncated so sext vs. zext doesn't matter.
2069     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2070   }
2071   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2072                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2073 }
2074
2075 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2076   if (N->getOpcode() == ISD::SIGN_EXTEND)
2077     return true;
2078   if (isExtendedBUILD_VECTOR(N, DAG, true))
2079     return true;
2080   return false;
2081 }
2082
2083 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2084   if (N->getOpcode() == ISD::ZERO_EXTEND)
2085     return true;
2086   if (isExtendedBUILD_VECTOR(N, DAG, false))
2087     return true;
2088   return false;
2089 }
2090
2091 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2092   unsigned Opcode = N->getOpcode();
2093   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2094     SDNode *N0 = N->getOperand(0).getNode();
2095     SDNode *N1 = N->getOperand(1).getNode();
2096     return N0->hasOneUse() && N1->hasOneUse() &&
2097       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2098   }
2099   return false;
2100 }
2101
2102 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2103   unsigned Opcode = N->getOpcode();
2104   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2105     SDNode *N0 = N->getOperand(0).getNode();
2106     SDNode *N1 = N->getOperand(1).getNode();
2107     return N0->hasOneUse() && N1->hasOneUse() &&
2108       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2109   }
2110   return false;
2111 }
2112
2113 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2114   // Multiplications are only custom-lowered for 128-bit vectors so that
2115   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2116   EVT VT = Op.getValueType();
2117   assert(VT.is128BitVector() && VT.isInteger() &&
2118          "unexpected type for custom-lowering ISD::MUL");
2119   SDNode *N0 = Op.getOperand(0).getNode();
2120   SDNode *N1 = Op.getOperand(1).getNode();
2121   unsigned NewOpc = 0;
2122   bool isMLA = false;
2123   bool isN0SExt = isSignExtended(N0, DAG);
2124   bool isN1SExt = isSignExtended(N1, DAG);
2125   if (isN0SExt && isN1SExt)
2126     NewOpc = AArch64ISD::SMULL;
2127   else {
2128     bool isN0ZExt = isZeroExtended(N0, DAG);
2129     bool isN1ZExt = isZeroExtended(N1, DAG);
2130     if (isN0ZExt && isN1ZExt)
2131       NewOpc = AArch64ISD::UMULL;
2132     else if (isN1SExt || isN1ZExt) {
2133       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2134       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2135       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2136         NewOpc = AArch64ISD::SMULL;
2137         isMLA = true;
2138       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2139         NewOpc =  AArch64ISD::UMULL;
2140         isMLA = true;
2141       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2142         std::swap(N0, N1);
2143         NewOpc =  AArch64ISD::UMULL;
2144         isMLA = true;
2145       }
2146     }
2147
2148     if (!NewOpc) {
2149       if (VT == MVT::v2i64)
2150         // Fall through to expand this.  It is not legal.
2151         return SDValue();
2152       else
2153         // Other vector multiplications are legal.
2154         return Op;
2155     }
2156   }
2157
2158   // Legalize to a S/UMULL instruction
2159   SDLoc DL(Op);
2160   SDValue Op0;
2161   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2162   if (!isMLA) {
2163     Op0 = skipExtensionForVectorMULL(N0, DAG);
2164     assert(Op0.getValueType().is64BitVector() &&
2165            Op1.getValueType().is64BitVector() &&
2166            "unexpected types for extended operands to VMULL");
2167     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2168   }
2169   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2170   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2171   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2172   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2173   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2174   EVT Op1VT = Op1.getValueType();
2175   return DAG.getNode(N0->getOpcode(), DL, VT,
2176                      DAG.getNode(NewOpc, DL, VT,
2177                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2178                      DAG.getNode(NewOpc, DL, VT,
2179                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2180 }
2181
2182 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2183                                                      SelectionDAG &DAG) const {
2184   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2185   SDLoc dl(Op);
2186   switch (IntNo) {
2187   default: return SDValue();    // Don't custom lower most intrinsics.
2188   case Intrinsic::aarch64_thread_pointer: {
2189     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2190     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2191   }
2192   case Intrinsic::aarch64_neon_smax:
2193     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2194                        Op.getOperand(1), Op.getOperand(2));
2195   case Intrinsic::aarch64_neon_umax:
2196     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2197                        Op.getOperand(1), Op.getOperand(2));
2198   case Intrinsic::aarch64_neon_smin:
2199     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2200                        Op.getOperand(1), Op.getOperand(2));
2201   case Intrinsic::aarch64_neon_umin:
2202     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2203                        Op.getOperand(1), Op.getOperand(2));
2204   }
2205 }
2206
2207 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2208                                               SelectionDAG &DAG) const {
2209   switch (Op.getOpcode()) {
2210   default:
2211     llvm_unreachable("unimplemented operand");
2212     return SDValue();
2213   case ISD::BITCAST:
2214     return LowerBITCAST(Op, DAG);
2215   case ISD::GlobalAddress:
2216     return LowerGlobalAddress(Op, DAG);
2217   case ISD::GlobalTLSAddress:
2218     return LowerGlobalTLSAddress(Op, DAG);
2219   case ISD::SETCC:
2220     return LowerSETCC(Op, DAG);
2221   case ISD::BR_CC:
2222     return LowerBR_CC(Op, DAG);
2223   case ISD::SELECT:
2224     return LowerSELECT(Op, DAG);
2225   case ISD::SELECT_CC:
2226     return LowerSELECT_CC(Op, DAG);
2227   case ISD::JumpTable:
2228     return LowerJumpTable(Op, DAG);
2229   case ISD::ConstantPool:
2230     return LowerConstantPool(Op, DAG);
2231   case ISD::BlockAddress:
2232     return LowerBlockAddress(Op, DAG);
2233   case ISD::VASTART:
2234     return LowerVASTART(Op, DAG);
2235   case ISD::VACOPY:
2236     return LowerVACOPY(Op, DAG);
2237   case ISD::VAARG:
2238     return LowerVAARG(Op, DAG);
2239   case ISD::ADDC:
2240   case ISD::ADDE:
2241   case ISD::SUBC:
2242   case ISD::SUBE:
2243     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2244   case ISD::SADDO:
2245   case ISD::UADDO:
2246   case ISD::SSUBO:
2247   case ISD::USUBO:
2248   case ISD::SMULO:
2249   case ISD::UMULO:
2250     return LowerXALUO(Op, DAG);
2251   case ISD::FADD:
2252     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2253   case ISD::FSUB:
2254     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2255   case ISD::FMUL:
2256     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2257   case ISD::FDIV:
2258     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2259   case ISD::FP_ROUND:
2260     return LowerFP_ROUND(Op, DAG);
2261   case ISD::FP_EXTEND:
2262     return LowerFP_EXTEND(Op, DAG);
2263   case ISD::FRAMEADDR:
2264     return LowerFRAMEADDR(Op, DAG);
2265   case ISD::RETURNADDR:
2266     return LowerRETURNADDR(Op, DAG);
2267   case ISD::INSERT_VECTOR_ELT:
2268     return LowerINSERT_VECTOR_ELT(Op, DAG);
2269   case ISD::EXTRACT_VECTOR_ELT:
2270     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2271   case ISD::BUILD_VECTOR:
2272     return LowerBUILD_VECTOR(Op, DAG);
2273   case ISD::VECTOR_SHUFFLE:
2274     return LowerVECTOR_SHUFFLE(Op, DAG);
2275   case ISD::EXTRACT_SUBVECTOR:
2276     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2277   case ISD::SRA:
2278   case ISD::SRL:
2279   case ISD::SHL:
2280     return LowerVectorSRA_SRL_SHL(Op, DAG);
2281   case ISD::SHL_PARTS:
2282     return LowerShiftLeftParts(Op, DAG);
2283   case ISD::SRL_PARTS:
2284   case ISD::SRA_PARTS:
2285     return LowerShiftRightParts(Op, DAG);
2286   case ISD::CTPOP:
2287     return LowerCTPOP(Op, DAG);
2288   case ISD::FCOPYSIGN:
2289     return LowerFCOPYSIGN(Op, DAG);
2290   case ISD::AND:
2291     return LowerVectorAND(Op, DAG);
2292   case ISD::OR:
2293     return LowerVectorOR(Op, DAG);
2294   case ISD::XOR:
2295     return LowerXOR(Op, DAG);
2296   case ISD::PREFETCH:
2297     return LowerPREFETCH(Op, DAG);
2298   case ISD::SINT_TO_FP:
2299   case ISD::UINT_TO_FP:
2300     return LowerINT_TO_FP(Op, DAG);
2301   case ISD::FP_TO_SINT:
2302   case ISD::FP_TO_UINT:
2303     return LowerFP_TO_INT(Op, DAG);
2304   case ISD::FSINCOS:
2305     return LowerFSINCOS(Op, DAG);
2306   case ISD::MUL:
2307     return LowerMUL(Op, DAG);
2308   case ISD::INTRINSIC_WO_CHAIN:
2309     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2310   }
2311 }
2312
2313 /// getFunctionAlignment - Return the Log2 alignment of this function.
2314 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2315   return 2;
2316 }
2317
2318 //===----------------------------------------------------------------------===//
2319 //                      Calling Convention Implementation
2320 //===----------------------------------------------------------------------===//
2321
2322 #include "AArch64GenCallingConv.inc"
2323
2324 /// Selects the correct CCAssignFn for a given CallingConvention value.
2325 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2326                                                      bool IsVarArg) const {
2327   switch (CC) {
2328   default:
2329     llvm_unreachable("Unsupported calling convention.");
2330   case CallingConv::WebKit_JS:
2331     return CC_AArch64_WebKit_JS;
2332   case CallingConv::GHC:
2333     return CC_AArch64_GHC;
2334   case CallingConv::C:
2335   case CallingConv::Fast:
2336     if (!Subtarget->isTargetDarwin())
2337       return CC_AArch64_AAPCS;
2338     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2339   }
2340 }
2341
2342 SDValue AArch64TargetLowering::LowerFormalArguments(
2343     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2344     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2345     SmallVectorImpl<SDValue> &InVals) const {
2346   MachineFunction &MF = DAG.getMachineFunction();
2347   MachineFrameInfo *MFI = MF.getFrameInfo();
2348
2349   // Assign locations to all of the incoming arguments.
2350   SmallVector<CCValAssign, 16> ArgLocs;
2351   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2352                  *DAG.getContext());
2353
2354   // At this point, Ins[].VT may already be promoted to i32. To correctly
2355   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2356   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2357   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2358   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2359   // LocVT.
2360   unsigned NumArgs = Ins.size();
2361   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2362   unsigned CurArgIdx = 0;
2363   for (unsigned i = 0; i != NumArgs; ++i) {
2364     MVT ValVT = Ins[i].VT;
2365     if (Ins[i].isOrigArg()) {
2366       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2367       CurArgIdx = Ins[i].getOrigArgIndex();
2368
2369       // Get type of the original argument.
2370       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2371                                   /*AllowUnknown*/ true);
2372       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2373       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2374       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2375         ValVT = MVT::i8;
2376       else if (ActualMVT == MVT::i16)
2377         ValVT = MVT::i16;
2378     }
2379     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2380     bool Res =
2381         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2382     assert(!Res && "Call operand has unhandled type");
2383     (void)Res;
2384   }
2385   assert(ArgLocs.size() == Ins.size());
2386   SmallVector<SDValue, 16> ArgValues;
2387   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2388     CCValAssign &VA = ArgLocs[i];
2389
2390     if (Ins[i].Flags.isByVal()) {
2391       // Byval is used for HFAs in the PCS, but the system should work in a
2392       // non-compliant manner for larger structs.
2393       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2394       int Size = Ins[i].Flags.getByValSize();
2395       unsigned NumRegs = (Size + 7) / 8;
2396
2397       // FIXME: This works on big-endian for composite byvals, which are the common
2398       // case. It should also work for fundamental types too.
2399       unsigned FrameIdx =
2400         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2401       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2402       InVals.push_back(FrameIdxN);
2403
2404       continue;
2405     }
2406     
2407     if (VA.isRegLoc()) {
2408       // Arguments stored in registers.
2409       EVT RegVT = VA.getLocVT();
2410
2411       SDValue ArgValue;
2412       const TargetRegisterClass *RC;
2413
2414       if (RegVT == MVT::i32)
2415         RC = &AArch64::GPR32RegClass;
2416       else if (RegVT == MVT::i64)
2417         RC = &AArch64::GPR64RegClass;
2418       else if (RegVT == MVT::f16)
2419         RC = &AArch64::FPR16RegClass;
2420       else if (RegVT == MVT::f32)
2421         RC = &AArch64::FPR32RegClass;
2422       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2423         RC = &AArch64::FPR64RegClass;
2424       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2425         RC = &AArch64::FPR128RegClass;
2426       else
2427         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2428
2429       // Transform the arguments in physical registers into virtual ones.
2430       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2431       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2432
2433       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2434       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2435       // truncate to the right size.
2436       switch (VA.getLocInfo()) {
2437       default:
2438         llvm_unreachable("Unknown loc info!");
2439       case CCValAssign::Full:
2440         break;
2441       case CCValAssign::BCvt:
2442         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2443         break;
2444       case CCValAssign::AExt:
2445       case CCValAssign::SExt:
2446       case CCValAssign::ZExt:
2447         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2448         // nodes after our lowering.
2449         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2450         break;
2451       }
2452
2453       InVals.push_back(ArgValue);
2454
2455     } else { // VA.isRegLoc()
2456       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2457       unsigned ArgOffset = VA.getLocMemOffset();
2458       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2459
2460       uint32_t BEAlign = 0;
2461       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2462           !Ins[i].Flags.isInConsecutiveRegs())
2463         BEAlign = 8 - ArgSize;
2464
2465       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2466
2467       // Create load nodes to retrieve arguments from the stack.
2468       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2469       SDValue ArgValue;
2470
2471       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2472       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2473       MVT MemVT = VA.getValVT();
2474
2475       switch (VA.getLocInfo()) {
2476       default:
2477         break;
2478       case CCValAssign::BCvt:
2479         MemVT = VA.getLocVT();
2480         break;
2481       case CCValAssign::SExt:
2482         ExtType = ISD::SEXTLOAD;
2483         break;
2484       case CCValAssign::ZExt:
2485         ExtType = ISD::ZEXTLOAD;
2486         break;
2487       case CCValAssign::AExt:
2488         ExtType = ISD::EXTLOAD;
2489         break;
2490       }
2491
2492       ArgValue = DAG.getExtLoad(
2493           ExtType, DL, VA.getLocVT(), Chain, FIN,
2494           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2495           MemVT, false, false, false, 0);
2496
2497       InVals.push_back(ArgValue);
2498     }
2499   }
2500
2501   // varargs
2502   if (isVarArg) {
2503     if (!Subtarget->isTargetDarwin()) {
2504       // The AAPCS variadic function ABI is identical to the non-variadic
2505       // one. As a result there may be more arguments in registers and we should
2506       // save them for future reference.
2507       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2508     }
2509
2510     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2511     // This will point to the next argument passed via stack.
2512     unsigned StackOffset = CCInfo.getNextStackOffset();
2513     // We currently pass all varargs at 8-byte alignment.
2514     StackOffset = ((StackOffset + 7) & ~7);
2515     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2516   }
2517
2518   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2519   unsigned StackArgSize = CCInfo.getNextStackOffset();
2520   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2521   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2522     // This is a non-standard ABI so by fiat I say we're allowed to make full
2523     // use of the stack area to be popped, which must be aligned to 16 bytes in
2524     // any case:
2525     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2526
2527     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2528     // a multiple of 16.
2529     FuncInfo->setArgumentStackToRestore(StackArgSize);
2530
2531     // This realignment carries over to the available bytes below. Our own
2532     // callers will guarantee the space is free by giving an aligned value to
2533     // CALLSEQ_START.
2534   }
2535   // Even if we're not expected to free up the space, it's useful to know how
2536   // much is there while considering tail calls (because we can reuse it).
2537   FuncInfo->setBytesInStackArgArea(StackArgSize);
2538
2539   return Chain;
2540 }
2541
2542 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2543                                                 SelectionDAG &DAG, SDLoc DL,
2544                                                 SDValue &Chain) const {
2545   MachineFunction &MF = DAG.getMachineFunction();
2546   MachineFrameInfo *MFI = MF.getFrameInfo();
2547   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2548   auto PtrVT = getPointerTy(DAG.getDataLayout());
2549
2550   SmallVector<SDValue, 8> MemOps;
2551
2552   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2553                                           AArch64::X3, AArch64::X4, AArch64::X5,
2554                                           AArch64::X6, AArch64::X7 };
2555   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2556   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2557
2558   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2559   int GPRIdx = 0;
2560   if (GPRSaveSize != 0) {
2561     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2562
2563     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2564
2565     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2566       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2567       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2568       SDValue Store = DAG.getStore(
2569           Val.getValue(1), DL, Val, FIN,
2570           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2571           false, 0);
2572       MemOps.push_back(Store);
2573       FIN =
2574           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2575     }
2576   }
2577   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2578   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2579
2580   if (Subtarget->hasFPARMv8()) {
2581     static const MCPhysReg FPRArgRegs[] = {
2582         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2583         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2584     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2585     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2586
2587     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2588     int FPRIdx = 0;
2589     if (FPRSaveSize != 0) {
2590       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2591
2592       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2593
2594       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2595         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2596         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2597
2598         SDValue Store = DAG.getStore(
2599             Val.getValue(1), DL, Val, FIN,
2600             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2601             false, false, 0);
2602         MemOps.push_back(Store);
2603         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2604                           DAG.getConstant(16, DL, PtrVT));
2605       }
2606     }
2607     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2608     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2609   }
2610
2611   if (!MemOps.empty()) {
2612     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2613   }
2614 }
2615
2616 /// LowerCallResult - Lower the result values of a call into the
2617 /// appropriate copies out of appropriate physical registers.
2618 SDValue AArch64TargetLowering::LowerCallResult(
2619     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2620     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2621     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2622     SDValue ThisVal) const {
2623   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2624                           ? RetCC_AArch64_WebKit_JS
2625                           : RetCC_AArch64_AAPCS;
2626   // Assign locations to each value returned by this call.
2627   SmallVector<CCValAssign, 16> RVLocs;
2628   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2629                  *DAG.getContext());
2630   CCInfo.AnalyzeCallResult(Ins, RetCC);
2631
2632   // Copy all of the result registers out of their specified physreg.
2633   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2634     CCValAssign VA = RVLocs[i];
2635
2636     // Pass 'this' value directly from the argument to return value, to avoid
2637     // reg unit interference
2638     if (i == 0 && isThisReturn) {
2639       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2640              "unexpected return calling convention register assignment");
2641       InVals.push_back(ThisVal);
2642       continue;
2643     }
2644
2645     SDValue Val =
2646         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2647     Chain = Val.getValue(1);
2648     InFlag = Val.getValue(2);
2649
2650     switch (VA.getLocInfo()) {
2651     default:
2652       llvm_unreachable("Unknown loc info!");
2653     case CCValAssign::Full:
2654       break;
2655     case CCValAssign::BCvt:
2656       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2657       break;
2658     }
2659
2660     InVals.push_back(Val);
2661   }
2662
2663   return Chain;
2664 }
2665
2666 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2667     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2668     bool isCalleeStructRet, bool isCallerStructRet,
2669     const SmallVectorImpl<ISD::OutputArg> &Outs,
2670     const SmallVectorImpl<SDValue> &OutVals,
2671     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2672   // For CallingConv::C this function knows whether the ABI needs
2673   // changing. That's not true for other conventions so they will have to opt in
2674   // manually.
2675   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2676     return false;
2677
2678   const MachineFunction &MF = DAG.getMachineFunction();
2679   const Function *CallerF = MF.getFunction();
2680   CallingConv::ID CallerCC = CallerF->getCallingConv();
2681   bool CCMatch = CallerCC == CalleeCC;
2682
2683   // Byval parameters hand the function a pointer directly into the stack area
2684   // we want to reuse during a tail call. Working around this *is* possible (see
2685   // X86) but less efficient and uglier in LowerCall.
2686   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2687                                     e = CallerF->arg_end();
2688        i != e; ++i)
2689     if (i->hasByValAttr())
2690       return false;
2691
2692   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2693     if (IsTailCallConvention(CalleeCC) && CCMatch)
2694       return true;
2695     return false;
2696   }
2697
2698   // Externally-defined functions with weak linkage should not be
2699   // tail-called on AArch64 when the OS does not support dynamic
2700   // pre-emption of symbols, as the AAELF spec requires normal calls
2701   // to undefined weak functions to be replaced with a NOP or jump to the
2702   // next instruction. The behaviour of branch instructions in this
2703   // situation (as used for tail calls) is implementation-defined, so we
2704   // cannot rely on the linker replacing the tail call with a return.
2705   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2706     const GlobalValue *GV = G->getGlobal();
2707     const Triple &TT = getTargetMachine().getTargetTriple();
2708     if (GV->hasExternalWeakLinkage() &&
2709         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2710       return false;
2711   }
2712
2713   // Now we search for cases where we can use a tail call without changing the
2714   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2715   // concept.
2716
2717   // I want anyone implementing a new calling convention to think long and hard
2718   // about this assert.
2719   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2720          "Unexpected variadic calling convention");
2721
2722   if (isVarArg && !Outs.empty()) {
2723     // At least two cases here: if caller is fastcc then we can't have any
2724     // memory arguments (we'd be expected to clean up the stack afterwards). If
2725     // caller is C then we could potentially use its argument area.
2726
2727     // FIXME: for now we take the most conservative of these in both cases:
2728     // disallow all variadic memory operands.
2729     SmallVector<CCValAssign, 16> ArgLocs;
2730     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2731                    *DAG.getContext());
2732
2733     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2734     for (const CCValAssign &ArgLoc : ArgLocs)
2735       if (!ArgLoc.isRegLoc())
2736         return false;
2737   }
2738
2739   // If the calling conventions do not match, then we'd better make sure the
2740   // results are returned in the same way as what the caller expects.
2741   if (!CCMatch) {
2742     SmallVector<CCValAssign, 16> RVLocs1;
2743     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2744                     *DAG.getContext());
2745     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2746
2747     SmallVector<CCValAssign, 16> RVLocs2;
2748     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2749                     *DAG.getContext());
2750     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2751
2752     if (RVLocs1.size() != RVLocs2.size())
2753       return false;
2754     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2755       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2756         return false;
2757       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2758         return false;
2759       if (RVLocs1[i].isRegLoc()) {
2760         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2761           return false;
2762       } else {
2763         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2764           return false;
2765       }
2766     }
2767   }
2768
2769   // Nothing more to check if the callee is taking no arguments
2770   if (Outs.empty())
2771     return true;
2772
2773   SmallVector<CCValAssign, 16> ArgLocs;
2774   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2775                  *DAG.getContext());
2776
2777   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2778
2779   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2780
2781   // If the stack arguments for this call would fit into our own save area then
2782   // the call can be made tail.
2783   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2784 }
2785
2786 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2787                                                    SelectionDAG &DAG,
2788                                                    MachineFrameInfo *MFI,
2789                                                    int ClobberedFI) const {
2790   SmallVector<SDValue, 8> ArgChains;
2791   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2792   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2793
2794   // Include the original chain at the beginning of the list. When this is
2795   // used by target LowerCall hooks, this helps legalize find the
2796   // CALLSEQ_BEGIN node.
2797   ArgChains.push_back(Chain);
2798
2799   // Add a chain value for each stack argument corresponding
2800   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2801                             UE = DAG.getEntryNode().getNode()->use_end();
2802        U != UE; ++U)
2803     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2804       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2805         if (FI->getIndex() < 0) {
2806           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2807           int64_t InLastByte = InFirstByte;
2808           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2809
2810           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2811               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2812             ArgChains.push_back(SDValue(L, 1));
2813         }
2814
2815   // Build a tokenfactor for all the chains.
2816   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2817 }
2818
2819 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2820                                                    bool TailCallOpt) const {
2821   return CallCC == CallingConv::Fast && TailCallOpt;
2822 }
2823
2824 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2825   return CallCC == CallingConv::Fast;
2826 }
2827
2828 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2829 /// and add input and output parameter nodes.
2830 SDValue
2831 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2832                                  SmallVectorImpl<SDValue> &InVals) const {
2833   SelectionDAG &DAG = CLI.DAG;
2834   SDLoc &DL = CLI.DL;
2835   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2836   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2837   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2838   SDValue Chain = CLI.Chain;
2839   SDValue Callee = CLI.Callee;
2840   bool &IsTailCall = CLI.IsTailCall;
2841   CallingConv::ID CallConv = CLI.CallConv;
2842   bool IsVarArg = CLI.IsVarArg;
2843
2844   MachineFunction &MF = DAG.getMachineFunction();
2845   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2846   bool IsThisReturn = false;
2847
2848   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2849   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2850   bool IsSibCall = false;
2851
2852   if (IsTailCall) {
2853     // Check if it's really possible to do a tail call.
2854     IsTailCall = isEligibleForTailCallOptimization(
2855         Callee, CallConv, IsVarArg, IsStructRet,
2856         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2857     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2858       report_fatal_error("failed to perform tail call elimination on a call "
2859                          "site marked musttail");
2860
2861     // A sibling call is one where we're under the usual C ABI and not planning
2862     // to change that but can still do a tail call:
2863     if (!TailCallOpt && IsTailCall)
2864       IsSibCall = true;
2865
2866     if (IsTailCall)
2867       ++NumTailCalls;
2868   }
2869
2870   // Analyze operands of the call, assigning locations to each operand.
2871   SmallVector<CCValAssign, 16> ArgLocs;
2872   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2873                  *DAG.getContext());
2874
2875   if (IsVarArg) {
2876     // Handle fixed and variable vector arguments differently.
2877     // Variable vector arguments always go into memory.
2878     unsigned NumArgs = Outs.size();
2879
2880     for (unsigned i = 0; i != NumArgs; ++i) {
2881       MVT ArgVT = Outs[i].VT;
2882       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2883       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2884                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2885       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2886       assert(!Res && "Call operand has unhandled type");
2887       (void)Res;
2888     }
2889   } else {
2890     // At this point, Outs[].VT may already be promoted to i32. To correctly
2891     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2892     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2893     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2894     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2895     // LocVT.
2896     unsigned NumArgs = Outs.size();
2897     for (unsigned i = 0; i != NumArgs; ++i) {
2898       MVT ValVT = Outs[i].VT;
2899       // Get type of the original argument.
2900       EVT ActualVT = getValueType(DAG.getDataLayout(),
2901                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2902                                   /*AllowUnknown*/ true);
2903       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2904       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2905       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2906       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2907         ValVT = MVT::i8;
2908       else if (ActualMVT == MVT::i16)
2909         ValVT = MVT::i16;
2910
2911       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2912       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2913       assert(!Res && "Call operand has unhandled type");
2914       (void)Res;
2915     }
2916   }
2917
2918   // Get a count of how many bytes are to be pushed on the stack.
2919   unsigned NumBytes = CCInfo.getNextStackOffset();
2920
2921   if (IsSibCall) {
2922     // Since we're not changing the ABI to make this a tail call, the memory
2923     // operands are already available in the caller's incoming argument space.
2924     NumBytes = 0;
2925   }
2926
2927   // FPDiff is the byte offset of the call's argument area from the callee's.
2928   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2929   // by this amount for a tail call. In a sibling call it must be 0 because the
2930   // caller will deallocate the entire stack and the callee still expects its
2931   // arguments to begin at SP+0. Completely unused for non-tail calls.
2932   int FPDiff = 0;
2933
2934   if (IsTailCall && !IsSibCall) {
2935     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2936
2937     // Since callee will pop argument stack as a tail call, we must keep the
2938     // popped size 16-byte aligned.
2939     NumBytes = RoundUpToAlignment(NumBytes, 16);
2940
2941     // FPDiff will be negative if this tail call requires more space than we
2942     // would automatically have in our incoming argument space. Positive if we
2943     // can actually shrink the stack.
2944     FPDiff = NumReusableBytes - NumBytes;
2945
2946     // The stack pointer must be 16-byte aligned at all times it's used for a
2947     // memory operation, which in practice means at *all* times and in
2948     // particular across call boundaries. Therefore our own arguments started at
2949     // a 16-byte aligned SP and the delta applied for the tail call should
2950     // satisfy the same constraint.
2951     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2952   }
2953
2954   // Adjust the stack pointer for the new arguments...
2955   // These operations are automatically eliminated by the prolog/epilog pass
2956   if (!IsSibCall)
2957     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2958                                                               true),
2959                                  DL);
2960
2961   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2962                                         getPointerTy(DAG.getDataLayout()));
2963
2964   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2965   SmallVector<SDValue, 8> MemOpChains;
2966   auto PtrVT = getPointerTy(DAG.getDataLayout());
2967
2968   // Walk the register/memloc assignments, inserting copies/loads.
2969   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2970        ++i, ++realArgIdx) {
2971     CCValAssign &VA = ArgLocs[i];
2972     SDValue Arg = OutVals[realArgIdx];
2973     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2974
2975     // Promote the value if needed.
2976     switch (VA.getLocInfo()) {
2977     default:
2978       llvm_unreachable("Unknown loc info!");
2979     case CCValAssign::Full:
2980       break;
2981     case CCValAssign::SExt:
2982       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2983       break;
2984     case CCValAssign::ZExt:
2985       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2986       break;
2987     case CCValAssign::AExt:
2988       if (Outs[realArgIdx].ArgVT == MVT::i1) {
2989         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2990         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2991         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2992       }
2993       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2994       break;
2995     case CCValAssign::BCvt:
2996       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2997       break;
2998     case CCValAssign::FPExt:
2999       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3000       break;
3001     }
3002
3003     if (VA.isRegLoc()) {
3004       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3005         assert(VA.getLocVT() == MVT::i64 &&
3006                "unexpected calling convention register assignment");
3007         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3008                "unexpected use of 'returned'");
3009         IsThisReturn = true;
3010       }
3011       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3012     } else {
3013       assert(VA.isMemLoc());
3014
3015       SDValue DstAddr;
3016       MachinePointerInfo DstInfo;
3017
3018       // FIXME: This works on big-endian for composite byvals, which are the
3019       // common case. It should also work for fundamental types too.
3020       uint32_t BEAlign = 0;
3021       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3022                                         : VA.getValVT().getSizeInBits();
3023       OpSize = (OpSize + 7) / 8;
3024       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3025           !Flags.isInConsecutiveRegs()) {
3026         if (OpSize < 8)
3027           BEAlign = 8 - OpSize;
3028       }
3029       unsigned LocMemOffset = VA.getLocMemOffset();
3030       int32_t Offset = LocMemOffset + BEAlign;
3031       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3032       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3033
3034       if (IsTailCall) {
3035         Offset = Offset + FPDiff;
3036         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3037
3038         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3039         DstInfo =
3040             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3041
3042         // Make sure any stack arguments overlapping with where we're storing
3043         // are loaded before this eventual operation. Otherwise they'll be
3044         // clobbered.
3045         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3046       } else {
3047         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3048
3049         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3050         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3051                                                LocMemOffset);
3052       }
3053
3054       if (Outs[i].Flags.isByVal()) {
3055         SDValue SizeNode =
3056             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3057         SDValue Cpy = DAG.getMemcpy(
3058             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3059             /*isVol = */ false, /*AlwaysInline = */ false,
3060             /*isTailCall = */ false,
3061             DstInfo, MachinePointerInfo());
3062
3063         MemOpChains.push_back(Cpy);
3064       } else {
3065         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3066         // promoted to a legal register type i32, we should truncate Arg back to
3067         // i1/i8/i16.
3068         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3069             VA.getValVT() == MVT::i16)
3070           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3071
3072         SDValue Store =
3073             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3074         MemOpChains.push_back(Store);
3075       }
3076     }
3077   }
3078
3079   if (!MemOpChains.empty())
3080     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3081
3082   // Build a sequence of copy-to-reg nodes chained together with token chain
3083   // and flag operands which copy the outgoing args into the appropriate regs.
3084   SDValue InFlag;
3085   for (auto &RegToPass : RegsToPass) {
3086     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3087                              RegToPass.second, InFlag);
3088     InFlag = Chain.getValue(1);
3089   }
3090
3091   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3092   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3093   // node so that legalize doesn't hack it.
3094   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3095       Subtarget->isTargetMachO()) {
3096     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3097       const GlobalValue *GV = G->getGlobal();
3098       bool InternalLinkage = GV->hasInternalLinkage();
3099       if (InternalLinkage)
3100         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3101       else {
3102         Callee =
3103             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3104         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3105       }
3106     } else if (ExternalSymbolSDNode *S =
3107                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3108       const char *Sym = S->getSymbol();
3109       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3110       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3111     }
3112   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3113     const GlobalValue *GV = G->getGlobal();
3114     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3115   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3116     const char *Sym = S->getSymbol();
3117     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3118   }
3119
3120   // We don't usually want to end the call-sequence here because we would tidy
3121   // the frame up *after* the call, however in the ABI-changing tail-call case
3122   // we've carefully laid out the parameters so that when sp is reset they'll be
3123   // in the correct location.
3124   if (IsTailCall && !IsSibCall) {
3125     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3126                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3127     InFlag = Chain.getValue(1);
3128   }
3129
3130   std::vector<SDValue> Ops;
3131   Ops.push_back(Chain);
3132   Ops.push_back(Callee);
3133
3134   if (IsTailCall) {
3135     // Each tail call may have to adjust the stack by a different amount, so
3136     // this information must travel along with the operation for eventual
3137     // consumption by emitEpilogue.
3138     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3139   }
3140
3141   // Add argument registers to the end of the list so that they are known live
3142   // into the call.
3143   for (auto &RegToPass : RegsToPass)
3144     Ops.push_back(DAG.getRegister(RegToPass.first,
3145                                   RegToPass.second.getValueType()));
3146
3147   // Add a register mask operand representing the call-preserved registers.
3148   const uint32_t *Mask;
3149   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3150   if (IsThisReturn) {
3151     // For 'this' returns, use the X0-preserving mask if applicable
3152     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3153     if (!Mask) {
3154       IsThisReturn = false;
3155       Mask = TRI->getCallPreservedMask(MF, CallConv);
3156     }
3157   } else
3158     Mask = TRI->getCallPreservedMask(MF, CallConv);
3159
3160   assert(Mask && "Missing call preserved mask for calling convention");
3161   Ops.push_back(DAG.getRegisterMask(Mask));
3162
3163   if (InFlag.getNode())
3164     Ops.push_back(InFlag);
3165
3166   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3167
3168   // If we're doing a tall call, use a TC_RETURN here rather than an
3169   // actual call instruction.
3170   if (IsTailCall) {
3171     MF.getFrameInfo()->setHasTailCall();
3172     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3173   }
3174
3175   // Returns a chain and a flag for retval copy to use.
3176   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3177   InFlag = Chain.getValue(1);
3178
3179   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3180                                 ? RoundUpToAlignment(NumBytes, 16)
3181                                 : 0;
3182
3183   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3184                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3185                              InFlag, DL);
3186   if (!Ins.empty())
3187     InFlag = Chain.getValue(1);
3188
3189   // Handle result values, copying them out of physregs into vregs that we
3190   // return.
3191   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3192                          InVals, IsThisReturn,
3193                          IsThisReturn ? OutVals[0] : SDValue());
3194 }
3195
3196 bool AArch64TargetLowering::CanLowerReturn(
3197     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3198     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3199   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3200                           ? RetCC_AArch64_WebKit_JS
3201                           : RetCC_AArch64_AAPCS;
3202   SmallVector<CCValAssign, 16> RVLocs;
3203   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3204   return CCInfo.CheckReturn(Outs, RetCC);
3205 }
3206
3207 SDValue
3208 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3209                                    bool isVarArg,
3210                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3211                                    const SmallVectorImpl<SDValue> &OutVals,
3212                                    SDLoc DL, SelectionDAG &DAG) const {
3213   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3214                           ? RetCC_AArch64_WebKit_JS
3215                           : RetCC_AArch64_AAPCS;
3216   SmallVector<CCValAssign, 16> RVLocs;
3217   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3218                  *DAG.getContext());
3219   CCInfo.AnalyzeReturn(Outs, RetCC);
3220
3221   // Copy the result values into the output registers.
3222   SDValue Flag;
3223   SmallVector<SDValue, 4> RetOps(1, Chain);
3224   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3225        ++i, ++realRVLocIdx) {
3226     CCValAssign &VA = RVLocs[i];
3227     assert(VA.isRegLoc() && "Can only return in registers!");
3228     SDValue Arg = OutVals[realRVLocIdx];
3229
3230     switch (VA.getLocInfo()) {
3231     default:
3232       llvm_unreachable("Unknown loc info!");
3233     case CCValAssign::Full:
3234       if (Outs[i].ArgVT == MVT::i1) {
3235         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3236         // value. This is strictly redundant on Darwin (which uses "zeroext
3237         // i1"), but will be optimised out before ISel.
3238         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3239         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3240       }
3241       break;
3242     case CCValAssign::BCvt:
3243       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3244       break;
3245     }
3246
3247     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3248     Flag = Chain.getValue(1);
3249     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3250   }
3251
3252   RetOps[0] = Chain; // Update chain.
3253
3254   // Add the flag if we have it.
3255   if (Flag.getNode())
3256     RetOps.push_back(Flag);
3257
3258   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3259 }
3260
3261 //===----------------------------------------------------------------------===//
3262 //  Other Lowering Code
3263 //===----------------------------------------------------------------------===//
3264
3265 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3266                                                   SelectionDAG &DAG) const {
3267   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3268   SDLoc DL(Op);
3269   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3270   const GlobalValue *GV = GN->getGlobal();
3271   unsigned char OpFlags =
3272       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3273
3274   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3275          "unexpected offset in global node");
3276
3277   // This also catched the large code model case for Darwin.
3278   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3279     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3280     // FIXME: Once remat is capable of dealing with instructions with register
3281     // operands, expand this into two nodes instead of using a wrapper node.
3282     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3283   }
3284
3285   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3286     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3287            "use of MO_CONSTPOOL only supported on small model");
3288     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3289     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3290     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3291     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3292     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3293     SDValue GlobalAddr = DAG.getLoad(
3294         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3295         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3296         /*isVolatile=*/false,
3297         /*isNonTemporal=*/true,
3298         /*isInvariant=*/true, 8);
3299     if (GN->getOffset() != 0)
3300       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3301                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3302     return GlobalAddr;
3303   }
3304
3305   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3306     const unsigned char MO_NC = AArch64II::MO_NC;
3307     return DAG.getNode(
3308         AArch64ISD::WrapperLarge, DL, PtrVT,
3309         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3310         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3311         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3312         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3313   } else {
3314     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3315     // the only correct model on Darwin.
3316     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3317                                             OpFlags | AArch64II::MO_PAGE);
3318     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3319     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3320
3321     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3322     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3323   }
3324 }
3325
3326 /// \brief Convert a TLS address reference into the correct sequence of loads
3327 /// and calls to compute the variable's address (for Darwin, currently) and
3328 /// return an SDValue containing the final node.
3329
3330 /// Darwin only has one TLS scheme which must be capable of dealing with the
3331 /// fully general situation, in the worst case. This means:
3332 ///     + "extern __thread" declaration.
3333 ///     + Defined in a possibly unknown dynamic library.
3334 ///
3335 /// The general system is that each __thread variable has a [3 x i64] descriptor
3336 /// which contains information used by the runtime to calculate the address. The
3337 /// only part of this the compiler needs to know about is the first xword, which
3338 /// contains a function pointer that must be called with the address of the
3339 /// entire descriptor in "x0".
3340 ///
3341 /// Since this descriptor may be in a different unit, in general even the
3342 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3343 /// is:
3344 ///     adrp x0, _var@TLVPPAGE
3345 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3346 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3347 ///                                      ; the function pointer
3348 ///     blr x1                           ; Uses descriptor address in x0
3349 ///     ; Address of _var is now in x0.
3350 ///
3351 /// If the address of _var's descriptor *is* known to the linker, then it can
3352 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3353 /// a slight efficiency gain.
3354 SDValue
3355 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3356                                                    SelectionDAG &DAG) const {
3357   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3358
3359   SDLoc DL(Op);
3360   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3361   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3362
3363   SDValue TLVPAddr =
3364       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3365   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3366
3367   // The first entry in the descriptor is a function pointer that we must call
3368   // to obtain the address of the variable.
3369   SDValue Chain = DAG.getEntryNode();
3370   SDValue FuncTLVGet =
3371       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3372                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3373                   true, true, 8);
3374   Chain = FuncTLVGet.getValue(1);
3375
3376   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3377   MFI->setAdjustsStack(true);
3378
3379   // TLS calls preserve all registers except those that absolutely must be
3380   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3381   // silly).
3382   const uint32_t *Mask =
3383       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3384
3385   // Finally, we can make the call. This is just a degenerate version of a
3386   // normal AArch64 call node: x0 takes the address of the descriptor, and
3387   // returns the address of the variable in this thread.
3388   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3389   Chain =
3390       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3391                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3392                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3393   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3394 }
3395
3396 /// When accessing thread-local variables under either the general-dynamic or
3397 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3398 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3399 /// is a function pointer to carry out the resolution.
3400 ///
3401 /// The sequence is:
3402 ///    adrp  x0, :tlsdesc:var
3403 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3404 ///    add   x0, x0, #:tlsdesc_lo12:var
3405 ///    .tlsdesccall var
3406 ///    blr   x1
3407 ///    (TPIDR_EL0 offset now in x0)
3408 ///
3409 ///  The above sequence must be produced unscheduled, to enable the linker to
3410 ///  optimize/relax this sequence.
3411 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3412 ///  above sequence, and expanded really late in the compilation flow, to ensure
3413 ///  the sequence is produced as per above.
3414 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3415                                                       SelectionDAG &DAG) const {
3416   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3417
3418   SDValue Chain = DAG.getEntryNode();
3419   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3420
3421   SmallVector<SDValue, 2> Ops;
3422   Ops.push_back(Chain);
3423   Ops.push_back(SymAddr);
3424
3425   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3426   SDValue Glue = Chain.getValue(1);
3427
3428   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3429 }
3430
3431 SDValue
3432 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3433                                                 SelectionDAG &DAG) const {
3434   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3435   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3436          "ELF TLS only supported in small memory model");
3437   // Different choices can be made for the maximum size of the TLS area for a
3438   // module. For the small address model, the default TLS size is 16MiB and the
3439   // maximum TLS size is 4GiB.
3440   // FIXME: add -mtls-size command line option and make it control the 16MiB
3441   // vs. 4GiB code sequence generation.
3442   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3443
3444   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3445
3446   if (DAG.getTarget().Options.EmulatedTLS)
3447     return LowerToTLSEmulatedModel(GA, DAG);
3448
3449   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3450     if (Model == TLSModel::LocalDynamic)
3451       Model = TLSModel::GeneralDynamic;
3452   }
3453
3454   SDValue TPOff;
3455   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3456   SDLoc DL(Op);
3457   const GlobalValue *GV = GA->getGlobal();
3458
3459   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3460
3461   if (Model == TLSModel::LocalExec) {
3462     SDValue HiVar = DAG.getTargetGlobalAddress(
3463         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3464     SDValue LoVar = DAG.getTargetGlobalAddress(
3465         GV, DL, PtrVT, 0,
3466         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3467
3468     SDValue TPWithOff_lo =
3469         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3470                                    HiVar,
3471                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3472                 0);
3473     SDValue TPWithOff =
3474         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3475                                    LoVar,
3476                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3477                 0);
3478     return TPWithOff;
3479   } else if (Model == TLSModel::InitialExec) {
3480     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3481     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3482   } else if (Model == TLSModel::LocalDynamic) {
3483     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3484     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3485     // the beginning of the module's TLS region, followed by a DTPREL offset
3486     // calculation.
3487
3488     // These accesses will need deduplicating if there's more than one.
3489     AArch64FunctionInfo *MFI =
3490         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3491     MFI->incNumLocalDynamicTLSAccesses();
3492
3493     // The call needs a relocation too for linker relaxation. It doesn't make
3494     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3495     // the address.
3496     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3497                                                   AArch64II::MO_TLS);
3498
3499     // Now we can calculate the offset from TPIDR_EL0 to this module's
3500     // thread-local area.
3501     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3502
3503     // Now use :dtprel_whatever: operations to calculate this variable's offset
3504     // in its thread-storage area.
3505     SDValue HiVar = DAG.getTargetGlobalAddress(
3506         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3507     SDValue LoVar = DAG.getTargetGlobalAddress(
3508         GV, DL, MVT::i64, 0,
3509         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3510
3511     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3512                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3513                     0);
3514     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3515                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3516                     0);
3517   } else if (Model == TLSModel::GeneralDynamic) {
3518     // The call needs a relocation too for linker relaxation. It doesn't make
3519     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3520     // the address.
3521     SDValue SymAddr =
3522         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3523
3524     // Finally we can make a call to calculate the offset from tpidr_el0.
3525     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3526   } else
3527     llvm_unreachable("Unsupported ELF TLS access model");
3528
3529   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3530 }
3531
3532 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3533                                                      SelectionDAG &DAG) const {
3534   if (Subtarget->isTargetDarwin())
3535     return LowerDarwinGlobalTLSAddress(Op, DAG);
3536   else if (Subtarget->isTargetELF())
3537     return LowerELFGlobalTLSAddress(Op, DAG);
3538
3539   llvm_unreachable("Unexpected platform trying to use TLS");
3540 }
3541 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3542   SDValue Chain = Op.getOperand(0);
3543   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3544   SDValue LHS = Op.getOperand(2);
3545   SDValue RHS = Op.getOperand(3);
3546   SDValue Dest = Op.getOperand(4);
3547   SDLoc dl(Op);
3548
3549   // Handle f128 first, since lowering it will result in comparing the return
3550   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3551   // is expecting to deal with.
3552   if (LHS.getValueType() == MVT::f128) {
3553     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3554
3555     // If softenSetCCOperands returned a scalar, we need to compare the result
3556     // against zero to select between true and false values.
3557     if (!RHS.getNode()) {
3558       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3559       CC = ISD::SETNE;
3560     }
3561   }
3562
3563   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3564   // instruction.
3565   unsigned Opc = LHS.getOpcode();
3566   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3567       cast<ConstantSDNode>(RHS)->isOne() &&
3568       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3569        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3570     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3571            "Unexpected condition code.");
3572     // Only lower legal XALUO ops.
3573     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3574       return SDValue();
3575
3576     // The actual operation with overflow check.
3577     AArch64CC::CondCode OFCC;
3578     SDValue Value, Overflow;
3579     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3580
3581     if (CC == ISD::SETNE)
3582       OFCC = getInvertedCondCode(OFCC);
3583     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3584
3585     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3586                        Overflow);
3587   }
3588
3589   if (LHS.getValueType().isInteger()) {
3590     assert((LHS.getValueType() == RHS.getValueType()) &&
3591            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3592
3593     // If the RHS of the comparison is zero, we can potentially fold this
3594     // to a specialized branch.
3595     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3596     if (RHSC && RHSC->getZExtValue() == 0) {
3597       if (CC == ISD::SETEQ) {
3598         // See if we can use a TBZ to fold in an AND as well.
3599         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3600         // out of bounds, a late MI-layer pass rewrites branches.
3601         // 403.gcc is an example that hits this case.
3602         if (LHS.getOpcode() == ISD::AND &&
3603             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3604             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3605           SDValue Test = LHS.getOperand(0);
3606           uint64_t Mask = LHS.getConstantOperandVal(1);
3607           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3608                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3609                              Dest);
3610         }
3611
3612         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3613       } else if (CC == ISD::SETNE) {
3614         // See if we can use a TBZ to fold in an AND as well.
3615         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3616         // out of bounds, a late MI-layer pass rewrites branches.
3617         // 403.gcc is an example that hits this case.
3618         if (LHS.getOpcode() == ISD::AND &&
3619             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3620             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3621           SDValue Test = LHS.getOperand(0);
3622           uint64_t Mask = LHS.getConstantOperandVal(1);
3623           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3624                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3625                              Dest);
3626         }
3627
3628         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3629       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3630         // Don't combine AND since emitComparison converts the AND to an ANDS
3631         // (a.k.a. TST) and the test in the test bit and branch instruction
3632         // becomes redundant.  This would also increase register pressure.
3633         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3634         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3635                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3636       }
3637     }
3638     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3639         LHS.getOpcode() != ISD::AND) {
3640       // Don't combine AND since emitComparison converts the AND to an ANDS
3641       // (a.k.a. TST) and the test in the test bit and branch instruction
3642       // becomes redundant.  This would also increase register pressure.
3643       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3644       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3645                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3646     }
3647
3648     SDValue CCVal;
3649     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3650     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3651                        Cmp);
3652   }
3653
3654   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3655
3656   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3657   // clean.  Some of them require two branches to implement.
3658   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3659   AArch64CC::CondCode CC1, CC2;
3660   changeFPCCToAArch64CC(CC, CC1, CC2);
3661   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3662   SDValue BR1 =
3663       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3664   if (CC2 != AArch64CC::AL) {
3665     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3666     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3667                        Cmp);
3668   }
3669
3670   return BR1;
3671 }
3672
3673 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3674                                               SelectionDAG &DAG) const {
3675   EVT VT = Op.getValueType();
3676   SDLoc DL(Op);
3677
3678   SDValue In1 = Op.getOperand(0);
3679   SDValue In2 = Op.getOperand(1);
3680   EVT SrcVT = In2.getValueType();
3681
3682   if (SrcVT.bitsLT(VT))
3683     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3684   else if (SrcVT.bitsGT(VT))
3685     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3686
3687   EVT VecVT;
3688   EVT EltVT;
3689   uint64_t EltMask;
3690   SDValue VecVal1, VecVal2;
3691   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3692     EltVT = MVT::i32;
3693     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3694     EltMask = 0x80000000ULL;
3695
3696     if (!VT.isVector()) {
3697       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3698                                           DAG.getUNDEF(VecVT), In1);
3699       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3700                                           DAG.getUNDEF(VecVT), In2);
3701     } else {
3702       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3703       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3704     }
3705   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3706     EltVT = MVT::i64;
3707     VecVT = MVT::v2i64;
3708
3709     // We want to materialize a mask with the high bit set, but the AdvSIMD
3710     // immediate moves cannot materialize that in a single instruction for
3711     // 64-bit elements. Instead, materialize zero and then negate it.
3712     EltMask = 0;
3713
3714     if (!VT.isVector()) {
3715       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3716                                           DAG.getUNDEF(VecVT), In1);
3717       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3718                                           DAG.getUNDEF(VecVT), In2);
3719     } else {
3720       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3721       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3722     }
3723   } else {
3724     llvm_unreachable("Invalid type for copysign!");
3725   }
3726
3727   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3728
3729   // If we couldn't materialize the mask above, then the mask vector will be
3730   // the zero vector, and we need to negate it here.
3731   if (VT == MVT::f64 || VT == MVT::v2f64) {
3732     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3733     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3734     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3735   }
3736
3737   SDValue Sel =
3738       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3739
3740   if (VT == MVT::f32)
3741     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3742   else if (VT == MVT::f64)
3743     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3744   else
3745     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3746 }
3747
3748 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3749   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3750           Attribute::NoImplicitFloat))
3751     return SDValue();
3752
3753   if (!Subtarget->hasNEON())
3754     return SDValue();
3755
3756   // While there is no integer popcount instruction, it can
3757   // be more efficiently lowered to the following sequence that uses
3758   // AdvSIMD registers/instructions as long as the copies to/from
3759   // the AdvSIMD registers are cheap.
3760   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3761   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3762   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3763   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3764   SDValue Val = Op.getOperand(0);
3765   SDLoc DL(Op);
3766   EVT VT = Op.getValueType();
3767
3768   if (VT == MVT::i32)
3769     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3770   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3771
3772   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3773   SDValue UaddLV = DAG.getNode(
3774       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3775       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3776
3777   if (VT == MVT::i64)
3778     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3779   return UaddLV;
3780 }
3781
3782 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3783
3784   if (Op.getValueType().isVector())
3785     return LowerVSETCC(Op, DAG);
3786
3787   SDValue LHS = Op.getOperand(0);
3788   SDValue RHS = Op.getOperand(1);
3789   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3790   SDLoc dl(Op);
3791
3792   // We chose ZeroOrOneBooleanContents, so use zero and one.
3793   EVT VT = Op.getValueType();
3794   SDValue TVal = DAG.getConstant(1, dl, VT);
3795   SDValue FVal = DAG.getConstant(0, dl, VT);
3796
3797   // Handle f128 first, since one possible outcome is a normal integer
3798   // comparison which gets picked up by the next if statement.
3799   if (LHS.getValueType() == MVT::f128) {
3800     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3801
3802     // If softenSetCCOperands returned a scalar, use it.
3803     if (!RHS.getNode()) {
3804       assert(LHS.getValueType() == Op.getValueType() &&
3805              "Unexpected setcc expansion!");
3806       return LHS;
3807     }
3808   }
3809
3810   if (LHS.getValueType().isInteger()) {
3811     SDValue CCVal;
3812     SDValue Cmp =
3813         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3814
3815     // Note that we inverted the condition above, so we reverse the order of
3816     // the true and false operands here.  This will allow the setcc to be
3817     // matched to a single CSINC instruction.
3818     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3819   }
3820
3821   // Now we know we're dealing with FP values.
3822   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3823
3824   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3825   // and do the comparison.
3826   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3827
3828   AArch64CC::CondCode CC1, CC2;
3829   changeFPCCToAArch64CC(CC, CC1, CC2);
3830   if (CC2 == AArch64CC::AL) {
3831     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3832     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3833
3834     // Note that we inverted the condition above, so we reverse the order of
3835     // the true and false operands here.  This will allow the setcc to be
3836     // matched to a single CSINC instruction.
3837     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3838   } else {
3839     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3840     // totally clean.  Some of them require two CSELs to implement.  As is in
3841     // this case, we emit the first CSEL and then emit a second using the output
3842     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3843
3844     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3845     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3846     SDValue CS1 =
3847         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3848
3849     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3850     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3851   }
3852 }
3853
3854 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3855                                               SDValue RHS, SDValue TVal,
3856                                               SDValue FVal, SDLoc dl,
3857                                               SelectionDAG &DAG) const {
3858   // Handle f128 first, because it will result in a comparison of some RTLIB
3859   // call result against zero.
3860   if (LHS.getValueType() == MVT::f128) {
3861     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3862
3863     // If softenSetCCOperands returned a scalar, we need to compare the result
3864     // against zero to select between true and false values.
3865     if (!RHS.getNode()) {
3866       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3867       CC = ISD::SETNE;
3868     }
3869   }
3870
3871   // Handle integers first.
3872   if (LHS.getValueType().isInteger()) {
3873     assert((LHS.getValueType() == RHS.getValueType()) &&
3874            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3875
3876     unsigned Opcode = AArch64ISD::CSEL;
3877
3878     // If both the TVal and the FVal are constants, see if we can swap them in
3879     // order to for a CSINV or CSINC out of them.
3880     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3881     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3882
3883     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3884       std::swap(TVal, FVal);
3885       std::swap(CTVal, CFVal);
3886       CC = ISD::getSetCCInverse(CC, true);
3887     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3888       std::swap(TVal, FVal);
3889       std::swap(CTVal, CFVal);
3890       CC = ISD::getSetCCInverse(CC, true);
3891     } else if (TVal.getOpcode() == ISD::XOR) {
3892       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3893       // with a CSINV rather than a CSEL.
3894       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3895
3896       if (CVal && CVal->isAllOnesValue()) {
3897         std::swap(TVal, FVal);
3898         std::swap(CTVal, CFVal);
3899         CC = ISD::getSetCCInverse(CC, true);
3900       }
3901     } else if (TVal.getOpcode() == ISD::SUB) {
3902       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3903       // that we can match with a CSNEG rather than a CSEL.
3904       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3905
3906       if (CVal && CVal->isNullValue()) {
3907         std::swap(TVal, FVal);
3908         std::swap(CTVal, CFVal);
3909         CC = ISD::getSetCCInverse(CC, true);
3910       }
3911     } else if (CTVal && CFVal) {
3912       const int64_t TrueVal = CTVal->getSExtValue();
3913       const int64_t FalseVal = CFVal->getSExtValue();
3914       bool Swap = false;
3915
3916       // If both TVal and FVal are constants, see if FVal is the
3917       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3918       // instead of a CSEL in that case.
3919       if (TrueVal == ~FalseVal) {
3920         Opcode = AArch64ISD::CSINV;
3921       } else if (TrueVal == -FalseVal) {
3922         Opcode = AArch64ISD::CSNEG;
3923       } else if (TVal.getValueType() == MVT::i32) {
3924         // If our operands are only 32-bit wide, make sure we use 32-bit
3925         // arithmetic for the check whether we can use CSINC. This ensures that
3926         // the addition in the check will wrap around properly in case there is
3927         // an overflow (which would not be the case if we do the check with
3928         // 64-bit arithmetic).
3929         const uint32_t TrueVal32 = CTVal->getZExtValue();
3930         const uint32_t FalseVal32 = CFVal->getZExtValue();
3931
3932         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3933           Opcode = AArch64ISD::CSINC;
3934
3935           if (TrueVal32 > FalseVal32) {
3936             Swap = true;
3937           }
3938         }
3939         // 64-bit check whether we can use CSINC.
3940       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3941         Opcode = AArch64ISD::CSINC;
3942
3943         if (TrueVal > FalseVal) {
3944           Swap = true;
3945         }
3946       }
3947
3948       // Swap TVal and FVal if necessary.
3949       if (Swap) {
3950         std::swap(TVal, FVal);
3951         std::swap(CTVal, CFVal);
3952         CC = ISD::getSetCCInverse(CC, true);
3953       }
3954
3955       if (Opcode != AArch64ISD::CSEL) {
3956         // Drop FVal since we can get its value by simply inverting/negating
3957         // TVal.
3958         FVal = TVal;
3959       }
3960     }
3961
3962     SDValue CCVal;
3963     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3964
3965     EVT VT = TVal.getValueType();
3966     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3967   }
3968
3969   // Now we know we're dealing with FP values.
3970   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3971   assert(LHS.getValueType() == RHS.getValueType());
3972   EVT VT = TVal.getValueType();
3973   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3974
3975   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3976   // clean.  Some of them require two CSELs to implement.
3977   AArch64CC::CondCode CC1, CC2;
3978   changeFPCCToAArch64CC(CC, CC1, CC2);
3979   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3980   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3981
3982   // If we need a second CSEL, emit it, using the output of the first as the
3983   // RHS.  We're effectively OR'ing the two CC's together.
3984   if (CC2 != AArch64CC::AL) {
3985     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3986     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3987   }
3988
3989   // Otherwise, return the output of the first CSEL.
3990   return CS1;
3991 }
3992
3993 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3994                                               SelectionDAG &DAG) const {
3995   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3996   SDValue LHS = Op.getOperand(0);
3997   SDValue RHS = Op.getOperand(1);
3998   SDValue TVal = Op.getOperand(2);
3999   SDValue FVal = Op.getOperand(3);
4000   SDLoc DL(Op);
4001   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4002 }
4003
4004 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4005                                            SelectionDAG &DAG) const {
4006   SDValue CCVal = Op->getOperand(0);
4007   SDValue TVal = Op->getOperand(1);
4008   SDValue FVal = Op->getOperand(2);
4009   SDLoc DL(Op);
4010
4011   unsigned Opc = CCVal.getOpcode();
4012   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4013   // instruction.
4014   if (CCVal.getResNo() == 1 &&
4015       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4016        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4017     // Only lower legal XALUO ops.
4018     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4019       return SDValue();
4020
4021     AArch64CC::CondCode OFCC;
4022     SDValue Value, Overflow;
4023     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4024     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4025
4026     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4027                        CCVal, Overflow);
4028   }
4029
4030   // Lower it the same way as we would lower a SELECT_CC node.
4031   ISD::CondCode CC;
4032   SDValue LHS, RHS;
4033   if (CCVal.getOpcode() == ISD::SETCC) {
4034     LHS = CCVal.getOperand(0);
4035     RHS = CCVal.getOperand(1);
4036     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4037   } else {
4038     LHS = CCVal;
4039     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4040     CC = ISD::SETNE;
4041   }
4042   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4043 }
4044
4045 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4046                                               SelectionDAG &DAG) const {
4047   // Jump table entries as PC relative offsets. No additional tweaking
4048   // is necessary here. Just get the address of the jump table.
4049   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4050   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4051   SDLoc DL(Op);
4052
4053   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4054       !Subtarget->isTargetMachO()) {
4055     const unsigned char MO_NC = AArch64II::MO_NC;
4056     return DAG.getNode(
4057         AArch64ISD::WrapperLarge, DL, PtrVT,
4058         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4059         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4060         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4061         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4062                                AArch64II::MO_G0 | MO_NC));
4063   }
4064
4065   SDValue Hi =
4066       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4067   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4068                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4069   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4070   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4071 }
4072
4073 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4074                                                  SelectionDAG &DAG) const {
4075   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4076   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4077   SDLoc DL(Op);
4078
4079   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4080     // Use the GOT for the large code model on iOS.
4081     if (Subtarget->isTargetMachO()) {
4082       SDValue GotAddr = DAG.getTargetConstantPool(
4083           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4084           AArch64II::MO_GOT);
4085       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4086     }
4087
4088     const unsigned char MO_NC = AArch64II::MO_NC;
4089     return DAG.getNode(
4090         AArch64ISD::WrapperLarge, DL, PtrVT,
4091         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4092                                   CP->getOffset(), AArch64II::MO_G3),
4093         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4094                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4095         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4096                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4097         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4098                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4099   } else {
4100     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4101     // ELF, the only valid one on Darwin.
4102     SDValue Hi =
4103         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4104                                   CP->getOffset(), AArch64II::MO_PAGE);
4105     SDValue Lo = DAG.getTargetConstantPool(
4106         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4107         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4108
4109     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4110     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4111   }
4112 }
4113
4114 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4115                                                SelectionDAG &DAG) const {
4116   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4117   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4118   SDLoc DL(Op);
4119   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4120       !Subtarget->isTargetMachO()) {
4121     const unsigned char MO_NC = AArch64II::MO_NC;
4122     return DAG.getNode(
4123         AArch64ISD::WrapperLarge, DL, PtrVT,
4124         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4125         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4126         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4127         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4128   } else {
4129     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4130     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4131                                                              AArch64II::MO_NC);
4132     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4133     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4134   }
4135 }
4136
4137 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4138                                                  SelectionDAG &DAG) const {
4139   AArch64FunctionInfo *FuncInfo =
4140       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4141
4142   SDLoc DL(Op);
4143   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4144                                  getPointerTy(DAG.getDataLayout()));
4145   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4146   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4147                       MachinePointerInfo(SV), false, false, 0);
4148 }
4149
4150 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4151                                                 SelectionDAG &DAG) const {
4152   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4153   // Standard, section B.3.
4154   MachineFunction &MF = DAG.getMachineFunction();
4155   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4156   auto PtrVT = getPointerTy(DAG.getDataLayout());
4157   SDLoc DL(Op);
4158
4159   SDValue Chain = Op.getOperand(0);
4160   SDValue VAList = Op.getOperand(1);
4161   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4162   SmallVector<SDValue, 4> MemOps;
4163
4164   // void *__stack at offset 0
4165   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4166   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4167                                 MachinePointerInfo(SV), false, false, 8));
4168
4169   // void *__gr_top at offset 8
4170   int GPRSize = FuncInfo->getVarArgsGPRSize();
4171   if (GPRSize > 0) {
4172     SDValue GRTop, GRTopAddr;
4173
4174     GRTopAddr =
4175         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4176
4177     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4178     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4179                         DAG.getConstant(GPRSize, DL, PtrVT));
4180
4181     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4182                                   MachinePointerInfo(SV, 8), false, false, 8));
4183   }
4184
4185   // void *__vr_top at offset 16
4186   int FPRSize = FuncInfo->getVarArgsFPRSize();
4187   if (FPRSize > 0) {
4188     SDValue VRTop, VRTopAddr;
4189     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4190                             DAG.getConstant(16, DL, PtrVT));
4191
4192     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4193     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4194                         DAG.getConstant(FPRSize, DL, PtrVT));
4195
4196     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4197                                   MachinePointerInfo(SV, 16), false, false, 8));
4198   }
4199
4200   // int __gr_offs at offset 24
4201   SDValue GROffsAddr =
4202       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4203   MemOps.push_back(DAG.getStore(Chain, DL,
4204                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4205                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4206                                 false, 4));
4207
4208   // int __vr_offs at offset 28
4209   SDValue VROffsAddr =
4210       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4211   MemOps.push_back(DAG.getStore(Chain, DL,
4212                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4213                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4214                                 false, 4));
4215
4216   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4217 }
4218
4219 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4220                                             SelectionDAG &DAG) const {
4221   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4222                                      : LowerAAPCS_VASTART(Op, DAG);
4223 }
4224
4225 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4226                                            SelectionDAG &DAG) const {
4227   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4228   // pointer.
4229   SDLoc DL(Op);
4230   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4231   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4232   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4233
4234   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4235                        Op.getOperand(2),
4236                        DAG.getConstant(VaListSize, DL, MVT::i32),
4237                        8, false, false, false, MachinePointerInfo(DestSV),
4238                        MachinePointerInfo(SrcSV));
4239 }
4240
4241 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4242   assert(Subtarget->isTargetDarwin() &&
4243          "automatic va_arg instruction only works on Darwin");
4244
4245   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4246   EVT VT = Op.getValueType();
4247   SDLoc DL(Op);
4248   SDValue Chain = Op.getOperand(0);
4249   SDValue Addr = Op.getOperand(1);
4250   unsigned Align = Op.getConstantOperandVal(3);
4251   auto PtrVT = getPointerTy(DAG.getDataLayout());
4252
4253   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4254                                false, false, false, 0);
4255   Chain = VAList.getValue(1);
4256
4257   if (Align > 8) {
4258     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4259     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4260                          DAG.getConstant(Align - 1, DL, PtrVT));
4261     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4262                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4263   }
4264
4265   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4266   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4267
4268   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4269   // up to 64 bits.  At the very least, we have to increase the striding of the
4270   // vaargs list to match this, and for FP values we need to introduce
4271   // FP_ROUND nodes as well.
4272   if (VT.isInteger() && !VT.isVector())
4273     ArgSize = 8;
4274   bool NeedFPTrunc = false;
4275   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4276     ArgSize = 8;
4277     NeedFPTrunc = true;
4278   }
4279
4280   // Increment the pointer, VAList, to the next vaarg
4281   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4282                                DAG.getConstant(ArgSize, DL, PtrVT));
4283   // Store the incremented VAList to the legalized pointer
4284   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4285                                  false, false, 0);
4286
4287   // Load the actual argument out of the pointer VAList
4288   if (NeedFPTrunc) {
4289     // Load the value as an f64.
4290     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4291                                  MachinePointerInfo(), false, false, false, 0);
4292     // Round the value down to an f32.
4293     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4294                                    DAG.getIntPtrConstant(1, DL));
4295     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4296     // Merge the rounded value with the chain output of the load.
4297     return DAG.getMergeValues(Ops, DL);
4298   }
4299
4300   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4301                      false, false, 0);
4302 }
4303
4304 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4305                                               SelectionDAG &DAG) const {
4306   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4307   MFI->setFrameAddressIsTaken(true);
4308
4309   EVT VT = Op.getValueType();
4310   SDLoc DL(Op);
4311   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4312   SDValue FrameAddr =
4313       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4314   while (Depth--)
4315     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4316                             MachinePointerInfo(), false, false, false, 0);
4317   return FrameAddr;
4318 }
4319
4320 // FIXME? Maybe this could be a TableGen attribute on some registers and
4321 // this table could be generated automatically from RegInfo.
4322 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4323                                                   SelectionDAG &DAG) const {
4324   unsigned Reg = StringSwitch<unsigned>(RegName)
4325                        .Case("sp", AArch64::SP)
4326                        .Default(0);
4327   if (Reg)
4328     return Reg;
4329   report_fatal_error(Twine("Invalid register name \""
4330                               + StringRef(RegName)  + "\"."));
4331 }
4332
4333 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4334                                                SelectionDAG &DAG) const {
4335   MachineFunction &MF = DAG.getMachineFunction();
4336   MachineFrameInfo *MFI = MF.getFrameInfo();
4337   MFI->setReturnAddressIsTaken(true);
4338
4339   EVT VT = Op.getValueType();
4340   SDLoc DL(Op);
4341   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4342   if (Depth) {
4343     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4344     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4345     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4346                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4347                        MachinePointerInfo(), false, false, false, 0);
4348   }
4349
4350   // Return LR, which contains the return address. Mark it an implicit live-in.
4351   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4352   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4353 }
4354
4355 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4356 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4357 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4358                                                     SelectionDAG &DAG) const {
4359   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4360   EVT VT = Op.getValueType();
4361   unsigned VTBits = VT.getSizeInBits();
4362   SDLoc dl(Op);
4363   SDValue ShOpLo = Op.getOperand(0);
4364   SDValue ShOpHi = Op.getOperand(1);
4365   SDValue ShAmt = Op.getOperand(2);
4366   SDValue ARMcc;
4367   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4368
4369   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4370
4371   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4372                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4373   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4374   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4375                                    DAG.getConstant(VTBits, dl, MVT::i64));
4376   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4377
4378   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4379                                ISD::SETGE, dl, DAG);
4380   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4381
4382   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4383   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4384   SDValue Lo =
4385       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4386
4387   // AArch64 shifts larger than the register width are wrapped rather than
4388   // clamped, so we can't just emit "hi >> x".
4389   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4390   SDValue TrueValHi = Opc == ISD::SRA
4391                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4392                                         DAG.getConstant(VTBits - 1, dl,
4393                                                         MVT::i64))
4394                           : DAG.getConstant(0, dl, VT);
4395   SDValue Hi =
4396       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4397
4398   SDValue Ops[2] = { Lo, Hi };
4399   return DAG.getMergeValues(Ops, dl);
4400 }
4401
4402 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4403 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4404 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4405                                                  SelectionDAG &DAG) const {
4406   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4407   EVT VT = Op.getValueType();
4408   unsigned VTBits = VT.getSizeInBits();
4409   SDLoc dl(Op);
4410   SDValue ShOpLo = Op.getOperand(0);
4411   SDValue ShOpHi = Op.getOperand(1);
4412   SDValue ShAmt = Op.getOperand(2);
4413   SDValue ARMcc;
4414
4415   assert(Op.getOpcode() == ISD::SHL_PARTS);
4416   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4417                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4418   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4419   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4420                                    DAG.getConstant(VTBits, dl, MVT::i64));
4421   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4422   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4423
4424   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4425
4426   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4427                                ISD::SETGE, dl, DAG);
4428   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4429   SDValue Hi =
4430       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4431
4432   // AArch64 shifts of larger than register sizes are wrapped rather than
4433   // clamped, so we can't just emit "lo << a" if a is too big.
4434   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4435   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4436   SDValue Lo =
4437       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4438
4439   SDValue Ops[2] = { Lo, Hi };
4440   return DAG.getMergeValues(Ops, dl);
4441 }
4442
4443 bool AArch64TargetLowering::isOffsetFoldingLegal(
4444     const GlobalAddressSDNode *GA) const {
4445   // The AArch64 target doesn't support folding offsets into global addresses.
4446   return false;
4447 }
4448
4449 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4450   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4451   // FIXME: We should be able to handle f128 as well with a clever lowering.
4452   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4453     return true;
4454
4455   if (VT == MVT::f64)
4456     return AArch64_AM::getFP64Imm(Imm) != -1;
4457   else if (VT == MVT::f32)
4458     return AArch64_AM::getFP32Imm(Imm) != -1;
4459   return false;
4460 }
4461
4462 //===----------------------------------------------------------------------===//
4463 //                          AArch64 Optimization Hooks
4464 //===----------------------------------------------------------------------===//
4465
4466 //===----------------------------------------------------------------------===//
4467 //                          AArch64 Inline Assembly Support
4468 //===----------------------------------------------------------------------===//
4469
4470 // Table of Constraints
4471 // TODO: This is the current set of constraints supported by ARM for the
4472 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4473 //
4474 // r - A general register
4475 // w - An FP/SIMD register of some size in the range v0-v31
4476 // x - An FP/SIMD register of some size in the range v0-v15
4477 // I - Constant that can be used with an ADD instruction
4478 // J - Constant that can be used with a SUB instruction
4479 // K - Constant that can be used with a 32-bit logical instruction
4480 // L - Constant that can be used with a 64-bit logical instruction
4481 // M - Constant that can be used as a 32-bit MOV immediate
4482 // N - Constant that can be used as a 64-bit MOV immediate
4483 // Q - A memory reference with base register and no offset
4484 // S - A symbolic address
4485 // Y - Floating point constant zero
4486 // Z - Integer constant zero
4487 //
4488 //   Note that general register operands will be output using their 64-bit x
4489 // register name, whatever the size of the variable, unless the asm operand
4490 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4491 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4492 // %q modifier.
4493
4494 /// getConstraintType - Given a constraint letter, return the type of
4495 /// constraint it is for this target.
4496 AArch64TargetLowering::ConstraintType
4497 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4498   if (Constraint.size() == 1) {
4499     switch (Constraint[0]) {
4500     default:
4501       break;
4502     case 'z':
4503       return C_Other;
4504     case 'x':
4505     case 'w':
4506       return C_RegisterClass;
4507     // An address with a single base register. Due to the way we
4508     // currently handle addresses it is the same as 'r'.
4509     case 'Q':
4510       return C_Memory;
4511     }
4512   }
4513   return TargetLowering::getConstraintType(Constraint);
4514 }
4515
4516 /// Examine constraint type and operand type and determine a weight value.
4517 /// This object must already have been set up with the operand type
4518 /// and the current alternative constraint selected.
4519 TargetLowering::ConstraintWeight
4520 AArch64TargetLowering::getSingleConstraintMatchWeight(
4521     AsmOperandInfo &info, const char *constraint) const {
4522   ConstraintWeight weight = CW_Invalid;
4523   Value *CallOperandVal = info.CallOperandVal;
4524   // If we don't have a value, we can't do a match,
4525   // but allow it at the lowest weight.
4526   if (!CallOperandVal)
4527     return CW_Default;
4528   Type *type = CallOperandVal->getType();
4529   // Look at the constraint type.
4530   switch (*constraint) {
4531   default:
4532     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4533     break;
4534   case 'x':
4535   case 'w':
4536     if (type->isFloatingPointTy() || type->isVectorTy())
4537       weight = CW_Register;
4538     break;
4539   case 'z':
4540     weight = CW_Constant;
4541     break;
4542   }
4543   return weight;
4544 }
4545
4546 std::pair<unsigned, const TargetRegisterClass *>
4547 AArch64TargetLowering::getRegForInlineAsmConstraint(
4548     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4549   if (Constraint.size() == 1) {
4550     switch (Constraint[0]) {
4551     case 'r':
4552       if (VT.getSizeInBits() == 64)
4553         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4554       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4555     case 'w':
4556       if (VT == MVT::f32)
4557         return std::make_pair(0U, &AArch64::FPR32RegClass);
4558       if (VT.getSizeInBits() == 64)
4559         return std::make_pair(0U, &AArch64::FPR64RegClass);
4560       if (VT.getSizeInBits() == 128)
4561         return std::make_pair(0U, &AArch64::FPR128RegClass);
4562       break;
4563     // The instructions that this constraint is designed for can
4564     // only take 128-bit registers so just use that regclass.
4565     case 'x':
4566       if (VT.getSizeInBits() == 128)
4567         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4568       break;
4569     }
4570   }
4571   if (StringRef("{cc}").equals_lower(Constraint))
4572     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4573
4574   // Use the default implementation in TargetLowering to convert the register
4575   // constraint into a member of a register class.
4576   std::pair<unsigned, const TargetRegisterClass *> Res;
4577   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4578
4579   // Not found as a standard register?
4580   if (!Res.second) {
4581     unsigned Size = Constraint.size();
4582     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4583         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4584       int RegNo;
4585       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4586       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4587         // v0 - v31 are aliases of q0 - q31.
4588         // By default we'll emit v0-v31 for this unless there's a modifier where
4589         // we'll emit the correct register as well.
4590         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4591         Res.second = &AArch64::FPR128RegClass;
4592       }
4593     }
4594   }
4595
4596   return Res;
4597 }
4598
4599 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4600 /// vector.  If it is invalid, don't add anything to Ops.
4601 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4602     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4603     SelectionDAG &DAG) const {
4604   SDValue Result;
4605
4606   // Currently only support length 1 constraints.
4607   if (Constraint.length() != 1)
4608     return;
4609
4610   char ConstraintLetter = Constraint[0];
4611   switch (ConstraintLetter) {
4612   default:
4613     break;
4614
4615   // This set of constraints deal with valid constants for various instructions.
4616   // Validate and return a target constant for them if we can.
4617   case 'z': {
4618     // 'z' maps to xzr or wzr so it needs an input of 0.
4619     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4620     if (!C || C->getZExtValue() != 0)
4621       return;
4622
4623     if (Op.getValueType() == MVT::i64)
4624       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4625     else
4626       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4627     break;
4628   }
4629
4630   case 'I':
4631   case 'J':
4632   case 'K':
4633   case 'L':
4634   case 'M':
4635   case 'N':
4636     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4637     if (!C)
4638       return;
4639
4640     // Grab the value and do some validation.
4641     uint64_t CVal = C->getZExtValue();
4642     switch (ConstraintLetter) {
4643     // The I constraint applies only to simple ADD or SUB immediate operands:
4644     // i.e. 0 to 4095 with optional shift by 12
4645     // The J constraint applies only to ADD or SUB immediates that would be
4646     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4647     // instruction [or vice versa], in other words -1 to -4095 with optional
4648     // left shift by 12.
4649     case 'I':
4650       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4651         break;
4652       return;
4653     case 'J': {
4654       uint64_t NVal = -C->getSExtValue();
4655       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4656         CVal = C->getSExtValue();
4657         break;
4658       }
4659       return;
4660     }
4661     // The K and L constraints apply *only* to logical immediates, including
4662     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4663     // been removed and MOV should be used). So these constraints have to
4664     // distinguish between bit patterns that are valid 32-bit or 64-bit
4665     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4666     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4667     // versa.
4668     case 'K':
4669       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4670         break;
4671       return;
4672     case 'L':
4673       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4674         break;
4675       return;
4676     // The M and N constraints are a superset of K and L respectively, for use
4677     // with the MOV (immediate) alias. As well as the logical immediates they
4678     // also match 32 or 64-bit immediates that can be loaded either using a
4679     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4680     // (M) or 64-bit 0x1234000000000000 (N) etc.
4681     // As a note some of this code is liberally stolen from the asm parser.
4682     case 'M': {
4683       if (!isUInt<32>(CVal))
4684         return;
4685       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4686         break;
4687       if ((CVal & 0xFFFF) == CVal)
4688         break;
4689       if ((CVal & 0xFFFF0000ULL) == CVal)
4690         break;
4691       uint64_t NCVal = ~(uint32_t)CVal;
4692       if ((NCVal & 0xFFFFULL) == NCVal)
4693         break;
4694       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4695         break;
4696       return;
4697     }
4698     case 'N': {
4699       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4700         break;
4701       if ((CVal & 0xFFFFULL) == CVal)
4702         break;
4703       if ((CVal & 0xFFFF0000ULL) == CVal)
4704         break;
4705       if ((CVal & 0xFFFF00000000ULL) == CVal)
4706         break;
4707       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4708         break;
4709       uint64_t NCVal = ~CVal;
4710       if ((NCVal & 0xFFFFULL) == NCVal)
4711         break;
4712       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4713         break;
4714       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4715         break;
4716       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4717         break;
4718       return;
4719     }
4720     default:
4721       return;
4722     }
4723
4724     // All assembler immediates are 64-bit integers.
4725     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4726     break;
4727   }
4728
4729   if (Result.getNode()) {
4730     Ops.push_back(Result);
4731     return;
4732   }
4733
4734   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4735 }
4736
4737 //===----------------------------------------------------------------------===//
4738 //                     AArch64 Advanced SIMD Support
4739 //===----------------------------------------------------------------------===//
4740
4741 /// WidenVector - Given a value in the V64 register class, produce the
4742 /// equivalent value in the V128 register class.
4743 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4744   EVT VT = V64Reg.getValueType();
4745   unsigned NarrowSize = VT.getVectorNumElements();
4746   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4747   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4748   SDLoc DL(V64Reg);
4749
4750   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4751                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4752 }
4753
4754 /// getExtFactor - Determine the adjustment factor for the position when
4755 /// generating an "extract from vector registers" instruction.
4756 static unsigned getExtFactor(SDValue &V) {
4757   EVT EltType = V.getValueType().getVectorElementType();
4758   return EltType.getSizeInBits() / 8;
4759 }
4760
4761 /// NarrowVector - Given a value in the V128 register class, produce the
4762 /// equivalent value in the V64 register class.
4763 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4764   EVT VT = V128Reg.getValueType();
4765   unsigned WideSize = VT.getVectorNumElements();
4766   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4767   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4768   SDLoc DL(V128Reg);
4769
4770   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4771 }
4772
4773 // Gather data to see if the operation can be modelled as a
4774 // shuffle in combination with VEXTs.
4775 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4776                                                   SelectionDAG &DAG) const {
4777   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4778   SDLoc dl(Op);
4779   EVT VT = Op.getValueType();
4780   unsigned NumElts = VT.getVectorNumElements();
4781
4782   struct ShuffleSourceInfo {
4783     SDValue Vec;
4784     unsigned MinElt;
4785     unsigned MaxElt;
4786
4787     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4788     // be compatible with the shuffle we intend to construct. As a result
4789     // ShuffleVec will be some sliding window into the original Vec.
4790     SDValue ShuffleVec;
4791
4792     // Code should guarantee that element i in Vec starts at element "WindowBase
4793     // + i * WindowScale in ShuffleVec".
4794     int WindowBase;
4795     int WindowScale;
4796
4797     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4798     ShuffleSourceInfo(SDValue Vec)
4799         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4800           WindowScale(1) {}
4801   };
4802
4803   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4804   // node.
4805   SmallVector<ShuffleSourceInfo, 2> Sources;
4806   for (unsigned i = 0; i < NumElts; ++i) {
4807     SDValue V = Op.getOperand(i);
4808     if (V.getOpcode() == ISD::UNDEF)
4809       continue;
4810     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4811       // A shuffle can only come from building a vector from various
4812       // elements of other vectors.
4813       return SDValue();
4814     }
4815
4816     // Add this element source to the list if it's not already there.
4817     SDValue SourceVec = V.getOperand(0);
4818     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4819     if (Source == Sources.end())
4820       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4821
4822     // Update the minimum and maximum lane number seen.
4823     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4824     Source->MinElt = std::min(Source->MinElt, EltNo);
4825     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4826   }
4827
4828   // Currently only do something sane when at most two source vectors
4829   // are involved.
4830   if (Sources.size() > 2)
4831     return SDValue();
4832
4833   // Find out the smallest element size among result and two sources, and use
4834   // it as element size to build the shuffle_vector.
4835   EVT SmallestEltTy = VT.getVectorElementType();
4836   for (auto &Source : Sources) {
4837     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4838     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4839       SmallestEltTy = SrcEltTy;
4840     }
4841   }
4842   unsigned ResMultiplier =
4843       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4844   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4845   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4846
4847   // If the source vector is too wide or too narrow, we may nevertheless be able
4848   // to construct a compatible shuffle either by concatenating it with UNDEF or
4849   // extracting a suitable range of elements.
4850   for (auto &Src : Sources) {
4851     EVT SrcVT = Src.ShuffleVec.getValueType();
4852
4853     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4854       continue;
4855
4856     // This stage of the search produces a source with the same element type as
4857     // the original, but with a total width matching the BUILD_VECTOR output.
4858     EVT EltVT = SrcVT.getVectorElementType();
4859     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4860     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4861
4862     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4863       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4864       // We can pad out the smaller vector for free, so if it's part of a
4865       // shuffle...
4866       Src.ShuffleVec =
4867           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4868                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4869       continue;
4870     }
4871
4872     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4873
4874     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4875       // Span too large for a VEXT to cope
4876       return SDValue();
4877     }
4878
4879     if (Src.MinElt >= NumSrcElts) {
4880       // The extraction can just take the second half
4881       Src.ShuffleVec =
4882           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4883                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4884       Src.WindowBase = -NumSrcElts;
4885     } else if (Src.MaxElt < NumSrcElts) {
4886       // The extraction can just take the first half
4887       Src.ShuffleVec =
4888           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4889                       DAG.getConstant(0, dl, MVT::i64));
4890     } else {
4891       // An actual VEXT is needed
4892       SDValue VEXTSrc1 =
4893           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4894                       DAG.getConstant(0, dl, MVT::i64));
4895       SDValue VEXTSrc2 =
4896           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4897                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4898       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4899
4900       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4901                                    VEXTSrc2,
4902                                    DAG.getConstant(Imm, dl, MVT::i32));
4903       Src.WindowBase = -Src.MinElt;
4904     }
4905   }
4906
4907   // Another possible incompatibility occurs from the vector element types. We
4908   // can fix this by bitcasting the source vectors to the same type we intend
4909   // for the shuffle.
4910   for (auto &Src : Sources) {
4911     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4912     if (SrcEltTy == SmallestEltTy)
4913       continue;
4914     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4915     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4916     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4917     Src.WindowBase *= Src.WindowScale;
4918   }
4919
4920   // Final sanity check before we try to actually produce a shuffle.
4921   DEBUG(
4922     for (auto Src : Sources)
4923       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4924   );
4925
4926   // The stars all align, our next step is to produce the mask for the shuffle.
4927   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4928   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4929   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4930     SDValue Entry = Op.getOperand(i);
4931     if (Entry.getOpcode() == ISD::UNDEF)
4932       continue;
4933
4934     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4935     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4936
4937     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4938     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4939     // segment.
4940     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4941     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4942                                VT.getVectorElementType().getSizeInBits());
4943     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4944
4945     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4946     // starting at the appropriate offset.
4947     int *LaneMask = &Mask[i * ResMultiplier];
4948
4949     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4950     ExtractBase += NumElts * (Src - Sources.begin());
4951     for (int j = 0; j < LanesDefined; ++j)
4952       LaneMask[j] = ExtractBase + j;
4953   }
4954
4955   // Final check before we try to produce nonsense...
4956   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4957     return SDValue();
4958
4959   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4960   for (unsigned i = 0; i < Sources.size(); ++i)
4961     ShuffleOps[i] = Sources[i].ShuffleVec;
4962
4963   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4964                                          ShuffleOps[1], &Mask[0]);
4965   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4966 }
4967
4968 // check if an EXT instruction can handle the shuffle mask when the
4969 // vector sources of the shuffle are the same.
4970 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4971   unsigned NumElts = VT.getVectorNumElements();
4972
4973   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4974   if (M[0] < 0)
4975     return false;
4976
4977   Imm = M[0];
4978
4979   // If this is a VEXT shuffle, the immediate value is the index of the first
4980   // element.  The other shuffle indices must be the successive elements after
4981   // the first one.
4982   unsigned ExpectedElt = Imm;
4983   for (unsigned i = 1; i < NumElts; ++i) {
4984     // Increment the expected index.  If it wraps around, just follow it
4985     // back to index zero and keep going.
4986     ++ExpectedElt;
4987     if (ExpectedElt == NumElts)
4988       ExpectedElt = 0;
4989
4990     if (M[i] < 0)
4991       continue; // ignore UNDEF indices
4992     if (ExpectedElt != static_cast<unsigned>(M[i]))
4993       return false;
4994   }
4995
4996   return true;
4997 }
4998
4999 // check if an EXT instruction can handle the shuffle mask when the
5000 // vector sources of the shuffle are different.
5001 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5002                       unsigned &Imm) {
5003   // Look for the first non-undef element.
5004   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5005       [](int Elt) {return Elt >= 0;});
5006
5007   // Benefit form APInt to handle overflow when calculating expected element.
5008   unsigned NumElts = VT.getVectorNumElements();
5009   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5010   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5011   // The following shuffle indices must be the successive elements after the
5012   // first real element.
5013   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5014       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5015   if (FirstWrongElt != M.end())
5016     return false;
5017
5018   // The index of an EXT is the first element if it is not UNDEF.
5019   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5020   // value of the first element.  E.g. 
5021   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5022   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5023   // ExpectedElt is the last mask index plus 1.
5024   Imm = ExpectedElt.getZExtValue();
5025
5026   // There are two difference cases requiring to reverse input vectors.
5027   // For example, for vector <4 x i32> we have the following cases,
5028   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5029   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5030   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5031   // to reverse two input vectors.
5032   if (Imm < NumElts)
5033     ReverseEXT = true;
5034   else
5035     Imm -= NumElts;
5036
5037   return true;
5038 }
5039
5040 /// isREVMask - Check if a vector shuffle corresponds to a REV
5041 /// instruction with the specified blocksize.  (The order of the elements
5042 /// within each block of the vector is reversed.)
5043 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5044   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5045          "Only possible block sizes for REV are: 16, 32, 64");
5046
5047   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5048   if (EltSz == 64)
5049     return false;
5050
5051   unsigned NumElts = VT.getVectorNumElements();
5052   unsigned BlockElts = M[0] + 1;
5053   // If the first shuffle index is UNDEF, be optimistic.
5054   if (M[0] < 0)
5055     BlockElts = BlockSize / EltSz;
5056
5057   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5058     return false;
5059
5060   for (unsigned i = 0; i < NumElts; ++i) {
5061     if (M[i] < 0)
5062       continue; // ignore UNDEF indices
5063     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5064       return false;
5065   }
5066
5067   return true;
5068 }
5069
5070 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5071   unsigned NumElts = VT.getVectorNumElements();
5072   WhichResult = (M[0] == 0 ? 0 : 1);
5073   unsigned Idx = WhichResult * NumElts / 2;
5074   for (unsigned i = 0; i != NumElts; i += 2) {
5075     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5076         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5077       return false;
5078     Idx += 1;
5079   }
5080
5081   return true;
5082 }
5083
5084 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5085   unsigned NumElts = VT.getVectorNumElements();
5086   WhichResult = (M[0] == 0 ? 0 : 1);
5087   for (unsigned i = 0; i != NumElts; ++i) {
5088     if (M[i] < 0)
5089       continue; // ignore UNDEF indices
5090     if ((unsigned)M[i] != 2 * i + WhichResult)
5091       return false;
5092   }
5093
5094   return true;
5095 }
5096
5097 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5098   unsigned NumElts = VT.getVectorNumElements();
5099   WhichResult = (M[0] == 0 ? 0 : 1);
5100   for (unsigned i = 0; i < NumElts; i += 2) {
5101     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5102         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5103       return false;
5104   }
5105   return true;
5106 }
5107
5108 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5109 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5110 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5111 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5112   unsigned NumElts = VT.getVectorNumElements();
5113   WhichResult = (M[0] == 0 ? 0 : 1);
5114   unsigned Idx = WhichResult * NumElts / 2;
5115   for (unsigned i = 0; i != NumElts; i += 2) {
5116     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5117         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5118       return false;
5119     Idx += 1;
5120   }
5121
5122   return true;
5123 }
5124
5125 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5126 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5127 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5128 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5129   unsigned Half = VT.getVectorNumElements() / 2;
5130   WhichResult = (M[0] == 0 ? 0 : 1);
5131   for (unsigned j = 0; j != 2; ++j) {
5132     unsigned Idx = WhichResult;
5133     for (unsigned i = 0; i != Half; ++i) {
5134       int MIdx = M[i + j * Half];
5135       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5136         return false;
5137       Idx += 2;
5138     }
5139   }
5140
5141   return true;
5142 }
5143
5144 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5145 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5146 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5147 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5148   unsigned NumElts = VT.getVectorNumElements();
5149   WhichResult = (M[0] == 0 ? 0 : 1);
5150   for (unsigned i = 0; i < NumElts; i += 2) {
5151     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5152         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5153       return false;
5154   }
5155   return true;
5156 }
5157
5158 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5159                       bool &DstIsLeft, int &Anomaly) {
5160   if (M.size() != static_cast<size_t>(NumInputElements))
5161     return false;
5162
5163   int NumLHSMatch = 0, NumRHSMatch = 0;
5164   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5165
5166   for (int i = 0; i < NumInputElements; ++i) {
5167     if (M[i] == -1) {
5168       ++NumLHSMatch;
5169       ++NumRHSMatch;
5170       continue;
5171     }
5172
5173     if (M[i] == i)
5174       ++NumLHSMatch;
5175     else
5176       LastLHSMismatch = i;
5177
5178     if (M[i] == i + NumInputElements)
5179       ++NumRHSMatch;
5180     else
5181       LastRHSMismatch = i;
5182   }
5183
5184   if (NumLHSMatch == NumInputElements - 1) {
5185     DstIsLeft = true;
5186     Anomaly = LastLHSMismatch;
5187     return true;
5188   } else if (NumRHSMatch == NumInputElements - 1) {
5189     DstIsLeft = false;
5190     Anomaly = LastRHSMismatch;
5191     return true;
5192   }
5193
5194   return false;
5195 }
5196
5197 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5198   if (VT.getSizeInBits() != 128)
5199     return false;
5200
5201   unsigned NumElts = VT.getVectorNumElements();
5202
5203   for (int I = 0, E = NumElts / 2; I != E; I++) {
5204     if (Mask[I] != I)
5205       return false;
5206   }
5207
5208   int Offset = NumElts / 2;
5209   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5210     if (Mask[I] != I + SplitLHS * Offset)
5211       return false;
5212   }
5213
5214   return true;
5215 }
5216
5217 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5218   SDLoc DL(Op);
5219   EVT VT = Op.getValueType();
5220   SDValue V0 = Op.getOperand(0);
5221   SDValue V1 = Op.getOperand(1);
5222   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5223
5224   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5225       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5226     return SDValue();
5227
5228   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5229
5230   if (!isConcatMask(Mask, VT, SplitV0))
5231     return SDValue();
5232
5233   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5234                                 VT.getVectorNumElements() / 2);
5235   if (SplitV0) {
5236     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5237                      DAG.getConstant(0, DL, MVT::i64));
5238   }
5239   if (V1.getValueType().getSizeInBits() == 128) {
5240     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5241                      DAG.getConstant(0, DL, MVT::i64));
5242   }
5243   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5244 }
5245
5246 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5247 /// the specified operations to build the shuffle.
5248 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5249                                       SDValue RHS, SelectionDAG &DAG,
5250                                       SDLoc dl) {
5251   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5252   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5253   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5254
5255   enum {
5256     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5257     OP_VREV,
5258     OP_VDUP0,
5259     OP_VDUP1,
5260     OP_VDUP2,
5261     OP_VDUP3,
5262     OP_VEXT1,
5263     OP_VEXT2,
5264     OP_VEXT3,
5265     OP_VUZPL, // VUZP, left result
5266     OP_VUZPR, // VUZP, right result
5267     OP_VZIPL, // VZIP, left result
5268     OP_VZIPR, // VZIP, right result
5269     OP_VTRNL, // VTRN, left result
5270     OP_VTRNR  // VTRN, right result
5271   };
5272
5273   if (OpNum == OP_COPY) {
5274     if (LHSID == (1 * 9 + 2) * 9 + 3)
5275       return LHS;
5276     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5277     return RHS;
5278   }
5279
5280   SDValue OpLHS, OpRHS;
5281   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5282   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5283   EVT VT = OpLHS.getValueType();
5284
5285   switch (OpNum) {
5286   default:
5287     llvm_unreachable("Unknown shuffle opcode!");
5288   case OP_VREV:
5289     // VREV divides the vector in half and swaps within the half.
5290     if (VT.getVectorElementType() == MVT::i32 ||
5291         VT.getVectorElementType() == MVT::f32)
5292       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5293     // vrev <4 x i16> -> REV32
5294     if (VT.getVectorElementType() == MVT::i16 ||
5295         VT.getVectorElementType() == MVT::f16)
5296       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5297     // vrev <4 x i8> -> REV16
5298     assert(VT.getVectorElementType() == MVT::i8);
5299     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5300   case OP_VDUP0:
5301   case OP_VDUP1:
5302   case OP_VDUP2:
5303   case OP_VDUP3: {
5304     EVT EltTy = VT.getVectorElementType();
5305     unsigned Opcode;
5306     if (EltTy == MVT::i8)
5307       Opcode = AArch64ISD::DUPLANE8;
5308     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5309       Opcode = AArch64ISD::DUPLANE16;
5310     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5311       Opcode = AArch64ISD::DUPLANE32;
5312     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5313       Opcode = AArch64ISD::DUPLANE64;
5314     else
5315       llvm_unreachable("Invalid vector element type?");
5316
5317     if (VT.getSizeInBits() == 64)
5318       OpLHS = WidenVector(OpLHS, DAG);
5319     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5320     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5321   }
5322   case OP_VEXT1:
5323   case OP_VEXT2:
5324   case OP_VEXT3: {
5325     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5326     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5327                        DAG.getConstant(Imm, dl, MVT::i32));
5328   }
5329   case OP_VUZPL:
5330     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5331                        OpRHS);
5332   case OP_VUZPR:
5333     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5334                        OpRHS);
5335   case OP_VZIPL:
5336     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5337                        OpRHS);
5338   case OP_VZIPR:
5339     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5340                        OpRHS);
5341   case OP_VTRNL:
5342     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5343                        OpRHS);
5344   case OP_VTRNR:
5345     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5346                        OpRHS);
5347   }
5348 }
5349
5350 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5351                            SelectionDAG &DAG) {
5352   // Check to see if we can use the TBL instruction.
5353   SDValue V1 = Op.getOperand(0);
5354   SDValue V2 = Op.getOperand(1);
5355   SDLoc DL(Op);
5356
5357   EVT EltVT = Op.getValueType().getVectorElementType();
5358   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5359
5360   SmallVector<SDValue, 8> TBLMask;
5361   for (int Val : ShuffleMask) {
5362     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5363       unsigned Offset = Byte + Val * BytesPerElt;
5364       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5365     }
5366   }
5367
5368   MVT IndexVT = MVT::v8i8;
5369   unsigned IndexLen = 8;
5370   if (Op.getValueType().getSizeInBits() == 128) {
5371     IndexVT = MVT::v16i8;
5372     IndexLen = 16;
5373   }
5374
5375   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5376   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5377
5378   SDValue Shuffle;
5379   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5380     if (IndexLen == 8)
5381       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5382     Shuffle = DAG.getNode(
5383         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5384         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5385         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5386                     makeArrayRef(TBLMask.data(), IndexLen)));
5387   } else {
5388     if (IndexLen == 8) {
5389       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5390       Shuffle = DAG.getNode(
5391           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5392           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5393           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5394                       makeArrayRef(TBLMask.data(), IndexLen)));
5395     } else {
5396       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5397       // cannot currently represent the register constraints on the input
5398       // table registers.
5399       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5400       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5401       //                               &TBLMask[0], IndexLen));
5402       Shuffle = DAG.getNode(
5403           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5404           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5405           V1Cst, V2Cst,
5406           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5407                       makeArrayRef(TBLMask.data(), IndexLen)));
5408     }
5409   }
5410   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5411 }
5412
5413 static unsigned getDUPLANEOp(EVT EltType) {
5414   if (EltType == MVT::i8)
5415     return AArch64ISD::DUPLANE8;
5416   if (EltType == MVT::i16 || EltType == MVT::f16)
5417     return AArch64ISD::DUPLANE16;
5418   if (EltType == MVT::i32 || EltType == MVT::f32)
5419     return AArch64ISD::DUPLANE32;
5420   if (EltType == MVT::i64 || EltType == MVT::f64)
5421     return AArch64ISD::DUPLANE64;
5422
5423   llvm_unreachable("Invalid vector element type?");
5424 }
5425
5426 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5427                                                    SelectionDAG &DAG) const {
5428   SDLoc dl(Op);
5429   EVT VT = Op.getValueType();
5430
5431   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5432
5433   // Convert shuffles that are directly supported on NEON to target-specific
5434   // DAG nodes, instead of keeping them as shuffles and matching them again
5435   // during code selection.  This is more efficient and avoids the possibility
5436   // of inconsistencies between legalization and selection.
5437   ArrayRef<int> ShuffleMask = SVN->getMask();
5438
5439   SDValue V1 = Op.getOperand(0);
5440   SDValue V2 = Op.getOperand(1);
5441
5442   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5443                                        V1.getValueType().getSimpleVT())) {
5444     int Lane = SVN->getSplatIndex();
5445     // If this is undef splat, generate it via "just" vdup, if possible.
5446     if (Lane == -1)
5447       Lane = 0;
5448
5449     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5450       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5451                          V1.getOperand(0));
5452     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5453     // constant. If so, we can just reference the lane's definition directly.
5454     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5455         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5456       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5457
5458     // Otherwise, duplicate from the lane of the input vector.
5459     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5460
5461     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5462     // to make a vector of the same size as this SHUFFLE. We can ignore the
5463     // extract entirely, and canonicalise the concat using WidenVector.
5464     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5465       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5466       V1 = V1.getOperand(0);
5467     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5468       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5469       Lane -= Idx * VT.getVectorNumElements() / 2;
5470       V1 = WidenVector(V1.getOperand(Idx), DAG);
5471     } else if (VT.getSizeInBits() == 64)
5472       V1 = WidenVector(V1, DAG);
5473
5474     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5475   }
5476
5477   if (isREVMask(ShuffleMask, VT, 64))
5478     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5479   if (isREVMask(ShuffleMask, VT, 32))
5480     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5481   if (isREVMask(ShuffleMask, VT, 16))
5482     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5483
5484   bool ReverseEXT = false;
5485   unsigned Imm;
5486   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5487     if (ReverseEXT)
5488       std::swap(V1, V2);
5489     Imm *= getExtFactor(V1);
5490     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5491                        DAG.getConstant(Imm, dl, MVT::i32));
5492   } else if (V2->getOpcode() == ISD::UNDEF &&
5493              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5494     Imm *= getExtFactor(V1);
5495     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5496                        DAG.getConstant(Imm, dl, MVT::i32));
5497   }
5498
5499   unsigned WhichResult;
5500   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5501     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5502     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5503   }
5504   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5505     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5506     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5507   }
5508   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5509     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5510     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5511   }
5512
5513   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5514     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5515     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5516   }
5517   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5518     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5519     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5520   }
5521   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5522     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5523     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5524   }
5525
5526   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5527   if (Concat.getNode())
5528     return Concat;
5529
5530   bool DstIsLeft;
5531   int Anomaly;
5532   int NumInputElements = V1.getValueType().getVectorNumElements();
5533   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5534     SDValue DstVec = DstIsLeft ? V1 : V2;
5535     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5536
5537     SDValue SrcVec = V1;
5538     int SrcLane = ShuffleMask[Anomaly];
5539     if (SrcLane >= NumInputElements) {
5540       SrcVec = V2;
5541       SrcLane -= VT.getVectorNumElements();
5542     }
5543     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5544
5545     EVT ScalarVT = VT.getVectorElementType();
5546
5547     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5548       ScalarVT = MVT::i32;
5549
5550     return DAG.getNode(
5551         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5552         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5553         DstLaneV);
5554   }
5555
5556   // If the shuffle is not directly supported and it has 4 elements, use
5557   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5558   unsigned NumElts = VT.getVectorNumElements();
5559   if (NumElts == 4) {
5560     unsigned PFIndexes[4];
5561     for (unsigned i = 0; i != 4; ++i) {
5562       if (ShuffleMask[i] < 0)
5563         PFIndexes[i] = 8;
5564       else
5565         PFIndexes[i] = ShuffleMask[i];
5566     }
5567
5568     // Compute the index in the perfect shuffle table.
5569     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5570                             PFIndexes[2] * 9 + PFIndexes[3];
5571     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5572     unsigned Cost = (PFEntry >> 30);
5573
5574     if (Cost <= 4)
5575       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5576   }
5577
5578   return GenerateTBL(Op, ShuffleMask, DAG);
5579 }
5580
5581 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5582                                APInt &UndefBits) {
5583   EVT VT = BVN->getValueType(0);
5584   APInt SplatBits, SplatUndef;
5585   unsigned SplatBitSize;
5586   bool HasAnyUndefs;
5587   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5588     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5589
5590     for (unsigned i = 0; i < NumSplats; ++i) {
5591       CnstBits <<= SplatBitSize;
5592       UndefBits <<= SplatBitSize;
5593       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5594       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5595     }
5596
5597     return true;
5598   }
5599
5600   return false;
5601 }
5602
5603 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5604                                               SelectionDAG &DAG) const {
5605   BuildVectorSDNode *BVN =
5606       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5607   SDValue LHS = Op.getOperand(0);
5608   SDLoc dl(Op);
5609   EVT VT = Op.getValueType();
5610
5611   if (!BVN)
5612     return Op;
5613
5614   APInt CnstBits(VT.getSizeInBits(), 0);
5615   APInt UndefBits(VT.getSizeInBits(), 0);
5616   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5617     // We only have BIC vector immediate instruction, which is and-not.
5618     CnstBits = ~CnstBits;
5619
5620     // We make use of a little bit of goto ickiness in order to avoid having to
5621     // duplicate the immediate matching logic for the undef toggled case.
5622     bool SecondTry = false;
5623   AttemptModImm:
5624
5625     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5626       CnstBits = CnstBits.zextOrTrunc(64);
5627       uint64_t CnstVal = CnstBits.getZExtValue();
5628
5629       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5630         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5631         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5632         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5633                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5634                                   DAG.getConstant(0, dl, MVT::i32));
5635         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5636       }
5637
5638       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5639         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5640         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5641         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5642                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5643                                   DAG.getConstant(8, dl, MVT::i32));
5644         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5645       }
5646
5647       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5648         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5649         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5650         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5651                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5652                                   DAG.getConstant(16, dl, MVT::i32));
5653         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5654       }
5655
5656       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5657         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5658         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5659         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5660                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5661                                   DAG.getConstant(24, dl, MVT::i32));
5662         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5663       }
5664
5665       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5666         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5667         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5668         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5669                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5670                                   DAG.getConstant(0, dl, MVT::i32));
5671         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5672       }
5673
5674       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5675         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5676         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5677         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5678                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5679                                   DAG.getConstant(8, dl, MVT::i32));
5680         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5681       }
5682     }
5683
5684     if (SecondTry)
5685       goto FailedModImm;
5686     SecondTry = true;
5687     CnstBits = ~UndefBits;
5688     goto AttemptModImm;
5689   }
5690
5691 // We can always fall back to a non-immediate AND.
5692 FailedModImm:
5693   return Op;
5694 }
5695
5696 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5697 // consists of only the same constant int value, returned in reference arg
5698 // ConstVal
5699 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5700                                      uint64_t &ConstVal) {
5701   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5702   if (!Bvec)
5703     return false;
5704   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5705   if (!FirstElt)
5706     return false;
5707   EVT VT = Bvec->getValueType(0);
5708   unsigned NumElts = VT.getVectorNumElements();
5709   for (unsigned i = 1; i < NumElts; ++i)
5710     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5711       return false;
5712   ConstVal = FirstElt->getZExtValue();
5713   return true;
5714 }
5715
5716 static unsigned getIntrinsicID(const SDNode *N) {
5717   unsigned Opcode = N->getOpcode();
5718   switch (Opcode) {
5719   default:
5720     return Intrinsic::not_intrinsic;
5721   case ISD::INTRINSIC_WO_CHAIN: {
5722     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5723     if (IID < Intrinsic::num_intrinsics)
5724       return IID;
5725     return Intrinsic::not_intrinsic;
5726   }
5727   }
5728 }
5729
5730 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5731 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5732 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5733 // Also, logical shift right -> sri, with the same structure.
5734 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5735   EVT VT = N->getValueType(0);
5736
5737   if (!VT.isVector())
5738     return SDValue();
5739
5740   SDLoc DL(N);
5741
5742   // Is the first op an AND?
5743   const SDValue And = N->getOperand(0);
5744   if (And.getOpcode() != ISD::AND)
5745     return SDValue();
5746
5747   // Is the second op an shl or lshr?
5748   SDValue Shift = N->getOperand(1);
5749   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5750   // or AArch64ISD::VLSHR vector, #shift
5751   unsigned ShiftOpc = Shift.getOpcode();
5752   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5753     return SDValue();
5754   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5755
5756   // Is the shift amount constant?
5757   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5758   if (!C2node)
5759     return SDValue();
5760
5761   // Is the and mask vector all constant?
5762   uint64_t C1;
5763   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5764     return SDValue();
5765
5766   // Is C1 == ~C2, taking into account how much one can shift elements of a
5767   // particular size?
5768   uint64_t C2 = C2node->getZExtValue();
5769   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5770   if (C2 > ElemSizeInBits)
5771     return SDValue();
5772   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5773   if ((C1 & ElemMask) != (~C2 & ElemMask))
5774     return SDValue();
5775
5776   SDValue X = And.getOperand(0);
5777   SDValue Y = Shift.getOperand(0);
5778
5779   unsigned Intrin =
5780       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5781   SDValue ResultSLI =
5782       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5783                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5784                   Shift.getOperand(1));
5785
5786   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5787   DEBUG(N->dump(&DAG));
5788   DEBUG(dbgs() << "into: \n");
5789   DEBUG(ResultSLI->dump(&DAG));
5790
5791   ++NumShiftInserts;
5792   return ResultSLI;
5793 }
5794
5795 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5796                                              SelectionDAG &DAG) const {
5797   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5798   if (EnableAArch64SlrGeneration) {
5799     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5800     if (Res.getNode())
5801       return Res;
5802   }
5803
5804   BuildVectorSDNode *BVN =
5805       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5806   SDValue LHS = Op.getOperand(1);
5807   SDLoc dl(Op);
5808   EVT VT = Op.getValueType();
5809
5810   // OR commutes, so try swapping the operands.
5811   if (!BVN) {
5812     LHS = Op.getOperand(0);
5813     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5814   }
5815   if (!BVN)
5816     return Op;
5817
5818   APInt CnstBits(VT.getSizeInBits(), 0);
5819   APInt UndefBits(VT.getSizeInBits(), 0);
5820   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5821     // We make use of a little bit of goto ickiness in order to avoid having to
5822     // duplicate the immediate matching logic for the undef toggled case.
5823     bool SecondTry = false;
5824   AttemptModImm:
5825
5826     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5827       CnstBits = CnstBits.zextOrTrunc(64);
5828       uint64_t CnstVal = CnstBits.getZExtValue();
5829
5830       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5831         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5832         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5833         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5834                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5835                                   DAG.getConstant(0, dl, MVT::i32));
5836         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5837       }
5838
5839       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5840         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5841         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5842         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5843                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5844                                   DAG.getConstant(8, dl, MVT::i32));
5845         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5846       }
5847
5848       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5849         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5850         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5851         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5852                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5853                                   DAG.getConstant(16, dl, MVT::i32));
5854         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5855       }
5856
5857       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5858         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5859         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5860         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5861                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5862                                   DAG.getConstant(24, dl, MVT::i32));
5863         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5864       }
5865
5866       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5867         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5868         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5869         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5870                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5871                                   DAG.getConstant(0, dl, MVT::i32));
5872         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5873       }
5874
5875       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5876         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5877         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5878         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5879                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5880                                   DAG.getConstant(8, dl, MVT::i32));
5881         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5882       }
5883     }
5884
5885     if (SecondTry)
5886       goto FailedModImm;
5887     SecondTry = true;
5888     CnstBits = UndefBits;
5889     goto AttemptModImm;
5890   }
5891
5892 // We can always fall back to a non-immediate OR.
5893 FailedModImm:
5894   return Op;
5895 }
5896
5897 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5898 // be truncated to fit element width.
5899 static SDValue NormalizeBuildVector(SDValue Op,
5900                                     SelectionDAG &DAG) {
5901   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5902   SDLoc dl(Op);
5903   EVT VT = Op.getValueType();
5904   EVT EltTy= VT.getVectorElementType();
5905
5906   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5907     return Op;
5908
5909   SmallVector<SDValue, 16> Ops;
5910   for (SDValue Lane : Op->ops()) {
5911     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5912       APInt LowBits(EltTy.getSizeInBits(),
5913                     CstLane->getZExtValue());
5914       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5915     }
5916     Ops.push_back(Lane);
5917   }
5918   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5919 }
5920
5921 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5922                                                  SelectionDAG &DAG) const {
5923   SDLoc dl(Op);
5924   EVT VT = Op.getValueType();
5925   Op = NormalizeBuildVector(Op, DAG);
5926   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5927
5928   APInt CnstBits(VT.getSizeInBits(), 0);
5929   APInt UndefBits(VT.getSizeInBits(), 0);
5930   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5931     // We make use of a little bit of goto ickiness in order to avoid having to
5932     // duplicate the immediate matching logic for the undef toggled case.
5933     bool SecondTry = false;
5934   AttemptModImm:
5935
5936     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5937       CnstBits = CnstBits.zextOrTrunc(64);
5938       uint64_t CnstVal = CnstBits.getZExtValue();
5939
5940       // Certain magic vector constants (used to express things like NOT
5941       // and NEG) are passed through unmodified.  This allows codegen patterns
5942       // for these operations to match.  Special-purpose patterns will lower
5943       // these immediates to MOVIs if it proves necessary.
5944       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5945         return Op;
5946
5947       // The many faces of MOVI...
5948       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5949         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5950         if (VT.getSizeInBits() == 128) {
5951           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5952                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5953           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5954         }
5955
5956         // Support the V64 version via subregister insertion.
5957         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5958                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5959         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5960       }
5961
5962       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5963         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5964         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5965         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5966                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5967                                   DAG.getConstant(0, dl, MVT::i32));
5968         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5969       }
5970
5971       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5972         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5973         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5974         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5975                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5976                                   DAG.getConstant(8, dl, MVT::i32));
5977         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5978       }
5979
5980       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5981         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5982         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5983         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5984                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5985                                   DAG.getConstant(16, dl, MVT::i32));
5986         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5987       }
5988
5989       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5990         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5991         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5992         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5993                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5994                                   DAG.getConstant(24, dl, MVT::i32));
5995         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5996       }
5997
5998       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5999         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6000         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6001         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6002                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6003                                   DAG.getConstant(0, dl, MVT::i32));
6004         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6005       }
6006
6007       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6008         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6009         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6010         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6011                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6012                                   DAG.getConstant(8, dl, MVT::i32));
6013         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6014       }
6015
6016       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6017         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6018         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6019         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6020                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6021                                   DAG.getConstant(264, dl, MVT::i32));
6022         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6023       }
6024
6025       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6026         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6027         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6028         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6029                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6030                                   DAG.getConstant(272, dl, MVT::i32));
6031         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6032       }
6033
6034       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6035         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6036         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6037         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6038                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6039         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6040       }
6041
6042       // The few faces of FMOV...
6043       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6044         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6045         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6046         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6047                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6048         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6049       }
6050
6051       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6052           VT.getSizeInBits() == 128) {
6053         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6054         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6055                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6056         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6057       }
6058
6059       // The many faces of MVNI...
6060       CnstVal = ~CnstVal;
6061       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6062         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6063         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6064         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6065                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6066                                   DAG.getConstant(0, dl, MVT::i32));
6067         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6068       }
6069
6070       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6071         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6072         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6073         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6074                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6075                                   DAG.getConstant(8, dl, MVT::i32));
6076         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6077       }
6078
6079       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6080         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6081         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6082         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6083                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6084                                   DAG.getConstant(16, dl, MVT::i32));
6085         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6086       }
6087
6088       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6089         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6090         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6091         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6092                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6093                                   DAG.getConstant(24, dl, MVT::i32));
6094         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6095       }
6096
6097       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6098         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6099         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6100         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6101                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6102                                   DAG.getConstant(0, dl, MVT::i32));
6103         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6104       }
6105
6106       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6107         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6108         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6109         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6110                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6111                                   DAG.getConstant(8, dl, MVT::i32));
6112         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6113       }
6114
6115       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6116         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6117         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6118         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6119                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6120                                   DAG.getConstant(264, dl, MVT::i32));
6121         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6122       }
6123
6124       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6125         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6126         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6127         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6128                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6129                                   DAG.getConstant(272, dl, MVT::i32));
6130         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6131       }
6132     }
6133
6134     if (SecondTry)
6135       goto FailedModImm;
6136     SecondTry = true;
6137     CnstBits = UndefBits;
6138     goto AttemptModImm;
6139   }
6140 FailedModImm:
6141
6142   // Scan through the operands to find some interesting properties we can
6143   // exploit:
6144   //   1) If only one value is used, we can use a DUP, or
6145   //   2) if only the low element is not undef, we can just insert that, or
6146   //   3) if only one constant value is used (w/ some non-constant lanes),
6147   //      we can splat the constant value into the whole vector then fill
6148   //      in the non-constant lanes.
6149   //   4) FIXME: If different constant values are used, but we can intelligently
6150   //             select the values we'll be overwriting for the non-constant
6151   //             lanes such that we can directly materialize the vector
6152   //             some other way (MOVI, e.g.), we can be sneaky.
6153   unsigned NumElts = VT.getVectorNumElements();
6154   bool isOnlyLowElement = true;
6155   bool usesOnlyOneValue = true;
6156   bool usesOnlyOneConstantValue = true;
6157   bool isConstant = true;
6158   unsigned NumConstantLanes = 0;
6159   SDValue Value;
6160   SDValue ConstantValue;
6161   for (unsigned i = 0; i < NumElts; ++i) {
6162     SDValue V = Op.getOperand(i);
6163     if (V.getOpcode() == ISD::UNDEF)
6164       continue;
6165     if (i > 0)
6166       isOnlyLowElement = false;
6167     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6168       isConstant = false;
6169
6170     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6171       ++NumConstantLanes;
6172       if (!ConstantValue.getNode())
6173         ConstantValue = V;
6174       else if (ConstantValue != V)
6175         usesOnlyOneConstantValue = false;
6176     }
6177
6178     if (!Value.getNode())
6179       Value = V;
6180     else if (V != Value)
6181       usesOnlyOneValue = false;
6182   }
6183
6184   if (!Value.getNode())
6185     return DAG.getUNDEF(VT);
6186
6187   if (isOnlyLowElement)
6188     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6189
6190   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6191   // i32 and try again.
6192   if (usesOnlyOneValue) {
6193     if (!isConstant) {
6194       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6195           Value.getValueType() != VT)
6196         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6197
6198       // This is actually a DUPLANExx operation, which keeps everything vectory.
6199
6200       // DUPLANE works on 128-bit vectors, widen it if necessary.
6201       SDValue Lane = Value.getOperand(1);
6202       Value = Value.getOperand(0);
6203       if (Value.getValueType().getSizeInBits() == 64)
6204         Value = WidenVector(Value, DAG);
6205
6206       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6207       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6208     }
6209
6210     if (VT.getVectorElementType().isFloatingPoint()) {
6211       SmallVector<SDValue, 8> Ops;
6212       EVT EltTy = VT.getVectorElementType();
6213       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6214               "Unsupported floating-point vector type");
6215       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6216       for (unsigned i = 0; i < NumElts; ++i)
6217         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6218       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6219       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6220       Val = LowerBUILD_VECTOR(Val, DAG);
6221       if (Val.getNode())
6222         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6223     }
6224   }
6225
6226   // If there was only one constant value used and for more than one lane,
6227   // start by splatting that value, then replace the non-constant lanes. This
6228   // is better than the default, which will perform a separate initialization
6229   // for each lane.
6230   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6231     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6232     // Now insert the non-constant lanes.
6233     for (unsigned i = 0; i < NumElts; ++i) {
6234       SDValue V = Op.getOperand(i);
6235       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6236       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6237         // Note that type legalization likely mucked about with the VT of the
6238         // source operand, so we may have to convert it here before inserting.
6239         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6240       }
6241     }
6242     return Val;
6243   }
6244
6245   // If all elements are constants and the case above didn't get hit, fall back
6246   // to the default expansion, which will generate a load from the constant
6247   // pool.
6248   if (isConstant)
6249     return SDValue();
6250
6251   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6252   if (NumElts >= 4) {
6253     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6254       return shuffle;
6255   }
6256
6257   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6258   // know the default expansion would otherwise fall back on something even
6259   // worse. For a vector with one or two non-undef values, that's
6260   // scalar_to_vector for the elements followed by a shuffle (provided the
6261   // shuffle is valid for the target) and materialization element by element
6262   // on the stack followed by a load for everything else.
6263   if (!isConstant && !usesOnlyOneValue) {
6264     SDValue Vec = DAG.getUNDEF(VT);
6265     SDValue Op0 = Op.getOperand(0);
6266     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6267     unsigned i = 0;
6268     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6269     // a) Avoid a RMW dependency on the full vector register, and
6270     // b) Allow the register coalescer to fold away the copy if the
6271     //    value is already in an S or D register.
6272     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6273     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6274     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6275         (ElemSize == 32 || ElemSize == 64)) {
6276       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6277       MachineSDNode *N =
6278           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6279                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6280       Vec = SDValue(N, 0);
6281       ++i;
6282     }
6283     for (; i < NumElts; ++i) {
6284       SDValue V = Op.getOperand(i);
6285       if (V.getOpcode() == ISD::UNDEF)
6286         continue;
6287       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6288       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6289     }
6290     return Vec;
6291   }
6292
6293   // Just use the default expansion. We failed to find a better alternative.
6294   return SDValue();
6295 }
6296
6297 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6298                                                       SelectionDAG &DAG) const {
6299   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6300
6301   // Check for non-constant or out of range lane.
6302   EVT VT = Op.getOperand(0).getValueType();
6303   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6304   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6305     return SDValue();
6306
6307
6308   // Insertion/extraction are legal for V128 types.
6309   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6310       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6311       VT == MVT::v8f16)
6312     return Op;
6313
6314   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6315       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6316     return SDValue();
6317
6318   // For V64 types, we perform insertion by expanding the value
6319   // to a V128 type and perform the insertion on that.
6320   SDLoc DL(Op);
6321   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6322   EVT WideTy = WideVec.getValueType();
6323
6324   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6325                              Op.getOperand(1), Op.getOperand(2));
6326   // Re-narrow the resultant vector.
6327   return NarrowVector(Node, DAG);
6328 }
6329
6330 SDValue
6331 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6332                                                SelectionDAG &DAG) const {
6333   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6334
6335   // Check for non-constant or out of range lane.
6336   EVT VT = Op.getOperand(0).getValueType();
6337   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6338   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6339     return SDValue();
6340
6341
6342   // Insertion/extraction are legal for V128 types.
6343   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6344       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6345       VT == MVT::v8f16)
6346     return Op;
6347
6348   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6349       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6350     return SDValue();
6351
6352   // For V64 types, we perform extraction by expanding the value
6353   // to a V128 type and perform the extraction on that.
6354   SDLoc DL(Op);
6355   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6356   EVT WideTy = WideVec.getValueType();
6357
6358   EVT ExtrTy = WideTy.getVectorElementType();
6359   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6360     ExtrTy = MVT::i32;
6361
6362   // For extractions, we just return the result directly.
6363   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6364                      Op.getOperand(1));
6365 }
6366
6367 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6368                                                       SelectionDAG &DAG) const {
6369   EVT VT = Op.getOperand(0).getValueType();
6370   SDLoc dl(Op);
6371   // Just in case...
6372   if (!VT.isVector())
6373     return SDValue();
6374
6375   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6376   if (!Cst)
6377     return SDValue();
6378   unsigned Val = Cst->getZExtValue();
6379
6380   unsigned Size = Op.getValueType().getSizeInBits();
6381   if (Val == 0) {
6382     switch (Size) {
6383     case 8:
6384       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6385                                         Op.getOperand(0));
6386     case 16:
6387       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6388                                         Op.getOperand(0));
6389     case 32:
6390       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6391                                         Op.getOperand(0));
6392     case 64:
6393       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6394                                         Op.getOperand(0));
6395     default:
6396       llvm_unreachable("Unexpected vector type in extract_subvector!");
6397     }
6398   }
6399   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6400   // that directly.
6401   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6402     return Op;
6403
6404   return SDValue();
6405 }
6406
6407 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6408                                                EVT VT) const {
6409   if (VT.getVectorNumElements() == 4 &&
6410       (VT.is128BitVector() || VT.is64BitVector())) {
6411     unsigned PFIndexes[4];
6412     for (unsigned i = 0; i != 4; ++i) {
6413       if (M[i] < 0)
6414         PFIndexes[i] = 8;
6415       else
6416         PFIndexes[i] = M[i];
6417     }
6418
6419     // Compute the index in the perfect shuffle table.
6420     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6421                             PFIndexes[2] * 9 + PFIndexes[3];
6422     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6423     unsigned Cost = (PFEntry >> 30);
6424
6425     if (Cost <= 4)
6426       return true;
6427   }
6428
6429   bool DummyBool;
6430   int DummyInt;
6431   unsigned DummyUnsigned;
6432
6433   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6434           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6435           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6436           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6437           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6438           isZIPMask(M, VT, DummyUnsigned) ||
6439           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6440           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6441           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6442           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6443           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6444 }
6445
6446 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6447 /// operand of a vector shift operation, where all the elements of the
6448 /// build_vector must have the same constant integer value.
6449 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6450   // Ignore bit_converts.
6451   while (Op.getOpcode() == ISD::BITCAST)
6452     Op = Op.getOperand(0);
6453   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6454   APInt SplatBits, SplatUndef;
6455   unsigned SplatBitSize;
6456   bool HasAnyUndefs;
6457   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6458                                     HasAnyUndefs, ElementBits) ||
6459       SplatBitSize > ElementBits)
6460     return false;
6461   Cnt = SplatBits.getSExtValue();
6462   return true;
6463 }
6464
6465 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6466 /// operand of a vector shift left operation.  That value must be in the range:
6467 ///   0 <= Value < ElementBits for a left shift; or
6468 ///   0 <= Value <= ElementBits for a long left shift.
6469 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6470   assert(VT.isVector() && "vector shift count is not a vector type");
6471   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6472   if (!getVShiftImm(Op, ElementBits, Cnt))
6473     return false;
6474   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6475 }
6476
6477 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6478 /// operand of a vector shift right operation. The value must be in the range:
6479 ///   1 <= Value <= ElementBits for a right shift; or
6480 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6481   assert(VT.isVector() && "vector shift count is not a vector type");
6482   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6483   if (!getVShiftImm(Op, ElementBits, Cnt))
6484     return false;
6485   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6486 }
6487
6488 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6489                                                       SelectionDAG &DAG) const {
6490   EVT VT = Op.getValueType();
6491   SDLoc DL(Op);
6492   int64_t Cnt;
6493
6494   if (!Op.getOperand(1).getValueType().isVector())
6495     return Op;
6496   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6497
6498   switch (Op.getOpcode()) {
6499   default:
6500     llvm_unreachable("unexpected shift opcode");
6501
6502   case ISD::SHL:
6503     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6504       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6505                          DAG.getConstant(Cnt, DL, MVT::i32));
6506     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6507                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6508                                        MVT::i32),
6509                        Op.getOperand(0), Op.getOperand(1));
6510   case ISD::SRA:
6511   case ISD::SRL:
6512     // Right shift immediate
6513     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6514       unsigned Opc =
6515           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6516       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6517                          DAG.getConstant(Cnt, DL, MVT::i32));
6518     }
6519
6520     // Right shift register.  Note, there is not a shift right register
6521     // instruction, but the shift left register instruction takes a signed
6522     // value, where negative numbers specify a right shift.
6523     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6524                                                 : Intrinsic::aarch64_neon_ushl;
6525     // negate the shift amount
6526     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6527     SDValue NegShiftLeft =
6528         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6529                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6530                     NegShift);
6531     return NegShiftLeft;
6532   }
6533
6534   return SDValue();
6535 }
6536
6537 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6538                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6539                                     SDLoc dl, SelectionDAG &DAG) {
6540   EVT SrcVT = LHS.getValueType();
6541   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6542          "function only supposed to emit natural comparisons");
6543
6544   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6545   APInt CnstBits(VT.getSizeInBits(), 0);
6546   APInt UndefBits(VT.getSizeInBits(), 0);
6547   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6548   bool IsZero = IsCnst && (CnstBits == 0);
6549
6550   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6551     switch (CC) {
6552     default:
6553       return SDValue();
6554     case AArch64CC::NE: {
6555       SDValue Fcmeq;
6556       if (IsZero)
6557         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6558       else
6559         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6560       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6561     }
6562     case AArch64CC::EQ:
6563       if (IsZero)
6564         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6565       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6566     case AArch64CC::GE:
6567       if (IsZero)
6568         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6569       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6570     case AArch64CC::GT:
6571       if (IsZero)
6572         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6573       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6574     case AArch64CC::LS:
6575       if (IsZero)
6576         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6577       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6578     case AArch64CC::LT:
6579       if (!NoNans)
6580         return SDValue();
6581     // If we ignore NaNs then we can use to the MI implementation.
6582     // Fallthrough.
6583     case AArch64CC::MI:
6584       if (IsZero)
6585         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6586       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6587     }
6588   }
6589
6590   switch (CC) {
6591   default:
6592     return SDValue();
6593   case AArch64CC::NE: {
6594     SDValue Cmeq;
6595     if (IsZero)
6596       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6597     else
6598       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6599     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6600   }
6601   case AArch64CC::EQ:
6602     if (IsZero)
6603       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6604     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6605   case AArch64CC::GE:
6606     if (IsZero)
6607       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6608     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6609   case AArch64CC::GT:
6610     if (IsZero)
6611       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6612     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6613   case AArch64CC::LE:
6614     if (IsZero)
6615       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6616     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6617   case AArch64CC::LS:
6618     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6619   case AArch64CC::LO:
6620     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6621   case AArch64CC::LT:
6622     if (IsZero)
6623       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6624     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6625   case AArch64CC::HI:
6626     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6627   case AArch64CC::HS:
6628     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6629   }
6630 }
6631
6632 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6633                                            SelectionDAG &DAG) const {
6634   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6635   SDValue LHS = Op.getOperand(0);
6636   SDValue RHS = Op.getOperand(1);
6637   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6638   SDLoc dl(Op);
6639
6640   if (LHS.getValueType().getVectorElementType().isInteger()) {
6641     assert(LHS.getValueType() == RHS.getValueType());
6642     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6643     SDValue Cmp =
6644         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6645     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6646   }
6647
6648   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6649          LHS.getValueType().getVectorElementType() == MVT::f64);
6650
6651   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6652   // clean.  Some of them require two branches to implement.
6653   AArch64CC::CondCode CC1, CC2;
6654   bool ShouldInvert;
6655   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6656
6657   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6658   SDValue Cmp =
6659       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6660   if (!Cmp.getNode())
6661     return SDValue();
6662
6663   if (CC2 != AArch64CC::AL) {
6664     SDValue Cmp2 =
6665         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6666     if (!Cmp2.getNode())
6667       return SDValue();
6668
6669     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6670   }
6671
6672   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6673
6674   if (ShouldInvert)
6675     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6676
6677   return Cmp;
6678 }
6679
6680 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6681 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6682 /// specified in the intrinsic calls.
6683 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6684                                                const CallInst &I,
6685                                                unsigned Intrinsic) const {
6686   auto &DL = I.getModule()->getDataLayout();
6687   switch (Intrinsic) {
6688   case Intrinsic::aarch64_neon_ld2:
6689   case Intrinsic::aarch64_neon_ld3:
6690   case Intrinsic::aarch64_neon_ld4:
6691   case Intrinsic::aarch64_neon_ld1x2:
6692   case Intrinsic::aarch64_neon_ld1x3:
6693   case Intrinsic::aarch64_neon_ld1x4:
6694   case Intrinsic::aarch64_neon_ld2lane:
6695   case Intrinsic::aarch64_neon_ld3lane:
6696   case Intrinsic::aarch64_neon_ld4lane:
6697   case Intrinsic::aarch64_neon_ld2r:
6698   case Intrinsic::aarch64_neon_ld3r:
6699   case Intrinsic::aarch64_neon_ld4r: {
6700     Info.opc = ISD::INTRINSIC_W_CHAIN;
6701     // Conservatively set memVT to the entire set of vectors loaded.
6702     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6703     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6704     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6705     Info.offset = 0;
6706     Info.align = 0;
6707     Info.vol = false; // volatile loads with NEON intrinsics not supported
6708     Info.readMem = true;
6709     Info.writeMem = false;
6710     return true;
6711   }
6712   case Intrinsic::aarch64_neon_st2:
6713   case Intrinsic::aarch64_neon_st3:
6714   case Intrinsic::aarch64_neon_st4:
6715   case Intrinsic::aarch64_neon_st1x2:
6716   case Intrinsic::aarch64_neon_st1x3:
6717   case Intrinsic::aarch64_neon_st1x4:
6718   case Intrinsic::aarch64_neon_st2lane:
6719   case Intrinsic::aarch64_neon_st3lane:
6720   case Intrinsic::aarch64_neon_st4lane: {
6721     Info.opc = ISD::INTRINSIC_VOID;
6722     // Conservatively set memVT to the entire set of vectors stored.
6723     unsigned NumElts = 0;
6724     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6725       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6726       if (!ArgTy->isVectorTy())
6727         break;
6728       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6729     }
6730     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6731     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6732     Info.offset = 0;
6733     Info.align = 0;
6734     Info.vol = false; // volatile stores with NEON intrinsics not supported
6735     Info.readMem = false;
6736     Info.writeMem = true;
6737     return true;
6738   }
6739   case Intrinsic::aarch64_ldaxr:
6740   case Intrinsic::aarch64_ldxr: {
6741     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6742     Info.opc = ISD::INTRINSIC_W_CHAIN;
6743     Info.memVT = MVT::getVT(PtrTy->getElementType());
6744     Info.ptrVal = I.getArgOperand(0);
6745     Info.offset = 0;
6746     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6747     Info.vol = true;
6748     Info.readMem = true;
6749     Info.writeMem = false;
6750     return true;
6751   }
6752   case Intrinsic::aarch64_stlxr:
6753   case Intrinsic::aarch64_stxr: {
6754     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6755     Info.opc = ISD::INTRINSIC_W_CHAIN;
6756     Info.memVT = MVT::getVT(PtrTy->getElementType());
6757     Info.ptrVal = I.getArgOperand(1);
6758     Info.offset = 0;
6759     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6760     Info.vol = true;
6761     Info.readMem = false;
6762     Info.writeMem = true;
6763     return true;
6764   }
6765   case Intrinsic::aarch64_ldaxp:
6766   case Intrinsic::aarch64_ldxp: {
6767     Info.opc = ISD::INTRINSIC_W_CHAIN;
6768     Info.memVT = MVT::i128;
6769     Info.ptrVal = I.getArgOperand(0);
6770     Info.offset = 0;
6771     Info.align = 16;
6772     Info.vol = true;
6773     Info.readMem = true;
6774     Info.writeMem = false;
6775     return true;
6776   }
6777   case Intrinsic::aarch64_stlxp:
6778   case Intrinsic::aarch64_stxp: {
6779     Info.opc = ISD::INTRINSIC_W_CHAIN;
6780     Info.memVT = MVT::i128;
6781     Info.ptrVal = I.getArgOperand(2);
6782     Info.offset = 0;
6783     Info.align = 16;
6784     Info.vol = true;
6785     Info.readMem = false;
6786     Info.writeMem = true;
6787     return true;
6788   }
6789   default:
6790     break;
6791   }
6792
6793   return false;
6794 }
6795
6796 // Truncations from 64-bit GPR to 32-bit GPR is free.
6797 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6798   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6799     return false;
6800   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6801   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6802   return NumBits1 > NumBits2;
6803 }
6804 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6805   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6806     return false;
6807   unsigned NumBits1 = VT1.getSizeInBits();
6808   unsigned NumBits2 = VT2.getSizeInBits();
6809   return NumBits1 > NumBits2;
6810 }
6811
6812 /// Check if it is profitable to hoist instruction in then/else to if.
6813 /// Not profitable if I and it's user can form a FMA instruction
6814 /// because we prefer FMSUB/FMADD.
6815 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6816   if (I->getOpcode() != Instruction::FMul)
6817     return true;
6818
6819   if (I->getNumUses() != 1)
6820     return true;
6821
6822   Instruction *User = I->user_back();
6823
6824   if (User &&
6825       !(User->getOpcode() == Instruction::FSub ||
6826         User->getOpcode() == Instruction::FAdd))
6827     return true;
6828
6829   const TargetOptions &Options = getTargetMachine().Options;
6830   const DataLayout &DL = I->getModule()->getDataLayout();
6831   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6832
6833   if (isFMAFasterThanFMulAndFAdd(VT) &&
6834       isOperationLegalOrCustom(ISD::FMA, VT) &&
6835       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6836     return false;
6837
6838   return true;
6839 }
6840
6841 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6842 // 64-bit GPR.
6843 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6844   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6845     return false;
6846   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6847   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6848   return NumBits1 == 32 && NumBits2 == 64;
6849 }
6850 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6851   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6852     return false;
6853   unsigned NumBits1 = VT1.getSizeInBits();
6854   unsigned NumBits2 = VT2.getSizeInBits();
6855   return NumBits1 == 32 && NumBits2 == 64;
6856 }
6857
6858 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6859   EVT VT1 = Val.getValueType();
6860   if (isZExtFree(VT1, VT2)) {
6861     return true;
6862   }
6863
6864   if (Val.getOpcode() != ISD::LOAD)
6865     return false;
6866
6867   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6868   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6869           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6870           VT1.getSizeInBits() <= 32);
6871 }
6872
6873 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6874   if (isa<FPExtInst>(Ext))
6875     return false;
6876
6877   // Vector types are next free.
6878   if (Ext->getType()->isVectorTy())
6879     return false;
6880
6881   for (const Use &U : Ext->uses()) {
6882     // The extension is free if we can fold it with a left shift in an
6883     // addressing mode or an arithmetic operation: add, sub, and cmp.
6884
6885     // Is there a shift?
6886     const Instruction *Instr = cast<Instruction>(U.getUser());
6887
6888     // Is this a constant shift?
6889     switch (Instr->getOpcode()) {
6890     case Instruction::Shl:
6891       if (!isa<ConstantInt>(Instr->getOperand(1)))
6892         return false;
6893       break;
6894     case Instruction::GetElementPtr: {
6895       gep_type_iterator GTI = gep_type_begin(Instr);
6896       auto &DL = Ext->getModule()->getDataLayout();
6897       std::advance(GTI, U.getOperandNo());
6898       Type *IdxTy = *GTI;
6899       // This extension will end up with a shift because of the scaling factor.
6900       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6901       // Get the shift amount based on the scaling factor:
6902       // log2(sizeof(IdxTy)) - log2(8).
6903       uint64_t ShiftAmt =
6904           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6905       // Is the constant foldable in the shift of the addressing mode?
6906       // I.e., shift amount is between 1 and 4 inclusive.
6907       if (ShiftAmt == 0 || ShiftAmt > 4)
6908         return false;
6909       break;
6910     }
6911     case Instruction::Trunc:
6912       // Check if this is a noop.
6913       // trunc(sext ty1 to ty2) to ty1.
6914       if (Instr->getType() == Ext->getOperand(0)->getType())
6915         continue;
6916     // FALL THROUGH.
6917     default:
6918       return false;
6919     }
6920
6921     // At this point we can use the bfm family, so this extension is free
6922     // for that use.
6923   }
6924   return true;
6925 }
6926
6927 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6928                                           unsigned &RequiredAligment) const {
6929   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6930     return false;
6931   // Cyclone supports unaligned accesses.
6932   RequiredAligment = 0;
6933   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6934   return NumBits == 32 || NumBits == 64;
6935 }
6936
6937 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6938                                           unsigned &RequiredAligment) const {
6939   if (!LoadedType.isSimple() ||
6940       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6941     return false;
6942   // Cyclone supports unaligned accesses.
6943   RequiredAligment = 0;
6944   unsigned NumBits = LoadedType.getSizeInBits();
6945   return NumBits == 32 || NumBits == 64;
6946 }
6947
6948 /// \brief Lower an interleaved load into a ldN intrinsic.
6949 ///
6950 /// E.g. Lower an interleaved load (Factor = 2):
6951 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6952 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
6953 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
6954 ///
6955 ///      Into:
6956 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6957 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6958 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6959 bool AArch64TargetLowering::lowerInterleavedLoad(
6960     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6961     ArrayRef<unsigned> Indices, unsigned Factor) const {
6962   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6963          "Invalid interleave factor");
6964   assert(!Shuffles.empty() && "Empty shufflevector input");
6965   assert(Shuffles.size() == Indices.size() &&
6966          "Unmatched number of shufflevectors and indices");
6967
6968   const DataLayout &DL = LI->getModule()->getDataLayout();
6969
6970   VectorType *VecTy = Shuffles[0]->getType();
6971   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6972
6973   // Skip illegal vector types.
6974   if (VecSize != 64 && VecSize != 128)
6975     return false;
6976
6977   // A pointer vector can not be the return type of the ldN intrinsics. Need to
6978   // load integer vectors first and then convert to pointer vectors.
6979   Type *EltTy = VecTy->getVectorElementType();
6980   if (EltTy->isPointerTy())
6981     VecTy =
6982         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6983
6984   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6985   Type *Tys[2] = {VecTy, PtrTy};
6986   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6987                                             Intrinsic::aarch64_neon_ld3,
6988                                             Intrinsic::aarch64_neon_ld4};
6989   Function *LdNFunc =
6990       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6991
6992   IRBuilder<> Builder(LI);
6993   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6994
6995   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6996
6997   // Replace uses of each shufflevector with the corresponding vector loaded
6998   // by ldN.
6999   for (unsigned i = 0; i < Shuffles.size(); i++) {
7000     ShuffleVectorInst *SVI = Shuffles[i];
7001     unsigned Index = Indices[i];
7002
7003     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7004
7005     // Convert the integer vector to pointer vector if the element is pointer.
7006     if (EltTy->isPointerTy())
7007       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7008
7009     SVI->replaceAllUsesWith(SubVec);
7010   }
7011
7012   return true;
7013 }
7014
7015 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7016 ///
7017 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7018 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7019                                    unsigned NumElts) {
7020   SmallVector<Constant *, 16> Mask;
7021   for (unsigned i = 0; i < NumElts; i++)
7022     Mask.push_back(Builder.getInt32(Start + i));
7023
7024   return ConstantVector::get(Mask);
7025 }
7026
7027 /// \brief Lower an interleaved store into a stN intrinsic.
7028 ///
7029 /// E.g. Lower an interleaved store (Factor = 3):
7030 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7031 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7032 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7033 ///
7034 ///      Into:
7035 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7036 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7037 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7038 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7039 ///
7040 /// Note that the new shufflevectors will be removed and we'll only generate one
7041 /// st3 instruction in CodeGen.
7042 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7043                                                   ShuffleVectorInst *SVI,
7044                                                   unsigned Factor) const {
7045   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7046          "Invalid interleave factor");
7047
7048   VectorType *VecTy = SVI->getType();
7049   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7050          "Invalid interleaved store");
7051
7052   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7053   Type *EltTy = VecTy->getVectorElementType();
7054   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7055
7056   const DataLayout &DL = SI->getModule()->getDataLayout();
7057   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7058
7059   // Skip illegal vector types.
7060   if (SubVecSize != 64 && SubVecSize != 128)
7061     return false;
7062
7063   Value *Op0 = SVI->getOperand(0);
7064   Value *Op1 = SVI->getOperand(1);
7065   IRBuilder<> Builder(SI);
7066
7067   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7068   // vectors to integer vectors.
7069   if (EltTy->isPointerTy()) {
7070     Type *IntTy = DL.getIntPtrType(EltTy);
7071     unsigned NumOpElts =
7072         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7073
7074     // Convert to the corresponding integer vector.
7075     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7076     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7077     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7078
7079     SubVecTy = VectorType::get(IntTy, NumSubElts);
7080   }
7081
7082   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7083   Type *Tys[2] = {SubVecTy, PtrTy};
7084   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7085                                              Intrinsic::aarch64_neon_st3,
7086                                              Intrinsic::aarch64_neon_st4};
7087   Function *StNFunc =
7088       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7089
7090   SmallVector<Value *, 5> Ops;
7091
7092   // Split the shufflevector operands into sub vectors for the new stN call.
7093   for (unsigned i = 0; i < Factor; i++)
7094     Ops.push_back(Builder.CreateShuffleVector(
7095         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7096
7097   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7098   Builder.CreateCall(StNFunc, Ops);
7099   return true;
7100 }
7101
7102 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7103                        unsigned AlignCheck) {
7104   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7105           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7106 }
7107
7108 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7109                                                unsigned SrcAlign, bool IsMemset,
7110                                                bool ZeroMemset,
7111                                                bool MemcpyStrSrc,
7112                                                MachineFunction &MF) const {
7113   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7114   // instruction to materialize the v2i64 zero and one store (with restrictive
7115   // addressing mode). Just do two i64 store of zero-registers.
7116   bool Fast;
7117   const Function *F = MF.getFunction();
7118   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7119       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7120       (memOpAlign(SrcAlign, DstAlign, 16) ||
7121        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7122     return MVT::f128;
7123
7124   if (Size >= 8 &&
7125       (memOpAlign(SrcAlign, DstAlign, 8) ||
7126        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7127     return MVT::i64;
7128
7129   if (Size >= 4 &&
7130       (memOpAlign(SrcAlign, DstAlign, 4) ||
7131        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7132     return MVT::i32;
7133
7134   return MVT::Other;
7135 }
7136
7137 // 12-bit optionally shifted immediates are legal for adds.
7138 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7139   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7140     return true;
7141   return false;
7142 }
7143
7144 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7145 // immediates is the same as for an add or a sub.
7146 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7147   if (Immed < 0)
7148     Immed *= -1;
7149   return isLegalAddImmediate(Immed);
7150 }
7151
7152 /// isLegalAddressingMode - Return true if the addressing mode represented
7153 /// by AM is legal for this target, for a load/store of the specified type.
7154 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7155                                                   const AddrMode &AM, Type *Ty,
7156                                                   unsigned AS) const {
7157   // AArch64 has five basic addressing modes:
7158   //  reg
7159   //  reg + 9-bit signed offset
7160   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7161   //  reg1 + reg2
7162   //  reg + SIZE_IN_BYTES * reg
7163
7164   // No global is ever allowed as a base.
7165   if (AM.BaseGV)
7166     return false;
7167
7168   // No reg+reg+imm addressing.
7169   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7170     return false;
7171
7172   // check reg + imm case:
7173   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7174   uint64_t NumBytes = 0;
7175   if (Ty->isSized()) {
7176     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7177     NumBytes = NumBits / 8;
7178     if (!isPowerOf2_64(NumBits))
7179       NumBytes = 0;
7180   }
7181
7182   if (!AM.Scale) {
7183     int64_t Offset = AM.BaseOffs;
7184
7185     // 9-bit signed offset
7186     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7187       return true;
7188
7189     // 12-bit unsigned offset
7190     unsigned shift = Log2_64(NumBytes);
7191     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7192         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7193         (Offset >> shift) << shift == Offset)
7194       return true;
7195     return false;
7196   }
7197
7198   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7199
7200   if (!AM.Scale || AM.Scale == 1 ||
7201       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7202     return true;
7203   return false;
7204 }
7205
7206 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7207                                                 const AddrMode &AM, Type *Ty,
7208                                                 unsigned AS) const {
7209   // Scaling factors are not free at all.
7210   // Operands                     | Rt Latency
7211   // -------------------------------------------
7212   // Rt, [Xn, Xm]                 | 4
7213   // -------------------------------------------
7214   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7215   // Rt, [Xn, Wm, <extend> #imm]  |
7216   if (isLegalAddressingMode(DL, AM, Ty, AS))
7217     // Scale represents reg2 * scale, thus account for 1 if
7218     // it is not equal to 0 or 1.
7219     return AM.Scale != 0 && AM.Scale != 1;
7220   return -1;
7221 }
7222
7223 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7224   VT = VT.getScalarType();
7225
7226   if (!VT.isSimple())
7227     return false;
7228
7229   switch (VT.getSimpleVT().SimpleTy) {
7230   case MVT::f32:
7231   case MVT::f64:
7232     return true;
7233   default:
7234     break;
7235   }
7236
7237   return false;
7238 }
7239
7240 const MCPhysReg *
7241 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7242   // LR is a callee-save register, but we must treat it as clobbered by any call
7243   // site. Hence we include LR in the scratch registers, which are in turn added
7244   // as implicit-defs for stackmaps and patchpoints.
7245   static const MCPhysReg ScratchRegs[] = {
7246     AArch64::X16, AArch64::X17, AArch64::LR, 0
7247   };
7248   return ScratchRegs;
7249 }
7250
7251 bool
7252 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7253   EVT VT = N->getValueType(0);
7254     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7255     // it with shift to let it be lowered to UBFX.
7256   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7257       isa<ConstantSDNode>(N->getOperand(1))) {
7258     uint64_t TruncMask = N->getConstantOperandVal(1);
7259     if (isMask_64(TruncMask) &&
7260       N->getOperand(0).getOpcode() == ISD::SRL &&
7261       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7262       return false;
7263   }
7264   return true;
7265 }
7266
7267 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7268                                                               Type *Ty) const {
7269   assert(Ty->isIntegerTy());
7270
7271   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7272   if (BitSize == 0)
7273     return false;
7274
7275   int64_t Val = Imm.getSExtValue();
7276   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7277     return true;
7278
7279   if ((int64_t)Val < 0)
7280     Val = ~Val;
7281   if (BitSize == 32)
7282     Val &= (1LL << 32) - 1;
7283
7284   unsigned LZ = countLeadingZeros((uint64_t)Val);
7285   unsigned Shift = (63 - LZ) / 16;
7286   // MOVZ is free so return true for one or fewer MOVK.
7287   return Shift < 3;
7288 }
7289
7290 // Generate SUBS and CSEL for integer abs.
7291 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7292   EVT VT = N->getValueType(0);
7293
7294   SDValue N0 = N->getOperand(0);
7295   SDValue N1 = N->getOperand(1);
7296   SDLoc DL(N);
7297
7298   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7299   // and change it to SUB and CSEL.
7300   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7301       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7302       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7303     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7304       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7305         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7306                                   N0.getOperand(0));
7307         // Generate SUBS & CSEL.
7308         SDValue Cmp =
7309             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7310                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7311         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7312                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7313                            SDValue(Cmp.getNode(), 1));
7314       }
7315   return SDValue();
7316 }
7317
7318 // performXorCombine - Attempts to handle integer ABS.
7319 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7320                                  TargetLowering::DAGCombinerInfo &DCI,
7321                                  const AArch64Subtarget *Subtarget) {
7322   if (DCI.isBeforeLegalizeOps())
7323     return SDValue();
7324
7325   return performIntegerAbsCombine(N, DAG);
7326 }
7327
7328 SDValue
7329 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7330                                      SelectionDAG &DAG,
7331                                      std::vector<SDNode *> *Created) const {
7332   // fold (sdiv X, pow2)
7333   EVT VT = N->getValueType(0);
7334   if ((VT != MVT::i32 && VT != MVT::i64) ||
7335       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7336     return SDValue();
7337
7338   SDLoc DL(N);
7339   SDValue N0 = N->getOperand(0);
7340   unsigned Lg2 = Divisor.countTrailingZeros();
7341   SDValue Zero = DAG.getConstant(0, DL, VT);
7342   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7343
7344   // Add (N0 < 0) ? Pow2 - 1 : 0;
7345   SDValue CCVal;
7346   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7347   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7348   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7349
7350   if (Created) {
7351     Created->push_back(Cmp.getNode());
7352     Created->push_back(Add.getNode());
7353     Created->push_back(CSel.getNode());
7354   }
7355
7356   // Divide by pow2.
7357   SDValue SRA =
7358       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7359
7360   // If we're dividing by a positive value, we're done.  Otherwise, we must
7361   // negate the result.
7362   if (Divisor.isNonNegative())
7363     return SRA;
7364
7365   if (Created)
7366     Created->push_back(SRA.getNode());
7367   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7368 }
7369
7370 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7371                                  TargetLowering::DAGCombinerInfo &DCI,
7372                                  const AArch64Subtarget *Subtarget) {
7373   if (DCI.isBeforeLegalizeOps())
7374     return SDValue();
7375
7376   // Multiplication of a power of two plus/minus one can be done more
7377   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7378   // future CPUs have a cheaper MADD instruction, this may need to be
7379   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7380   // 64-bit is 5 cycles, so this is always a win.
7381   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7382     APInt Value = C->getAPIntValue();
7383     EVT VT = N->getValueType(0);
7384     SDLoc DL(N);
7385     if (Value.isNonNegative()) {
7386       // (mul x, 2^N + 1) => (add (shl x, N), x)
7387       APInt VM1 = Value - 1;
7388       if (VM1.isPowerOf2()) {
7389         SDValue ShiftedVal =
7390             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7391                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7392         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7393                            N->getOperand(0));
7394       }
7395       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7396       APInt VP1 = Value + 1;
7397       if (VP1.isPowerOf2()) {
7398         SDValue ShiftedVal =
7399             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7400                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7401         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7402                            N->getOperand(0));
7403       }
7404     } else {
7405       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7406       APInt VNP1 = -Value + 1;
7407       if (VNP1.isPowerOf2()) {
7408         SDValue ShiftedVal =
7409             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7410                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7411         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7412                            ShiftedVal);
7413       }
7414       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7415       APInt VNM1 = -Value - 1;
7416       if (VNM1.isPowerOf2()) {
7417         SDValue ShiftedVal =
7418             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7419                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7420         SDValue Add =
7421             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7422         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7423       }
7424     }
7425   }
7426   return SDValue();
7427 }
7428
7429 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7430                                                          SelectionDAG &DAG) {
7431   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7432   // optimize away operation when it's from a constant.
7433   //
7434   // The general transformation is:
7435   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7436   //       AND(VECTOR_CMP(x,y), constant2)
7437   //    constant2 = UNARYOP(constant)
7438
7439   // Early exit if this isn't a vector operation, the operand of the
7440   // unary operation isn't a bitwise AND, or if the sizes of the operations
7441   // aren't the same.
7442   EVT VT = N->getValueType(0);
7443   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7444       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7445       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7446     return SDValue();
7447
7448   // Now check that the other operand of the AND is a constant. We could
7449   // make the transformation for non-constant splats as well, but it's unclear
7450   // that would be a benefit as it would not eliminate any operations, just
7451   // perform one more step in scalar code before moving to the vector unit.
7452   if (BuildVectorSDNode *BV =
7453           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7454     // Bail out if the vector isn't a constant.
7455     if (!BV->isConstant())
7456       return SDValue();
7457
7458     // Everything checks out. Build up the new and improved node.
7459     SDLoc DL(N);
7460     EVT IntVT = BV->getValueType(0);
7461     // Create a new constant of the appropriate type for the transformed
7462     // DAG.
7463     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7464     // The AND node needs bitcasts to/from an integer vector type around it.
7465     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7466     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7467                                  N->getOperand(0)->getOperand(0), MaskConst);
7468     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7469     return Res;
7470   }
7471
7472   return SDValue();
7473 }
7474
7475 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7476                                      const AArch64Subtarget *Subtarget) {
7477   // First try to optimize away the conversion when it's conditionally from
7478   // a constant. Vectors only.
7479   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7480     return Res;
7481
7482   EVT VT = N->getValueType(0);
7483   if (VT != MVT::f32 && VT != MVT::f64)
7484     return SDValue();
7485
7486   // Only optimize when the source and destination types have the same width.
7487   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7488     return SDValue();
7489
7490   // If the result of an integer load is only used by an integer-to-float
7491   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7492   // This eliminates an "integer-to-vector-move UOP and improve throughput.
7493   SDValue N0 = N->getOperand(0);
7494   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7495       // Do not change the width of a volatile load.
7496       !cast<LoadSDNode>(N0)->isVolatile()) {
7497     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7498     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7499                                LN0->getPointerInfo(), LN0->isVolatile(),
7500                                LN0->isNonTemporal(), LN0->isInvariant(),
7501                                LN0->getAlignment());
7502
7503     // Make sure successors of the original load stay after it by updating them
7504     // to use the new Chain.
7505     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7506
7507     unsigned Opcode =
7508         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7509     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7510   }
7511
7512   return SDValue();
7513 }
7514
7515 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7516 /// searches for and classifies those shifts.
7517 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7518                          bool &FromHi) {
7519   if (N.getOpcode() == ISD::SHL)
7520     FromHi = false;
7521   else if (N.getOpcode() == ISD::SRL)
7522     FromHi = true;
7523   else
7524     return false;
7525
7526   if (!isa<ConstantSDNode>(N.getOperand(1)))
7527     return false;
7528
7529   ShiftAmount = N->getConstantOperandVal(1);
7530   Src = N->getOperand(0);
7531   return true;
7532 }
7533
7534 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7535 /// registers viewed as a high/low pair. This function looks for the pattern:
7536 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7537 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7538 /// independent.
7539 static SDValue tryCombineToEXTR(SDNode *N,
7540                                 TargetLowering::DAGCombinerInfo &DCI) {
7541   SelectionDAG &DAG = DCI.DAG;
7542   SDLoc DL(N);
7543   EVT VT = N->getValueType(0);
7544
7545   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7546
7547   if (VT != MVT::i32 && VT != MVT::i64)
7548     return SDValue();
7549
7550   SDValue LHS;
7551   uint32_t ShiftLHS = 0;
7552   bool LHSFromHi = 0;
7553   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7554     return SDValue();
7555
7556   SDValue RHS;
7557   uint32_t ShiftRHS = 0;
7558   bool RHSFromHi = 0;
7559   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7560     return SDValue();
7561
7562   // If they're both trying to come from the high part of the register, they're
7563   // not really an EXTR.
7564   if (LHSFromHi == RHSFromHi)
7565     return SDValue();
7566
7567   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7568     return SDValue();
7569
7570   if (LHSFromHi) {
7571     std::swap(LHS, RHS);
7572     std::swap(ShiftLHS, ShiftRHS);
7573   }
7574
7575   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7576                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7577 }
7578
7579 static SDValue tryCombineToBSL(SDNode *N,
7580                                 TargetLowering::DAGCombinerInfo &DCI) {
7581   EVT VT = N->getValueType(0);
7582   SelectionDAG &DAG = DCI.DAG;
7583   SDLoc DL(N);
7584
7585   if (!VT.isVector())
7586     return SDValue();
7587
7588   SDValue N0 = N->getOperand(0);
7589   if (N0.getOpcode() != ISD::AND)
7590     return SDValue();
7591
7592   SDValue N1 = N->getOperand(1);
7593   if (N1.getOpcode() != ISD::AND)
7594     return SDValue();
7595
7596   // We only have to look for constant vectors here since the general, variable
7597   // case can be handled in TableGen.
7598   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7599   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7600   for (int i = 1; i >= 0; --i)
7601     for (int j = 1; j >= 0; --j) {
7602       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7603       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7604       if (!BVN0 || !BVN1)
7605         continue;
7606
7607       bool FoundMatch = true;
7608       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7609         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7610         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7611         if (!CN0 || !CN1 ||
7612             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7613           FoundMatch = false;
7614           break;
7615         }
7616       }
7617
7618       if (FoundMatch)
7619         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7620                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7621     }
7622
7623   return SDValue();
7624 }
7625
7626 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7627                                 const AArch64Subtarget *Subtarget) {
7628   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7629   if (!EnableAArch64ExtrGeneration)
7630     return SDValue();
7631   SelectionDAG &DAG = DCI.DAG;
7632   EVT VT = N->getValueType(0);
7633
7634   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7635     return SDValue();
7636
7637   SDValue Res = tryCombineToEXTR(N, DCI);
7638   if (Res.getNode())
7639     return Res;
7640
7641   Res = tryCombineToBSL(N, DCI);
7642   if (Res.getNode())
7643     return Res;
7644
7645   return SDValue();
7646 }
7647
7648 static SDValue performBitcastCombine(SDNode *N,
7649                                      TargetLowering::DAGCombinerInfo &DCI,
7650                                      SelectionDAG &DAG) {
7651   // Wait 'til after everything is legalized to try this. That way we have
7652   // legal vector types and such.
7653   if (DCI.isBeforeLegalizeOps())
7654     return SDValue();
7655
7656   // Remove extraneous bitcasts around an extract_subvector.
7657   // For example,
7658   //    (v4i16 (bitconvert
7659   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7660   //  becomes
7661   //    (extract_subvector ((v8i16 ...), (i64 4)))
7662
7663   // Only interested in 64-bit vectors as the ultimate result.
7664   EVT VT = N->getValueType(0);
7665   if (!VT.isVector())
7666     return SDValue();
7667   if (VT.getSimpleVT().getSizeInBits() != 64)
7668     return SDValue();
7669   // Is the operand an extract_subvector starting at the beginning or halfway
7670   // point of the vector? A low half may also come through as an
7671   // EXTRACT_SUBREG, so look for that, too.
7672   SDValue Op0 = N->getOperand(0);
7673   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7674       !(Op0->isMachineOpcode() &&
7675         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7676     return SDValue();
7677   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7678   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7679     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7680       return SDValue();
7681   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7682     if (idx != AArch64::dsub)
7683       return SDValue();
7684     // The dsub reference is equivalent to a lane zero subvector reference.
7685     idx = 0;
7686   }
7687   // Look through the bitcast of the input to the extract.
7688   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7689     return SDValue();
7690   SDValue Source = Op0->getOperand(0)->getOperand(0);
7691   // If the source type has twice the number of elements as our destination
7692   // type, we know this is an extract of the high or low half of the vector.
7693   EVT SVT = Source->getValueType(0);
7694   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7695     return SDValue();
7696
7697   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7698
7699   // Create the simplified form to just extract the low or high half of the
7700   // vector directly rather than bothering with the bitcasts.
7701   SDLoc dl(N);
7702   unsigned NumElements = VT.getVectorNumElements();
7703   if (idx) {
7704     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7705     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7706   } else {
7707     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7708     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7709                                       Source, SubReg),
7710                    0);
7711   }
7712 }
7713
7714 static SDValue performConcatVectorsCombine(SDNode *N,
7715                                            TargetLowering::DAGCombinerInfo &DCI,
7716                                            SelectionDAG &DAG) {
7717   SDLoc dl(N);
7718   EVT VT = N->getValueType(0);
7719   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7720
7721   // Optimize concat_vectors of truncated vectors, where the intermediate
7722   // type is illegal, to avoid said illegality,  e.g.,
7723   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7724   //                          (v2i16 (truncate (v2i64)))))
7725   // ->
7726   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7727   //                                    (v4i32 (bitcast (v2i64))),
7728   //                                    <0, 2, 4, 6>)))
7729   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7730   // on both input and result type, so we might generate worse code.
7731   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7732   if (N->getNumOperands() == 2 &&
7733       N0->getOpcode() == ISD::TRUNCATE &&
7734       N1->getOpcode() == ISD::TRUNCATE) {
7735     SDValue N00 = N0->getOperand(0);
7736     SDValue N10 = N1->getOperand(0);
7737     EVT N00VT = N00.getValueType();
7738
7739     if (N00VT == N10.getValueType() &&
7740         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7741         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7742       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7743       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7744       for (size_t i = 0; i < Mask.size(); ++i)
7745         Mask[i] = i * 2;
7746       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7747                          DAG.getVectorShuffle(
7748                              MidVT, dl,
7749                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7750                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7751     }
7752   }
7753
7754   // Wait 'til after everything is legalized to try this. That way we have
7755   // legal vector types and such.
7756   if (DCI.isBeforeLegalizeOps())
7757     return SDValue();
7758
7759   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7760   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7761   // canonicalise to that.
7762   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7763     assert(VT.getVectorElementType().getSizeInBits() == 64);
7764     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7765                        DAG.getConstant(0, dl, MVT::i64));
7766   }
7767
7768   // Canonicalise concat_vectors so that the right-hand vector has as few
7769   // bit-casts as possible before its real operation. The primary matching
7770   // destination for these operations will be the narrowing "2" instructions,
7771   // which depend on the operation being performed on this right-hand vector.
7772   // For example,
7773   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7774   // becomes
7775   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7776
7777   if (N1->getOpcode() != ISD::BITCAST)
7778     return SDValue();
7779   SDValue RHS = N1->getOperand(0);
7780   MVT RHSTy = RHS.getValueType().getSimpleVT();
7781   // If the RHS is not a vector, this is not the pattern we're looking for.
7782   if (!RHSTy.isVector())
7783     return SDValue();
7784
7785   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7786
7787   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7788                                   RHSTy.getVectorNumElements() * 2);
7789   return DAG.getNode(ISD::BITCAST, dl, VT,
7790                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7791                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7792                                  RHS));
7793 }
7794
7795 static SDValue tryCombineFixedPointConvert(SDNode *N,
7796                                            TargetLowering::DAGCombinerInfo &DCI,
7797                                            SelectionDAG &DAG) {
7798   // Wait 'til after everything is legalized to try this. That way we have
7799   // legal vector types and such.
7800   if (DCI.isBeforeLegalizeOps())
7801     return SDValue();
7802   // Transform a scalar conversion of a value from a lane extract into a
7803   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7804   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7805   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7806   //
7807   // The second form interacts better with instruction selection and the
7808   // register allocator to avoid cross-class register copies that aren't
7809   // coalescable due to a lane reference.
7810
7811   // Check the operand and see if it originates from a lane extract.
7812   SDValue Op1 = N->getOperand(1);
7813   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7814     // Yep, no additional predication needed. Perform the transform.
7815     SDValue IID = N->getOperand(0);
7816     SDValue Shift = N->getOperand(2);
7817     SDValue Vec = Op1.getOperand(0);
7818     SDValue Lane = Op1.getOperand(1);
7819     EVT ResTy = N->getValueType(0);
7820     EVT VecResTy;
7821     SDLoc DL(N);
7822
7823     // The vector width should be 128 bits by the time we get here, even
7824     // if it started as 64 bits (the extract_vector handling will have
7825     // done so).
7826     assert(Vec.getValueType().getSizeInBits() == 128 &&
7827            "unexpected vector size on extract_vector_elt!");
7828     if (Vec.getValueType() == MVT::v4i32)
7829       VecResTy = MVT::v4f32;
7830     else if (Vec.getValueType() == MVT::v2i64)
7831       VecResTy = MVT::v2f64;
7832     else
7833       llvm_unreachable("unexpected vector type!");
7834
7835     SDValue Convert =
7836         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7837     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7838   }
7839   return SDValue();
7840 }
7841
7842 // AArch64 high-vector "long" operations are formed by performing the non-high
7843 // version on an extract_subvector of each operand which gets the high half:
7844 //
7845 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7846 //
7847 // However, there are cases which don't have an extract_high explicitly, but
7848 // have another operation that can be made compatible with one for free. For
7849 // example:
7850 //
7851 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7852 //
7853 // This routine does the actual conversion of such DUPs, once outer routines
7854 // have determined that everything else is in order.
7855 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7856 // similarly here.
7857 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7858   switch (N.getOpcode()) {
7859   case AArch64ISD::DUP:
7860   case AArch64ISD::DUPLANE8:
7861   case AArch64ISD::DUPLANE16:
7862   case AArch64ISD::DUPLANE32:
7863   case AArch64ISD::DUPLANE64:
7864   case AArch64ISD::MOVI:
7865   case AArch64ISD::MOVIshift:
7866   case AArch64ISD::MOVIedit:
7867   case AArch64ISD::MOVImsl:
7868   case AArch64ISD::MVNIshift:
7869   case AArch64ISD::MVNImsl:
7870     break;
7871   default:
7872     // FMOV could be supported, but isn't very useful, as it would only occur
7873     // if you passed a bitcast' floating point immediate to an eligible long
7874     // integer op (addl, smull, ...).
7875     return SDValue();
7876   }
7877
7878   MVT NarrowTy = N.getSimpleValueType();
7879   if (!NarrowTy.is64BitVector())
7880     return SDValue();
7881
7882   MVT ElementTy = NarrowTy.getVectorElementType();
7883   unsigned NumElems = NarrowTy.getVectorNumElements();
7884   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7885
7886   SDLoc dl(N);
7887   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7888                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
7889                      DAG.getConstant(NumElems, dl, MVT::i64));
7890 }
7891
7892 static bool isEssentiallyExtractSubvector(SDValue N) {
7893   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7894     return true;
7895
7896   return N.getOpcode() == ISD::BITCAST &&
7897          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7898 }
7899
7900 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7901 struct GenericSetCCInfo {
7902   const SDValue *Opnd0;
7903   const SDValue *Opnd1;
7904   ISD::CondCode CC;
7905 };
7906
7907 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7908 struct AArch64SetCCInfo {
7909   const SDValue *Cmp;
7910   AArch64CC::CondCode CC;
7911 };
7912
7913 /// \brief Helper structure to keep track of SetCC information.
7914 union SetCCInfo {
7915   GenericSetCCInfo Generic;
7916   AArch64SetCCInfo AArch64;
7917 };
7918
7919 /// \brief Helper structure to be able to read SetCC information.  If set to
7920 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7921 /// GenericSetCCInfo.
7922 struct SetCCInfoAndKind {
7923   SetCCInfo Info;
7924   bool IsAArch64;
7925 };
7926
7927 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7928 /// an
7929 /// AArch64 lowered one.
7930 /// \p SetCCInfo is filled accordingly.
7931 /// \post SetCCInfo is meanginfull only when this function returns true.
7932 /// \return True when Op is a kind of SET_CC operation.
7933 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7934   // If this is a setcc, this is straight forward.
7935   if (Op.getOpcode() == ISD::SETCC) {
7936     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7937     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7938     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7939     SetCCInfo.IsAArch64 = false;
7940     return true;
7941   }
7942   // Otherwise, check if this is a matching csel instruction.
7943   // In other words:
7944   // - csel 1, 0, cc
7945   // - csel 0, 1, !cc
7946   if (Op.getOpcode() != AArch64ISD::CSEL)
7947     return false;
7948   // Set the information about the operands.
7949   // TODO: we want the operands of the Cmp not the csel
7950   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7951   SetCCInfo.IsAArch64 = true;
7952   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7953       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7954
7955   // Check that the operands matches the constraints:
7956   // (1) Both operands must be constants.
7957   // (2) One must be 1 and the other must be 0.
7958   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7959   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7960
7961   // Check (1).
7962   if (!TValue || !FValue)
7963     return false;
7964
7965   // Check (2).
7966   if (!TValue->isOne()) {
7967     // Update the comparison when we are interested in !cc.
7968     std::swap(TValue, FValue);
7969     SetCCInfo.Info.AArch64.CC =
7970         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7971   }
7972   return TValue->isOne() && FValue->isNullValue();
7973 }
7974
7975 // Returns true if Op is setcc or zext of setcc.
7976 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7977   if (isSetCC(Op, Info))
7978     return true;
7979   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7980     isSetCC(Op->getOperand(0), Info));
7981 }
7982
7983 // The folding we want to perform is:
7984 // (add x, [zext] (setcc cc ...) )
7985 //   -->
7986 // (csel x, (add x, 1), !cc ...)
7987 //
7988 // The latter will get matched to a CSINC instruction.
7989 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7990   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7991   SDValue LHS = Op->getOperand(0);
7992   SDValue RHS = Op->getOperand(1);
7993   SetCCInfoAndKind InfoAndKind;
7994
7995   // If neither operand is a SET_CC, give up.
7996   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7997     std::swap(LHS, RHS);
7998     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7999       return SDValue();
8000   }
8001
8002   // FIXME: This could be generatized to work for FP comparisons.
8003   EVT CmpVT = InfoAndKind.IsAArch64
8004                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8005                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8006   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8007     return SDValue();
8008
8009   SDValue CCVal;
8010   SDValue Cmp;
8011   SDLoc dl(Op);
8012   if (InfoAndKind.IsAArch64) {
8013     CCVal = DAG.getConstant(
8014         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8015         MVT::i32);
8016     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8017   } else
8018     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8019                       *InfoAndKind.Info.Generic.Opnd1,
8020                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8021                       CCVal, DAG, dl);
8022
8023   EVT VT = Op->getValueType(0);
8024   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8025   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8026 }
8027
8028 // The basic add/sub long vector instructions have variants with "2" on the end
8029 // which act on the high-half of their inputs. They are normally matched by
8030 // patterns like:
8031 //
8032 // (add (zeroext (extract_high LHS)),
8033 //      (zeroext (extract_high RHS)))
8034 // -> uaddl2 vD, vN, vM
8035 //
8036 // However, if one of the extracts is something like a duplicate, this
8037 // instruction can still be used profitably. This function puts the DAG into a
8038 // more appropriate form for those patterns to trigger.
8039 static SDValue performAddSubLongCombine(SDNode *N,
8040                                         TargetLowering::DAGCombinerInfo &DCI,
8041                                         SelectionDAG &DAG) {
8042   if (DCI.isBeforeLegalizeOps())
8043     return SDValue();
8044
8045   MVT VT = N->getSimpleValueType(0);
8046   if (!VT.is128BitVector()) {
8047     if (N->getOpcode() == ISD::ADD)
8048       return performSetccAddFolding(N, DAG);
8049     return SDValue();
8050   }
8051
8052   // Make sure both branches are extended in the same way.
8053   SDValue LHS = N->getOperand(0);
8054   SDValue RHS = N->getOperand(1);
8055   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8056        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8057       LHS.getOpcode() != RHS.getOpcode())
8058     return SDValue();
8059
8060   unsigned ExtType = LHS.getOpcode();
8061
8062   // It's not worth doing if at least one of the inputs isn't already an
8063   // extract, but we don't know which it'll be so we have to try both.
8064   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8065     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8066     if (!RHS.getNode())
8067       return SDValue();
8068
8069     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8070   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8071     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8072     if (!LHS.getNode())
8073       return SDValue();
8074
8075     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8076   }
8077
8078   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8079 }
8080
8081 // Massage DAGs which we can use the high-half "long" operations on into
8082 // something isel will recognize better. E.g.
8083 //
8084 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8085 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8086 //                     (extract_high (v2i64 (dup128 scalar)))))
8087 //
8088 static SDValue tryCombineLongOpWithDup(SDNode *N,
8089                                        TargetLowering::DAGCombinerInfo &DCI,
8090                                        SelectionDAG &DAG) {
8091   if (DCI.isBeforeLegalizeOps())
8092     return SDValue();
8093
8094   bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8095   SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8096   SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8097   assert(LHS.getValueType().is64BitVector() &&
8098          RHS.getValueType().is64BitVector() &&
8099          "unexpected shape for long operation");
8100
8101   // Either node could be a DUP, but it's not worth doing both of them (you'd
8102   // just as well use the non-high version) so look for a corresponding extract
8103   // operation on the other "wing".
8104   if (isEssentiallyExtractSubvector(LHS)) {
8105     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8106     if (!RHS.getNode())
8107       return SDValue();
8108   } else if (isEssentiallyExtractSubvector(RHS)) {
8109     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8110     if (!LHS.getNode())
8111       return SDValue();
8112   }
8113
8114   // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8115   if (IsIntrinsic)
8116     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8117                        N->getOperand(0), LHS, RHS);
8118   else
8119     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8120                        LHS, RHS);
8121 }
8122
8123 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8124   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8125   unsigned ElemBits = ElemTy.getSizeInBits();
8126
8127   int64_t ShiftAmount;
8128   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8129     APInt SplatValue, SplatUndef;
8130     unsigned SplatBitSize;
8131     bool HasAnyUndefs;
8132     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8133                               HasAnyUndefs, ElemBits) ||
8134         SplatBitSize != ElemBits)
8135       return SDValue();
8136
8137     ShiftAmount = SplatValue.getSExtValue();
8138   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8139     ShiftAmount = CVN->getSExtValue();
8140   } else
8141     return SDValue();
8142
8143   unsigned Opcode;
8144   bool IsRightShift;
8145   switch (IID) {
8146   default:
8147     llvm_unreachable("Unknown shift intrinsic");
8148   case Intrinsic::aarch64_neon_sqshl:
8149     Opcode = AArch64ISD::SQSHL_I;
8150     IsRightShift = false;
8151     break;
8152   case Intrinsic::aarch64_neon_uqshl:
8153     Opcode = AArch64ISD::UQSHL_I;
8154     IsRightShift = false;
8155     break;
8156   case Intrinsic::aarch64_neon_srshl:
8157     Opcode = AArch64ISD::SRSHR_I;
8158     IsRightShift = true;
8159     break;
8160   case Intrinsic::aarch64_neon_urshl:
8161     Opcode = AArch64ISD::URSHR_I;
8162     IsRightShift = true;
8163     break;
8164   case Intrinsic::aarch64_neon_sqshlu:
8165     Opcode = AArch64ISD::SQSHLU_I;
8166     IsRightShift = false;
8167     break;
8168   }
8169
8170   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8171     SDLoc dl(N);
8172     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8173                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8174   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8175     SDLoc dl(N);
8176     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8177                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8178   }
8179
8180   return SDValue();
8181 }
8182
8183 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8184 // the intrinsics must be legal and take an i32, this means there's almost
8185 // certainly going to be a zext in the DAG which we can eliminate.
8186 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8187   SDValue AndN = N->getOperand(2);
8188   if (AndN.getOpcode() != ISD::AND)
8189     return SDValue();
8190
8191   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8192   if (!CMask || CMask->getZExtValue() != Mask)
8193     return SDValue();
8194
8195   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8196                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8197 }
8198
8199 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8200                                            SelectionDAG &DAG) {
8201   SDLoc dl(N);
8202   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8203                      DAG.getNode(Opc, dl,
8204                                  N->getOperand(1).getSimpleValueType(),
8205                                  N->getOperand(1)),
8206                      DAG.getConstant(0, dl, MVT::i64));
8207 }
8208
8209 static SDValue performIntrinsicCombine(SDNode *N,
8210                                        TargetLowering::DAGCombinerInfo &DCI,
8211                                        const AArch64Subtarget *Subtarget) {
8212   SelectionDAG &DAG = DCI.DAG;
8213   unsigned IID = getIntrinsicID(N);
8214   switch (IID) {
8215   default:
8216     break;
8217   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8218   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8219     return tryCombineFixedPointConvert(N, DCI, DAG);
8220   case Intrinsic::aarch64_neon_saddv:
8221     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8222   case Intrinsic::aarch64_neon_uaddv:
8223     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8224   case Intrinsic::aarch64_neon_sminv:
8225     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8226   case Intrinsic::aarch64_neon_uminv:
8227     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8228   case Intrinsic::aarch64_neon_smaxv:
8229     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8230   case Intrinsic::aarch64_neon_umaxv:
8231     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8232   case Intrinsic::aarch64_neon_fmax:
8233     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8234                        N->getOperand(1), N->getOperand(2));
8235   case Intrinsic::aarch64_neon_fmin:
8236     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8237                        N->getOperand(1), N->getOperand(2));
8238   case Intrinsic::aarch64_neon_sabd:
8239     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8240                        N->getOperand(1), N->getOperand(2));
8241   case Intrinsic::aarch64_neon_uabd:
8242     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8243                        N->getOperand(1), N->getOperand(2));
8244   case Intrinsic::aarch64_neon_fmaxnm:
8245     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8246                        N->getOperand(1), N->getOperand(2));
8247   case Intrinsic::aarch64_neon_fminnm:
8248     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8249                        N->getOperand(1), N->getOperand(2));
8250   case Intrinsic::aarch64_neon_smull:
8251   case Intrinsic::aarch64_neon_umull:
8252   case Intrinsic::aarch64_neon_pmull:
8253   case Intrinsic::aarch64_neon_sqdmull:
8254     return tryCombineLongOpWithDup(N, DCI, DAG);
8255   case Intrinsic::aarch64_neon_sqshl:
8256   case Intrinsic::aarch64_neon_uqshl:
8257   case Intrinsic::aarch64_neon_sqshlu:
8258   case Intrinsic::aarch64_neon_srshl:
8259   case Intrinsic::aarch64_neon_urshl:
8260     return tryCombineShiftImm(IID, N, DAG);
8261   case Intrinsic::aarch64_crc32b:
8262   case Intrinsic::aarch64_crc32cb:
8263     return tryCombineCRC32(0xff, N, DAG);
8264   case Intrinsic::aarch64_crc32h:
8265   case Intrinsic::aarch64_crc32ch:
8266     return tryCombineCRC32(0xffff, N, DAG);
8267   }
8268   return SDValue();
8269 }
8270
8271 static SDValue performExtendCombine(SDNode *N,
8272                                     TargetLowering::DAGCombinerInfo &DCI,
8273                                     SelectionDAG &DAG) {
8274   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8275   // we can convert that DUP into another extract_high (of a bigger DUP), which
8276   // helps the backend to decide that an sabdl2 would be useful, saving a real
8277   // extract_high operation.
8278   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8279       (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8280        N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8281     SDNode *ABDNode = N->getOperand(0).getNode();
8282     SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8283     if (!NewABD.getNode())
8284       return SDValue();
8285
8286     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8287                        NewABD);
8288   }
8289
8290   // This is effectively a custom type legalization for AArch64.
8291   //
8292   // Type legalization will split an extend of a small, legal, type to a larger
8293   // illegal type by first splitting the destination type, often creating
8294   // illegal source types, which then get legalized in isel-confusing ways,
8295   // leading to really terrible codegen. E.g.,
8296   //   %result = v8i32 sext v8i8 %value
8297   // becomes
8298   //   %losrc = extract_subreg %value, ...
8299   //   %hisrc = extract_subreg %value, ...
8300   //   %lo = v4i32 sext v4i8 %losrc
8301   //   %hi = v4i32 sext v4i8 %hisrc
8302   // Things go rapidly downhill from there.
8303   //
8304   // For AArch64, the [sz]ext vector instructions can only go up one element
8305   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8306   // take two instructions.
8307   //
8308   // This implies that the most efficient way to do the extend from v8i8
8309   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8310   // the normal splitting to happen for the v8i16->v8i32.
8311
8312   // This is pre-legalization to catch some cases where the default
8313   // type legalization will create ill-tempered code.
8314   if (!DCI.isBeforeLegalizeOps())
8315     return SDValue();
8316
8317   // We're only interested in cleaning things up for non-legal vector types
8318   // here. If both the source and destination are legal, things will just
8319   // work naturally without any fiddling.
8320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8321   EVT ResVT = N->getValueType(0);
8322   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8323     return SDValue();
8324   // If the vector type isn't a simple VT, it's beyond the scope of what
8325   // we're  worried about here. Let legalization do its thing and hope for
8326   // the best.
8327   SDValue Src = N->getOperand(0);
8328   EVT SrcVT = Src->getValueType(0);
8329   if (!ResVT.isSimple() || !SrcVT.isSimple())
8330     return SDValue();
8331
8332   // If the source VT is a 64-bit vector, we can play games and get the
8333   // better results we want.
8334   if (SrcVT.getSizeInBits() != 64)
8335     return SDValue();
8336
8337   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8338   unsigned ElementCount = SrcVT.getVectorNumElements();
8339   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8340   SDLoc DL(N);
8341   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8342
8343   // Now split the rest of the operation into two halves, each with a 64
8344   // bit source.
8345   EVT LoVT, HiVT;
8346   SDValue Lo, Hi;
8347   unsigned NumElements = ResVT.getVectorNumElements();
8348   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8349   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8350                                  ResVT.getVectorElementType(), NumElements / 2);
8351
8352   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8353                                LoVT.getVectorNumElements());
8354   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8355                    DAG.getConstant(0, DL, MVT::i64));
8356   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8357                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8358   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8359   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8360
8361   // Now combine the parts back together so we still have a single result
8362   // like the combiner expects.
8363   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8364 }
8365
8366 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8367 /// value. The load store optimizer pass will merge them to store pair stores.
8368 /// This has better performance than a splat of the scalar followed by a split
8369 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8370 /// followed by an ext.b and two stores.
8371 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8372   SDValue StVal = St->getValue();
8373   EVT VT = StVal.getValueType();
8374
8375   // Don't replace floating point stores, they possibly won't be transformed to
8376   // stp because of the store pair suppress pass.
8377   if (VT.isFloatingPoint())
8378     return SDValue();
8379
8380   // Check for insert vector elements.
8381   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8382     return SDValue();
8383
8384   // We can express a splat as store pair(s) for 2 or 4 elements.
8385   unsigned NumVecElts = VT.getVectorNumElements();
8386   if (NumVecElts != 4 && NumVecElts != 2)
8387     return SDValue();
8388   SDValue SplatVal = StVal.getOperand(1);
8389   unsigned RemainInsertElts = NumVecElts - 1;
8390
8391   // Check that this is a splat.
8392   while (--RemainInsertElts) {
8393     SDValue NextInsertElt = StVal.getOperand(0);
8394     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8395       return SDValue();
8396     if (NextInsertElt.getOperand(1) != SplatVal)
8397       return SDValue();
8398     StVal = NextInsertElt;
8399   }
8400   unsigned OrigAlignment = St->getAlignment();
8401   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8402   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8403
8404   // Create scalar stores. This is at least as good as the code sequence for a
8405   // split unaligned store which is a dup.s, ext.b, and two stores.
8406   // Most of the time the three stores should be replaced by store pair
8407   // instructions (stp).
8408   SDLoc DL(St);
8409   SDValue BasePtr = St->getBasePtr();
8410   SDValue NewST1 =
8411       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8412                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8413
8414   unsigned Offset = EltOffset;
8415   while (--NumVecElts) {
8416     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8417                                     DAG.getConstant(Offset, DL, MVT::i64));
8418     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8419                           St->getPointerInfo(), St->isVolatile(),
8420                           St->isNonTemporal(), Alignment);
8421     Offset += EltOffset;
8422   }
8423   return NewST1;
8424 }
8425
8426 static SDValue performSTORECombine(SDNode *N,
8427                                    TargetLowering::DAGCombinerInfo &DCI,
8428                                    SelectionDAG &DAG,
8429                                    const AArch64Subtarget *Subtarget) {
8430   if (!DCI.isBeforeLegalize())
8431     return SDValue();
8432
8433   StoreSDNode *S = cast<StoreSDNode>(N);
8434   if (S->isVolatile())
8435     return SDValue();
8436
8437   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8438   // page boundaries. We want to split such stores.
8439   if (!Subtarget->isCyclone())
8440     return SDValue();
8441
8442   // Don't split at -Oz.
8443   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8444     return SDValue();
8445
8446   SDValue StVal = S->getValue();
8447   EVT VT = StVal.getValueType();
8448
8449   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8450   // those up regresses performance on micro-benchmarks and olden/bh.
8451   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8452     return SDValue();
8453
8454   // Split unaligned 16B stores. They are terrible for performance.
8455   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8456   // extensions can use this to mark that it does not want splitting to happen
8457   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8458   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8459   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8460       S->getAlignment() <= 2)
8461     return SDValue();
8462
8463   // If we get a splat of a scalar convert this vector store to a store of
8464   // scalars. They will be merged into store pairs thereby removing two
8465   // instructions.
8466   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8467     return ReplacedSplat;
8468
8469   SDLoc DL(S);
8470   unsigned NumElts = VT.getVectorNumElements() / 2;
8471   // Split VT into two.
8472   EVT HalfVT =
8473       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8474   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8475                                    DAG.getConstant(0, DL, MVT::i64));
8476   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8477                                    DAG.getConstant(NumElts, DL, MVT::i64));
8478   SDValue BasePtr = S->getBasePtr();
8479   SDValue NewST1 =
8480       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8481                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8482   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8483                                   DAG.getConstant(8, DL, MVT::i64));
8484   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8485                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8486                       S->getAlignment());
8487 }
8488
8489 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8490 /// post-increment LD1R.
8491 static SDValue performPostLD1Combine(SDNode *N,
8492                                      TargetLowering::DAGCombinerInfo &DCI,
8493                                      bool IsLaneOp) {
8494   if (DCI.isBeforeLegalizeOps())
8495     return SDValue();
8496
8497   SelectionDAG &DAG = DCI.DAG;
8498   EVT VT = N->getValueType(0);
8499
8500   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8501   SDNode *LD = N->getOperand(LoadIdx).getNode();
8502   // If it is not LOAD, can not do such combine.
8503   if (LD->getOpcode() != ISD::LOAD)
8504     return SDValue();
8505
8506   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8507   EVT MemVT = LoadSDN->getMemoryVT();
8508   // Check if memory operand is the same type as the vector element.
8509   if (MemVT != VT.getVectorElementType())
8510     return SDValue();
8511
8512   // Check if there are other uses. If so, do not combine as it will introduce
8513   // an extra load.
8514   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8515        ++UI) {
8516     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8517       continue;
8518     if (*UI != N)
8519       return SDValue();
8520   }
8521
8522   SDValue Addr = LD->getOperand(1);
8523   SDValue Vector = N->getOperand(0);
8524   // Search for a use of the address operand that is an increment.
8525   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8526        Addr.getNode()->use_end(); UI != UE; ++UI) {
8527     SDNode *User = *UI;
8528     if (User->getOpcode() != ISD::ADD
8529         || UI.getUse().getResNo() != Addr.getResNo())
8530       continue;
8531
8532     // Check that the add is independent of the load.  Otherwise, folding it
8533     // would create a cycle.
8534     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8535       continue;
8536     // Also check that add is not used in the vector operand.  This would also
8537     // create a cycle.
8538     if (User->isPredecessorOf(Vector.getNode()))
8539       continue;
8540
8541     // If the increment is a constant, it must match the memory ref size.
8542     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8543     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8544       uint32_t IncVal = CInc->getZExtValue();
8545       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8546       if (IncVal != NumBytes)
8547         continue;
8548       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8549     }
8550
8551     // Finally, check that the vector doesn't depend on the load.
8552     // Again, this would create a cycle.
8553     // The load depending on the vector is fine, as that's the case for the
8554     // LD1*post we'll eventually generate anyway.
8555     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8556       continue;
8557
8558     SmallVector<SDValue, 8> Ops;
8559     Ops.push_back(LD->getOperand(0));  // Chain
8560     if (IsLaneOp) {
8561       Ops.push_back(Vector);           // The vector to be inserted
8562       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8563     }
8564     Ops.push_back(Addr);
8565     Ops.push_back(Inc);
8566
8567     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8568     SDVTList SDTys = DAG.getVTList(Tys);
8569     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8570     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8571                                            MemVT,
8572                                            LoadSDN->getMemOperand());
8573
8574     // Update the uses.
8575     SmallVector<SDValue, 2> NewResults;
8576     NewResults.push_back(SDValue(LD, 0));             // The result of load
8577     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8578     DCI.CombineTo(LD, NewResults);
8579     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8580     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8581
8582     break;
8583   }
8584   return SDValue();
8585 }
8586
8587 /// Target-specific DAG combine function for NEON load/store intrinsics
8588 /// to merge base address updates.
8589 static SDValue performNEONPostLDSTCombine(SDNode *N,
8590                                           TargetLowering::DAGCombinerInfo &DCI,
8591                                           SelectionDAG &DAG) {
8592   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8593     return SDValue();
8594
8595   unsigned AddrOpIdx = N->getNumOperands() - 1;
8596   SDValue Addr = N->getOperand(AddrOpIdx);
8597
8598   // Search for a use of the address operand that is an increment.
8599   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8600        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8601     SDNode *User = *UI;
8602     if (User->getOpcode() != ISD::ADD ||
8603         UI.getUse().getResNo() != Addr.getResNo())
8604       continue;
8605
8606     // Check that the add is independent of the load/store.  Otherwise, folding
8607     // it would create a cycle.
8608     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8609       continue;
8610
8611     // Find the new opcode for the updating load/store.
8612     bool IsStore = false;
8613     bool IsLaneOp = false;
8614     bool IsDupOp = false;
8615     unsigned NewOpc = 0;
8616     unsigned NumVecs = 0;
8617     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8618     switch (IntNo) {
8619     default: llvm_unreachable("unexpected intrinsic for Neon base update");
8620     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
8621       NumVecs = 2; break;
8622     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
8623       NumVecs = 3; break;
8624     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
8625       NumVecs = 4; break;
8626     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
8627       NumVecs = 2; IsStore = true; break;
8628     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
8629       NumVecs = 3; IsStore = true; break;
8630     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
8631       NumVecs = 4; IsStore = true; break;
8632     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
8633       NumVecs = 2; break;
8634     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
8635       NumVecs = 3; break;
8636     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
8637       NumVecs = 4; break;
8638     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
8639       NumVecs = 2; IsStore = true; break;
8640     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
8641       NumVecs = 3; IsStore = true; break;
8642     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
8643       NumVecs = 4; IsStore = true; break;
8644     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
8645       NumVecs = 2; IsDupOp = true; break;
8646     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
8647       NumVecs = 3; IsDupOp = true; break;
8648     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
8649       NumVecs = 4; IsDupOp = true; break;
8650     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
8651       NumVecs = 2; IsLaneOp = true; break;
8652     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
8653       NumVecs = 3; IsLaneOp = true; break;
8654     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
8655       NumVecs = 4; IsLaneOp = true; break;
8656     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
8657       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8658     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
8659       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8660     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
8661       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8662     }
8663
8664     EVT VecTy;
8665     if (IsStore)
8666       VecTy = N->getOperand(2).getValueType();
8667     else
8668       VecTy = N->getValueType(0);
8669
8670     // If the increment is a constant, it must match the memory ref size.
8671     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8672     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8673       uint32_t IncVal = CInc->getZExtValue();
8674       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8675       if (IsLaneOp || IsDupOp)
8676         NumBytes /= VecTy.getVectorNumElements();
8677       if (IncVal != NumBytes)
8678         continue;
8679       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8680     }
8681     SmallVector<SDValue, 8> Ops;
8682     Ops.push_back(N->getOperand(0)); // Incoming chain
8683     // Load lane and store have vector list as input.
8684     if (IsLaneOp || IsStore)
8685       for (unsigned i = 2; i < AddrOpIdx; ++i)
8686         Ops.push_back(N->getOperand(i));
8687     Ops.push_back(Addr); // Base register
8688     Ops.push_back(Inc);
8689
8690     // Return Types.
8691     EVT Tys[6];
8692     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8693     unsigned n;
8694     for (n = 0; n < NumResultVecs; ++n)
8695       Tys[n] = VecTy;
8696     Tys[n++] = MVT::i64;  // Type of write back register
8697     Tys[n] = MVT::Other;  // Type of the chain
8698     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8699
8700     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8701     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8702                                            MemInt->getMemoryVT(),
8703                                            MemInt->getMemOperand());
8704
8705     // Update the uses.
8706     std::vector<SDValue> NewResults;
8707     for (unsigned i = 0; i < NumResultVecs; ++i) {
8708       NewResults.push_back(SDValue(UpdN.getNode(), i));
8709     }
8710     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8711     DCI.CombineTo(N, NewResults);
8712     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8713
8714     break;
8715   }
8716   return SDValue();
8717 }
8718
8719 // Checks to see if the value is the prescribed width and returns information
8720 // about its extension mode.
8721 static
8722 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8723   ExtType = ISD::NON_EXTLOAD;
8724   switch(V.getNode()->getOpcode()) {
8725   default:
8726     return false;
8727   case ISD::LOAD: {
8728     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8729     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8730        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8731       ExtType = LoadNode->getExtensionType();
8732       return true;
8733     }
8734     return false;
8735   }
8736   case ISD::AssertSext: {
8737     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8738     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8739        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8740       ExtType = ISD::SEXTLOAD;
8741       return true;
8742     }
8743     return false;
8744   }
8745   case ISD::AssertZext: {
8746     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8747     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8748        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8749       ExtType = ISD::ZEXTLOAD;
8750       return true;
8751     }
8752     return false;
8753   }
8754   case ISD::Constant:
8755   case ISD::TargetConstant: {
8756     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8757         1LL << (width - 1))
8758       return true;
8759     return false;
8760   }
8761   }
8762
8763   return true;
8764 }
8765
8766 // This function does a whole lot of voodoo to determine if the tests are
8767 // equivalent without and with a mask. Essentially what happens is that given a
8768 // DAG resembling:
8769 //
8770 //  +-------------+ +-------------+ +-------------+ +-------------+
8771 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
8772 //  +-------------+ +-------------+ +-------------+ +-------------+
8773 //           |           |           |               |
8774 //           V           V           |    +----------+
8775 //          +-------------+  +----+  |    |
8776 //          |     ADD     |  |0xff|  |    |
8777 //          +-------------+  +----+  |    |
8778 //                  |           |    |    |
8779 //                  V           V    |    |
8780 //                 +-------------+   |    |
8781 //                 |     AND     |   |    |
8782 //                 +-------------+   |    |
8783 //                      |            |    |
8784 //                      +-----+      |    |
8785 //                            |      |    |
8786 //                            V      V    V
8787 //                           +-------------+
8788 //                           |     CMP     |
8789 //                           +-------------+
8790 //
8791 // The AND node may be safely removed for some combinations of inputs. In
8792 // particular we need to take into account the extension type of the Input,
8793 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8794 // width of the input (this can work for any width inputs, the above graph is
8795 // specific to 8 bits.
8796 //
8797 // The specific equations were worked out by generating output tables for each
8798 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8799 // problem was simplified by working with 4 bit inputs, which means we only
8800 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8801 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8802 // patterns present in both extensions (0,7). For every distinct set of
8803 // AddConstant and CompConstants bit patterns we can consider the masked and
8804 // unmasked versions to be equivalent if the result of this function is true for
8805 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8806 //
8807 //   sub      w8, w0, w1
8808 //   and      w10, w8, #0x0f
8809 //   cmp      w8, w2
8810 //   cset     w9, AArch64CC
8811 //   cmp      w10, w2
8812 //   cset     w11, AArch64CC
8813 //   cmp      w9, w11
8814 //   cset     w0, eq
8815 //   ret
8816 //
8817 // Since the above function shows when the outputs are equivalent it defines
8818 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8819 // would be expensive to run during compiles. The equations below were written
8820 // in a test harness that confirmed they gave equivalent outputs to the above
8821 // for all inputs function, so they can be used determine if the removal is
8822 // legal instead.
8823 //
8824 // isEquivalentMaskless() is the code for testing if the AND can be removed
8825 // factored out of the DAG recognition as the DAG can take several forms.
8826
8827 static
8828 bool isEquivalentMaskless(unsigned CC, unsigned width,
8829                           ISD::LoadExtType ExtType, signed AddConstant,
8830                           signed CompConstant) {
8831   // By being careful about our equations and only writing the in term
8832   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8833   // make them generally applicable to all bit widths.
8834   signed MaxUInt = (1 << width);
8835
8836   // For the purposes of these comparisons sign extending the type is
8837   // equivalent to zero extending the add and displacing it by half the integer
8838   // width. Provided we are careful and make sure our equations are valid over
8839   // the whole range we can just adjust the input and avoid writing equations
8840   // for sign extended inputs.
8841   if (ExtType == ISD::SEXTLOAD)
8842     AddConstant -= (1 << (width-1));
8843
8844   switch(CC) {
8845   case AArch64CC::LE:
8846   case AArch64CC::GT: {
8847     if ((AddConstant == 0) ||
8848         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8849         (AddConstant >= 0 && CompConstant < 0) ||
8850         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8851       return true;
8852   } break;
8853   case AArch64CC::LT:
8854   case AArch64CC::GE: {
8855     if ((AddConstant == 0) ||
8856         (AddConstant >= 0 && CompConstant <= 0) ||
8857         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8858       return true;
8859   } break;
8860   case AArch64CC::HI:
8861   case AArch64CC::LS: {
8862     if ((AddConstant >= 0 && CompConstant < 0) ||
8863        (AddConstant <= 0 && CompConstant >= -1 &&
8864         CompConstant < AddConstant + MaxUInt))
8865       return true;
8866   } break;
8867   case AArch64CC::PL:
8868   case AArch64CC::MI: {
8869     if ((AddConstant == 0) ||
8870         (AddConstant > 0 && CompConstant <= 0) ||
8871         (AddConstant < 0 && CompConstant <= AddConstant))
8872       return true;
8873   } break;
8874   case AArch64CC::LO:
8875   case AArch64CC::HS: {
8876     if ((AddConstant >= 0 && CompConstant <= 0) ||
8877         (AddConstant <= 0 && CompConstant >= 0 &&
8878          CompConstant <= AddConstant + MaxUInt))
8879       return true;
8880   } break;
8881   case AArch64CC::EQ:
8882   case AArch64CC::NE: {
8883     if ((AddConstant > 0 && CompConstant < 0) ||
8884         (AddConstant < 0 && CompConstant >= 0 &&
8885          CompConstant < AddConstant + MaxUInt) ||
8886         (AddConstant >= 0 && CompConstant >= 0 &&
8887          CompConstant >= AddConstant) ||
8888         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8889
8890       return true;
8891   } break;
8892   case AArch64CC::VS:
8893   case AArch64CC::VC:
8894   case AArch64CC::AL:
8895   case AArch64CC::NV:
8896     return true;
8897   case AArch64CC::Invalid:
8898     break;
8899   }
8900
8901   return false;
8902 }
8903
8904 static
8905 SDValue performCONDCombine(SDNode *N,
8906                            TargetLowering::DAGCombinerInfo &DCI,
8907                            SelectionDAG &DAG, unsigned CCIndex,
8908                            unsigned CmpIndex) {
8909   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8910   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8911   unsigned CondOpcode = SubsNode->getOpcode();
8912
8913   if (CondOpcode != AArch64ISD::SUBS)
8914     return SDValue();
8915
8916   // There is a SUBS feeding this condition. Is it fed by a mask we can
8917   // use?
8918
8919   SDNode *AndNode = SubsNode->getOperand(0).getNode();
8920   unsigned MaskBits = 0;
8921
8922   if (AndNode->getOpcode() != ISD::AND)
8923     return SDValue();
8924
8925   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8926     uint32_t CNV = CN->getZExtValue();
8927     if (CNV == 255)
8928       MaskBits = 8;
8929     else if (CNV == 65535)
8930       MaskBits = 16;
8931   }
8932
8933   if (!MaskBits)
8934     return SDValue();
8935
8936   SDValue AddValue = AndNode->getOperand(0);
8937
8938   if (AddValue.getOpcode() != ISD::ADD)
8939     return SDValue();
8940
8941   // The basic dag structure is correct, grab the inputs and validate them.
8942
8943   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8944   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8945   SDValue SubsInputValue = SubsNode->getOperand(1);
8946
8947   // The mask is present and the provenance of all the values is a smaller type,
8948   // lets see if the mask is superfluous.
8949
8950   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8951       !isa<ConstantSDNode>(SubsInputValue.getNode()))
8952     return SDValue();
8953
8954   ISD::LoadExtType ExtType;
8955
8956   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8957       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8958       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8959     return SDValue();
8960
8961   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8962                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8963                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8964     return SDValue();
8965
8966   // The AND is not necessary, remove it.
8967
8968   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8969                                SubsNode->getValueType(1));
8970   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8971
8972   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8973   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8974
8975   return SDValue(N, 0);
8976 }
8977
8978 // Optimize compare with zero and branch.
8979 static SDValue performBRCONDCombine(SDNode *N,
8980                                     TargetLowering::DAGCombinerInfo &DCI,
8981                                     SelectionDAG &DAG) {
8982   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8983   if (NV.getNode())
8984     N = NV.getNode();
8985   SDValue Chain = N->getOperand(0);
8986   SDValue Dest = N->getOperand(1);
8987   SDValue CCVal = N->getOperand(2);
8988   SDValue Cmp = N->getOperand(3);
8989
8990   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8991   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8992   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8993     return SDValue();
8994
8995   unsigned CmpOpc = Cmp.getOpcode();
8996   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8997     return SDValue();
8998
8999   // Only attempt folding if there is only one use of the flag and no use of the
9000   // value.
9001   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9002     return SDValue();
9003
9004   SDValue LHS = Cmp.getOperand(0);
9005   SDValue RHS = Cmp.getOperand(1);
9006
9007   assert(LHS.getValueType() == RHS.getValueType() &&
9008          "Expected the value type to be the same for both operands!");
9009   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9010     return SDValue();
9011
9012   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9013     std::swap(LHS, RHS);
9014
9015   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9016     return SDValue();
9017
9018   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9019       LHS.getOpcode() == ISD::SRL)
9020     return SDValue();
9021
9022   // Fold the compare into the branch instruction.
9023   SDValue BR;
9024   if (CC == AArch64CC::EQ)
9025     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9026   else
9027     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9028
9029   // Do not add new nodes to DAG combiner worklist.
9030   DCI.CombineTo(N, BR, false);
9031
9032   return SDValue();
9033 }
9034
9035 // vselect (v1i1 setcc) ->
9036 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9037 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9038 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9039 // such VSELECT.
9040 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9041   SDValue N0 = N->getOperand(0);
9042   EVT CCVT = N0.getValueType();
9043
9044   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9045       CCVT.getVectorElementType() != MVT::i1)
9046     return SDValue();
9047
9048   EVT ResVT = N->getValueType(0);
9049   EVT CmpVT = N0.getOperand(0).getValueType();
9050   // Only combine when the result type is of the same size as the compared
9051   // operands.
9052   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9053     return SDValue();
9054
9055   SDValue IfTrue = N->getOperand(1);
9056   SDValue IfFalse = N->getOperand(2);
9057   SDValue SetCC =
9058       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9059                    N0.getOperand(0), N0.getOperand(1),
9060                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9061   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9062                      IfTrue, IfFalse);
9063 }
9064
9065 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9066 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9067 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9068 /// with a vector one followed by a DUP shuffle on the result.
9069 static SDValue performSelectCombine(SDNode *N,
9070                                     TargetLowering::DAGCombinerInfo &DCI) {
9071   SelectionDAG &DAG = DCI.DAG;
9072   SDValue N0 = N->getOperand(0);
9073   EVT ResVT = N->getValueType(0);
9074
9075   if (N0.getOpcode() != ISD::SETCC)
9076     return SDValue();
9077
9078   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9079   // scalar SetCCResultType. We also don't expect vectors, because we assume
9080   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9081   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9082          "Scalar-SETCC feeding SELECT has unexpected result type!");
9083
9084   // If NumMaskElts == 0, the comparison is larger than select result. The
9085   // largest real NEON comparison is 64-bits per lane, which means the result is
9086   // at most 32-bits and an illegal vector. Just bail out for now.
9087   EVT SrcVT = N0.getOperand(0).getValueType();
9088
9089   // Don't try to do this optimization when the setcc itself has i1 operands.
9090   // There are no legal vectors of i1, so this would be pointless.
9091   if (SrcVT == MVT::i1)
9092     return SDValue();
9093
9094   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9095   if (!ResVT.isVector() || NumMaskElts == 0)
9096     return SDValue();
9097
9098   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9099   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9100
9101   // Also bail out if the vector CCVT isn't the same size as ResVT.
9102   // This can happen if the SETCC operand size doesn't divide the ResVT size
9103   // (e.g., f64 vs v3f32).
9104   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9105     return SDValue();
9106
9107   // Make sure we didn't create illegal types, if we're not supposed to.
9108   assert(DCI.isBeforeLegalize() ||
9109          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9110
9111   // First perform a vector comparison, where lane 0 is the one we're interested
9112   // in.
9113   SDLoc DL(N0);
9114   SDValue LHS =
9115       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9116   SDValue RHS =
9117       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9118   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9119
9120   // Now duplicate the comparison mask we want across all other lanes.
9121   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9122   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9123   Mask = DAG.getNode(ISD::BITCAST, DL,
9124                      ResVT.changeVectorElementTypeToInteger(), Mask);
9125
9126   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9127 }
9128
9129 /// Get rid of unnecessary NVCASTs (that don't change the type).
9130 static SDValue performNVCASTCombine(SDNode *N) {
9131   if (N->getValueType(0) == N->getOperand(0).getValueType())
9132     return N->getOperand(0);
9133
9134   return SDValue();
9135 }
9136
9137 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9138                                                  DAGCombinerInfo &DCI) const {
9139   SelectionDAG &DAG = DCI.DAG;
9140   switch (N->getOpcode()) {
9141   default:
9142     break;
9143   case ISD::ADD:
9144   case ISD::SUB:
9145     return performAddSubLongCombine(N, DCI, DAG);
9146   case ISD::XOR:
9147     return performXorCombine(N, DAG, DCI, Subtarget);
9148   case ISD::MUL:
9149     return performMulCombine(N, DAG, DCI, Subtarget);
9150   case ISD::SINT_TO_FP:
9151   case ISD::UINT_TO_FP:
9152     return performIntToFpCombine(N, DAG, Subtarget);
9153   case ISD::OR:
9154     return performORCombine(N, DCI, Subtarget);
9155   case ISD::INTRINSIC_WO_CHAIN:
9156     return performIntrinsicCombine(N, DCI, Subtarget);
9157   case ISD::ANY_EXTEND:
9158   case ISD::ZERO_EXTEND:
9159   case ISD::SIGN_EXTEND:
9160     return performExtendCombine(N, DCI, DAG);
9161   case ISD::BITCAST:
9162     return performBitcastCombine(N, DCI, DAG);
9163   case ISD::CONCAT_VECTORS:
9164     return performConcatVectorsCombine(N, DCI, DAG);
9165   case ISD::SELECT:
9166     return performSelectCombine(N, DCI);
9167   case ISD::VSELECT:
9168     return performVSelectCombine(N, DCI.DAG);
9169   case ISD::STORE:
9170     return performSTORECombine(N, DCI, DAG, Subtarget);
9171   case AArch64ISD::BRCOND:
9172     return performBRCONDCombine(N, DCI, DAG);
9173   case AArch64ISD::CSEL:
9174     return performCONDCombine(N, DCI, DAG, 2, 3);
9175   case AArch64ISD::DUP:
9176     return performPostLD1Combine(N, DCI, false);
9177   case AArch64ISD::NVCAST:
9178     return performNVCASTCombine(N);
9179   case ISD::INSERT_VECTOR_ELT:
9180     return performPostLD1Combine(N, DCI, true);
9181   case ISD::INTRINSIC_VOID:
9182   case ISD::INTRINSIC_W_CHAIN:
9183     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9184     case Intrinsic::aarch64_neon_ld2:
9185     case Intrinsic::aarch64_neon_ld3:
9186     case Intrinsic::aarch64_neon_ld4:
9187     case Intrinsic::aarch64_neon_ld1x2:
9188     case Intrinsic::aarch64_neon_ld1x3:
9189     case Intrinsic::aarch64_neon_ld1x4:
9190     case Intrinsic::aarch64_neon_ld2lane:
9191     case Intrinsic::aarch64_neon_ld3lane:
9192     case Intrinsic::aarch64_neon_ld4lane:
9193     case Intrinsic::aarch64_neon_ld2r:
9194     case Intrinsic::aarch64_neon_ld3r:
9195     case Intrinsic::aarch64_neon_ld4r:
9196     case Intrinsic::aarch64_neon_st2:
9197     case Intrinsic::aarch64_neon_st3:
9198     case Intrinsic::aarch64_neon_st4:
9199     case Intrinsic::aarch64_neon_st1x2:
9200     case Intrinsic::aarch64_neon_st1x3:
9201     case Intrinsic::aarch64_neon_st1x4:
9202     case Intrinsic::aarch64_neon_st2lane:
9203     case Intrinsic::aarch64_neon_st3lane:
9204     case Intrinsic::aarch64_neon_st4lane:
9205       return performNEONPostLDSTCombine(N, DCI, DAG);
9206     default:
9207       break;
9208     }
9209   }
9210   return SDValue();
9211 }
9212
9213 // Check if the return value is used as only a return value, as otherwise
9214 // we can't perform a tail-call. In particular, we need to check for
9215 // target ISD nodes that are returns and any other "odd" constructs
9216 // that the generic analysis code won't necessarily catch.
9217 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9218                                                SDValue &Chain) const {
9219   if (N->getNumValues() != 1)
9220     return false;
9221   if (!N->hasNUsesOfValue(1, 0))
9222     return false;
9223
9224   SDValue TCChain = Chain;
9225   SDNode *Copy = *N->use_begin();
9226   if (Copy->getOpcode() == ISD::CopyToReg) {
9227     // If the copy has a glue operand, we conservatively assume it isn't safe to
9228     // perform a tail call.
9229     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9230         MVT::Glue)
9231       return false;
9232     TCChain = Copy->getOperand(0);
9233   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9234     return false;
9235
9236   bool HasRet = false;
9237   for (SDNode *Node : Copy->uses()) {
9238     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9239       return false;
9240     HasRet = true;
9241   }
9242
9243   if (!HasRet)
9244     return false;
9245
9246   Chain = TCChain;
9247   return true;
9248 }
9249
9250 // Return whether the an instruction can potentially be optimized to a tail
9251 // call. This will cause the optimizers to attempt to move, or duplicate,
9252 // return instructions to help enable tail call optimizations for this
9253 // instruction.
9254 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9255   if (!CI->isTailCall())
9256     return false;
9257
9258   return true;
9259 }
9260
9261 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9262                                                    SDValue &Offset,
9263                                                    ISD::MemIndexedMode &AM,
9264                                                    bool &IsInc,
9265                                                    SelectionDAG &DAG) const {
9266   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9267     return false;
9268
9269   Base = Op->getOperand(0);
9270   // All of the indexed addressing mode instructions take a signed
9271   // 9 bit immediate offset.
9272   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9273     int64_t RHSC = (int64_t)RHS->getZExtValue();
9274     if (RHSC >= 256 || RHSC <= -256)
9275       return false;
9276     IsInc = (Op->getOpcode() == ISD::ADD);
9277     Offset = Op->getOperand(1);
9278     return true;
9279   }
9280   return false;
9281 }
9282
9283 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9284                                                       SDValue &Offset,
9285                                                       ISD::MemIndexedMode &AM,
9286                                                       SelectionDAG &DAG) const {
9287   EVT VT;
9288   SDValue Ptr;
9289   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9290     VT = LD->getMemoryVT();
9291     Ptr = LD->getBasePtr();
9292   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9293     VT = ST->getMemoryVT();
9294     Ptr = ST->getBasePtr();
9295   } else
9296     return false;
9297
9298   bool IsInc;
9299   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9300     return false;
9301   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9302   return true;
9303 }
9304
9305 bool AArch64TargetLowering::getPostIndexedAddressParts(
9306     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9307     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9308   EVT VT;
9309   SDValue Ptr;
9310   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9311     VT = LD->getMemoryVT();
9312     Ptr = LD->getBasePtr();
9313   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9314     VT = ST->getMemoryVT();
9315     Ptr = ST->getBasePtr();
9316   } else
9317     return false;
9318
9319   bool IsInc;
9320   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9321     return false;
9322   // Post-indexing updates the base, so it's not a valid transform
9323   // if that's not the same as the load's pointer.
9324   if (Ptr != Base)
9325     return false;
9326   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9327   return true;
9328 }
9329
9330 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9331                                   SelectionDAG &DAG) {
9332   SDLoc DL(N);
9333   SDValue Op = N->getOperand(0);
9334
9335   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9336     return;
9337
9338   Op = SDValue(
9339       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9340                          DAG.getUNDEF(MVT::i32), Op,
9341                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9342       0);
9343   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9344   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9345 }
9346
9347 void AArch64TargetLowering::ReplaceNodeResults(
9348     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9349   switch (N->getOpcode()) {
9350   default:
9351     llvm_unreachable("Don't know how to custom expand this");
9352   case ISD::BITCAST:
9353     ReplaceBITCASTResults(N, Results, DAG);
9354     return;
9355   case ISD::FP_TO_UINT:
9356   case ISD::FP_TO_SINT:
9357     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9358     // Let normal code take care of it by not adding anything to Results.
9359     return;
9360   }
9361 }
9362
9363 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9364   return true;
9365 }
9366
9367 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9368   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9369   // reciprocal if there are three or more FDIVs.
9370   return 3;
9371 }
9372
9373 TargetLoweringBase::LegalizeTypeAction
9374 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9375   MVT SVT = VT.getSimpleVT();
9376   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
9377   // v4i16, v2i32 instead of to promote.
9378   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9379       || SVT == MVT::v1f32)
9380     return TypeWidenVector;
9381
9382   return TargetLoweringBase::getPreferredVectorAction(VT);
9383 }
9384
9385 // Loads and stores less than 128-bits are already atomic; ones above that
9386 // are doomed anyway, so defer to the default libcall and blame the OS when
9387 // things go wrong.
9388 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9389   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9390   return Size == 128;
9391 }
9392
9393 // Loads and stores less than 128-bits are already atomic; ones above that
9394 // are doomed anyway, so defer to the default libcall and blame the OS when
9395 // things go wrong.
9396 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9397   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9398   return Size == 128;
9399 }
9400
9401 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9402 TargetLoweringBase::AtomicRMWExpansionKind
9403 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9404   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9405   return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9406                      : AtomicRMWExpansionKind::None;
9407 }
9408
9409 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9410   return true;
9411 }
9412
9413 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9414                                              AtomicOrdering Ord) const {
9415   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9416   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9417   bool IsAcquire = isAtLeastAcquire(Ord);
9418
9419   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9420   // intrinsic must return {i64, i64} and we have to recombine them into a
9421   // single i128 here.
9422   if (ValTy->getPrimitiveSizeInBits() == 128) {
9423     Intrinsic::ID Int =
9424         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9425     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9426
9427     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9428     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9429
9430     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9431     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9432     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9433     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9434     return Builder.CreateOr(
9435         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9436   }
9437
9438   Type *Tys[] = { Addr->getType() };
9439   Intrinsic::ID Int =
9440       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9441   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9442
9443   return Builder.CreateTruncOrBitCast(
9444       Builder.CreateCall(Ldxr, Addr),
9445       cast<PointerType>(Addr->getType())->getElementType());
9446 }
9447
9448 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9449                                                    Value *Val, Value *Addr,
9450                                                    AtomicOrdering Ord) const {
9451   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9452   bool IsRelease = isAtLeastRelease(Ord);
9453
9454   // Since the intrinsics must have legal type, the i128 intrinsics take two
9455   // parameters: "i64, i64". We must marshal Val into the appropriate form
9456   // before the call.
9457   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9458     Intrinsic::ID Int =
9459         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9460     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9461     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9462
9463     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9464     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9465     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9466     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9467   }
9468
9469   Intrinsic::ID Int =
9470       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9471   Type *Tys[] = { Addr->getType() };
9472   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9473
9474   return Builder.CreateCall(Stxr,
9475                             {Builder.CreateZExtOrBitCast(
9476                                  Val, Stxr->getFunctionType()->getParamType(0)),
9477                              Addr});
9478 }
9479
9480 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9481     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9482   return Ty->isArrayTy();
9483 }
9484
9485 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9486                                                             EVT) const {
9487   return false;
9488 }