]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Upgrade our copies of clang, llvm, lldb, compiler-rt and libc++ to 3.9.0
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 static cl::opt<bool>
44 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
45                            cl::desc("Allow AArch64 SLI/SRI formation"),
46                            cl::init(false));
47
48 // FIXME: The necessary dtprel relocations don't seem to be supported
49 // well in the GNU bfd and gold linkers at the moment. Therefore, by
50 // default, for now, fall back to GeneralDynamic code generation.
51 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52     "aarch64-elf-ldtls-generation", cl::Hidden,
53     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
54     cl::init(false));
55
56 // Disabled for causing self-hosting failures once returned-attribute inference
57 // was enabled.
58 static cl::opt<bool>
59 EnableThisRetForwarding("aarch64-this-return-forwarding", cl::Hidden,
60                         cl::desc("Directly forward this return"),
61                         cl::init(false));
62
63 /// Value type used for condition codes.
64 static const MVT MVT_CC = MVT::i32;
65
66 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
67                                              const AArch64Subtarget &STI)
68     : TargetLowering(TM), Subtarget(&STI) {
69
70   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
71   // we have to make something up. Arbitrarily, choose ZeroOrOne.
72   setBooleanContents(ZeroOrOneBooleanContent);
73   // When comparing vectors the result sets the different elements in the
74   // vector to all-one or all-zero.
75   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
76
77   // Set up the register classes.
78   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
79   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
80
81   if (Subtarget->hasFPARMv8()) {
82     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
83     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
84     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
85     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
86   }
87
88   if (Subtarget->hasNEON()) {
89     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
90     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
91     // Someone set us up the NEON.
92     addDRTypeForNEON(MVT::v2f32);
93     addDRTypeForNEON(MVT::v8i8);
94     addDRTypeForNEON(MVT::v4i16);
95     addDRTypeForNEON(MVT::v2i32);
96     addDRTypeForNEON(MVT::v1i64);
97     addDRTypeForNEON(MVT::v1f64);
98     addDRTypeForNEON(MVT::v4f16);
99
100     addQRTypeForNEON(MVT::v4f32);
101     addQRTypeForNEON(MVT::v2f64);
102     addQRTypeForNEON(MVT::v16i8);
103     addQRTypeForNEON(MVT::v8i16);
104     addQRTypeForNEON(MVT::v4i32);
105     addQRTypeForNEON(MVT::v2i64);
106     addQRTypeForNEON(MVT::v8f16);
107   }
108
109   // Compute derived properties from the register classes
110   computeRegisterProperties(Subtarget->getRegisterInfo());
111
112   // Provide all sorts of operation actions
113   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
114   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
115   setOperationAction(ISD::SETCC, MVT::i32, Custom);
116   setOperationAction(ISD::SETCC, MVT::i64, Custom);
117   setOperationAction(ISD::SETCC, MVT::f32, Custom);
118   setOperationAction(ISD::SETCC, MVT::f64, Custom);
119   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
120   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
121   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
123   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
124   setOperationAction(ISD::SELECT, MVT::i32, Custom);
125   setOperationAction(ISD::SELECT, MVT::i64, Custom);
126   setOperationAction(ISD::SELECT, MVT::f32, Custom);
127   setOperationAction(ISD::SELECT, MVT::f64, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
131   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
132   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
133   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134
135   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
137   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
138
139   setOperationAction(ISD::FREM, MVT::f32, Expand);
140   setOperationAction(ISD::FREM, MVT::f64, Expand);
141   setOperationAction(ISD::FREM, MVT::f80, Expand);
142
143   // Custom lowering hooks are needed for XOR
144   // to fold it into CSINC/CSINV.
145   setOperationAction(ISD::XOR, MVT::i32, Custom);
146   setOperationAction(ISD::XOR, MVT::i64, Custom);
147
148   // Virtually no operation on f128 is legal, but LLVM can't expand them when
149   // there's a valid register class, so we need custom operations in most cases.
150   setOperationAction(ISD::FABS, MVT::f128, Expand);
151   setOperationAction(ISD::FADD, MVT::f128, Custom);
152   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
153   setOperationAction(ISD::FCOS, MVT::f128, Expand);
154   setOperationAction(ISD::FDIV, MVT::f128, Custom);
155   setOperationAction(ISD::FMA, MVT::f128, Expand);
156   setOperationAction(ISD::FMUL, MVT::f128, Custom);
157   setOperationAction(ISD::FNEG, MVT::f128, Expand);
158   setOperationAction(ISD::FPOW, MVT::f128, Expand);
159   setOperationAction(ISD::FREM, MVT::f128, Expand);
160   setOperationAction(ISD::FRINT, MVT::f128, Expand);
161   setOperationAction(ISD::FSIN, MVT::f128, Expand);
162   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
163   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
164   setOperationAction(ISD::FSUB, MVT::f128, Custom);
165   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
166   setOperationAction(ISD::SETCC, MVT::f128, Custom);
167   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
168   setOperationAction(ISD::SELECT, MVT::f128, Custom);
169   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
170   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
171
172   // Lowering for many of the conversions is actually specified by the non-f128
173   // type. The LowerXXX function will be trivial when f128 isn't involved.
174   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
175   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
176   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
177   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
178   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
179   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
180   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
181   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
182   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
183   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
184   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
185   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
186   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
187   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
188
189   // Variable arguments.
190   setOperationAction(ISD::VASTART, MVT::Other, Custom);
191   setOperationAction(ISD::VAARG, MVT::Other, Custom);
192   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
193   setOperationAction(ISD::VAEND, MVT::Other, Expand);
194
195   // Variable-sized objects.
196   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
197   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
198   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
199
200   // Constant pool entries
201   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
202
203   // BlockAddress
204   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
205
206   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
207   setOperationAction(ISD::ADDC, MVT::i32, Custom);
208   setOperationAction(ISD::ADDE, MVT::i32, Custom);
209   setOperationAction(ISD::SUBC, MVT::i32, Custom);
210   setOperationAction(ISD::SUBE, MVT::i32, Custom);
211   setOperationAction(ISD::ADDC, MVT::i64, Custom);
212   setOperationAction(ISD::ADDE, MVT::i64, Custom);
213   setOperationAction(ISD::SUBC, MVT::i64, Custom);
214   setOperationAction(ISD::SUBE, MVT::i64, Custom);
215
216   // AArch64 lacks both left-rotate and popcount instructions.
217   setOperationAction(ISD::ROTL, MVT::i32, Expand);
218   setOperationAction(ISD::ROTL, MVT::i64, Expand);
219   for (MVT VT : MVT::vector_valuetypes()) {
220     setOperationAction(ISD::ROTL, VT, Expand);
221     setOperationAction(ISD::ROTR, VT, Expand);
222   }
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   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
230   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
231
232   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
233   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
234   for (MVT VT : MVT::vector_valuetypes()) {
235     setOperationAction(ISD::SDIVREM, VT, Expand);
236     setOperationAction(ISD::UDIVREM, VT, Expand);
237   }
238   setOperationAction(ISD::SREM, MVT::i32, Expand);
239   setOperationAction(ISD::SREM, MVT::i64, Expand);
240   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
241   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
242   setOperationAction(ISD::UREM, MVT::i32, Expand);
243   setOperationAction(ISD::UREM, MVT::i64, Expand);
244
245   // Custom lower Add/Sub/Mul with overflow.
246   setOperationAction(ISD::SADDO, MVT::i32, Custom);
247   setOperationAction(ISD::SADDO, MVT::i64, Custom);
248   setOperationAction(ISD::UADDO, MVT::i32, Custom);
249   setOperationAction(ISD::UADDO, MVT::i64, Custom);
250   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
251   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
252   setOperationAction(ISD::USUBO, MVT::i32, Custom);
253   setOperationAction(ISD::USUBO, MVT::i64, Custom);
254   setOperationAction(ISD::SMULO, MVT::i32, Custom);
255   setOperationAction(ISD::SMULO, MVT::i64, Custom);
256   setOperationAction(ISD::UMULO, MVT::i32, Custom);
257   setOperationAction(ISD::UMULO, MVT::i64, Custom);
258
259   setOperationAction(ISD::FSIN, MVT::f32, Expand);
260   setOperationAction(ISD::FSIN, MVT::f64, Expand);
261   setOperationAction(ISD::FCOS, MVT::f32, Expand);
262   setOperationAction(ISD::FCOS, MVT::f64, Expand);
263   setOperationAction(ISD::FPOW, MVT::f32, Expand);
264   setOperationAction(ISD::FPOW, MVT::f64, Expand);
265   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
266   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
267
268   // f16 is a storage-only type, always promote it to f32.
269   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
270   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
271   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
272   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
273   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
274   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
275   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
276   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
277   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
278   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
279   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
280   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
281   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
282   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
283   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
284   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
285   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
286   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
287   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
288   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
289   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
290   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
291   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
292   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
293   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
294   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
295   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
296   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
297   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
298   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
299   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
300   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
301   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
302   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
303
304   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
305   // known to be safe.
306   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
307   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
308   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
309   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
310   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
311   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
312   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
313   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
314   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
315   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
316   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
317   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
318
319   // Expand all other v4f16 operations.
320   // FIXME: We could generate better code by promoting some operations to
321   // a pair of v4f32s
322   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
323   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
324   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
325   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
326   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
327   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
328   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
329   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
330   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
331   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
332   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
333   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
334   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
335   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
336   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
337   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
338   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
339   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
340   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
341   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
342   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
343   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
344   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
345   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
346   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
347   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
348
349
350   // v8f16 is also a storage-only type, so expand it.
351   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
352   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
353   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
354   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
355   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
356   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
357   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
358   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
359   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
360   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
361   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
362   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
363   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
364   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
365   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
366   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
367   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
368   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
369   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
370   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
371   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
372   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
373   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
374   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
375   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
376   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
377   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
378   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
379   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
380   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
381   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
382
383   // AArch64 has implementations of a lot of rounding-like FP operations.
384   for (MVT Ty : {MVT::f32, MVT::f64}) {
385     setOperationAction(ISD::FFLOOR, Ty, Legal);
386     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
387     setOperationAction(ISD::FCEIL, Ty, Legal);
388     setOperationAction(ISD::FRINT, Ty, Legal);
389     setOperationAction(ISD::FTRUNC, Ty, Legal);
390     setOperationAction(ISD::FROUND, Ty, Legal);
391     setOperationAction(ISD::FMINNUM, Ty, Legal);
392     setOperationAction(ISD::FMAXNUM, Ty, Legal);
393     setOperationAction(ISD::FMINNAN, Ty, Legal);
394     setOperationAction(ISD::FMAXNAN, Ty, Legal);
395   }
396
397   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
398
399   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
400
401   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
402   // This requires the Performance Monitors extension.
403   if (Subtarget->hasPerfMon())
404     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
405
406   if (Subtarget->isTargetMachO()) {
407     // For iOS, we don't want to the normal expansion of a libcall to
408     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
409     // traffic.
410     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
411     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
412   } else {
413     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
414     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
415   }
416
417   // Make floating-point constants legal for the large code model, so they don't
418   // become loads from the constant pool.
419   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
420     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
421     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
422   }
423
424   // AArch64 does not have floating-point extending loads, i1 sign-extending
425   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
426   for (MVT VT : MVT::fp_valuetypes()) {
427     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
428     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
429     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
431   }
432   for (MVT VT : MVT::integer_valuetypes())
433     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
434
435   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
436   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
437   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
438   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
439   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
440   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
442
443   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
444   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
445
446   // Indexed loads and stores are supported.
447   for (unsigned im = (unsigned)ISD::PRE_INC;
448        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
449     setIndexedLoadAction(im, MVT::i8, Legal);
450     setIndexedLoadAction(im, MVT::i16, Legal);
451     setIndexedLoadAction(im, MVT::i32, Legal);
452     setIndexedLoadAction(im, MVT::i64, Legal);
453     setIndexedLoadAction(im, MVT::f64, Legal);
454     setIndexedLoadAction(im, MVT::f32, Legal);
455     setIndexedLoadAction(im, MVT::f16, Legal);
456     setIndexedStoreAction(im, MVT::i8, Legal);
457     setIndexedStoreAction(im, MVT::i16, Legal);
458     setIndexedStoreAction(im, MVT::i32, Legal);
459     setIndexedStoreAction(im, MVT::i64, Legal);
460     setIndexedStoreAction(im, MVT::f64, Legal);
461     setIndexedStoreAction(im, MVT::f32, Legal);
462     setIndexedStoreAction(im, MVT::f16, Legal);
463   }
464
465   // Trap.
466   setOperationAction(ISD::TRAP, MVT::Other, Legal);
467
468   // We combine OR nodes for bitfield operations.
469   setTargetDAGCombine(ISD::OR);
470
471   // Vector add and sub nodes may conceal a high-half opportunity.
472   // Also, try to fold ADD into CSINC/CSINV..
473   setTargetDAGCombine(ISD::ADD);
474   setTargetDAGCombine(ISD::SUB);
475   setTargetDAGCombine(ISD::SRL);
476   setTargetDAGCombine(ISD::XOR);
477   setTargetDAGCombine(ISD::SINT_TO_FP);
478   setTargetDAGCombine(ISD::UINT_TO_FP);
479
480   setTargetDAGCombine(ISD::FP_TO_SINT);
481   setTargetDAGCombine(ISD::FP_TO_UINT);
482   setTargetDAGCombine(ISD::FDIV);
483
484   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
485
486   setTargetDAGCombine(ISD::ANY_EXTEND);
487   setTargetDAGCombine(ISD::ZERO_EXTEND);
488   setTargetDAGCombine(ISD::SIGN_EXTEND);
489   setTargetDAGCombine(ISD::BITCAST);
490   setTargetDAGCombine(ISD::CONCAT_VECTORS);
491   setTargetDAGCombine(ISD::STORE);
492   if (Subtarget->supportsAddressTopByteIgnored())
493     setTargetDAGCombine(ISD::LOAD);
494
495   setTargetDAGCombine(ISD::MUL);
496
497   setTargetDAGCombine(ISD::SELECT);
498   setTargetDAGCombine(ISD::VSELECT);
499
500   setTargetDAGCombine(ISD::INTRINSIC_VOID);
501   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
503   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
504
505   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
506   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
507   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
508
509   setStackPointerRegisterToSaveRestore(AArch64::SP);
510
511   setSchedulingPreference(Sched::Hybrid);
512
513   // Enable TBZ/TBNZ
514   MaskAndBranchFoldingIsLegal = true;
515   EnableExtLdPromotion = true;
516
517   // Set required alignment.
518   setMinFunctionAlignment(2);
519   // Set preferred alignments.
520   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
521   setPrefLoopAlignment(STI.getPrefLoopAlignment());
522
523   setHasExtractBitsInsn(true);
524
525   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526
527   if (Subtarget->hasNEON()) {
528     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529     // silliness like this:
530     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555
556     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561
562     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563
564     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565     // elements smaller than i32, so promote the input to i32 first.
566     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
570     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571     // -> v8f16 conversions.
572     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
576     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
581     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
582     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
585
586     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
587     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
588
589     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
590     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
591     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
592     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
593     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
594     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
595     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
596     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
597
598     // AArch64 doesn't have MUL.2d:
599     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
600     // Custom handling for some quad-vector types to detect MULL.
601     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
602     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
603     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
604
605     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
606     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
607     // Likewise, narrowing and extending vector loads/stores aren't handled
608     // directly.
609     for (MVT VT : MVT::vector_valuetypes()) {
610       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
611
612       setOperationAction(ISD::MULHS, VT, Expand);
613       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
614       setOperationAction(ISD::MULHU, VT, Expand);
615       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
616
617       setOperationAction(ISD::BSWAP, VT, Expand);
618
619       for (MVT InnerVT : MVT::vector_valuetypes()) {
620         setTruncStoreAction(VT, InnerVT, Expand);
621         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
622         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
623         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
624       }
625     }
626
627     // AArch64 has implementations of a lot of rounding-like FP operations.
628     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
629       setOperationAction(ISD::FFLOOR, Ty, Legal);
630       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
631       setOperationAction(ISD::FCEIL, Ty, Legal);
632       setOperationAction(ISD::FRINT, Ty, Legal);
633       setOperationAction(ISD::FTRUNC, Ty, Legal);
634       setOperationAction(ISD::FROUND, Ty, Legal);
635     }
636   }
637
638   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
639 }
640
641 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
642   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
643     setOperationAction(ISD::LOAD, VT, Promote);
644     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
645
646     setOperationAction(ISD::STORE, VT, Promote);
647     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
648   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
649     setOperationAction(ISD::LOAD, VT, Promote);
650     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
651
652     setOperationAction(ISD::STORE, VT, Promote);
653     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
654   }
655
656   // Mark vector float intrinsics as expand.
657   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
658     setOperationAction(ISD::FSIN, VT, Expand);
659     setOperationAction(ISD::FCOS, VT, Expand);
660     setOperationAction(ISD::FPOWI, VT, Expand);
661     setOperationAction(ISD::FPOW, VT, Expand);
662     setOperationAction(ISD::FLOG, VT, Expand);
663     setOperationAction(ISD::FLOG2, VT, Expand);
664     setOperationAction(ISD::FLOG10, VT, Expand);
665     setOperationAction(ISD::FEXP, VT, Expand);
666     setOperationAction(ISD::FEXP2, VT, Expand);
667
668     // But we do support custom-lowering for FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
670   }
671
672   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
673   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
674   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
675   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
676   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
677   setOperationAction(ISD::SRA, VT, Custom);
678   setOperationAction(ISD::SRL, VT, Custom);
679   setOperationAction(ISD::SHL, VT, Custom);
680   setOperationAction(ISD::AND, VT, Custom);
681   setOperationAction(ISD::OR, VT, Custom);
682   setOperationAction(ISD::SETCC, VT, Custom);
683   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
684
685   setOperationAction(ISD::SELECT, VT, Expand);
686   setOperationAction(ISD::SELECT_CC, VT, Expand);
687   setOperationAction(ISD::VSELECT, VT, Expand);
688   for (MVT InnerVT : MVT::all_valuetypes())
689     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
690
691   // CNT supports only B element sizes.
692   if (VT != MVT::v8i8 && VT != MVT::v16i8)
693     setOperationAction(ISD::CTPOP, VT, Expand);
694
695   setOperationAction(ISD::UDIV, VT, Expand);
696   setOperationAction(ISD::SDIV, VT, Expand);
697   setOperationAction(ISD::UREM, VT, Expand);
698   setOperationAction(ISD::SREM, VT, Expand);
699   setOperationAction(ISD::FREM, VT, Expand);
700
701   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
702   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
703
704   // [SU][MIN|MAX] are available for all NEON types apart from i64.
705   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
706     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
707       setOperationAction(Opcode, VT, Legal);
708
709   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
710   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
711     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
712                             ISD::FMINNUM, ISD::FMAXNUM})
713       setOperationAction(Opcode, VT, Legal);
714
715   if (Subtarget->isLittleEndian()) {
716     for (unsigned im = (unsigned)ISD::PRE_INC;
717          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
718       setIndexedLoadAction(im, VT, Legal);
719       setIndexedStoreAction(im, VT, Legal);
720     }
721   }
722 }
723
724 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
725   addRegisterClass(VT, &AArch64::FPR64RegClass);
726   addTypeForNEON(VT, MVT::v2i32);
727 }
728
729 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
730   addRegisterClass(VT, &AArch64::FPR128RegClass);
731   addTypeForNEON(VT, MVT::v4i32);
732 }
733
734 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
735                                               EVT VT) const {
736   if (!VT.isVector())
737     return MVT::i32;
738   return VT.changeVectorElementTypeToInteger();
739 }
740
741 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
742 /// Mask are known to be either zero or one and return them in the
743 /// KnownZero/KnownOne bitsets.
744 void AArch64TargetLowering::computeKnownBitsForTargetNode(
745     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
746     const SelectionDAG &DAG, unsigned Depth) const {
747   switch (Op.getOpcode()) {
748   default:
749     break;
750   case AArch64ISD::CSEL: {
751     APInt KnownZero2, KnownOne2;
752     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
753     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
754     KnownZero &= KnownZero2;
755     KnownOne &= KnownOne2;
756     break;
757   }
758   case ISD::INTRINSIC_W_CHAIN: {
759     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
760     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
761     switch (IntID) {
762     default: return;
763     case Intrinsic::aarch64_ldaxr:
764     case Intrinsic::aarch64_ldxr: {
765       unsigned BitWidth = KnownOne.getBitWidth();
766       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
767       unsigned MemBits = VT.getScalarType().getSizeInBits();
768       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
769       return;
770     }
771     }
772     break;
773   }
774   case ISD::INTRINSIC_WO_CHAIN:
775   case ISD::INTRINSIC_VOID: {
776     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
777     switch (IntNo) {
778     default:
779       break;
780     case Intrinsic::aarch64_neon_umaxv:
781     case Intrinsic::aarch64_neon_uminv: {
782       // Figure out the datatype of the vector operand. The UMINV instruction
783       // will zero extend the result, so we can mark as known zero all the
784       // bits larger than the element datatype. 32-bit or larget doesn't need
785       // this as those are legal types and will be handled by isel directly.
786       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
787       unsigned BitWidth = KnownZero.getBitWidth();
788       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
789         assert(BitWidth >= 8 && "Unexpected width!");
790         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
791         KnownZero |= Mask;
792       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
793         assert(BitWidth >= 16 && "Unexpected width!");
794         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
795         KnownZero |= Mask;
796       }
797       break;
798     } break;
799     }
800   }
801   }
802 }
803
804 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
805                                                   EVT) const {
806   return MVT::i64;
807 }
808
809 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
810                                                            unsigned AddrSpace,
811                                                            unsigned Align,
812                                                            bool *Fast) const {
813   if (Subtarget->requiresStrictAlign())
814     return false;
815
816   if (Fast) {
817     // Some CPUs are fine with unaligned stores except for 128-bit ones.
818     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
819             // See comments in performSTORECombine() for more details about
820             // these conditions.
821
822             // Code that uses clang vector extensions can mark that it
823             // wants unaligned accesses to be treated as fast by
824             // underspecifying alignment to be 1 or 2.
825             Align <= 2 ||
826
827             // Disregard v2i64. Memcpy lowering produces those and splitting
828             // them regresses performance on micro-benchmarks and olden/bh.
829             VT == MVT::v2i64;
830   }
831   return true;
832 }
833
834 FastISel *
835 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
836                                       const TargetLibraryInfo *libInfo) const {
837   return AArch64::createFastISel(funcInfo, libInfo);
838 }
839
840 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
841   switch ((AArch64ISD::NodeType)Opcode) {
842   case AArch64ISD::FIRST_NUMBER:      break;
843   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
844   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
845   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
846   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
847   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
848   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
849   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
850   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
851   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
852   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
853   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
854   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
855   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
856   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
857   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
858   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
859   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
860   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
861   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
862   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
863   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
864   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
865   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
866   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
867   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
868   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
869   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
870   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
871   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
872   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
873   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
874   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
875   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
876   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
877   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
878   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
879   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
880   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
881   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
882   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
883   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
884   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
885   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
886   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
887   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
888   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
889   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
890   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
891   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
892   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
893   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
894   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
895   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
896   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
897   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
898   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
899   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
900   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
901   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
902   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
903   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
904   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
905   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
906   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
907   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
908   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
909   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
910   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
911   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
912   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
913   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
914   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
915   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
916   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
917   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
918   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
919   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
920   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
921   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
922   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
923   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
924   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
925   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
926   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
927   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
928   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
929   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
930   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
931   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
932   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
933   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
934   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
935   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
936   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
937   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
938   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
939   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
940   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
941   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
942   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
943   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
944   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
945   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
946   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
947   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
948   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
949   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
950   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
951   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
952   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
953   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
954   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
955   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
956   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
957   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
958   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
959   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
960   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
961   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
962   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
963   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
964   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
965   }
966   return nullptr;
967 }
968
969 MachineBasicBlock *
970 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
971                                     MachineBasicBlock *MBB) const {
972   // We materialise the F128CSEL pseudo-instruction as some control flow and a
973   // phi node:
974
975   // OrigBB:
976   //     [... previous instrs leading to comparison ...]
977   //     b.ne TrueBB
978   //     b EndBB
979   // TrueBB:
980   //     ; Fallthrough
981   // EndBB:
982   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
983
984   MachineFunction *MF = MBB->getParent();
985   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
986   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
987   DebugLoc DL = MI.getDebugLoc();
988   MachineFunction::iterator It = ++MBB->getIterator();
989
990   unsigned DestReg = MI.getOperand(0).getReg();
991   unsigned IfTrueReg = MI.getOperand(1).getReg();
992   unsigned IfFalseReg = MI.getOperand(2).getReg();
993   unsigned CondCode = MI.getOperand(3).getImm();
994   bool NZCVKilled = MI.getOperand(4).isKill();
995
996   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
997   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
998   MF->insert(It, TrueBB);
999   MF->insert(It, EndBB);
1000
1001   // Transfer rest of current basic-block to EndBB
1002   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1003                 MBB->end());
1004   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1005
1006   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1007   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1008   MBB->addSuccessor(TrueBB);
1009   MBB->addSuccessor(EndBB);
1010
1011   // TrueBB falls through to the end.
1012   TrueBB->addSuccessor(EndBB);
1013
1014   if (!NZCVKilled) {
1015     TrueBB->addLiveIn(AArch64::NZCV);
1016     EndBB->addLiveIn(AArch64::NZCV);
1017   }
1018
1019   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1020       .addReg(IfTrueReg)
1021       .addMBB(TrueBB)
1022       .addReg(IfFalseReg)
1023       .addMBB(MBB);
1024
1025   MI.eraseFromParent();
1026   return EndBB;
1027 }
1028
1029 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1030     MachineInstr &MI, MachineBasicBlock *BB) const {
1031   switch (MI.getOpcode()) {
1032   default:
1033 #ifndef NDEBUG
1034     MI.dump();
1035 #endif
1036     llvm_unreachable("Unexpected instruction for custom inserter!");
1037
1038   case AArch64::F128CSEL:
1039     return EmitF128CSEL(MI, BB);
1040
1041   case TargetOpcode::STACKMAP:
1042   case TargetOpcode::PATCHPOINT:
1043     return emitPatchPoint(MI, BB);
1044   }
1045 }
1046
1047 //===----------------------------------------------------------------------===//
1048 // AArch64 Lowering private implementation.
1049 //===----------------------------------------------------------------------===//
1050
1051 //===----------------------------------------------------------------------===//
1052 // Lowering Code
1053 //===----------------------------------------------------------------------===//
1054
1055 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1056 /// CC
1057 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1058   switch (CC) {
1059   default:
1060     llvm_unreachable("Unknown condition code!");
1061   case ISD::SETNE:
1062     return AArch64CC::NE;
1063   case ISD::SETEQ:
1064     return AArch64CC::EQ;
1065   case ISD::SETGT:
1066     return AArch64CC::GT;
1067   case ISD::SETGE:
1068     return AArch64CC::GE;
1069   case ISD::SETLT:
1070     return AArch64CC::LT;
1071   case ISD::SETLE:
1072     return AArch64CC::LE;
1073   case ISD::SETUGT:
1074     return AArch64CC::HI;
1075   case ISD::SETUGE:
1076     return AArch64CC::HS;
1077   case ISD::SETULT:
1078     return AArch64CC::LO;
1079   case ISD::SETULE:
1080     return AArch64CC::LS;
1081   }
1082 }
1083
1084 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1085 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1086                                   AArch64CC::CondCode &CondCode,
1087                                   AArch64CC::CondCode &CondCode2) {
1088   CondCode2 = AArch64CC::AL;
1089   switch (CC) {
1090   default:
1091     llvm_unreachable("Unknown FP condition!");
1092   case ISD::SETEQ:
1093   case ISD::SETOEQ:
1094     CondCode = AArch64CC::EQ;
1095     break;
1096   case ISD::SETGT:
1097   case ISD::SETOGT:
1098     CondCode = AArch64CC::GT;
1099     break;
1100   case ISD::SETGE:
1101   case ISD::SETOGE:
1102     CondCode = AArch64CC::GE;
1103     break;
1104   case ISD::SETOLT:
1105     CondCode = AArch64CC::MI;
1106     break;
1107   case ISD::SETOLE:
1108     CondCode = AArch64CC::LS;
1109     break;
1110   case ISD::SETONE:
1111     CondCode = AArch64CC::MI;
1112     CondCode2 = AArch64CC::GT;
1113     break;
1114   case ISD::SETO:
1115     CondCode = AArch64CC::VC;
1116     break;
1117   case ISD::SETUO:
1118     CondCode = AArch64CC::VS;
1119     break;
1120   case ISD::SETUEQ:
1121     CondCode = AArch64CC::EQ;
1122     CondCode2 = AArch64CC::VS;
1123     break;
1124   case ISD::SETUGT:
1125     CondCode = AArch64CC::HI;
1126     break;
1127   case ISD::SETUGE:
1128     CondCode = AArch64CC::PL;
1129     break;
1130   case ISD::SETLT:
1131   case ISD::SETULT:
1132     CondCode = AArch64CC::LT;
1133     break;
1134   case ISD::SETLE:
1135   case ISD::SETULE:
1136     CondCode = AArch64CC::LE;
1137     break;
1138   case ISD::SETNE:
1139   case ISD::SETUNE:
1140     CondCode = AArch64CC::NE;
1141     break;
1142   }
1143 }
1144
1145 /// Convert a DAG fp condition code to an AArch64 CC.
1146 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1147 /// should be AND'ed instead of OR'ed.
1148 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1149                                      AArch64CC::CondCode &CondCode,
1150                                      AArch64CC::CondCode &CondCode2) {
1151   CondCode2 = AArch64CC::AL;
1152   switch (CC) {
1153   default:
1154     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1155     assert(CondCode2 == AArch64CC::AL);
1156     break;
1157   case ISD::SETONE:
1158     // (a one b)
1159     // == ((a olt b) || (a ogt b))
1160     // == ((a ord b) && (a une b))
1161     CondCode = AArch64CC::VC;
1162     CondCode2 = AArch64CC::NE;
1163     break;
1164   case ISD::SETUEQ:
1165     // (a ueq b)
1166     // == ((a uno b) || (a oeq b))
1167     // == ((a ule b) && (a uge b))
1168     CondCode = AArch64CC::PL;
1169     CondCode2 = AArch64CC::LE;
1170     break;
1171   }
1172 }
1173
1174 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1175 /// CC usable with the vector instructions. Fewer operations are available
1176 /// without a real NZCV register, so we have to use less efficient combinations
1177 /// to get the same effect.
1178 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1179                                         AArch64CC::CondCode &CondCode,
1180                                         AArch64CC::CondCode &CondCode2,
1181                                         bool &Invert) {
1182   Invert = false;
1183   switch (CC) {
1184   default:
1185     // Mostly the scalar mappings work fine.
1186     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1187     break;
1188   case ISD::SETUO:
1189     Invert = true; // Fallthrough
1190   case ISD::SETO:
1191     CondCode = AArch64CC::MI;
1192     CondCode2 = AArch64CC::GE;
1193     break;
1194   case ISD::SETUEQ:
1195   case ISD::SETULT:
1196   case ISD::SETULE:
1197   case ISD::SETUGT:
1198   case ISD::SETUGE:
1199     // All of the compare-mask comparisons are ordered, but we can switch
1200     // between the two by a double inversion. E.g. ULE == !OGT.
1201     Invert = true;
1202     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1203     break;
1204   }
1205 }
1206
1207 static bool isLegalArithImmed(uint64_t C) {
1208   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1209   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1210 }
1211
1212 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1213                               const SDLoc &dl, SelectionDAG &DAG) {
1214   EVT VT = LHS.getValueType();
1215
1216   if (VT.isFloatingPoint()) {
1217     assert(VT != MVT::f128);
1218     if (VT == MVT::f16) {
1219       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1220       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1221       VT = MVT::f32;
1222     }
1223     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1224   }
1225
1226   // The CMP instruction is just an alias for SUBS, and representing it as
1227   // SUBS means that it's possible to get CSE with subtract operations.
1228   // A later phase can perform the optimization of setting the destination
1229   // register to WZR/XZR if it ends up being unused.
1230   unsigned Opcode = AArch64ISD::SUBS;
1231
1232   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1233       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1234     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1235     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1236     // can be set differently by this operation. It comes down to whether
1237     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1238     // everything is fine. If not then the optimization is wrong. Thus general
1239     // comparisons are only valid if op2 != 0.
1240
1241     // So, finally, the only LLVM-native comparisons that don't mention C and V
1242     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1243     // the absence of information about op2.
1244     Opcode = AArch64ISD::ADDS;
1245     RHS = RHS.getOperand(1);
1246   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1247              !isUnsignedIntSetCC(CC)) {
1248     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1249     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1250     // of the signed comparisons.
1251     Opcode = AArch64ISD::ANDS;
1252     RHS = LHS.getOperand(1);
1253     LHS = LHS.getOperand(0);
1254   }
1255
1256   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1257       .getValue(1);
1258 }
1259
1260 /// \defgroup AArch64CCMP CMP;CCMP matching
1261 ///
1262 /// These functions deal with the formation of CMP;CCMP;... sequences.
1263 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1264 /// a comparison. They set the NZCV flags to a predefined value if their
1265 /// predicate is false. This allows to express arbitrary conjunctions, for
1266 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1267 /// expressed as:
1268 ///   cmp A
1269 ///   ccmp B, inv(CB), CA
1270 ///   check for CB flags
1271 ///
1272 /// In general we can create code for arbitrary "... (and (and A B) C)"
1273 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1274 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1275 /// negation operations:
1276 /// We can negate the results of a single comparison by inverting the flags
1277 /// used when the predicate fails and inverting the flags tested in the next
1278 /// instruction; We can also negate the results of the whole previous
1279 /// conditional compare sequence by inverting the flags tested in the next
1280 /// instruction. However there is no way to negate the result of a partial
1281 /// sequence.
1282 ///
1283 /// Therefore on encountering an "or" expression we can negate the subtree on
1284 /// one side and have to be able to push the negate to the leafs of the subtree
1285 /// on the other side (see also the comments in code). As complete example:
1286 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1287 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1288 /// is transformed to
1289 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1290 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1291 /// and implemented as:
1292 ///   cmp C
1293 ///   ccmp D, inv(CD), CC
1294 ///   ccmp A, CA, inv(CD)
1295 ///   ccmp B, CB, inv(CA)
1296 ///   check for CB flags
1297 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1298 /// by conditional compare sequences.
1299 /// @{
1300
1301 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1302 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1303                                          ISD::CondCode CC, SDValue CCOp,
1304                                          AArch64CC::CondCode Predicate,
1305                                          AArch64CC::CondCode OutCC,
1306                                          const SDLoc &DL, SelectionDAG &DAG) {
1307   unsigned Opcode = 0;
1308   if (LHS.getValueType().isFloatingPoint()) {
1309     assert(LHS.getValueType() != MVT::f128);
1310     if (LHS.getValueType() == MVT::f16) {
1311       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1312       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1313     }
1314     Opcode = AArch64ISD::FCCMP;
1315   } else if (RHS.getOpcode() == ISD::SUB) {
1316     SDValue SubOp0 = RHS.getOperand(0);
1317     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1318       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1319       Opcode = AArch64ISD::CCMN;
1320       RHS = RHS.getOperand(1);
1321     }
1322   }
1323   if (Opcode == 0)
1324     Opcode = AArch64ISD::CCMP;
1325
1326   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1327   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1328   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1329   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1330   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1331 }
1332
1333 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1334 /// CanPushNegate is set to true if we can push a negate operation through
1335 /// the tree in a was that we are left with AND operations and negate operations
1336 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1337 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1338 /// brought into such a form.
1339 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1340                                          unsigned Depth = 0) {
1341   if (!Val.hasOneUse())
1342     return false;
1343   unsigned Opcode = Val->getOpcode();
1344   if (Opcode == ISD::SETCC) {
1345     if (Val->getOperand(0).getValueType() == MVT::f128)
1346       return false;
1347     CanNegate = true;
1348     return true;
1349   }
1350   // Protect against exponential runtime and stack overflow.
1351   if (Depth > 6)
1352     return false;
1353   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1354     SDValue O0 = Val->getOperand(0);
1355     SDValue O1 = Val->getOperand(1);
1356     bool CanNegateL;
1357     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1358       return false;
1359     bool CanNegateR;
1360     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1361       return false;
1362
1363     if (Opcode == ISD::OR) {
1364       // For an OR expression we need to be able to negate at least one side or
1365       // we cannot do the transformation at all.
1366       if (!CanNegateL && !CanNegateR)
1367         return false;
1368       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1369       // can negate the x and y subtrees.
1370       CanNegate = CanNegateL && CanNegateR;
1371     } else {
1372       // If the operands are OR expressions then we finally need to negate their
1373       // outputs, we can only do that for the operand with emitted last by
1374       // negating OutCC, not for both operands.
1375       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1376       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1377       if (NeedsNegOutL && NeedsNegOutR)
1378         return false;
1379       // We cannot negate an AND operation (it would become an OR),
1380       CanNegate = false;
1381     }
1382     return true;
1383   }
1384   return false;
1385 }
1386
1387 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1388 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1389 /// Tries to transform the given i1 producing node @p Val to a series compare
1390 /// and conditional compare operations. @returns an NZCV flags producing node
1391 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1392 /// transformation was not possible.
1393 /// On recursive invocations @p PushNegate may be set to true to have negation
1394 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1395 /// for the comparisons in the current subtree; @p Depth limits the search
1396 /// depth to avoid stack overflow.
1397 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1398     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1399     AArch64CC::CondCode Predicate) {
1400   // We're at a tree leaf, produce a conditional comparison operation.
1401   unsigned Opcode = Val->getOpcode();
1402   if (Opcode == ISD::SETCC) {
1403     SDValue LHS = Val->getOperand(0);
1404     SDValue RHS = Val->getOperand(1);
1405     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1406     bool isInteger = LHS.getValueType().isInteger();
1407     if (Negate)
1408       CC = getSetCCInverse(CC, isInteger);
1409     SDLoc DL(Val);
1410     // Determine OutCC and handle FP special case.
1411     if (isInteger) {
1412       OutCC = changeIntCCToAArch64CC(CC);
1413     } else {
1414       assert(LHS.getValueType().isFloatingPoint());
1415       AArch64CC::CondCode ExtraCC;
1416       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1417       // Some floating point conditions can't be tested with a single condition
1418       // code. Construct an additional comparison in this case.
1419       if (ExtraCC != AArch64CC::AL) {
1420         SDValue ExtraCmp;
1421         if (!CCOp.getNode())
1422           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1423         else
1424           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1425                                                ExtraCC, DL, DAG);
1426         CCOp = ExtraCmp;
1427         Predicate = ExtraCC;
1428       }
1429     }
1430
1431     // Produce a normal comparison if we are first in the chain
1432     if (!CCOp)
1433       return emitComparison(LHS, RHS, CC, DL, DAG);
1434     // Otherwise produce a ccmp.
1435     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1436                                      DAG);
1437   }
1438   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1439          "Valid conjunction/disjunction tree");
1440
1441   // Check if both sides can be transformed.
1442   SDValue LHS = Val->getOperand(0);
1443   SDValue RHS = Val->getOperand(1);
1444
1445   // In case of an OR we need to negate our operands and the result.
1446   // (A v B) <=> not(not(A) ^ not(B))
1447   bool NegateOpsAndResult = Opcode == ISD::OR;
1448   // We can negate the results of all previous operations by inverting the
1449   // predicate flags giving us a free negation for one side. The other side
1450   // must be negatable by itself.
1451   if (NegateOpsAndResult) {
1452     // See which side we can negate.
1453     bool CanNegateL;
1454     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1455     assert(isValidL && "Valid conjunction/disjunction tree");
1456     (void)isValidL;
1457
1458 #ifndef NDEBUG
1459     bool CanNegateR;
1460     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1461     assert(isValidR && "Valid conjunction/disjunction tree");
1462     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1463 #endif
1464
1465     // Order the side which we cannot negate to RHS so we can emit it first.
1466     if (!CanNegateL)
1467       std::swap(LHS, RHS);
1468   } else {
1469     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1470     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1471            "Valid conjunction/disjunction tree");
1472     // Order the side where we need to negate the output flags to RHS so it
1473     // gets emitted first.
1474     if (NeedsNegOutL)
1475       std::swap(LHS, RHS);
1476   }
1477
1478   // Emit RHS. If we want to negate the tree we only need to push a negate
1479   // through if we are already in a PushNegate case, otherwise we can negate
1480   // the "flags to test" afterwards.
1481   AArch64CC::CondCode RHSCC;
1482   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1483                                                    CCOp, Predicate);
1484   if (NegateOpsAndResult && !Negate)
1485     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1486   // Emit LHS. We may need to negate it.
1487   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1488                                                    NegateOpsAndResult, CmpR,
1489                                                    RHSCC);
1490   // If we transformed an OR to and AND then we have to negate the result
1491   // (or absorb the Negate parameter).
1492   if (NegateOpsAndResult && !Negate)
1493     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1494   return CmpL;
1495 }
1496
1497 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1498 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1499 /// \see emitConjunctionDisjunctionTreeRec().
1500 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1501                                               AArch64CC::CondCode &OutCC) {
1502   bool CanNegate;
1503   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1504     return SDValue();
1505
1506   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1507                                            AArch64CC::AL);
1508 }
1509
1510 /// @}
1511
1512 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1513                              SDValue &AArch64cc, SelectionDAG &DAG,
1514                              const SDLoc &dl) {
1515   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1516     EVT VT = RHS.getValueType();
1517     uint64_t C = RHSC->getZExtValue();
1518     if (!isLegalArithImmed(C)) {
1519       // Constant does not fit, try adjusting it by one?
1520       switch (CC) {
1521       default:
1522         break;
1523       case ISD::SETLT:
1524       case ISD::SETGE:
1525         if ((VT == MVT::i32 && C != 0x80000000 &&
1526              isLegalArithImmed((uint32_t)(C - 1))) ||
1527             (VT == MVT::i64 && C != 0x80000000ULL &&
1528              isLegalArithImmed(C - 1ULL))) {
1529           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1530           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1531           RHS = DAG.getConstant(C, dl, VT);
1532         }
1533         break;
1534       case ISD::SETULT:
1535       case ISD::SETUGE:
1536         if ((VT == MVT::i32 && C != 0 &&
1537              isLegalArithImmed((uint32_t)(C - 1))) ||
1538             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1539           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1540           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1541           RHS = DAG.getConstant(C, dl, VT);
1542         }
1543         break;
1544       case ISD::SETLE:
1545       case ISD::SETGT:
1546         if ((VT == MVT::i32 && C != INT32_MAX &&
1547              isLegalArithImmed((uint32_t)(C + 1))) ||
1548             (VT == MVT::i64 && C != INT64_MAX &&
1549              isLegalArithImmed(C + 1ULL))) {
1550           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1551           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1552           RHS = DAG.getConstant(C, dl, VT);
1553         }
1554         break;
1555       case ISD::SETULE:
1556       case ISD::SETUGT:
1557         if ((VT == MVT::i32 && C != UINT32_MAX &&
1558              isLegalArithImmed((uint32_t)(C + 1))) ||
1559             (VT == MVT::i64 && C != UINT64_MAX &&
1560              isLegalArithImmed(C + 1ULL))) {
1561           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1562           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1563           RHS = DAG.getConstant(C, dl, VT);
1564         }
1565         break;
1566       }
1567     }
1568   }
1569   SDValue Cmp;
1570   AArch64CC::CondCode AArch64CC;
1571   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1572     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1573
1574     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1575     // For the i8 operand, the largest immediate is 255, so this can be easily
1576     // encoded in the compare instruction. For the i16 operand, however, the
1577     // largest immediate cannot be encoded in the compare.
1578     // Therefore, use a sign extending load and cmn to avoid materializing the
1579     // -1 constant. For example,
1580     // movz w1, #65535
1581     // ldrh w0, [x0, #0]
1582     // cmp w0, w1
1583     // >
1584     // ldrsh w0, [x0, #0]
1585     // cmn w0, #1
1586     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1587     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1588     // ensure both the LHS and RHS are truly zero extended and to make sure the
1589     // transformation is profitable.
1590     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1591         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1592         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1593         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1594       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1595       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1596         SDValue SExt =
1597             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1598                         DAG.getValueType(MVT::i16));
1599         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1600                                                    RHS.getValueType()),
1601                              CC, dl, DAG);
1602         AArch64CC = changeIntCCToAArch64CC(CC);
1603       }
1604     }
1605
1606     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1607       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1608         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1609           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1610       }
1611     }
1612   }
1613
1614   if (!Cmp) {
1615     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1616     AArch64CC = changeIntCCToAArch64CC(CC);
1617   }
1618   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1619   return Cmp;
1620 }
1621
1622 static std::pair<SDValue, SDValue>
1623 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1624   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1625          "Unsupported value type");
1626   SDValue Value, Overflow;
1627   SDLoc DL(Op);
1628   SDValue LHS = Op.getOperand(0);
1629   SDValue RHS = Op.getOperand(1);
1630   unsigned Opc = 0;
1631   switch (Op.getOpcode()) {
1632   default:
1633     llvm_unreachable("Unknown overflow instruction!");
1634   case ISD::SADDO:
1635     Opc = AArch64ISD::ADDS;
1636     CC = AArch64CC::VS;
1637     break;
1638   case ISD::UADDO:
1639     Opc = AArch64ISD::ADDS;
1640     CC = AArch64CC::HS;
1641     break;
1642   case ISD::SSUBO:
1643     Opc = AArch64ISD::SUBS;
1644     CC = AArch64CC::VS;
1645     break;
1646   case ISD::USUBO:
1647     Opc = AArch64ISD::SUBS;
1648     CC = AArch64CC::LO;
1649     break;
1650   // Multiply needs a little bit extra work.
1651   case ISD::SMULO:
1652   case ISD::UMULO: {
1653     CC = AArch64CC::NE;
1654     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1655     if (Op.getValueType() == MVT::i32) {
1656       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1657       // For a 32 bit multiply with overflow check we want the instruction
1658       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1659       // need to generate the following pattern:
1660       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1661       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1662       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1663       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1664       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1665                                 DAG.getConstant(0, DL, MVT::i64));
1666       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1667       // operation. We need to clear out the upper 32 bits, because we used a
1668       // widening multiply that wrote all 64 bits. In the end this should be a
1669       // noop.
1670       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1671       if (IsSigned) {
1672         // The signed overflow check requires more than just a simple check for
1673         // any bit set in the upper 32 bits of the result. These bits could be
1674         // just the sign bits of a negative number. To perform the overflow
1675         // check we have to arithmetic shift right the 32nd bit of the result by
1676         // 31 bits. Then we compare the result to the upper 32 bits.
1677         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1678                                         DAG.getConstant(32, DL, MVT::i64));
1679         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1680         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1681                                         DAG.getConstant(31, DL, MVT::i64));
1682         // It is important that LowerBits is last, otherwise the arithmetic
1683         // shift will not be folded into the compare (SUBS).
1684         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1685         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1686                        .getValue(1);
1687       } else {
1688         // The overflow check for unsigned multiply is easy. We only need to
1689         // check if any of the upper 32 bits are set. This can be done with a
1690         // CMP (shifted register). For that we need to generate the following
1691         // pattern:
1692         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1693         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1694                                         DAG.getConstant(32, DL, MVT::i64));
1695         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1696         Overflow =
1697             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1698                         DAG.getConstant(0, DL, MVT::i64),
1699                         UpperBits).getValue(1);
1700       }
1701       break;
1702     }
1703     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1704     // For the 64 bit multiply
1705     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1706     if (IsSigned) {
1707       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1708       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1709                                       DAG.getConstant(63, DL, MVT::i64));
1710       // It is important that LowerBits is last, otherwise the arithmetic
1711       // shift will not be folded into the compare (SUBS).
1712       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1713       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1714                      .getValue(1);
1715     } else {
1716       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1717       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1718       Overflow =
1719           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1720                       DAG.getConstant(0, DL, MVT::i64),
1721                       UpperBits).getValue(1);
1722     }
1723     break;
1724   }
1725   } // switch (...)
1726
1727   if (Opc) {
1728     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1729
1730     // Emit the AArch64 operation with overflow check.
1731     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1732     Overflow = Value.getValue(1);
1733   }
1734   return std::make_pair(Value, Overflow);
1735 }
1736
1737 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1738                                              RTLIB::Libcall Call) const {
1739   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1740   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1741 }
1742
1743 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1744   SDValue Sel = Op.getOperand(0);
1745   SDValue Other = Op.getOperand(1);
1746
1747   // If neither operand is a SELECT_CC, give up.
1748   if (Sel.getOpcode() != ISD::SELECT_CC)
1749     std::swap(Sel, Other);
1750   if (Sel.getOpcode() != ISD::SELECT_CC)
1751     return Op;
1752
1753   // The folding we want to perform is:
1754   // (xor x, (select_cc a, b, cc, 0, -1) )
1755   //   -->
1756   // (csel x, (xor x, -1), cc ...)
1757   //
1758   // The latter will get matched to a CSINV instruction.
1759
1760   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1761   SDValue LHS = Sel.getOperand(0);
1762   SDValue RHS = Sel.getOperand(1);
1763   SDValue TVal = Sel.getOperand(2);
1764   SDValue FVal = Sel.getOperand(3);
1765   SDLoc dl(Sel);
1766
1767   // FIXME: This could be generalized to non-integer comparisons.
1768   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1769     return Op;
1770
1771   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1772   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1773
1774   // The values aren't constants, this isn't the pattern we're looking for.
1775   if (!CFVal || !CTVal)
1776     return Op;
1777
1778   // We can commute the SELECT_CC by inverting the condition.  This
1779   // might be needed to make this fit into a CSINV pattern.
1780   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1781     std::swap(TVal, FVal);
1782     std::swap(CTVal, CFVal);
1783     CC = ISD::getSetCCInverse(CC, true);
1784   }
1785
1786   // If the constants line up, perform the transform!
1787   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1788     SDValue CCVal;
1789     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1790
1791     FVal = Other;
1792     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1793                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1794
1795     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1796                        CCVal, Cmp);
1797   }
1798
1799   return Op;
1800 }
1801
1802 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1803   EVT VT = Op.getValueType();
1804
1805   // Let legalize expand this if it isn't a legal type yet.
1806   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1807     return SDValue();
1808
1809   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1810
1811   unsigned Opc;
1812   bool ExtraOp = false;
1813   switch (Op.getOpcode()) {
1814   default:
1815     llvm_unreachable("Invalid code");
1816   case ISD::ADDC:
1817     Opc = AArch64ISD::ADDS;
1818     break;
1819   case ISD::SUBC:
1820     Opc = AArch64ISD::SUBS;
1821     break;
1822   case ISD::ADDE:
1823     Opc = AArch64ISD::ADCS;
1824     ExtraOp = true;
1825     break;
1826   case ISD::SUBE:
1827     Opc = AArch64ISD::SBCS;
1828     ExtraOp = true;
1829     break;
1830   }
1831
1832   if (!ExtraOp)
1833     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1834   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1835                      Op.getOperand(2));
1836 }
1837
1838 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1839   // Let legalize expand this if it isn't a legal type yet.
1840   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1841     return SDValue();
1842
1843   SDLoc dl(Op);
1844   AArch64CC::CondCode CC;
1845   // The actual operation that sets the overflow or carry flag.
1846   SDValue Value, Overflow;
1847   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1848
1849   // We use 0 and 1 as false and true values.
1850   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1851   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1852
1853   // We use an inverted condition, because the conditional select is inverted
1854   // too. This will allow it to be selected to a single instruction:
1855   // CSINC Wd, WZR, WZR, invert(cond).
1856   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1857   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1858                          CCVal, Overflow);
1859
1860   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1861   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1862 }
1863
1864 // Prefetch operands are:
1865 // 1: Address to prefetch
1866 // 2: bool isWrite
1867 // 3: int locality (0 = no locality ... 3 = extreme locality)
1868 // 4: bool isDataCache
1869 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1870   SDLoc DL(Op);
1871   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1872   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1873   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1874
1875   bool IsStream = !Locality;
1876   // When the locality number is set
1877   if (Locality) {
1878     // The front-end should have filtered out the out-of-range values
1879     assert(Locality <= 3 && "Prefetch locality out-of-range");
1880     // The locality degree is the opposite of the cache speed.
1881     // Put the number the other way around.
1882     // The encoding starts at 0 for level 1
1883     Locality = 3 - Locality;
1884   }
1885
1886   // built the mask value encoding the expected behavior.
1887   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1888                    (!IsData << 3) |     // IsDataCache bit
1889                    (Locality << 1) |    // Cache level bits
1890                    (unsigned)IsStream;  // Stream bit
1891   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1892                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1893 }
1894
1895 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1896                                               SelectionDAG &DAG) const {
1897   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1898
1899   RTLIB::Libcall LC;
1900   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1901
1902   return LowerF128Call(Op, DAG, LC);
1903 }
1904
1905 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1906                                              SelectionDAG &DAG) const {
1907   if (Op.getOperand(0).getValueType() != MVT::f128) {
1908     // It's legal except when f128 is involved
1909     return Op;
1910   }
1911
1912   RTLIB::Libcall LC;
1913   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1914
1915   // FP_ROUND node has a second operand indicating whether it is known to be
1916   // precise. That doesn't take part in the LibCall so we can't directly use
1917   // LowerF128Call.
1918   SDValue SrcVal = Op.getOperand(0);
1919   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1920                      SDLoc(Op)).first;
1921 }
1922
1923 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1924   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1925   // Any additional optimization in this function should be recorded
1926   // in the cost tables.
1927   EVT InVT = Op.getOperand(0).getValueType();
1928   EVT VT = Op.getValueType();
1929   unsigned NumElts = InVT.getVectorNumElements();
1930
1931   // f16 vectors are promoted to f32 before a conversion.
1932   if (InVT.getVectorElementType() == MVT::f16) {
1933     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1934     SDLoc dl(Op);
1935     return DAG.getNode(
1936         Op.getOpcode(), dl, Op.getValueType(),
1937         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1938   }
1939
1940   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1941     SDLoc dl(Op);
1942     SDValue Cv =
1943         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1944                     Op.getOperand(0));
1945     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1946   }
1947
1948   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1949     SDLoc dl(Op);
1950     MVT ExtVT =
1951         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1952                          VT.getVectorNumElements());
1953     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1954     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1955   }
1956
1957   // Type changing conversions are illegal.
1958   return Op;
1959 }
1960
1961 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1962                                               SelectionDAG &DAG) const {
1963   if (Op.getOperand(0).getValueType().isVector())
1964     return LowerVectorFP_TO_INT(Op, DAG);
1965
1966   // f16 conversions are promoted to f32.
1967   if (Op.getOperand(0).getValueType() == MVT::f16) {
1968     SDLoc dl(Op);
1969     return DAG.getNode(
1970         Op.getOpcode(), dl, Op.getValueType(),
1971         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1972   }
1973
1974   if (Op.getOperand(0).getValueType() != MVT::f128) {
1975     // It's legal except when f128 is involved
1976     return Op;
1977   }
1978
1979   RTLIB::Libcall LC;
1980   if (Op.getOpcode() == ISD::FP_TO_SINT)
1981     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1982   else
1983     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1984
1985   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1986   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1987 }
1988
1989 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1990   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1991   // Any additional optimization in this function should be recorded
1992   // in the cost tables.
1993   EVT VT = Op.getValueType();
1994   SDLoc dl(Op);
1995   SDValue In = Op.getOperand(0);
1996   EVT InVT = In.getValueType();
1997
1998   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1999     MVT CastVT =
2000         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2001                          InVT.getVectorNumElements());
2002     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2003     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2004   }
2005
2006   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2007     unsigned CastOpc =
2008         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2009     EVT CastVT = VT.changeVectorElementTypeToInteger();
2010     In = DAG.getNode(CastOpc, dl, CastVT, In);
2011     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2012   }
2013
2014   return Op;
2015 }
2016
2017 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2018                                             SelectionDAG &DAG) const {
2019   if (Op.getValueType().isVector())
2020     return LowerVectorINT_TO_FP(Op, DAG);
2021
2022   // f16 conversions are promoted to f32.
2023   if (Op.getValueType() == MVT::f16) {
2024     SDLoc dl(Op);
2025     return DAG.getNode(
2026         ISD::FP_ROUND, dl, MVT::f16,
2027         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2028         DAG.getIntPtrConstant(0, dl));
2029   }
2030
2031   // i128 conversions are libcalls.
2032   if (Op.getOperand(0).getValueType() == MVT::i128)
2033     return SDValue();
2034
2035   // Other conversions are legal, unless it's to the completely software-based
2036   // fp128.
2037   if (Op.getValueType() != MVT::f128)
2038     return Op;
2039
2040   RTLIB::Libcall LC;
2041   if (Op.getOpcode() == ISD::SINT_TO_FP)
2042     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2043   else
2044     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2045
2046   return LowerF128Call(Op, DAG, LC);
2047 }
2048
2049 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2050                                             SelectionDAG &DAG) const {
2051   // For iOS, we want to call an alternative entry point: __sincos_stret,
2052   // which returns the values in two S / D registers.
2053   SDLoc dl(Op);
2054   SDValue Arg = Op.getOperand(0);
2055   EVT ArgVT = Arg.getValueType();
2056   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2057
2058   ArgListTy Args;
2059   ArgListEntry Entry;
2060
2061   Entry.Node = Arg;
2062   Entry.Ty = ArgTy;
2063   Entry.isSExt = false;
2064   Entry.isZExt = false;
2065   Args.push_back(Entry);
2066
2067   const char *LibcallName =
2068       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2069   SDValue Callee =
2070       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2071
2072   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2073   TargetLowering::CallLoweringInfo CLI(DAG);
2074   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2075     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2076
2077   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2078   return CallResult.first;
2079 }
2080
2081 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2082   if (Op.getValueType() != MVT::f16)
2083     return SDValue();
2084
2085   assert(Op.getOperand(0).getValueType() == MVT::i16);
2086   SDLoc DL(Op);
2087
2088   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2089   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2090   return SDValue(
2091       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2092                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2093       0);
2094 }
2095
2096 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2097   if (OrigVT.getSizeInBits() >= 64)
2098     return OrigVT;
2099
2100   assert(OrigVT.isSimple() && "Expecting a simple value type");
2101
2102   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2103   switch (OrigSimpleTy) {
2104   default: llvm_unreachable("Unexpected Vector Type");
2105   case MVT::v2i8:
2106   case MVT::v2i16:
2107      return MVT::v2i32;
2108   case MVT::v4i8:
2109     return  MVT::v4i16;
2110   }
2111 }
2112
2113 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2114                                                  const EVT &OrigTy,
2115                                                  const EVT &ExtTy,
2116                                                  unsigned ExtOpcode) {
2117   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2118   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2119   // 64-bits we need to insert a new extension so that it will be 64-bits.
2120   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2121   if (OrigTy.getSizeInBits() >= 64)
2122     return N;
2123
2124   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2125   EVT NewVT = getExtensionTo64Bits(OrigTy);
2126
2127   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2128 }
2129
2130 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2131                                    bool isSigned) {
2132   EVT VT = N->getValueType(0);
2133
2134   if (N->getOpcode() != ISD::BUILD_VECTOR)
2135     return false;
2136
2137   for (const SDValue &Elt : N->op_values()) {
2138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2139       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2140       unsigned HalfSize = EltSize / 2;
2141       if (isSigned) {
2142         if (!isIntN(HalfSize, C->getSExtValue()))
2143           return false;
2144       } else {
2145         if (!isUIntN(HalfSize, C->getZExtValue()))
2146           return false;
2147       }
2148       continue;
2149     }
2150     return false;
2151   }
2152
2153   return true;
2154 }
2155
2156 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2157   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2158     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2159                                              N->getOperand(0)->getValueType(0),
2160                                              N->getValueType(0),
2161                                              N->getOpcode());
2162
2163   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2164   EVT VT = N->getValueType(0);
2165   SDLoc dl(N);
2166   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2167   unsigned NumElts = VT.getVectorNumElements();
2168   MVT TruncVT = MVT::getIntegerVT(EltSize);
2169   SmallVector<SDValue, 8> Ops;
2170   for (unsigned i = 0; i != NumElts; ++i) {
2171     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2172     const APInt &CInt = C->getAPIntValue();
2173     // Element types smaller than 32 bits are not legal, so use i32 elements.
2174     // The values are implicitly truncated so sext vs. zext doesn't matter.
2175     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2176   }
2177   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2178 }
2179
2180 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2181   if (N->getOpcode() == ISD::SIGN_EXTEND)
2182     return true;
2183   if (isExtendedBUILD_VECTOR(N, DAG, true))
2184     return true;
2185   return false;
2186 }
2187
2188 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2189   if (N->getOpcode() == ISD::ZERO_EXTEND)
2190     return true;
2191   if (isExtendedBUILD_VECTOR(N, DAG, false))
2192     return true;
2193   return false;
2194 }
2195
2196 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2197   unsigned Opcode = N->getOpcode();
2198   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2199     SDNode *N0 = N->getOperand(0).getNode();
2200     SDNode *N1 = N->getOperand(1).getNode();
2201     return N0->hasOneUse() && N1->hasOneUse() &&
2202       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2203   }
2204   return false;
2205 }
2206
2207 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2208   unsigned Opcode = N->getOpcode();
2209   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2210     SDNode *N0 = N->getOperand(0).getNode();
2211     SDNode *N1 = N->getOperand(1).getNode();
2212     return N0->hasOneUse() && N1->hasOneUse() &&
2213       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2214   }
2215   return false;
2216 }
2217
2218 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2219   // Multiplications are only custom-lowered for 128-bit vectors so that
2220   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2221   EVT VT = Op.getValueType();
2222   assert(VT.is128BitVector() && VT.isInteger() &&
2223          "unexpected type for custom-lowering ISD::MUL");
2224   SDNode *N0 = Op.getOperand(0).getNode();
2225   SDNode *N1 = Op.getOperand(1).getNode();
2226   unsigned NewOpc = 0;
2227   bool isMLA = false;
2228   bool isN0SExt = isSignExtended(N0, DAG);
2229   bool isN1SExt = isSignExtended(N1, DAG);
2230   if (isN0SExt && isN1SExt)
2231     NewOpc = AArch64ISD::SMULL;
2232   else {
2233     bool isN0ZExt = isZeroExtended(N0, DAG);
2234     bool isN1ZExt = isZeroExtended(N1, DAG);
2235     if (isN0ZExt && isN1ZExt)
2236       NewOpc = AArch64ISD::UMULL;
2237     else if (isN1SExt || isN1ZExt) {
2238       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2239       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2240       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2241         NewOpc = AArch64ISD::SMULL;
2242         isMLA = true;
2243       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2244         NewOpc =  AArch64ISD::UMULL;
2245         isMLA = true;
2246       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2247         std::swap(N0, N1);
2248         NewOpc =  AArch64ISD::UMULL;
2249         isMLA = true;
2250       }
2251     }
2252
2253     if (!NewOpc) {
2254       if (VT == MVT::v2i64)
2255         // Fall through to expand this.  It is not legal.
2256         return SDValue();
2257       else
2258         // Other vector multiplications are legal.
2259         return Op;
2260     }
2261   }
2262
2263   // Legalize to a S/UMULL instruction
2264   SDLoc DL(Op);
2265   SDValue Op0;
2266   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2267   if (!isMLA) {
2268     Op0 = skipExtensionForVectorMULL(N0, DAG);
2269     assert(Op0.getValueType().is64BitVector() &&
2270            Op1.getValueType().is64BitVector() &&
2271            "unexpected types for extended operands to VMULL");
2272     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2273   }
2274   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2275   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2276   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2277   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2278   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2279   EVT Op1VT = Op1.getValueType();
2280   return DAG.getNode(N0->getOpcode(), DL, VT,
2281                      DAG.getNode(NewOpc, DL, VT,
2282                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2283                      DAG.getNode(NewOpc, DL, VT,
2284                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2285 }
2286
2287 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2288                                                      SelectionDAG &DAG) const {
2289   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2290   SDLoc dl(Op);
2291   switch (IntNo) {
2292   default: return SDValue();    // Don't custom lower most intrinsics.
2293   case Intrinsic::thread_pointer: {
2294     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2295     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2296   }
2297   case Intrinsic::aarch64_neon_smax:
2298     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2299                        Op.getOperand(1), Op.getOperand(2));
2300   case Intrinsic::aarch64_neon_umax:
2301     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2302                        Op.getOperand(1), Op.getOperand(2));
2303   case Intrinsic::aarch64_neon_smin:
2304     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2305                        Op.getOperand(1), Op.getOperand(2));
2306   case Intrinsic::aarch64_neon_umin:
2307     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2308                        Op.getOperand(1), Op.getOperand(2));
2309   }
2310 }
2311
2312 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2313                                               SelectionDAG &DAG) const {
2314   switch (Op.getOpcode()) {
2315   default:
2316     llvm_unreachable("unimplemented operand");
2317     return SDValue();
2318   case ISD::BITCAST:
2319     return LowerBITCAST(Op, DAG);
2320   case ISD::GlobalAddress:
2321     return LowerGlobalAddress(Op, DAG);
2322   case ISD::GlobalTLSAddress:
2323     return LowerGlobalTLSAddress(Op, DAG);
2324   case ISD::SETCC:
2325     return LowerSETCC(Op, DAG);
2326   case ISD::BR_CC:
2327     return LowerBR_CC(Op, DAG);
2328   case ISD::SELECT:
2329     return LowerSELECT(Op, DAG);
2330   case ISD::SELECT_CC:
2331     return LowerSELECT_CC(Op, DAG);
2332   case ISD::JumpTable:
2333     return LowerJumpTable(Op, DAG);
2334   case ISD::ConstantPool:
2335     return LowerConstantPool(Op, DAG);
2336   case ISD::BlockAddress:
2337     return LowerBlockAddress(Op, DAG);
2338   case ISD::VASTART:
2339     return LowerVASTART(Op, DAG);
2340   case ISD::VACOPY:
2341     return LowerVACOPY(Op, DAG);
2342   case ISD::VAARG:
2343     return LowerVAARG(Op, DAG);
2344   case ISD::ADDC:
2345   case ISD::ADDE:
2346   case ISD::SUBC:
2347   case ISD::SUBE:
2348     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2349   case ISD::SADDO:
2350   case ISD::UADDO:
2351   case ISD::SSUBO:
2352   case ISD::USUBO:
2353   case ISD::SMULO:
2354   case ISD::UMULO:
2355     return LowerXALUO(Op, DAG);
2356   case ISD::FADD:
2357     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2358   case ISD::FSUB:
2359     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2360   case ISD::FMUL:
2361     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2362   case ISD::FDIV:
2363     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2364   case ISD::FP_ROUND:
2365     return LowerFP_ROUND(Op, DAG);
2366   case ISD::FP_EXTEND:
2367     return LowerFP_EXTEND(Op, DAG);
2368   case ISD::FRAMEADDR:
2369     return LowerFRAMEADDR(Op, DAG);
2370   case ISD::RETURNADDR:
2371     return LowerRETURNADDR(Op, DAG);
2372   case ISD::INSERT_VECTOR_ELT:
2373     return LowerINSERT_VECTOR_ELT(Op, DAG);
2374   case ISD::EXTRACT_VECTOR_ELT:
2375     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2376   case ISD::BUILD_VECTOR:
2377     return LowerBUILD_VECTOR(Op, DAG);
2378   case ISD::VECTOR_SHUFFLE:
2379     return LowerVECTOR_SHUFFLE(Op, DAG);
2380   case ISD::EXTRACT_SUBVECTOR:
2381     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2382   case ISD::SRA:
2383   case ISD::SRL:
2384   case ISD::SHL:
2385     return LowerVectorSRA_SRL_SHL(Op, DAG);
2386   case ISD::SHL_PARTS:
2387     return LowerShiftLeftParts(Op, DAG);
2388   case ISD::SRL_PARTS:
2389   case ISD::SRA_PARTS:
2390     return LowerShiftRightParts(Op, DAG);
2391   case ISD::CTPOP:
2392     return LowerCTPOP(Op, DAG);
2393   case ISD::FCOPYSIGN:
2394     return LowerFCOPYSIGN(Op, DAG);
2395   case ISD::AND:
2396     return LowerVectorAND(Op, DAG);
2397   case ISD::OR:
2398     return LowerVectorOR(Op, DAG);
2399   case ISD::XOR:
2400     return LowerXOR(Op, DAG);
2401   case ISD::PREFETCH:
2402     return LowerPREFETCH(Op, DAG);
2403   case ISD::SINT_TO_FP:
2404   case ISD::UINT_TO_FP:
2405     return LowerINT_TO_FP(Op, DAG);
2406   case ISD::FP_TO_SINT:
2407   case ISD::FP_TO_UINT:
2408     return LowerFP_TO_INT(Op, DAG);
2409   case ISD::FSINCOS:
2410     return LowerFSINCOS(Op, DAG);
2411   case ISD::MUL:
2412     return LowerMUL(Op, DAG);
2413   case ISD::INTRINSIC_WO_CHAIN:
2414     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2415   }
2416 }
2417
2418 //===----------------------------------------------------------------------===//
2419 //                      Calling Convention Implementation
2420 //===----------------------------------------------------------------------===//
2421
2422 #include "AArch64GenCallingConv.inc"
2423
2424 /// Selects the correct CCAssignFn for a given CallingConvention value.
2425 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2426                                                      bool IsVarArg) const {
2427   switch (CC) {
2428   default:
2429     llvm_unreachable("Unsupported calling convention.");
2430   case CallingConv::WebKit_JS:
2431     return CC_AArch64_WebKit_JS;
2432   case CallingConv::GHC:
2433     return CC_AArch64_GHC;
2434   case CallingConv::C:
2435   case CallingConv::Fast:
2436   case CallingConv::PreserveMost:
2437   case CallingConv::CXX_FAST_TLS:
2438     if (!Subtarget->isTargetDarwin())
2439       return CC_AArch64_AAPCS;
2440     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2441   }
2442 }
2443
2444 SDValue AArch64TargetLowering::LowerFormalArguments(
2445     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2446     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2447     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2448   MachineFunction &MF = DAG.getMachineFunction();
2449   MachineFrameInfo *MFI = MF.getFrameInfo();
2450
2451   // Assign locations to all of the incoming arguments.
2452   SmallVector<CCValAssign, 16> ArgLocs;
2453   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2454                  *DAG.getContext());
2455
2456   // At this point, Ins[].VT may already be promoted to i32. To correctly
2457   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2458   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2459   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2460   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2461   // LocVT.
2462   unsigned NumArgs = Ins.size();
2463   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2464   unsigned CurArgIdx = 0;
2465   for (unsigned i = 0; i != NumArgs; ++i) {
2466     MVT ValVT = Ins[i].VT;
2467     if (Ins[i].isOrigArg()) {
2468       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2469       CurArgIdx = Ins[i].getOrigArgIndex();
2470
2471       // Get type of the original argument.
2472       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2473                                   /*AllowUnknown*/ true);
2474       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2475       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2476       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2477         ValVT = MVT::i8;
2478       else if (ActualMVT == MVT::i16)
2479         ValVT = MVT::i16;
2480     }
2481     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2482     bool Res =
2483         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2484     assert(!Res && "Call operand has unhandled type");
2485     (void)Res;
2486   }
2487   assert(ArgLocs.size() == Ins.size());
2488   SmallVector<SDValue, 16> ArgValues;
2489   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2490     CCValAssign &VA = ArgLocs[i];
2491
2492     if (Ins[i].Flags.isByVal()) {
2493       // Byval is used for HFAs in the PCS, but the system should work in a
2494       // non-compliant manner for larger structs.
2495       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2496       int Size = Ins[i].Flags.getByValSize();
2497       unsigned NumRegs = (Size + 7) / 8;
2498
2499       // FIXME: This works on big-endian for composite byvals, which are the common
2500       // case. It should also work for fundamental types too.
2501       unsigned FrameIdx =
2502         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2503       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2504       InVals.push_back(FrameIdxN);
2505
2506       continue;
2507     }
2508
2509     if (VA.isRegLoc()) {
2510       // Arguments stored in registers.
2511       EVT RegVT = VA.getLocVT();
2512
2513       SDValue ArgValue;
2514       const TargetRegisterClass *RC;
2515
2516       if (RegVT == MVT::i32)
2517         RC = &AArch64::GPR32RegClass;
2518       else if (RegVT == MVT::i64)
2519         RC = &AArch64::GPR64RegClass;
2520       else if (RegVT == MVT::f16)
2521         RC = &AArch64::FPR16RegClass;
2522       else if (RegVT == MVT::f32)
2523         RC = &AArch64::FPR32RegClass;
2524       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2525         RC = &AArch64::FPR64RegClass;
2526       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2527         RC = &AArch64::FPR128RegClass;
2528       else
2529         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2530
2531       // Transform the arguments in physical registers into virtual ones.
2532       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2533       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2534
2535       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2536       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2537       // truncate to the right size.
2538       switch (VA.getLocInfo()) {
2539       default:
2540         llvm_unreachable("Unknown loc info!");
2541       case CCValAssign::Full:
2542         break;
2543       case CCValAssign::BCvt:
2544         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2545         break;
2546       case CCValAssign::AExt:
2547       case CCValAssign::SExt:
2548       case CCValAssign::ZExt:
2549         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2550         // nodes after our lowering.
2551         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2552         break;
2553       }
2554
2555       InVals.push_back(ArgValue);
2556
2557     } else { // VA.isRegLoc()
2558       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2559       unsigned ArgOffset = VA.getLocMemOffset();
2560       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2561
2562       uint32_t BEAlign = 0;
2563       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2564           !Ins[i].Flags.isInConsecutiveRegs())
2565         BEAlign = 8 - ArgSize;
2566
2567       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2568
2569       // Create load nodes to retrieve arguments from the stack.
2570       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2571       SDValue ArgValue;
2572
2573       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2574       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2575       MVT MemVT = VA.getValVT();
2576
2577       switch (VA.getLocInfo()) {
2578       default:
2579         break;
2580       case CCValAssign::BCvt:
2581         MemVT = VA.getLocVT();
2582         break;
2583       case CCValAssign::SExt:
2584         ExtType = ISD::SEXTLOAD;
2585         break;
2586       case CCValAssign::ZExt:
2587         ExtType = ISD::ZEXTLOAD;
2588         break;
2589       case CCValAssign::AExt:
2590         ExtType = ISD::EXTLOAD;
2591         break;
2592       }
2593
2594       ArgValue = DAG.getExtLoad(
2595           ExtType, DL, VA.getLocVT(), Chain, FIN,
2596           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2597           MemVT);
2598
2599       InVals.push_back(ArgValue);
2600     }
2601   }
2602
2603   // varargs
2604   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2605   if (isVarArg) {
2606     if (!Subtarget->isTargetDarwin()) {
2607       // The AAPCS variadic function ABI is identical to the non-variadic
2608       // one. As a result there may be more arguments in registers and we should
2609       // save them for future reference.
2610       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2611     }
2612
2613     // This will point to the next argument passed via stack.
2614     unsigned StackOffset = CCInfo.getNextStackOffset();
2615     // We currently pass all varargs at 8-byte alignment.
2616     StackOffset = ((StackOffset + 7) & ~7);
2617     FuncInfo->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2618   }
2619
2620   unsigned StackArgSize = CCInfo.getNextStackOffset();
2621   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2622   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2623     // This is a non-standard ABI so by fiat I say we're allowed to make full
2624     // use of the stack area to be popped, which must be aligned to 16 bytes in
2625     // any case:
2626     StackArgSize = alignTo(StackArgSize, 16);
2627
2628     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2629     // a multiple of 16.
2630     FuncInfo->setArgumentStackToRestore(StackArgSize);
2631
2632     // This realignment carries over to the available bytes below. Our own
2633     // callers will guarantee the space is free by giving an aligned value to
2634     // CALLSEQ_START.
2635   }
2636   // Even if we're not expected to free up the space, it's useful to know how
2637   // much is there while considering tail calls (because we can reuse it).
2638   FuncInfo->setBytesInStackArgArea(StackArgSize);
2639
2640   return Chain;
2641 }
2642
2643 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2644                                                 SelectionDAG &DAG,
2645                                                 const SDLoc &DL,
2646                                                 SDValue &Chain) const {
2647   MachineFunction &MF = DAG.getMachineFunction();
2648   MachineFrameInfo *MFI = MF.getFrameInfo();
2649   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2650   auto PtrVT = getPointerTy(DAG.getDataLayout());
2651
2652   SmallVector<SDValue, 8> MemOps;
2653
2654   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2655                                           AArch64::X3, AArch64::X4, AArch64::X5,
2656                                           AArch64::X6, AArch64::X7 };
2657   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2658   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2659
2660   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2661   int GPRIdx = 0;
2662   if (GPRSaveSize != 0) {
2663     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2664
2665     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2666
2667     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2668       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2669       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2670       SDValue Store = DAG.getStore(
2671           Val.getValue(1), DL, Val, FIN,
2672           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2673       MemOps.push_back(Store);
2674       FIN =
2675           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2676     }
2677   }
2678   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2679   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2680
2681   if (Subtarget->hasFPARMv8()) {
2682     static const MCPhysReg FPRArgRegs[] = {
2683         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2684         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2685     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2686     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2687
2688     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2689     int FPRIdx = 0;
2690     if (FPRSaveSize != 0) {
2691       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2692
2693       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2694
2695       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2696         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2697         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2698
2699         SDValue Store = DAG.getStore(
2700             Val.getValue(1), DL, Val, FIN,
2701             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2702         MemOps.push_back(Store);
2703         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2704                           DAG.getConstant(16, DL, PtrVT));
2705       }
2706     }
2707     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2708     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2709   }
2710
2711   if (!MemOps.empty()) {
2712     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2713   }
2714 }
2715
2716 /// LowerCallResult - Lower the result values of a call into the
2717 /// appropriate copies out of appropriate physical registers.
2718 SDValue AArch64TargetLowering::LowerCallResult(
2719     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2720     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2721     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2722     SDValue ThisVal) const {
2723   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2724                           ? RetCC_AArch64_WebKit_JS
2725                           : RetCC_AArch64_AAPCS;
2726   // Assign locations to each value returned by this call.
2727   SmallVector<CCValAssign, 16> RVLocs;
2728   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2729                  *DAG.getContext());
2730   CCInfo.AnalyzeCallResult(Ins, RetCC);
2731
2732   // Copy all of the result registers out of their specified physreg.
2733   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2734     CCValAssign VA = RVLocs[i];
2735
2736     // Pass 'this' value directly from the argument to return value, to avoid
2737     // reg unit interference
2738     if (i == 0 && isThisReturn && EnableThisRetForwarding) {
2739       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2740              "unexpected return calling convention register assignment");
2741       InVals.push_back(ThisVal);
2742       continue;
2743     }
2744
2745     SDValue Val =
2746         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2747     Chain = Val.getValue(1);
2748     InFlag = Val.getValue(2);
2749
2750     switch (VA.getLocInfo()) {
2751     default:
2752       llvm_unreachable("Unknown loc info!");
2753     case CCValAssign::Full:
2754       break;
2755     case CCValAssign::BCvt:
2756       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2757       break;
2758     }
2759
2760     InVals.push_back(Val);
2761   }
2762
2763   return Chain;
2764 }
2765
2766 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2767     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2768     const SmallVectorImpl<ISD::OutputArg> &Outs,
2769     const SmallVectorImpl<SDValue> &OutVals,
2770     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2771   // For CallingConv::C this function knows whether the ABI needs
2772   // changing. That's not true for other conventions so they will have to opt in
2773   // manually.
2774   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2775     return false;
2776
2777   MachineFunction &MF = DAG.getMachineFunction();
2778   const Function *CallerF = MF.getFunction();
2779   CallingConv::ID CallerCC = CallerF->getCallingConv();
2780   bool CCMatch = CallerCC == CalleeCC;
2781
2782   // Byval parameters hand the function a pointer directly into the stack area
2783   // we want to reuse during a tail call. Working around this *is* possible (see
2784   // X86) but less efficient and uglier in LowerCall.
2785   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2786                                     e = CallerF->arg_end();
2787        i != e; ++i)
2788     if (i->hasByValAttr())
2789       return false;
2790
2791   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2792     return IsTailCallConvention(CalleeCC) && CCMatch;
2793   }
2794
2795   // Externally-defined functions with weak linkage should not be
2796   // tail-called on AArch64 when the OS does not support dynamic
2797   // pre-emption of symbols, as the AAELF spec requires normal calls
2798   // to undefined weak functions to be replaced with a NOP or jump to the
2799   // next instruction. The behaviour of branch instructions in this
2800   // situation (as used for tail calls) is implementation-defined, so we
2801   // cannot rely on the linker replacing the tail call with a return.
2802   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2803     const GlobalValue *GV = G->getGlobal();
2804     const Triple &TT = getTargetMachine().getTargetTriple();
2805     if (GV->hasExternalWeakLinkage() &&
2806         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2807       return false;
2808   }
2809
2810   // Now we search for cases where we can use a tail call without changing the
2811   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2812   // concept.
2813
2814   // I want anyone implementing a new calling convention to think long and hard
2815   // about this assert.
2816   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2817          "Unexpected variadic calling convention");
2818
2819   LLVMContext &C = *DAG.getContext();
2820   if (isVarArg && !Outs.empty()) {
2821     // At least two cases here: if caller is fastcc then we can't have any
2822     // memory arguments (we'd be expected to clean up the stack afterwards). If
2823     // caller is C then we could potentially use its argument area.
2824
2825     // FIXME: for now we take the most conservative of these in both cases:
2826     // disallow all variadic memory operands.
2827     SmallVector<CCValAssign, 16> ArgLocs;
2828     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2829
2830     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2831     for (const CCValAssign &ArgLoc : ArgLocs)
2832       if (!ArgLoc.isRegLoc())
2833         return false;
2834   }
2835
2836   // Check that the call results are passed in the same way.
2837   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2838                                   CCAssignFnForCall(CalleeCC, isVarArg),
2839                                   CCAssignFnForCall(CallerCC, isVarArg)))
2840     return false;
2841   // The callee has to preserve all registers the caller needs to preserve.
2842   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2843   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2844   if (!CCMatch) {
2845     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2846     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2847       return false;
2848   }
2849
2850   // Nothing more to check if the callee is taking no arguments
2851   if (Outs.empty())
2852     return true;
2853
2854   SmallVector<CCValAssign, 16> ArgLocs;
2855   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2856
2857   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2858
2859   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2860
2861   // If the stack arguments for this call do not fit into our own save area then
2862   // the call cannot be made tail.
2863   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2864     return false;
2865
2866   const MachineRegisterInfo &MRI = MF.getRegInfo();
2867   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2868     return false;
2869
2870   return true;
2871 }
2872
2873 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2874                                                    SelectionDAG &DAG,
2875                                                    MachineFrameInfo *MFI,
2876                                                    int ClobberedFI) const {
2877   SmallVector<SDValue, 8> ArgChains;
2878   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2879   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2880
2881   // Include the original chain at the beginning of the list. When this is
2882   // used by target LowerCall hooks, this helps legalize find the
2883   // CALLSEQ_BEGIN node.
2884   ArgChains.push_back(Chain);
2885
2886   // Add a chain value for each stack argument corresponding
2887   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2888                             UE = DAG.getEntryNode().getNode()->use_end();
2889        U != UE; ++U)
2890     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2891       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2892         if (FI->getIndex() < 0) {
2893           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2894           int64_t InLastByte = InFirstByte;
2895           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2896
2897           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2898               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2899             ArgChains.push_back(SDValue(L, 1));
2900         }
2901
2902   // Build a tokenfactor for all the chains.
2903   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2904 }
2905
2906 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2907                                                    bool TailCallOpt) const {
2908   return CallCC == CallingConv::Fast && TailCallOpt;
2909 }
2910
2911 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2912   return CallCC == CallingConv::Fast ||
2913          CallCC == CallingConv::PreserveMost;
2914 }
2915
2916 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2917 /// and add input and output parameter nodes.
2918 SDValue
2919 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2920                                  SmallVectorImpl<SDValue> &InVals) const {
2921   SelectionDAG &DAG = CLI.DAG;
2922   SDLoc &DL = CLI.DL;
2923   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2924   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2925   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2926   SDValue Chain = CLI.Chain;
2927   SDValue Callee = CLI.Callee;
2928   bool &IsTailCall = CLI.IsTailCall;
2929   CallingConv::ID CallConv = CLI.CallConv;
2930   bool IsVarArg = CLI.IsVarArg;
2931
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   bool IsThisReturn = false;
2934
2935   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2936   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2937   bool IsSibCall = false;
2938
2939   if (IsTailCall) {
2940     // Check if it's really possible to do a tail call.
2941     IsTailCall = isEligibleForTailCallOptimization(
2942         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2943     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2944       report_fatal_error("failed to perform tail call elimination on a call "
2945                          "site marked musttail");
2946
2947     // A sibling call is one where we're under the usual C ABI and not planning
2948     // to change that but can still do a tail call:
2949     if (!TailCallOpt && IsTailCall)
2950       IsSibCall = true;
2951
2952     if (IsTailCall)
2953       ++NumTailCalls;
2954   }
2955
2956   // Analyze operands of the call, assigning locations to each operand.
2957   SmallVector<CCValAssign, 16> ArgLocs;
2958   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2959                  *DAG.getContext());
2960
2961   if (IsVarArg) {
2962     // Handle fixed and variable vector arguments differently.
2963     // Variable vector arguments always go into memory.
2964     unsigned NumArgs = Outs.size();
2965
2966     for (unsigned i = 0; i != NumArgs; ++i) {
2967       MVT ArgVT = Outs[i].VT;
2968       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2969       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2970                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2971       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2972       assert(!Res && "Call operand has unhandled type");
2973       (void)Res;
2974     }
2975   } else {
2976     // At this point, Outs[].VT may already be promoted to i32. To correctly
2977     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2978     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2979     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2980     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2981     // LocVT.
2982     unsigned NumArgs = Outs.size();
2983     for (unsigned i = 0; i != NumArgs; ++i) {
2984       MVT ValVT = Outs[i].VT;
2985       // Get type of the original argument.
2986       EVT ActualVT = getValueType(DAG.getDataLayout(),
2987                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2988                                   /*AllowUnknown*/ true);
2989       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2990       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2991       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2992       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2993         ValVT = MVT::i8;
2994       else if (ActualMVT == MVT::i16)
2995         ValVT = MVT::i16;
2996
2997       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2998       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2999       assert(!Res && "Call operand has unhandled type");
3000       (void)Res;
3001     }
3002   }
3003
3004   // Get a count of how many bytes are to be pushed on the stack.
3005   unsigned NumBytes = CCInfo.getNextStackOffset();
3006
3007   if (IsSibCall) {
3008     // Since we're not changing the ABI to make this a tail call, the memory
3009     // operands are already available in the caller's incoming argument space.
3010     NumBytes = 0;
3011   }
3012
3013   // FPDiff is the byte offset of the call's argument area from the callee's.
3014   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3015   // by this amount for a tail call. In a sibling call it must be 0 because the
3016   // caller will deallocate the entire stack and the callee still expects its
3017   // arguments to begin at SP+0. Completely unused for non-tail calls.
3018   int FPDiff = 0;
3019
3020   if (IsTailCall && !IsSibCall) {
3021     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3022
3023     // Since callee will pop argument stack as a tail call, we must keep the
3024     // popped size 16-byte aligned.
3025     NumBytes = alignTo(NumBytes, 16);
3026
3027     // FPDiff will be negative if this tail call requires more space than we
3028     // would automatically have in our incoming argument space. Positive if we
3029     // can actually shrink the stack.
3030     FPDiff = NumReusableBytes - NumBytes;
3031
3032     // The stack pointer must be 16-byte aligned at all times it's used for a
3033     // memory operation, which in practice means at *all* times and in
3034     // particular across call boundaries. Therefore our own arguments started at
3035     // a 16-byte aligned SP and the delta applied for the tail call should
3036     // satisfy the same constraint.
3037     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3038   }
3039
3040   // Adjust the stack pointer for the new arguments...
3041   // These operations are automatically eliminated by the prolog/epilog pass
3042   if (!IsSibCall)
3043     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3044                                                               true),
3045                                  DL);
3046
3047   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3048                                         getPointerTy(DAG.getDataLayout()));
3049
3050   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3051   SmallVector<SDValue, 8> MemOpChains;
3052   auto PtrVT = getPointerTy(DAG.getDataLayout());
3053
3054   // Walk the register/memloc assignments, inserting copies/loads.
3055   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3056        ++i, ++realArgIdx) {
3057     CCValAssign &VA = ArgLocs[i];
3058     SDValue Arg = OutVals[realArgIdx];
3059     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3060
3061     // Promote the value if needed.
3062     switch (VA.getLocInfo()) {
3063     default:
3064       llvm_unreachable("Unknown loc info!");
3065     case CCValAssign::Full:
3066       break;
3067     case CCValAssign::SExt:
3068       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3069       break;
3070     case CCValAssign::ZExt:
3071       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3072       break;
3073     case CCValAssign::AExt:
3074       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3075         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3076         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3077         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3078       }
3079       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3080       break;
3081     case CCValAssign::BCvt:
3082       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3083       break;
3084     case CCValAssign::FPExt:
3085       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3086       break;
3087     }
3088
3089     if (VA.isRegLoc()) {
3090       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3091         assert(VA.getLocVT() == MVT::i64 &&
3092                "unexpected calling convention register assignment");
3093         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3094                "unexpected use of 'returned'");
3095         IsThisReturn = true;
3096       }
3097       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3098     } else {
3099       assert(VA.isMemLoc());
3100
3101       SDValue DstAddr;
3102       MachinePointerInfo DstInfo;
3103
3104       // FIXME: This works on big-endian for composite byvals, which are the
3105       // common case. It should also work for fundamental types too.
3106       uint32_t BEAlign = 0;
3107       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3108                                         : VA.getValVT().getSizeInBits();
3109       OpSize = (OpSize + 7) / 8;
3110       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3111           !Flags.isInConsecutiveRegs()) {
3112         if (OpSize < 8)
3113           BEAlign = 8 - OpSize;
3114       }
3115       unsigned LocMemOffset = VA.getLocMemOffset();
3116       int32_t Offset = LocMemOffset + BEAlign;
3117       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3118       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3119
3120       if (IsTailCall) {
3121         Offset = Offset + FPDiff;
3122         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3123
3124         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3125         DstInfo =
3126             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3127
3128         // Make sure any stack arguments overlapping with where we're storing
3129         // are loaded before this eventual operation. Otherwise they'll be
3130         // clobbered.
3131         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3132       } else {
3133         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3134
3135         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3136         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3137                                                LocMemOffset);
3138       }
3139
3140       if (Outs[i].Flags.isByVal()) {
3141         SDValue SizeNode =
3142             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3143         SDValue Cpy = DAG.getMemcpy(
3144             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3145             /*isVol = */ false, /*AlwaysInline = */ false,
3146             /*isTailCall = */ false,
3147             DstInfo, MachinePointerInfo());
3148
3149         MemOpChains.push_back(Cpy);
3150       } else {
3151         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3152         // promoted to a legal register type i32, we should truncate Arg back to
3153         // i1/i8/i16.
3154         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3155             VA.getValVT() == MVT::i16)
3156           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3157
3158         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3159         MemOpChains.push_back(Store);
3160       }
3161     }
3162   }
3163
3164   if (!MemOpChains.empty())
3165     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3166
3167   // Build a sequence of copy-to-reg nodes chained together with token chain
3168   // and flag operands which copy the outgoing args into the appropriate regs.
3169   SDValue InFlag;
3170   for (auto &RegToPass : RegsToPass) {
3171     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3172                              RegToPass.second, InFlag);
3173     InFlag = Chain.getValue(1);
3174   }
3175
3176   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3177   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3178   // node so that legalize doesn't hack it.
3179   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3180       Subtarget->isTargetMachO()) {
3181     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3182       const GlobalValue *GV = G->getGlobal();
3183       bool InternalLinkage = GV->hasInternalLinkage();
3184       if (InternalLinkage)
3185         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3186       else {
3187         Callee =
3188             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3189         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3190       }
3191     } else if (ExternalSymbolSDNode *S =
3192                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3193       const char *Sym = S->getSymbol();
3194       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3195       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3196     }
3197   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3198     const GlobalValue *GV = G->getGlobal();
3199     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3200   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3201     const char *Sym = S->getSymbol();
3202     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3203   }
3204
3205   // We don't usually want to end the call-sequence here because we would tidy
3206   // the frame up *after* the call, however in the ABI-changing tail-call case
3207   // we've carefully laid out the parameters so that when sp is reset they'll be
3208   // in the correct location.
3209   if (IsTailCall && !IsSibCall) {
3210     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3211                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3212     InFlag = Chain.getValue(1);
3213   }
3214
3215   std::vector<SDValue> Ops;
3216   Ops.push_back(Chain);
3217   Ops.push_back(Callee);
3218
3219   if (IsTailCall) {
3220     // Each tail call may have to adjust the stack by a different amount, so
3221     // this information must travel along with the operation for eventual
3222     // consumption by emitEpilogue.
3223     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3224   }
3225
3226   // Add argument registers to the end of the list so that they are known live
3227   // into the call.
3228   for (auto &RegToPass : RegsToPass)
3229     Ops.push_back(DAG.getRegister(RegToPass.first,
3230                                   RegToPass.second.getValueType()));
3231
3232   // Add a register mask operand representing the call-preserved registers.
3233   const uint32_t *Mask;
3234   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3235   if (IsThisReturn) {
3236     // For 'this' returns, use the X0-preserving mask if applicable
3237     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3238     if (!Mask) {
3239       IsThisReturn = false;
3240       Mask = TRI->getCallPreservedMask(MF, CallConv);
3241     }
3242   } else
3243     Mask = TRI->getCallPreservedMask(MF, CallConv);
3244
3245   assert(Mask && "Missing call preserved mask for calling convention");
3246   Ops.push_back(DAG.getRegisterMask(Mask));
3247
3248   if (InFlag.getNode())
3249     Ops.push_back(InFlag);
3250
3251   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3252
3253   // If we're doing a tall call, use a TC_RETURN here rather than an
3254   // actual call instruction.
3255   if (IsTailCall) {
3256     MF.getFrameInfo()->setHasTailCall();
3257     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3258   }
3259
3260   // Returns a chain and a flag for retval copy to use.
3261   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3262   InFlag = Chain.getValue(1);
3263
3264   uint64_t CalleePopBytes =
3265       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3266
3267   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3268                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3269                              InFlag, DL);
3270   if (!Ins.empty())
3271     InFlag = Chain.getValue(1);
3272
3273   // Handle result values, copying them out of physregs into vregs that we
3274   // return.
3275   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3276                          InVals, IsThisReturn,
3277                          IsThisReturn ? OutVals[0] : SDValue());
3278 }
3279
3280 bool AArch64TargetLowering::CanLowerReturn(
3281     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3282     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3283   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3284                           ? RetCC_AArch64_WebKit_JS
3285                           : RetCC_AArch64_AAPCS;
3286   SmallVector<CCValAssign, 16> RVLocs;
3287   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3288   return CCInfo.CheckReturn(Outs, RetCC);
3289 }
3290
3291 SDValue
3292 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3293                                    bool isVarArg,
3294                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3295                                    const SmallVectorImpl<SDValue> &OutVals,
3296                                    const SDLoc &DL, SelectionDAG &DAG) const {
3297   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3298                           ? RetCC_AArch64_WebKit_JS
3299                           : RetCC_AArch64_AAPCS;
3300   SmallVector<CCValAssign, 16> RVLocs;
3301   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3302                  *DAG.getContext());
3303   CCInfo.AnalyzeReturn(Outs, RetCC);
3304
3305   // Copy the result values into the output registers.
3306   SDValue Flag;
3307   SmallVector<SDValue, 4> RetOps(1, Chain);
3308   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3309        ++i, ++realRVLocIdx) {
3310     CCValAssign &VA = RVLocs[i];
3311     assert(VA.isRegLoc() && "Can only return in registers!");
3312     SDValue Arg = OutVals[realRVLocIdx];
3313
3314     switch (VA.getLocInfo()) {
3315     default:
3316       llvm_unreachable("Unknown loc info!");
3317     case CCValAssign::Full:
3318       if (Outs[i].ArgVT == MVT::i1) {
3319         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3320         // value. This is strictly redundant on Darwin (which uses "zeroext
3321         // i1"), but will be optimised out before ISel.
3322         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3323         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3324       }
3325       break;
3326     case CCValAssign::BCvt:
3327       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3328       break;
3329     }
3330
3331     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3332     Flag = Chain.getValue(1);
3333     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3334   }
3335   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3336   const MCPhysReg *I =
3337       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3338   if (I) {
3339     for (; *I; ++I) {
3340       if (AArch64::GPR64RegClass.contains(*I))
3341         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3342       else if (AArch64::FPR64RegClass.contains(*I))
3343         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3344       else
3345         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3346     }
3347   }
3348
3349   RetOps[0] = Chain; // Update chain.
3350
3351   // Add the flag if we have it.
3352   if (Flag.getNode())
3353     RetOps.push_back(Flag);
3354
3355   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3356 }
3357
3358 //===----------------------------------------------------------------------===//
3359 //  Other Lowering Code
3360 //===----------------------------------------------------------------------===//
3361
3362 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3363                                                   SelectionDAG &DAG) const {
3364   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3365   SDLoc DL(Op);
3366   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3367   const GlobalValue *GV = GN->getGlobal();
3368   unsigned char OpFlags =
3369       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3370
3371   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3372          "unexpected offset in global node");
3373
3374   // This also catched the large code model case for Darwin.
3375   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3376     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3377     // FIXME: Once remat is capable of dealing with instructions with register
3378     // operands, expand this into two nodes instead of using a wrapper node.
3379     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3380   }
3381
3382   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3383     const unsigned char MO_NC = AArch64II::MO_NC;
3384     return DAG.getNode(
3385         AArch64ISD::WrapperLarge, DL, PtrVT,
3386         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3387         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3388         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3389         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3390   } else {
3391     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3392     // the only correct model on Darwin.
3393     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3394                                             OpFlags | AArch64II::MO_PAGE);
3395     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3396     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3397
3398     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3399     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3400   }
3401 }
3402
3403 /// \brief Convert a TLS address reference into the correct sequence of loads
3404 /// and calls to compute the variable's address (for Darwin, currently) and
3405 /// return an SDValue containing the final node.
3406
3407 /// Darwin only has one TLS scheme which must be capable of dealing with the
3408 /// fully general situation, in the worst case. This means:
3409 ///     + "extern __thread" declaration.
3410 ///     + Defined in a possibly unknown dynamic library.
3411 ///
3412 /// The general system is that each __thread variable has a [3 x i64] descriptor
3413 /// which contains information used by the runtime to calculate the address. The
3414 /// only part of this the compiler needs to know about is the first xword, which
3415 /// contains a function pointer that must be called with the address of the
3416 /// entire descriptor in "x0".
3417 ///
3418 /// Since this descriptor may be in a different unit, in general even the
3419 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3420 /// is:
3421 ///     adrp x0, _var@TLVPPAGE
3422 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3423 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3424 ///                                      ; the function pointer
3425 ///     blr x1                           ; Uses descriptor address in x0
3426 ///     ; Address of _var is now in x0.
3427 ///
3428 /// If the address of _var's descriptor *is* known to the linker, then it can
3429 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3430 /// a slight efficiency gain.
3431 SDValue
3432 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3433                                                    SelectionDAG &DAG) const {
3434   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3435
3436   SDLoc DL(Op);
3437   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3438   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3439
3440   SDValue TLVPAddr =
3441       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3442   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3443
3444   // The first entry in the descriptor is a function pointer that we must call
3445   // to obtain the address of the variable.
3446   SDValue Chain = DAG.getEntryNode();
3447   SDValue FuncTLVGet =
3448       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3449                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3450                   /* Alignment = */ 8, MachineMemOperand::MONonTemporal |
3451                                            MachineMemOperand::MOInvariant);
3452   Chain = FuncTLVGet.getValue(1);
3453
3454   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3455   MFI->setAdjustsStack(true);
3456
3457   // TLS calls preserve all registers except those that absolutely must be
3458   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3459   // silly).
3460   const uint32_t *Mask =
3461       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3462
3463   // Finally, we can make the call. This is just a degenerate version of a
3464   // normal AArch64 call node: x0 takes the address of the descriptor, and
3465   // returns the address of the variable in this thread.
3466   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3467   Chain =
3468       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3469                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3470                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3471   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3472 }
3473
3474 /// When accessing thread-local variables under either the general-dynamic or
3475 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3476 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3477 /// is a function pointer to carry out the resolution.
3478 ///
3479 /// The sequence is:
3480 ///    adrp  x0, :tlsdesc:var
3481 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3482 ///    add   x0, x0, #:tlsdesc_lo12:var
3483 ///    .tlsdesccall var
3484 ///    blr   x1
3485 ///    (TPIDR_EL0 offset now in x0)
3486 ///
3487 ///  The above sequence must be produced unscheduled, to enable the linker to
3488 ///  optimize/relax this sequence.
3489 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3490 ///  above sequence, and expanded really late in the compilation flow, to ensure
3491 ///  the sequence is produced as per above.
3492 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3493                                                       const SDLoc &DL,
3494                                                       SelectionDAG &DAG) const {
3495   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3496
3497   SDValue Chain = DAG.getEntryNode();
3498   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3499
3500   Chain =
3501       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3502   SDValue Glue = Chain.getValue(1);
3503
3504   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3505 }
3506
3507 SDValue
3508 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3509                                                 SelectionDAG &DAG) const {
3510   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3511   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3512          "ELF TLS only supported in small memory model");
3513   // Different choices can be made for the maximum size of the TLS area for a
3514   // module. For the small address model, the default TLS size is 16MiB and the
3515   // maximum TLS size is 4GiB.
3516   // FIXME: add -mtls-size command line option and make it control the 16MiB
3517   // vs. 4GiB code sequence generation.
3518   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3519
3520   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3521
3522   if (DAG.getTarget().Options.EmulatedTLS)
3523     return LowerToTLSEmulatedModel(GA, DAG);
3524
3525   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3526     if (Model == TLSModel::LocalDynamic)
3527       Model = TLSModel::GeneralDynamic;
3528   }
3529
3530   SDValue TPOff;
3531   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3532   SDLoc DL(Op);
3533   const GlobalValue *GV = GA->getGlobal();
3534
3535   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3536
3537   if (Model == TLSModel::LocalExec) {
3538     SDValue HiVar = DAG.getTargetGlobalAddress(
3539         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3540     SDValue LoVar = DAG.getTargetGlobalAddress(
3541         GV, DL, PtrVT, 0,
3542         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3543
3544     SDValue TPWithOff_lo =
3545         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3546                                    HiVar,
3547                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3548                 0);
3549     SDValue TPWithOff =
3550         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3551                                    LoVar,
3552                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3553                 0);
3554     return TPWithOff;
3555   } else if (Model == TLSModel::InitialExec) {
3556     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3557     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3558   } else if (Model == TLSModel::LocalDynamic) {
3559     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3560     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3561     // the beginning of the module's TLS region, followed by a DTPREL offset
3562     // calculation.
3563
3564     // These accesses will need deduplicating if there's more than one.
3565     AArch64FunctionInfo *MFI =
3566         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3567     MFI->incNumLocalDynamicTLSAccesses();
3568
3569     // The call needs a relocation too for linker relaxation. It doesn't make
3570     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3571     // the address.
3572     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3573                                                   AArch64II::MO_TLS);
3574
3575     // Now we can calculate the offset from TPIDR_EL0 to this module's
3576     // thread-local area.
3577     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3578
3579     // Now use :dtprel_whatever: operations to calculate this variable's offset
3580     // in its thread-storage area.
3581     SDValue HiVar = DAG.getTargetGlobalAddress(
3582         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3583     SDValue LoVar = DAG.getTargetGlobalAddress(
3584         GV, DL, MVT::i64, 0,
3585         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3586
3587     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3588                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3589                     0);
3590     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3591                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3592                     0);
3593   } else if (Model == TLSModel::GeneralDynamic) {
3594     // The call needs a relocation too for linker relaxation. It doesn't make
3595     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3596     // the address.
3597     SDValue SymAddr =
3598         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3599
3600     // Finally we can make a call to calculate the offset from tpidr_el0.
3601     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3602   } else
3603     llvm_unreachable("Unsupported ELF TLS access model");
3604
3605   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3606 }
3607
3608 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3609                                                      SelectionDAG &DAG) const {
3610   if (Subtarget->isTargetDarwin())
3611     return LowerDarwinGlobalTLSAddress(Op, DAG);
3612   else if (Subtarget->isTargetELF())
3613     return LowerELFGlobalTLSAddress(Op, DAG);
3614
3615   llvm_unreachable("Unexpected platform trying to use TLS");
3616 }
3617 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3618   SDValue Chain = Op.getOperand(0);
3619   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3620   SDValue LHS = Op.getOperand(2);
3621   SDValue RHS = Op.getOperand(3);
3622   SDValue Dest = Op.getOperand(4);
3623   SDLoc dl(Op);
3624
3625   // Handle f128 first, since lowering it will result in comparing the return
3626   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3627   // is expecting to deal with.
3628   if (LHS.getValueType() == MVT::f128) {
3629     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3630
3631     // If softenSetCCOperands returned a scalar, we need to compare the result
3632     // against zero to select between true and false values.
3633     if (!RHS.getNode()) {
3634       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3635       CC = ISD::SETNE;
3636     }
3637   }
3638
3639   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3640   // instruction.
3641   unsigned Opc = LHS.getOpcode();
3642   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3643       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3644        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3645     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3646            "Unexpected condition code.");
3647     // Only lower legal XALUO ops.
3648     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3649       return SDValue();
3650
3651     // The actual operation with overflow check.
3652     AArch64CC::CondCode OFCC;
3653     SDValue Value, Overflow;
3654     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3655
3656     if (CC == ISD::SETNE)
3657       OFCC = getInvertedCondCode(OFCC);
3658     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3659
3660     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3661                        Overflow);
3662   }
3663
3664   if (LHS.getValueType().isInteger()) {
3665     assert((LHS.getValueType() == RHS.getValueType()) &&
3666            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3667
3668     // If the RHS of the comparison is zero, we can potentially fold this
3669     // to a specialized branch.
3670     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3671     if (RHSC && RHSC->getZExtValue() == 0) {
3672       if (CC == ISD::SETEQ) {
3673         // See if we can use a TBZ to fold in an AND as well.
3674         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3675         // out of bounds, a late MI-layer pass rewrites branches.
3676         // 403.gcc is an example that hits this case.
3677         if (LHS.getOpcode() == ISD::AND &&
3678             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3679             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3680           SDValue Test = LHS.getOperand(0);
3681           uint64_t Mask = LHS.getConstantOperandVal(1);
3682           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3683                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3684                              Dest);
3685         }
3686
3687         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3688       } else if (CC == ISD::SETNE) {
3689         // See if we can use a TBZ to fold in an AND as well.
3690         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3691         // out of bounds, a late MI-layer pass rewrites branches.
3692         // 403.gcc is an example that hits this case.
3693         if (LHS.getOpcode() == ISD::AND &&
3694             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3695             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3696           SDValue Test = LHS.getOperand(0);
3697           uint64_t Mask = LHS.getConstantOperandVal(1);
3698           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3699                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3700                              Dest);
3701         }
3702
3703         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3704       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3705         // Don't combine AND since emitComparison converts the AND to an ANDS
3706         // (a.k.a. TST) and the test in the test bit and branch instruction
3707         // becomes redundant.  This would also increase register pressure.
3708         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3709         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3710                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3711       }
3712     }
3713     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3714         LHS.getOpcode() != ISD::AND) {
3715       // Don't combine AND since emitComparison converts the AND to an ANDS
3716       // (a.k.a. TST) and the test in the test bit and branch instruction
3717       // becomes redundant.  This would also increase register pressure.
3718       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3719       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3720                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3721     }
3722
3723     SDValue CCVal;
3724     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3725     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3726                        Cmp);
3727   }
3728
3729   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3730
3731   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3732   // clean.  Some of them require two branches to implement.
3733   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3734   AArch64CC::CondCode CC1, CC2;
3735   changeFPCCToAArch64CC(CC, CC1, CC2);
3736   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3737   SDValue BR1 =
3738       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3739   if (CC2 != AArch64CC::AL) {
3740     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3741     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3742                        Cmp);
3743   }
3744
3745   return BR1;
3746 }
3747
3748 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3749                                               SelectionDAG &DAG) const {
3750   EVT VT = Op.getValueType();
3751   SDLoc DL(Op);
3752
3753   SDValue In1 = Op.getOperand(0);
3754   SDValue In2 = Op.getOperand(1);
3755   EVT SrcVT = In2.getValueType();
3756
3757   if (SrcVT.bitsLT(VT))
3758     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3759   else if (SrcVT.bitsGT(VT))
3760     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3761
3762   EVT VecVT;
3763   EVT EltVT;
3764   uint64_t EltMask;
3765   SDValue VecVal1, VecVal2;
3766   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3767     EltVT = MVT::i32;
3768     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3769     EltMask = 0x80000000ULL;
3770
3771     if (!VT.isVector()) {
3772       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3773                                           DAG.getUNDEF(VecVT), In1);
3774       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3775                                           DAG.getUNDEF(VecVT), In2);
3776     } else {
3777       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3778       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3779     }
3780   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3781     EltVT = MVT::i64;
3782     VecVT = MVT::v2i64;
3783
3784     // We want to materialize a mask with the high bit set, but the AdvSIMD
3785     // immediate moves cannot materialize that in a single instruction for
3786     // 64-bit elements. Instead, materialize zero and then negate it.
3787     EltMask = 0;
3788
3789     if (!VT.isVector()) {
3790       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3791                                           DAG.getUNDEF(VecVT), In1);
3792       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3793                                           DAG.getUNDEF(VecVT), In2);
3794     } else {
3795       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3796       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3797     }
3798   } else {
3799     llvm_unreachable("Invalid type for copysign!");
3800   }
3801
3802   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3803
3804   // If we couldn't materialize the mask above, then the mask vector will be
3805   // the zero vector, and we need to negate it here.
3806   if (VT == MVT::f64 || VT == MVT::v2f64) {
3807     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3808     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3809     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3810   }
3811
3812   SDValue Sel =
3813       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3814
3815   if (VT == MVT::f32)
3816     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3817   else if (VT == MVT::f64)
3818     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3819   else
3820     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3821 }
3822
3823 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3824   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3825           Attribute::NoImplicitFloat))
3826     return SDValue();
3827
3828   if (!Subtarget->hasNEON())
3829     return SDValue();
3830
3831   // While there is no integer popcount instruction, it can
3832   // be more efficiently lowered to the following sequence that uses
3833   // AdvSIMD registers/instructions as long as the copies to/from
3834   // the AdvSIMD registers are cheap.
3835   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3836   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3837   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3838   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3839   SDValue Val = Op.getOperand(0);
3840   SDLoc DL(Op);
3841   EVT VT = Op.getValueType();
3842
3843   if (VT == MVT::i32)
3844     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3845   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3846
3847   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3848   SDValue UaddLV = DAG.getNode(
3849       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3850       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3851
3852   if (VT == MVT::i64)
3853     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3854   return UaddLV;
3855 }
3856
3857 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3858
3859   if (Op.getValueType().isVector())
3860     return LowerVSETCC(Op, DAG);
3861
3862   SDValue LHS = Op.getOperand(0);
3863   SDValue RHS = Op.getOperand(1);
3864   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3865   SDLoc dl(Op);
3866
3867   // We chose ZeroOrOneBooleanContents, so use zero and one.
3868   EVT VT = Op.getValueType();
3869   SDValue TVal = DAG.getConstant(1, dl, VT);
3870   SDValue FVal = DAG.getConstant(0, dl, VT);
3871
3872   // Handle f128 first, since one possible outcome is a normal integer
3873   // comparison which gets picked up by the next if statement.
3874   if (LHS.getValueType() == MVT::f128) {
3875     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3876
3877     // If softenSetCCOperands returned a scalar, use it.
3878     if (!RHS.getNode()) {
3879       assert(LHS.getValueType() == Op.getValueType() &&
3880              "Unexpected setcc expansion!");
3881       return LHS;
3882     }
3883   }
3884
3885   if (LHS.getValueType().isInteger()) {
3886     SDValue CCVal;
3887     SDValue Cmp =
3888         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3889
3890     // Note that we inverted the condition above, so we reverse the order of
3891     // the true and false operands here.  This will allow the setcc to be
3892     // matched to a single CSINC instruction.
3893     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3894   }
3895
3896   // Now we know we're dealing with FP values.
3897   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3898
3899   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3900   // and do the comparison.
3901   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3902
3903   AArch64CC::CondCode CC1, CC2;
3904   changeFPCCToAArch64CC(CC, CC1, CC2);
3905   if (CC2 == AArch64CC::AL) {
3906     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3907     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3908
3909     // Note that we inverted the condition above, so we reverse the order of
3910     // the true and false operands here.  This will allow the setcc to be
3911     // matched to a single CSINC instruction.
3912     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3913   } else {
3914     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3915     // totally clean.  Some of them require two CSELs to implement.  As is in
3916     // this case, we emit the first CSEL and then emit a second using the output
3917     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3918
3919     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3920     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3921     SDValue CS1 =
3922         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3923
3924     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3925     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3926   }
3927 }
3928
3929 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3930                                               SDValue RHS, SDValue TVal,
3931                                               SDValue FVal, const SDLoc &dl,
3932                                               SelectionDAG &DAG) const {
3933   // Handle f128 first, because it will result in a comparison of some RTLIB
3934   // call result against zero.
3935   if (LHS.getValueType() == MVT::f128) {
3936     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3937
3938     // If softenSetCCOperands returned a scalar, we need to compare the result
3939     // against zero to select between true and false values.
3940     if (!RHS.getNode()) {
3941       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3942       CC = ISD::SETNE;
3943     }
3944   }
3945
3946   // Also handle f16, for which we need to do a f32 comparison.
3947   if (LHS.getValueType() == MVT::f16) {
3948     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3949     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3950   }
3951
3952   // Next, handle integers.
3953   if (LHS.getValueType().isInteger()) {
3954     assert((LHS.getValueType() == RHS.getValueType()) &&
3955            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3956
3957     unsigned Opcode = AArch64ISD::CSEL;
3958
3959     // If both the TVal and the FVal are constants, see if we can swap them in
3960     // order to for a CSINV or CSINC out of them.
3961     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3962     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3963
3964     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3965       std::swap(TVal, FVal);
3966       std::swap(CTVal, CFVal);
3967       CC = ISD::getSetCCInverse(CC, true);
3968     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3969       std::swap(TVal, FVal);
3970       std::swap(CTVal, CFVal);
3971       CC = ISD::getSetCCInverse(CC, true);
3972     } else if (TVal.getOpcode() == ISD::XOR) {
3973       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3974       // with a CSINV rather than a CSEL.
3975       if (isAllOnesConstant(TVal.getOperand(1))) {
3976         std::swap(TVal, FVal);
3977         std::swap(CTVal, CFVal);
3978         CC = ISD::getSetCCInverse(CC, true);
3979       }
3980     } else if (TVal.getOpcode() == ISD::SUB) {
3981       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3982       // that we can match with a CSNEG rather than a CSEL.
3983       if (isNullConstant(TVal.getOperand(0))) {
3984         std::swap(TVal, FVal);
3985         std::swap(CTVal, CFVal);
3986         CC = ISD::getSetCCInverse(CC, true);
3987       }
3988     } else if (CTVal && CFVal) {
3989       const int64_t TrueVal = CTVal->getSExtValue();
3990       const int64_t FalseVal = CFVal->getSExtValue();
3991       bool Swap = false;
3992
3993       // If both TVal and FVal are constants, see if FVal is the
3994       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3995       // instead of a CSEL in that case.
3996       if (TrueVal == ~FalseVal) {
3997         Opcode = AArch64ISD::CSINV;
3998       } else if (TrueVal == -FalseVal) {
3999         Opcode = AArch64ISD::CSNEG;
4000       } else if (TVal.getValueType() == MVT::i32) {
4001         // If our operands are only 32-bit wide, make sure we use 32-bit
4002         // arithmetic for the check whether we can use CSINC. This ensures that
4003         // the addition in the check will wrap around properly in case there is
4004         // an overflow (which would not be the case if we do the check with
4005         // 64-bit arithmetic).
4006         const uint32_t TrueVal32 = CTVal->getZExtValue();
4007         const uint32_t FalseVal32 = CFVal->getZExtValue();
4008
4009         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4010           Opcode = AArch64ISD::CSINC;
4011
4012           if (TrueVal32 > FalseVal32) {
4013             Swap = true;
4014           }
4015         }
4016         // 64-bit check whether we can use CSINC.
4017       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4018         Opcode = AArch64ISD::CSINC;
4019
4020         if (TrueVal > FalseVal) {
4021           Swap = true;
4022         }
4023       }
4024
4025       // Swap TVal and FVal if necessary.
4026       if (Swap) {
4027         std::swap(TVal, FVal);
4028         std::swap(CTVal, CFVal);
4029         CC = ISD::getSetCCInverse(CC, true);
4030       }
4031
4032       if (Opcode != AArch64ISD::CSEL) {
4033         // Drop FVal since we can get its value by simply inverting/negating
4034         // TVal.
4035         FVal = TVal;
4036       }
4037     }
4038
4039     SDValue CCVal;
4040     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4041
4042     EVT VT = TVal.getValueType();
4043     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4044   }
4045
4046   // Now we know we're dealing with FP values.
4047   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4048   assert(LHS.getValueType() == RHS.getValueType());
4049   EVT VT = TVal.getValueType();
4050   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4051
4052   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4053   // clean.  Some of them require two CSELs to implement.
4054   AArch64CC::CondCode CC1, CC2;
4055   changeFPCCToAArch64CC(CC, CC1, CC2);
4056   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4057   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4058
4059   // If we need a second CSEL, emit it, using the output of the first as the
4060   // RHS.  We're effectively OR'ing the two CC's together.
4061   if (CC2 != AArch64CC::AL) {
4062     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4063     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4064   }
4065
4066   // Otherwise, return the output of the first CSEL.
4067   return CS1;
4068 }
4069
4070 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4071                                               SelectionDAG &DAG) const {
4072   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4073   SDValue LHS = Op.getOperand(0);
4074   SDValue RHS = Op.getOperand(1);
4075   SDValue TVal = Op.getOperand(2);
4076   SDValue FVal = Op.getOperand(3);
4077   SDLoc DL(Op);
4078   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4079 }
4080
4081 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4082                                            SelectionDAG &DAG) const {
4083   SDValue CCVal = Op->getOperand(0);
4084   SDValue TVal = Op->getOperand(1);
4085   SDValue FVal = Op->getOperand(2);
4086   SDLoc DL(Op);
4087
4088   unsigned Opc = CCVal.getOpcode();
4089   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4090   // instruction.
4091   if (CCVal.getResNo() == 1 &&
4092       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4093        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4094     // Only lower legal XALUO ops.
4095     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4096       return SDValue();
4097
4098     AArch64CC::CondCode OFCC;
4099     SDValue Value, Overflow;
4100     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4101     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4102
4103     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4104                        CCVal, Overflow);
4105   }
4106
4107   // Lower it the same way as we would lower a SELECT_CC node.
4108   ISD::CondCode CC;
4109   SDValue LHS, RHS;
4110   if (CCVal.getOpcode() == ISD::SETCC) {
4111     LHS = CCVal.getOperand(0);
4112     RHS = CCVal.getOperand(1);
4113     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4114   } else {
4115     LHS = CCVal;
4116     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4117     CC = ISD::SETNE;
4118   }
4119   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4120 }
4121
4122 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4123                                               SelectionDAG &DAG) const {
4124   // Jump table entries as PC relative offsets. No additional tweaking
4125   // is necessary here. Just get the address of the jump table.
4126   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4127   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4128   SDLoc DL(Op);
4129
4130   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4131       !Subtarget->isTargetMachO()) {
4132     const unsigned char MO_NC = AArch64II::MO_NC;
4133     return DAG.getNode(
4134         AArch64ISD::WrapperLarge, DL, PtrVT,
4135         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4136         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4137         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4138         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4139                                AArch64II::MO_G0 | MO_NC));
4140   }
4141
4142   SDValue Hi =
4143       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4144   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4145                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4146   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4147   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4148 }
4149
4150 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4151                                                  SelectionDAG &DAG) const {
4152   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4153   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4154   SDLoc DL(Op);
4155
4156   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4157     // Use the GOT for the large code model on iOS.
4158     if (Subtarget->isTargetMachO()) {
4159       SDValue GotAddr = DAG.getTargetConstantPool(
4160           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4161           AArch64II::MO_GOT);
4162       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4163     }
4164
4165     const unsigned char MO_NC = AArch64II::MO_NC;
4166     return DAG.getNode(
4167         AArch64ISD::WrapperLarge, DL, PtrVT,
4168         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4169                                   CP->getOffset(), AArch64II::MO_G3),
4170         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4171                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4172         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4173                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4174         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4175                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4176   } else {
4177     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4178     // ELF, the only valid one on Darwin.
4179     SDValue Hi =
4180         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4181                                   CP->getOffset(), AArch64II::MO_PAGE);
4182     SDValue Lo = DAG.getTargetConstantPool(
4183         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4184         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4185
4186     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4187     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4188   }
4189 }
4190
4191 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4192                                                SelectionDAG &DAG) const {
4193   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4194   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4195   SDLoc DL(Op);
4196   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4197       !Subtarget->isTargetMachO()) {
4198     const unsigned char MO_NC = AArch64II::MO_NC;
4199     return DAG.getNode(
4200         AArch64ISD::WrapperLarge, DL, PtrVT,
4201         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4202         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4203         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4204         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4205   } else {
4206     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4207     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4208                                                              AArch64II::MO_NC);
4209     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4210     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4211   }
4212 }
4213
4214 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4215                                                  SelectionDAG &DAG) const {
4216   AArch64FunctionInfo *FuncInfo =
4217       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4218
4219   SDLoc DL(Op);
4220   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4221                                  getPointerTy(DAG.getDataLayout()));
4222   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4223   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4224                       MachinePointerInfo(SV));
4225 }
4226
4227 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4228                                                 SelectionDAG &DAG) const {
4229   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4230   // Standard, section B.3.
4231   MachineFunction &MF = DAG.getMachineFunction();
4232   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4233   auto PtrVT = getPointerTy(DAG.getDataLayout());
4234   SDLoc DL(Op);
4235
4236   SDValue Chain = Op.getOperand(0);
4237   SDValue VAList = Op.getOperand(1);
4238   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4239   SmallVector<SDValue, 4> MemOps;
4240
4241   // void *__stack at offset 0
4242   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4243   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4244                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4245
4246   // void *__gr_top at offset 8
4247   int GPRSize = FuncInfo->getVarArgsGPRSize();
4248   if (GPRSize > 0) {
4249     SDValue GRTop, GRTopAddr;
4250
4251     GRTopAddr =
4252         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4253
4254     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4255     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4256                         DAG.getConstant(GPRSize, DL, PtrVT));
4257
4258     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4259                                   MachinePointerInfo(SV, 8),
4260                                   /* Alignment = */ 8));
4261   }
4262
4263   // void *__vr_top at offset 16
4264   int FPRSize = FuncInfo->getVarArgsFPRSize();
4265   if (FPRSize > 0) {
4266     SDValue VRTop, VRTopAddr;
4267     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4268                             DAG.getConstant(16, DL, PtrVT));
4269
4270     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4271     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4272                         DAG.getConstant(FPRSize, DL, PtrVT));
4273
4274     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4275                                   MachinePointerInfo(SV, 16),
4276                                   /* Alignment = */ 8));
4277   }
4278
4279   // int __gr_offs at offset 24
4280   SDValue GROffsAddr =
4281       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4282   MemOps.push_back(DAG.getStore(
4283       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4284       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4285
4286   // int __vr_offs at offset 28
4287   SDValue VROffsAddr =
4288       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4289   MemOps.push_back(DAG.getStore(
4290       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4291       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4292
4293   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4294 }
4295
4296 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4297                                             SelectionDAG &DAG) const {
4298   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4299                                      : LowerAAPCS_VASTART(Op, DAG);
4300 }
4301
4302 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4303                                            SelectionDAG &DAG) const {
4304   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4305   // pointer.
4306   SDLoc DL(Op);
4307   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4308   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4309   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4310
4311   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4312                        Op.getOperand(2),
4313                        DAG.getConstant(VaListSize, DL, MVT::i32),
4314                        8, false, false, false, MachinePointerInfo(DestSV),
4315                        MachinePointerInfo(SrcSV));
4316 }
4317
4318 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4319   assert(Subtarget->isTargetDarwin() &&
4320          "automatic va_arg instruction only works on Darwin");
4321
4322   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4323   EVT VT = Op.getValueType();
4324   SDLoc DL(Op);
4325   SDValue Chain = Op.getOperand(0);
4326   SDValue Addr = Op.getOperand(1);
4327   unsigned Align = Op.getConstantOperandVal(3);
4328   auto PtrVT = getPointerTy(DAG.getDataLayout());
4329
4330   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4331   Chain = VAList.getValue(1);
4332
4333   if (Align > 8) {
4334     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4335     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4336                          DAG.getConstant(Align - 1, DL, PtrVT));
4337     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4338                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4339   }
4340
4341   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4342   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4343
4344   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4345   // up to 64 bits.  At the very least, we have to increase the striding of the
4346   // vaargs list to match this, and for FP values we need to introduce
4347   // FP_ROUND nodes as well.
4348   if (VT.isInteger() && !VT.isVector())
4349     ArgSize = 8;
4350   bool NeedFPTrunc = false;
4351   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4352     ArgSize = 8;
4353     NeedFPTrunc = true;
4354   }
4355
4356   // Increment the pointer, VAList, to the next vaarg
4357   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4358                                DAG.getConstant(ArgSize, DL, PtrVT));
4359   // Store the incremented VAList to the legalized pointer
4360   SDValue APStore =
4361       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4362
4363   // Load the actual argument out of the pointer VAList
4364   if (NeedFPTrunc) {
4365     // Load the value as an f64.
4366     SDValue WideFP =
4367         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4368     // Round the value down to an f32.
4369     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4370                                    DAG.getIntPtrConstant(1, DL));
4371     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4372     // Merge the rounded value with the chain output of the load.
4373     return DAG.getMergeValues(Ops, DL);
4374   }
4375
4376   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4377 }
4378
4379 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4380                                               SelectionDAG &DAG) const {
4381   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4382   MFI->setFrameAddressIsTaken(true);
4383
4384   EVT VT = Op.getValueType();
4385   SDLoc DL(Op);
4386   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4387   SDValue FrameAddr =
4388       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4389   while (Depth--)
4390     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4391                             MachinePointerInfo());
4392   return FrameAddr;
4393 }
4394
4395 // FIXME? Maybe this could be a TableGen attribute on some registers and
4396 // this table could be generated automatically from RegInfo.
4397 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4398                                                   SelectionDAG &DAG) const {
4399   unsigned Reg = StringSwitch<unsigned>(RegName)
4400                        .Case("sp", AArch64::SP)
4401                        .Default(0);
4402   if (Reg)
4403     return Reg;
4404   report_fatal_error(Twine("Invalid register name \""
4405                               + StringRef(RegName)  + "\"."));
4406 }
4407
4408 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4409                                                SelectionDAG &DAG) const {
4410   MachineFunction &MF = DAG.getMachineFunction();
4411   MachineFrameInfo *MFI = MF.getFrameInfo();
4412   MFI->setReturnAddressIsTaken(true);
4413
4414   EVT VT = Op.getValueType();
4415   SDLoc DL(Op);
4416   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4417   if (Depth) {
4418     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4419     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4420     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4421                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4422                        MachinePointerInfo());
4423   }
4424
4425   // Return LR, which contains the return address. Mark it an implicit live-in.
4426   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4427   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4428 }
4429
4430 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4431 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4432 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4433                                                     SelectionDAG &DAG) const {
4434   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4435   EVT VT = Op.getValueType();
4436   unsigned VTBits = VT.getSizeInBits();
4437   SDLoc dl(Op);
4438   SDValue ShOpLo = Op.getOperand(0);
4439   SDValue ShOpHi = Op.getOperand(1);
4440   SDValue ShAmt = Op.getOperand(2);
4441   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4442
4443   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4444
4445   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4446                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4447   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4448
4449   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4450   // is "undef". We wanted 0, so CSEL it directly.
4451   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4452                                ISD::SETEQ, dl, DAG);
4453   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4454   HiBitsForLo =
4455       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4456                   HiBitsForLo, CCVal, Cmp);
4457
4458   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4459                                    DAG.getConstant(VTBits, dl, MVT::i64));
4460
4461   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4462   SDValue LoForNormalShift =
4463       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4464
4465   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4466                        dl, DAG);
4467   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4468   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4469   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4470                            LoForNormalShift, CCVal, Cmp);
4471
4472   // AArch64 shifts larger than the register width are wrapped rather than
4473   // clamped, so we can't just emit "hi >> x".
4474   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4475   SDValue HiForBigShift =
4476       Opc == ISD::SRA
4477           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4478                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4479           : DAG.getConstant(0, dl, VT);
4480   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4481                            HiForNormalShift, CCVal, Cmp);
4482
4483   SDValue Ops[2] = { Lo, Hi };
4484   return DAG.getMergeValues(Ops, dl);
4485 }
4486
4487
4488 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4489 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4490 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4491                                                    SelectionDAG &DAG) const {
4492   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4493   EVT VT = Op.getValueType();
4494   unsigned VTBits = VT.getSizeInBits();
4495   SDLoc dl(Op);
4496   SDValue ShOpLo = Op.getOperand(0);
4497   SDValue ShOpHi = Op.getOperand(1);
4498   SDValue ShAmt = Op.getOperand(2);
4499
4500   assert(Op.getOpcode() == ISD::SHL_PARTS);
4501   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4502                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4503   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4504
4505   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4506   // is "undef". We wanted 0, so CSEL it directly.
4507   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4508                                ISD::SETEQ, dl, DAG);
4509   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4510   LoBitsForHi =
4511       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4512                   LoBitsForHi, CCVal, Cmp);
4513
4514   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4515                                    DAG.getConstant(VTBits, dl, MVT::i64));
4516   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4517   SDValue HiForNormalShift =
4518       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4519
4520   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4521
4522   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4523                        dl, DAG);
4524   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4525   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4526                            HiForNormalShift, CCVal, Cmp);
4527
4528   // AArch64 shifts of larger than register sizes are wrapped rather than
4529   // clamped, so we can't just emit "lo << a" if a is too big.
4530   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4531   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4532   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4533                            LoForNormalShift, CCVal, Cmp);
4534
4535   SDValue Ops[2] = { Lo, Hi };
4536   return DAG.getMergeValues(Ops, dl);
4537 }
4538
4539 bool AArch64TargetLowering::isOffsetFoldingLegal(
4540     const GlobalAddressSDNode *GA) const {
4541   // The AArch64 target doesn't support folding offsets into global addresses.
4542   return false;
4543 }
4544
4545 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4546   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4547   // FIXME: We should be able to handle f128 as well with a clever lowering.
4548   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4549     return true;
4550
4551   if (VT == MVT::f64)
4552     return AArch64_AM::getFP64Imm(Imm) != -1;
4553   else if (VT == MVT::f32)
4554     return AArch64_AM::getFP32Imm(Imm) != -1;
4555   return false;
4556 }
4557
4558 //===----------------------------------------------------------------------===//
4559 //                          AArch64 Optimization Hooks
4560 //===----------------------------------------------------------------------===//
4561
4562 /// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4563 /// or the reciprocal square root.
4564 static SDValue getEstimate(const AArch64Subtarget &ST,
4565   const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4566   const SDValue &Operand, unsigned &ExtraSteps) {
4567   if (!ST.hasNEON())
4568     return SDValue();
4569
4570   EVT VT = Operand.getValueType();
4571
4572   std::string RecipOp;
4573   RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4574   RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4575   RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4576
4577   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4578   if (!Recips.isEnabled(RecipOp))
4579     return SDValue();
4580
4581   ExtraSteps = Recips.getRefinementSteps(RecipOp);
4582   return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4583 }
4584
4585 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4586   DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4587   return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4588 }
4589
4590 SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4591   DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4592   UseOneConst = true;
4593   return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4594 }
4595
4596 //===----------------------------------------------------------------------===//
4597 //                          AArch64 Inline Assembly Support
4598 //===----------------------------------------------------------------------===//
4599
4600 // Table of Constraints
4601 // TODO: This is the current set of constraints supported by ARM for the
4602 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4603 //
4604 // r - A general register
4605 // w - An FP/SIMD register of some size in the range v0-v31
4606 // x - An FP/SIMD register of some size in the range v0-v15
4607 // I - Constant that can be used with an ADD instruction
4608 // J - Constant that can be used with a SUB instruction
4609 // K - Constant that can be used with a 32-bit logical instruction
4610 // L - Constant that can be used with a 64-bit logical instruction
4611 // M - Constant that can be used as a 32-bit MOV immediate
4612 // N - Constant that can be used as a 64-bit MOV immediate
4613 // Q - A memory reference with base register and no offset
4614 // S - A symbolic address
4615 // Y - Floating point constant zero
4616 // Z - Integer constant zero
4617 //
4618 //   Note that general register operands will be output using their 64-bit x
4619 // register name, whatever the size of the variable, unless the asm operand
4620 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4621 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4622 // %q modifier.
4623 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4624   // At this point, we have to lower this constraint to something else, so we
4625   // lower it to an "r" or "w". However, by doing this we will force the result
4626   // to be in register, while the X constraint is much more permissive.
4627   //
4628   // Although we are correct (we are free to emit anything, without
4629   // constraints), we might break use cases that would expect us to be more
4630   // efficient and emit something else.
4631   if (!Subtarget->hasFPARMv8())
4632     return "r";
4633
4634   if (ConstraintVT.isFloatingPoint())
4635     return "w";
4636
4637   if (ConstraintVT.isVector() &&
4638      (ConstraintVT.getSizeInBits() == 64 ||
4639       ConstraintVT.getSizeInBits() == 128))
4640     return "w";
4641
4642   return "r";
4643 }
4644
4645 /// getConstraintType - Given a constraint letter, return the type of
4646 /// constraint it is for this target.
4647 AArch64TargetLowering::ConstraintType
4648 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4649   if (Constraint.size() == 1) {
4650     switch (Constraint[0]) {
4651     default:
4652       break;
4653     case 'z':
4654       return C_Other;
4655     case 'x':
4656     case 'w':
4657       return C_RegisterClass;
4658     // An address with a single base register. Due to the way we
4659     // currently handle addresses it is the same as 'r'.
4660     case 'Q':
4661       return C_Memory;
4662     }
4663   }
4664   return TargetLowering::getConstraintType(Constraint);
4665 }
4666
4667 /// Examine constraint type and operand type and determine a weight value.
4668 /// This object must already have been set up with the operand type
4669 /// and the current alternative constraint selected.
4670 TargetLowering::ConstraintWeight
4671 AArch64TargetLowering::getSingleConstraintMatchWeight(
4672     AsmOperandInfo &info, const char *constraint) const {
4673   ConstraintWeight weight = CW_Invalid;
4674   Value *CallOperandVal = info.CallOperandVal;
4675   // If we don't have a value, we can't do a match,
4676   // but allow it at the lowest weight.
4677   if (!CallOperandVal)
4678     return CW_Default;
4679   Type *type = CallOperandVal->getType();
4680   // Look at the constraint type.
4681   switch (*constraint) {
4682   default:
4683     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4684     break;
4685   case 'x':
4686   case 'w':
4687     if (type->isFloatingPointTy() || type->isVectorTy())
4688       weight = CW_Register;
4689     break;
4690   case 'z':
4691     weight = CW_Constant;
4692     break;
4693   }
4694   return weight;
4695 }
4696
4697 std::pair<unsigned, const TargetRegisterClass *>
4698 AArch64TargetLowering::getRegForInlineAsmConstraint(
4699     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4700   if (Constraint.size() == 1) {
4701     switch (Constraint[0]) {
4702     case 'r':
4703       if (VT.getSizeInBits() == 64)
4704         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4705       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4706     case 'w':
4707       if (VT == MVT::f32)
4708         return std::make_pair(0U, &AArch64::FPR32RegClass);
4709       if (VT.getSizeInBits() == 64)
4710         return std::make_pair(0U, &AArch64::FPR64RegClass);
4711       if (VT.getSizeInBits() == 128)
4712         return std::make_pair(0U, &AArch64::FPR128RegClass);
4713       break;
4714     // The instructions that this constraint is designed for can
4715     // only take 128-bit registers so just use that regclass.
4716     case 'x':
4717       if (VT.getSizeInBits() == 128)
4718         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4719       break;
4720     }
4721   }
4722   if (StringRef("{cc}").equals_lower(Constraint))
4723     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4724
4725   // Use the default implementation in TargetLowering to convert the register
4726   // constraint into a member of a register class.
4727   std::pair<unsigned, const TargetRegisterClass *> Res;
4728   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4729
4730   // Not found as a standard register?
4731   if (!Res.second) {
4732     unsigned Size = Constraint.size();
4733     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4734         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4735       int RegNo;
4736       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4737       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4738         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4739         // By default we'll emit v0-v31 for this unless there's a modifier where
4740         // we'll emit the correct register as well.
4741         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4742           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4743           Res.second = &AArch64::FPR64RegClass;
4744         } else {
4745           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4746           Res.second = &AArch64::FPR128RegClass;
4747         }
4748       }
4749     }
4750   }
4751
4752   return Res;
4753 }
4754
4755 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4756 /// vector.  If it is invalid, don't add anything to Ops.
4757 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4758     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4759     SelectionDAG &DAG) const {
4760   SDValue Result;
4761
4762   // Currently only support length 1 constraints.
4763   if (Constraint.length() != 1)
4764     return;
4765
4766   char ConstraintLetter = Constraint[0];
4767   switch (ConstraintLetter) {
4768   default:
4769     break;
4770
4771   // This set of constraints deal with valid constants for various instructions.
4772   // Validate and return a target constant for them if we can.
4773   case 'z': {
4774     // 'z' maps to xzr or wzr so it needs an input of 0.
4775     if (!isNullConstant(Op))
4776       return;
4777
4778     if (Op.getValueType() == MVT::i64)
4779       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4780     else
4781       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4782     break;
4783   }
4784
4785   case 'I':
4786   case 'J':
4787   case 'K':
4788   case 'L':
4789   case 'M':
4790   case 'N':
4791     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4792     if (!C)
4793       return;
4794
4795     // Grab the value and do some validation.
4796     uint64_t CVal = C->getZExtValue();
4797     switch (ConstraintLetter) {
4798     // The I constraint applies only to simple ADD or SUB immediate operands:
4799     // i.e. 0 to 4095 with optional shift by 12
4800     // The J constraint applies only to ADD or SUB immediates that would be
4801     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4802     // instruction [or vice versa], in other words -1 to -4095 with optional
4803     // left shift by 12.
4804     case 'I':
4805       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4806         break;
4807       return;
4808     case 'J': {
4809       uint64_t NVal = -C->getSExtValue();
4810       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4811         CVal = C->getSExtValue();
4812         break;
4813       }
4814       return;
4815     }
4816     // The K and L constraints apply *only* to logical immediates, including
4817     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4818     // been removed and MOV should be used). So these constraints have to
4819     // distinguish between bit patterns that are valid 32-bit or 64-bit
4820     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4821     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4822     // versa.
4823     case 'K':
4824       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4825         break;
4826       return;
4827     case 'L':
4828       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4829         break;
4830       return;
4831     // The M and N constraints are a superset of K and L respectively, for use
4832     // with the MOV (immediate) alias. As well as the logical immediates they
4833     // also match 32 or 64-bit immediates that can be loaded either using a
4834     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4835     // (M) or 64-bit 0x1234000000000000 (N) etc.
4836     // As a note some of this code is liberally stolen from the asm parser.
4837     case 'M': {
4838       if (!isUInt<32>(CVal))
4839         return;
4840       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4841         break;
4842       if ((CVal & 0xFFFF) == CVal)
4843         break;
4844       if ((CVal & 0xFFFF0000ULL) == CVal)
4845         break;
4846       uint64_t NCVal = ~(uint32_t)CVal;
4847       if ((NCVal & 0xFFFFULL) == NCVal)
4848         break;
4849       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4850         break;
4851       return;
4852     }
4853     case 'N': {
4854       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4855         break;
4856       if ((CVal & 0xFFFFULL) == CVal)
4857         break;
4858       if ((CVal & 0xFFFF0000ULL) == CVal)
4859         break;
4860       if ((CVal & 0xFFFF00000000ULL) == CVal)
4861         break;
4862       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4863         break;
4864       uint64_t NCVal = ~CVal;
4865       if ((NCVal & 0xFFFFULL) == NCVal)
4866         break;
4867       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4868         break;
4869       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4870         break;
4871       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4872         break;
4873       return;
4874     }
4875     default:
4876       return;
4877     }
4878
4879     // All assembler immediates are 64-bit integers.
4880     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4881     break;
4882   }
4883
4884   if (Result.getNode()) {
4885     Ops.push_back(Result);
4886     return;
4887   }
4888
4889   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4890 }
4891
4892 //===----------------------------------------------------------------------===//
4893 //                     AArch64 Advanced SIMD Support
4894 //===----------------------------------------------------------------------===//
4895
4896 /// WidenVector - Given a value in the V64 register class, produce the
4897 /// equivalent value in the V128 register class.
4898 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4899   EVT VT = V64Reg.getValueType();
4900   unsigned NarrowSize = VT.getVectorNumElements();
4901   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4902   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4903   SDLoc DL(V64Reg);
4904
4905   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4906                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4907 }
4908
4909 /// getExtFactor - Determine the adjustment factor for the position when
4910 /// generating an "extract from vector registers" instruction.
4911 static unsigned getExtFactor(SDValue &V) {
4912   EVT EltType = V.getValueType().getVectorElementType();
4913   return EltType.getSizeInBits() / 8;
4914 }
4915
4916 /// NarrowVector - Given a value in the V128 register class, produce the
4917 /// equivalent value in the V64 register class.
4918 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4919   EVT VT = V128Reg.getValueType();
4920   unsigned WideSize = VT.getVectorNumElements();
4921   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4922   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4923   SDLoc DL(V128Reg);
4924
4925   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4926 }
4927
4928 // Gather data to see if the operation can be modelled as a
4929 // shuffle in combination with VEXTs.
4930 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4931                                                   SelectionDAG &DAG) const {
4932   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4933   SDLoc dl(Op);
4934   EVT VT = Op.getValueType();
4935   unsigned NumElts = VT.getVectorNumElements();
4936
4937   struct ShuffleSourceInfo {
4938     SDValue Vec;
4939     unsigned MinElt;
4940     unsigned MaxElt;
4941
4942     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4943     // be compatible with the shuffle we intend to construct. As a result
4944     // ShuffleVec will be some sliding window into the original Vec.
4945     SDValue ShuffleVec;
4946
4947     // Code should guarantee that element i in Vec starts at element "WindowBase
4948     // + i * WindowScale in ShuffleVec".
4949     int WindowBase;
4950     int WindowScale;
4951
4952     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4953     ShuffleSourceInfo(SDValue Vec)
4954         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4955           WindowScale(1) {}
4956   };
4957
4958   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4959   // node.
4960   SmallVector<ShuffleSourceInfo, 2> Sources;
4961   for (unsigned i = 0; i < NumElts; ++i) {
4962     SDValue V = Op.getOperand(i);
4963     if (V.isUndef())
4964       continue;
4965     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4966              !isa<ConstantSDNode>(V.getOperand(1))) {
4967       // A shuffle can only come from building a vector from various
4968       // elements of other vectors, provided their indices are constant.
4969       return SDValue();
4970     }
4971
4972     // Add this element source to the list if it's not already there.
4973     SDValue SourceVec = V.getOperand(0);
4974     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4975     if (Source == Sources.end())
4976       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4977
4978     // Update the minimum and maximum lane number seen.
4979     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4980     Source->MinElt = std::min(Source->MinElt, EltNo);
4981     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4982   }
4983
4984   // Currently only do something sane when at most two source vectors
4985   // are involved.
4986   if (Sources.size() > 2)
4987     return SDValue();
4988
4989   // Find out the smallest element size among result and two sources, and use
4990   // it as element size to build the shuffle_vector.
4991   EVT SmallestEltTy = VT.getVectorElementType();
4992   for (auto &Source : Sources) {
4993     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4994     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4995       SmallestEltTy = SrcEltTy;
4996     }
4997   }
4998   unsigned ResMultiplier =
4999       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5000   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5001   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5002
5003   // If the source vector is too wide or too narrow, we may nevertheless be able
5004   // to construct a compatible shuffle either by concatenating it with UNDEF or
5005   // extracting a suitable range of elements.
5006   for (auto &Src : Sources) {
5007     EVT SrcVT = Src.ShuffleVec.getValueType();
5008
5009     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5010       continue;
5011
5012     // This stage of the search produces a source with the same element type as
5013     // the original, but with a total width matching the BUILD_VECTOR output.
5014     EVT EltVT = SrcVT.getVectorElementType();
5015     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5016     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5017
5018     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5019       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5020       // We can pad out the smaller vector for free, so if it's part of a
5021       // shuffle...
5022       Src.ShuffleVec =
5023           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5024                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5025       continue;
5026     }
5027
5028     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5029
5030     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5031       // Span too large for a VEXT to cope
5032       return SDValue();
5033     }
5034
5035     if (Src.MinElt >= NumSrcElts) {
5036       // The extraction can just take the second half
5037       Src.ShuffleVec =
5038           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5039                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5040       Src.WindowBase = -NumSrcElts;
5041     } else if (Src.MaxElt < NumSrcElts) {
5042       // The extraction can just take the first half
5043       Src.ShuffleVec =
5044           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5045                       DAG.getConstant(0, dl, MVT::i64));
5046     } else {
5047       // An actual VEXT is needed
5048       SDValue VEXTSrc1 =
5049           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5050                       DAG.getConstant(0, dl, MVT::i64));
5051       SDValue VEXTSrc2 =
5052           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5053                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5054       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5055
5056       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5057                                    VEXTSrc2,
5058                                    DAG.getConstant(Imm, dl, MVT::i32));
5059       Src.WindowBase = -Src.MinElt;
5060     }
5061   }
5062
5063   // Another possible incompatibility occurs from the vector element types. We
5064   // can fix this by bitcasting the source vectors to the same type we intend
5065   // for the shuffle.
5066   for (auto &Src : Sources) {
5067     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5068     if (SrcEltTy == SmallestEltTy)
5069       continue;
5070     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5071     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5072     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5073     Src.WindowBase *= Src.WindowScale;
5074   }
5075
5076   // Final sanity check before we try to actually produce a shuffle.
5077   DEBUG(
5078     for (auto Src : Sources)
5079       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5080   );
5081
5082   // The stars all align, our next step is to produce the mask for the shuffle.
5083   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5084   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5085   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5086     SDValue Entry = Op.getOperand(i);
5087     if (Entry.isUndef())
5088       continue;
5089
5090     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5091     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5092
5093     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5094     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5095     // segment.
5096     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5097     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5098                                VT.getVectorElementType().getSizeInBits());
5099     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5100
5101     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5102     // starting at the appropriate offset.
5103     int *LaneMask = &Mask[i * ResMultiplier];
5104
5105     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5106     ExtractBase += NumElts * (Src - Sources.begin());
5107     for (int j = 0; j < LanesDefined; ++j)
5108       LaneMask[j] = ExtractBase + j;
5109   }
5110
5111   // Final check before we try to produce nonsense...
5112   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5113     return SDValue();
5114
5115   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5116   for (unsigned i = 0; i < Sources.size(); ++i)
5117     ShuffleOps[i] = Sources[i].ShuffleVec;
5118
5119   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5120                                          ShuffleOps[1], Mask);
5121   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5122 }
5123
5124 // check if an EXT instruction can handle the shuffle mask when the
5125 // vector sources of the shuffle are the same.
5126 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5127   unsigned NumElts = VT.getVectorNumElements();
5128
5129   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5130   if (M[0] < 0)
5131     return false;
5132
5133   Imm = M[0];
5134
5135   // If this is a VEXT shuffle, the immediate value is the index of the first
5136   // element.  The other shuffle indices must be the successive elements after
5137   // the first one.
5138   unsigned ExpectedElt = Imm;
5139   for (unsigned i = 1; i < NumElts; ++i) {
5140     // Increment the expected index.  If it wraps around, just follow it
5141     // back to index zero and keep going.
5142     ++ExpectedElt;
5143     if (ExpectedElt == NumElts)
5144       ExpectedElt = 0;
5145
5146     if (M[i] < 0)
5147       continue; // ignore UNDEF indices
5148     if (ExpectedElt != static_cast<unsigned>(M[i]))
5149       return false;
5150   }
5151
5152   return true;
5153 }
5154
5155 // check if an EXT instruction can handle the shuffle mask when the
5156 // vector sources of the shuffle are different.
5157 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5158                       unsigned &Imm) {
5159   // Look for the first non-undef element.
5160   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5161       [](int Elt) {return Elt >= 0;});
5162
5163   // Benefit form APInt to handle overflow when calculating expected element.
5164   unsigned NumElts = VT.getVectorNumElements();
5165   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5166   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5167   // The following shuffle indices must be the successive elements after the
5168   // first real element.
5169   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5170       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5171   if (FirstWrongElt != M.end())
5172     return false;
5173
5174   // The index of an EXT is the first element if it is not UNDEF.
5175   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5176   // value of the first element.  E.g.
5177   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5178   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5179   // ExpectedElt is the last mask index plus 1.
5180   Imm = ExpectedElt.getZExtValue();
5181
5182   // There are two difference cases requiring to reverse input vectors.
5183   // For example, for vector <4 x i32> we have the following cases,
5184   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5185   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5186   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5187   // to reverse two input vectors.
5188   if (Imm < NumElts)
5189     ReverseEXT = true;
5190   else
5191     Imm -= NumElts;
5192
5193   return true;
5194 }
5195
5196 /// isREVMask - Check if a vector shuffle corresponds to a REV
5197 /// instruction with the specified blocksize.  (The order of the elements
5198 /// within each block of the vector is reversed.)
5199 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5200   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5201          "Only possible block sizes for REV are: 16, 32, 64");
5202
5203   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5204   if (EltSz == 64)
5205     return false;
5206
5207   unsigned NumElts = VT.getVectorNumElements();
5208   unsigned BlockElts = M[0] + 1;
5209   // If the first shuffle index is UNDEF, be optimistic.
5210   if (M[0] < 0)
5211     BlockElts = BlockSize / EltSz;
5212
5213   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5214     return false;
5215
5216   for (unsigned i = 0; i < NumElts; ++i) {
5217     if (M[i] < 0)
5218       continue; // ignore UNDEF indices
5219     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5220       return false;
5221   }
5222
5223   return true;
5224 }
5225
5226 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5227   unsigned NumElts = VT.getVectorNumElements();
5228   WhichResult = (M[0] == 0 ? 0 : 1);
5229   unsigned Idx = WhichResult * NumElts / 2;
5230   for (unsigned i = 0; i != NumElts; i += 2) {
5231     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5232         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5233       return false;
5234     Idx += 1;
5235   }
5236
5237   return true;
5238 }
5239
5240 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5241   unsigned NumElts = VT.getVectorNumElements();
5242   WhichResult = (M[0] == 0 ? 0 : 1);
5243   for (unsigned i = 0; i != NumElts; ++i) {
5244     if (M[i] < 0)
5245       continue; // ignore UNDEF indices
5246     if ((unsigned)M[i] != 2 * i + WhichResult)
5247       return false;
5248   }
5249
5250   return true;
5251 }
5252
5253 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5254   unsigned NumElts = VT.getVectorNumElements();
5255   WhichResult = (M[0] == 0 ? 0 : 1);
5256   for (unsigned i = 0; i < NumElts; i += 2) {
5257     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5258         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5259       return false;
5260   }
5261   return true;
5262 }
5263
5264 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5265 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5266 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5267 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5268   unsigned NumElts = VT.getVectorNumElements();
5269   WhichResult = (M[0] == 0 ? 0 : 1);
5270   unsigned Idx = WhichResult * NumElts / 2;
5271   for (unsigned i = 0; i != NumElts; i += 2) {
5272     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5273         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5274       return false;
5275     Idx += 1;
5276   }
5277
5278   return true;
5279 }
5280
5281 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5282 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5283 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5284 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5285   unsigned Half = VT.getVectorNumElements() / 2;
5286   WhichResult = (M[0] == 0 ? 0 : 1);
5287   for (unsigned j = 0; j != 2; ++j) {
5288     unsigned Idx = WhichResult;
5289     for (unsigned i = 0; i != Half; ++i) {
5290       int MIdx = M[i + j * Half];
5291       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5292         return false;
5293       Idx += 2;
5294     }
5295   }
5296
5297   return true;
5298 }
5299
5300 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5301 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5302 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5303 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5304   unsigned NumElts = VT.getVectorNumElements();
5305   WhichResult = (M[0] == 0 ? 0 : 1);
5306   for (unsigned i = 0; i < NumElts; i += 2) {
5307     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5308         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5309       return false;
5310   }
5311   return true;
5312 }
5313
5314 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5315                       bool &DstIsLeft, int &Anomaly) {
5316   if (M.size() != static_cast<size_t>(NumInputElements))
5317     return false;
5318
5319   int NumLHSMatch = 0, NumRHSMatch = 0;
5320   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5321
5322   for (int i = 0; i < NumInputElements; ++i) {
5323     if (M[i] == -1) {
5324       ++NumLHSMatch;
5325       ++NumRHSMatch;
5326       continue;
5327     }
5328
5329     if (M[i] == i)
5330       ++NumLHSMatch;
5331     else
5332       LastLHSMismatch = i;
5333
5334     if (M[i] == i + NumInputElements)
5335       ++NumRHSMatch;
5336     else
5337       LastRHSMismatch = i;
5338   }
5339
5340   if (NumLHSMatch == NumInputElements - 1) {
5341     DstIsLeft = true;
5342     Anomaly = LastLHSMismatch;
5343     return true;
5344   } else if (NumRHSMatch == NumInputElements - 1) {
5345     DstIsLeft = false;
5346     Anomaly = LastRHSMismatch;
5347     return true;
5348   }
5349
5350   return false;
5351 }
5352
5353 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5354   if (VT.getSizeInBits() != 128)
5355     return false;
5356
5357   unsigned NumElts = VT.getVectorNumElements();
5358
5359   for (int I = 0, E = NumElts / 2; I != E; I++) {
5360     if (Mask[I] != I)
5361       return false;
5362   }
5363
5364   int Offset = NumElts / 2;
5365   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5366     if (Mask[I] != I + SplitLHS * Offset)
5367       return false;
5368   }
5369
5370   return true;
5371 }
5372
5373 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5374   SDLoc DL(Op);
5375   EVT VT = Op.getValueType();
5376   SDValue V0 = Op.getOperand(0);
5377   SDValue V1 = Op.getOperand(1);
5378   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5379
5380   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5381       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5382     return SDValue();
5383
5384   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5385
5386   if (!isConcatMask(Mask, VT, SplitV0))
5387     return SDValue();
5388
5389   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5390                                 VT.getVectorNumElements() / 2);
5391   if (SplitV0) {
5392     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5393                      DAG.getConstant(0, DL, MVT::i64));
5394   }
5395   if (V1.getValueType().getSizeInBits() == 128) {
5396     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5397                      DAG.getConstant(0, DL, MVT::i64));
5398   }
5399   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5400 }
5401
5402 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5403 /// the specified operations to build the shuffle.
5404 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5405                                       SDValue RHS, SelectionDAG &DAG,
5406                                       const SDLoc &dl) {
5407   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5408   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5409   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5410
5411   enum {
5412     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5413     OP_VREV,
5414     OP_VDUP0,
5415     OP_VDUP1,
5416     OP_VDUP2,
5417     OP_VDUP3,
5418     OP_VEXT1,
5419     OP_VEXT2,
5420     OP_VEXT3,
5421     OP_VUZPL, // VUZP, left result
5422     OP_VUZPR, // VUZP, right result
5423     OP_VZIPL, // VZIP, left result
5424     OP_VZIPR, // VZIP, right result
5425     OP_VTRNL, // VTRN, left result
5426     OP_VTRNR  // VTRN, right result
5427   };
5428
5429   if (OpNum == OP_COPY) {
5430     if (LHSID == (1 * 9 + 2) * 9 + 3)
5431       return LHS;
5432     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5433     return RHS;
5434   }
5435
5436   SDValue OpLHS, OpRHS;
5437   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5438   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5439   EVT VT = OpLHS.getValueType();
5440
5441   switch (OpNum) {
5442   default:
5443     llvm_unreachable("Unknown shuffle opcode!");
5444   case OP_VREV:
5445     // VREV divides the vector in half and swaps within the half.
5446     if (VT.getVectorElementType() == MVT::i32 ||
5447         VT.getVectorElementType() == MVT::f32)
5448       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5449     // vrev <4 x i16> -> REV32
5450     if (VT.getVectorElementType() == MVT::i16 ||
5451         VT.getVectorElementType() == MVT::f16)
5452       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5453     // vrev <4 x i8> -> REV16
5454     assert(VT.getVectorElementType() == MVT::i8);
5455     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5456   case OP_VDUP0:
5457   case OP_VDUP1:
5458   case OP_VDUP2:
5459   case OP_VDUP3: {
5460     EVT EltTy = VT.getVectorElementType();
5461     unsigned Opcode;
5462     if (EltTy == MVT::i8)
5463       Opcode = AArch64ISD::DUPLANE8;
5464     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5465       Opcode = AArch64ISD::DUPLANE16;
5466     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5467       Opcode = AArch64ISD::DUPLANE32;
5468     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5469       Opcode = AArch64ISD::DUPLANE64;
5470     else
5471       llvm_unreachable("Invalid vector element type?");
5472
5473     if (VT.getSizeInBits() == 64)
5474       OpLHS = WidenVector(OpLHS, DAG);
5475     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5476     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5477   }
5478   case OP_VEXT1:
5479   case OP_VEXT2:
5480   case OP_VEXT3: {
5481     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5482     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5483                        DAG.getConstant(Imm, dl, MVT::i32));
5484   }
5485   case OP_VUZPL:
5486     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5487                        OpRHS);
5488   case OP_VUZPR:
5489     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5490                        OpRHS);
5491   case OP_VZIPL:
5492     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5493                        OpRHS);
5494   case OP_VZIPR:
5495     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5496                        OpRHS);
5497   case OP_VTRNL:
5498     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5499                        OpRHS);
5500   case OP_VTRNR:
5501     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5502                        OpRHS);
5503   }
5504 }
5505
5506 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5507                            SelectionDAG &DAG) {
5508   // Check to see if we can use the TBL instruction.
5509   SDValue V1 = Op.getOperand(0);
5510   SDValue V2 = Op.getOperand(1);
5511   SDLoc DL(Op);
5512
5513   EVT EltVT = Op.getValueType().getVectorElementType();
5514   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5515
5516   SmallVector<SDValue, 8> TBLMask;
5517   for (int Val : ShuffleMask) {
5518     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5519       unsigned Offset = Byte + Val * BytesPerElt;
5520       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5521     }
5522   }
5523
5524   MVT IndexVT = MVT::v8i8;
5525   unsigned IndexLen = 8;
5526   if (Op.getValueType().getSizeInBits() == 128) {
5527     IndexVT = MVT::v16i8;
5528     IndexLen = 16;
5529   }
5530
5531   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5532   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5533
5534   SDValue Shuffle;
5535   if (V2.getNode()->isUndef()) {
5536     if (IndexLen == 8)
5537       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5538     Shuffle = DAG.getNode(
5539         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5540         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5541         DAG.getBuildVector(IndexVT, DL,
5542                            makeArrayRef(TBLMask.data(), IndexLen)));
5543   } else {
5544     if (IndexLen == 8) {
5545       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5546       Shuffle = DAG.getNode(
5547           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5548           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5549           DAG.getBuildVector(IndexVT, DL,
5550                              makeArrayRef(TBLMask.data(), IndexLen)));
5551     } else {
5552       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5553       // cannot currently represent the register constraints on the input
5554       // table registers.
5555       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5556       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5557       //                   IndexLen));
5558       Shuffle = DAG.getNode(
5559           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5560           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5561           V2Cst, DAG.getBuildVector(IndexVT, DL,
5562                                     makeArrayRef(TBLMask.data(), IndexLen)));
5563     }
5564   }
5565   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5566 }
5567
5568 static unsigned getDUPLANEOp(EVT EltType) {
5569   if (EltType == MVT::i8)
5570     return AArch64ISD::DUPLANE8;
5571   if (EltType == MVT::i16 || EltType == MVT::f16)
5572     return AArch64ISD::DUPLANE16;
5573   if (EltType == MVT::i32 || EltType == MVT::f32)
5574     return AArch64ISD::DUPLANE32;
5575   if (EltType == MVT::i64 || EltType == MVT::f64)
5576     return AArch64ISD::DUPLANE64;
5577
5578   llvm_unreachable("Invalid vector element type?");
5579 }
5580
5581 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5582                                                    SelectionDAG &DAG) const {
5583   SDLoc dl(Op);
5584   EVT VT = Op.getValueType();
5585
5586   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5587
5588   // Convert shuffles that are directly supported on NEON to target-specific
5589   // DAG nodes, instead of keeping them as shuffles and matching them again
5590   // during code selection.  This is more efficient and avoids the possibility
5591   // of inconsistencies between legalization and selection.
5592   ArrayRef<int> ShuffleMask = SVN->getMask();
5593
5594   SDValue V1 = Op.getOperand(0);
5595   SDValue V2 = Op.getOperand(1);
5596
5597   if (SVN->isSplat()) {
5598     int Lane = SVN->getSplatIndex();
5599     // If this is undef splat, generate it via "just" vdup, if possible.
5600     if (Lane == -1)
5601       Lane = 0;
5602
5603     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5604       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5605                          V1.getOperand(0));
5606     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5607     // constant. If so, we can just reference the lane's definition directly.
5608     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5609         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5610       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5611
5612     // Otherwise, duplicate from the lane of the input vector.
5613     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5614
5615     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5616     // to make a vector of the same size as this SHUFFLE. We can ignore the
5617     // extract entirely, and canonicalise the concat using WidenVector.
5618     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5619       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5620       V1 = V1.getOperand(0);
5621     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5622       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5623       Lane -= Idx * VT.getVectorNumElements() / 2;
5624       V1 = WidenVector(V1.getOperand(Idx), DAG);
5625     } else if (VT.getSizeInBits() == 64)
5626       V1 = WidenVector(V1, DAG);
5627
5628     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5629   }
5630
5631   if (isREVMask(ShuffleMask, VT, 64))
5632     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5633   if (isREVMask(ShuffleMask, VT, 32))
5634     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5635   if (isREVMask(ShuffleMask, VT, 16))
5636     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5637
5638   bool ReverseEXT = false;
5639   unsigned Imm;
5640   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5641     if (ReverseEXT)
5642       std::swap(V1, V2);
5643     Imm *= getExtFactor(V1);
5644     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5645                        DAG.getConstant(Imm, dl, MVT::i32));
5646   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5647     Imm *= getExtFactor(V1);
5648     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5649                        DAG.getConstant(Imm, dl, MVT::i32));
5650   }
5651
5652   unsigned WhichResult;
5653   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5654     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5655     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5656   }
5657   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5658     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5659     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5660   }
5661   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5662     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5663     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5664   }
5665
5666   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5667     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5668     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5669   }
5670   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5671     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5672     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5673   }
5674   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5675     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5676     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5677   }
5678
5679   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5680     return Concat;
5681
5682   bool DstIsLeft;
5683   int Anomaly;
5684   int NumInputElements = V1.getValueType().getVectorNumElements();
5685   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5686     SDValue DstVec = DstIsLeft ? V1 : V2;
5687     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5688
5689     SDValue SrcVec = V1;
5690     int SrcLane = ShuffleMask[Anomaly];
5691     if (SrcLane >= NumInputElements) {
5692       SrcVec = V2;
5693       SrcLane -= VT.getVectorNumElements();
5694     }
5695     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5696
5697     EVT ScalarVT = VT.getVectorElementType();
5698
5699     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5700       ScalarVT = MVT::i32;
5701
5702     return DAG.getNode(
5703         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5704         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5705         DstLaneV);
5706   }
5707
5708   // If the shuffle is not directly supported and it has 4 elements, use
5709   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5710   unsigned NumElts = VT.getVectorNumElements();
5711   if (NumElts == 4) {
5712     unsigned PFIndexes[4];
5713     for (unsigned i = 0; i != 4; ++i) {
5714       if (ShuffleMask[i] < 0)
5715         PFIndexes[i] = 8;
5716       else
5717         PFIndexes[i] = ShuffleMask[i];
5718     }
5719
5720     // Compute the index in the perfect shuffle table.
5721     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5722                             PFIndexes[2] * 9 + PFIndexes[3];
5723     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5724     unsigned Cost = (PFEntry >> 30);
5725
5726     if (Cost <= 4)
5727       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5728   }
5729
5730   return GenerateTBL(Op, ShuffleMask, DAG);
5731 }
5732
5733 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5734                                APInt &UndefBits) {
5735   EVT VT = BVN->getValueType(0);
5736   APInt SplatBits, SplatUndef;
5737   unsigned SplatBitSize;
5738   bool HasAnyUndefs;
5739   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5740     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5741
5742     for (unsigned i = 0; i < NumSplats; ++i) {
5743       CnstBits <<= SplatBitSize;
5744       UndefBits <<= SplatBitSize;
5745       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5746       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5747     }
5748
5749     return true;
5750   }
5751
5752   return false;
5753 }
5754
5755 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5756                                               SelectionDAG &DAG) const {
5757   BuildVectorSDNode *BVN =
5758       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5759   SDValue LHS = Op.getOperand(0);
5760   SDLoc dl(Op);
5761   EVT VT = Op.getValueType();
5762
5763   if (!BVN)
5764     return Op;
5765
5766   APInt CnstBits(VT.getSizeInBits(), 0);
5767   APInt UndefBits(VT.getSizeInBits(), 0);
5768   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5769     // We only have BIC vector immediate instruction, which is and-not.
5770     CnstBits = ~CnstBits;
5771
5772     // We make use of a little bit of goto ickiness in order to avoid having to
5773     // duplicate the immediate matching logic for the undef toggled case.
5774     bool SecondTry = false;
5775   AttemptModImm:
5776
5777     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5778       CnstBits = CnstBits.zextOrTrunc(64);
5779       uint64_t CnstVal = CnstBits.getZExtValue();
5780
5781       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5782         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5783         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5784         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5785                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5786                                   DAG.getConstant(0, dl, MVT::i32));
5787         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5788       }
5789
5790       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5791         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5792         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5793         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5794                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5795                                   DAG.getConstant(8, dl, MVT::i32));
5796         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5797       }
5798
5799       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5800         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5801         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5802         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5803                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5804                                   DAG.getConstant(16, dl, MVT::i32));
5805         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5806       }
5807
5808       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5809         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5810         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5811         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5812                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5813                                   DAG.getConstant(24, dl, MVT::i32));
5814         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5815       }
5816
5817       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5818         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5819         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5820         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5821                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5822                                   DAG.getConstant(0, dl, MVT::i32));
5823         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5824       }
5825
5826       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5827         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5828         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5829         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5830                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5831                                   DAG.getConstant(8, dl, MVT::i32));
5832         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5833       }
5834     }
5835
5836     if (SecondTry)
5837       goto FailedModImm;
5838     SecondTry = true;
5839     CnstBits = ~UndefBits;
5840     goto AttemptModImm;
5841   }
5842
5843 // We can always fall back to a non-immediate AND.
5844 FailedModImm:
5845   return Op;
5846 }
5847
5848 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5849 // consists of only the same constant int value, returned in reference arg
5850 // ConstVal
5851 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5852                                      uint64_t &ConstVal) {
5853   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5854   if (!Bvec)
5855     return false;
5856   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5857   if (!FirstElt)
5858     return false;
5859   EVT VT = Bvec->getValueType(0);
5860   unsigned NumElts = VT.getVectorNumElements();
5861   for (unsigned i = 1; i < NumElts; ++i)
5862     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5863       return false;
5864   ConstVal = FirstElt->getZExtValue();
5865   return true;
5866 }
5867
5868 static unsigned getIntrinsicID(const SDNode *N) {
5869   unsigned Opcode = N->getOpcode();
5870   switch (Opcode) {
5871   default:
5872     return Intrinsic::not_intrinsic;
5873   case ISD::INTRINSIC_WO_CHAIN: {
5874     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5875     if (IID < Intrinsic::num_intrinsics)
5876       return IID;
5877     return Intrinsic::not_intrinsic;
5878   }
5879   }
5880 }
5881
5882 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5883 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5884 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5885 // Also, logical shift right -> sri, with the same structure.
5886 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5887   EVT VT = N->getValueType(0);
5888
5889   if (!VT.isVector())
5890     return SDValue();
5891
5892   SDLoc DL(N);
5893
5894   // Is the first op an AND?
5895   const SDValue And = N->getOperand(0);
5896   if (And.getOpcode() != ISD::AND)
5897     return SDValue();
5898
5899   // Is the second op an shl or lshr?
5900   SDValue Shift = N->getOperand(1);
5901   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5902   // or AArch64ISD::VLSHR vector, #shift
5903   unsigned ShiftOpc = Shift.getOpcode();
5904   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5905     return SDValue();
5906   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5907
5908   // Is the shift amount constant?
5909   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5910   if (!C2node)
5911     return SDValue();
5912
5913   // Is the and mask vector all constant?
5914   uint64_t C1;
5915   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5916     return SDValue();
5917
5918   // Is C1 == ~C2, taking into account how much one can shift elements of a
5919   // particular size?
5920   uint64_t C2 = C2node->getZExtValue();
5921   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5922   if (C2 > ElemSizeInBits)
5923     return SDValue();
5924   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5925   if ((C1 & ElemMask) != (~C2 & ElemMask))
5926     return SDValue();
5927
5928   SDValue X = And.getOperand(0);
5929   SDValue Y = Shift.getOperand(0);
5930
5931   unsigned Intrin =
5932       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5933   SDValue ResultSLI =
5934       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5935                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5936                   Shift.getOperand(1));
5937
5938   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5939   DEBUG(N->dump(&DAG));
5940   DEBUG(dbgs() << "into: \n");
5941   DEBUG(ResultSLI->dump(&DAG));
5942
5943   ++NumShiftInserts;
5944   return ResultSLI;
5945 }
5946
5947 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5948                                              SelectionDAG &DAG) const {
5949   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5950   if (EnableAArch64SlrGeneration) {
5951     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
5952       return Res;
5953   }
5954
5955   BuildVectorSDNode *BVN =
5956       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5957   SDValue LHS = Op.getOperand(1);
5958   SDLoc dl(Op);
5959   EVT VT = Op.getValueType();
5960
5961   // OR commutes, so try swapping the operands.
5962   if (!BVN) {
5963     LHS = Op.getOperand(0);
5964     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5965   }
5966   if (!BVN)
5967     return Op;
5968
5969   APInt CnstBits(VT.getSizeInBits(), 0);
5970   APInt UndefBits(VT.getSizeInBits(), 0);
5971   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5972     // We make use of a little bit of goto ickiness in order to avoid having to
5973     // duplicate the immediate matching logic for the undef toggled case.
5974     bool SecondTry = false;
5975   AttemptModImm:
5976
5977     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5978       CnstBits = CnstBits.zextOrTrunc(64);
5979       uint64_t CnstVal = CnstBits.getZExtValue();
5980
5981       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5982         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5983         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5984         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5985                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5986                                   DAG.getConstant(0, dl, MVT::i32));
5987         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5988       }
5989
5990       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5991         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5992         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5993         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5994                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5995                                   DAG.getConstant(8, dl, MVT::i32));
5996         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5997       }
5998
5999       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6000         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6001         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6002         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6003                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6004                                   DAG.getConstant(16, dl, MVT::i32));
6005         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6006       }
6007
6008       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6009         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6010         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6011         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6012                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6013                                   DAG.getConstant(24, dl, MVT::i32));
6014         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6015       }
6016
6017       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6018         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6019         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6020         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6021                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6022                                   DAG.getConstant(0, dl, MVT::i32));
6023         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6024       }
6025
6026       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6027         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6028         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6029         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6030                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6031                                   DAG.getConstant(8, dl, MVT::i32));
6032         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6033       }
6034     }
6035
6036     if (SecondTry)
6037       goto FailedModImm;
6038     SecondTry = true;
6039     CnstBits = UndefBits;
6040     goto AttemptModImm;
6041   }
6042
6043 // We can always fall back to a non-immediate OR.
6044 FailedModImm:
6045   return Op;
6046 }
6047
6048 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6049 // be truncated to fit element width.
6050 static SDValue NormalizeBuildVector(SDValue Op,
6051                                     SelectionDAG &DAG) {
6052   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6053   SDLoc dl(Op);
6054   EVT VT = Op.getValueType();
6055   EVT EltTy= VT.getVectorElementType();
6056
6057   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6058     return Op;
6059
6060   SmallVector<SDValue, 16> Ops;
6061   for (SDValue Lane : Op->ops()) {
6062     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6063       APInt LowBits(EltTy.getSizeInBits(),
6064                     CstLane->getZExtValue());
6065       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6066     }
6067     Ops.push_back(Lane);
6068   }
6069   return DAG.getBuildVector(VT, dl, Ops);
6070 }
6071
6072 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6073                                                  SelectionDAG &DAG) const {
6074   SDLoc dl(Op);
6075   EVT VT = Op.getValueType();
6076   Op = NormalizeBuildVector(Op, DAG);
6077   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6078
6079   APInt CnstBits(VT.getSizeInBits(), 0);
6080   APInt UndefBits(VT.getSizeInBits(), 0);
6081   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6082     // We make use of a little bit of goto ickiness in order to avoid having to
6083     // duplicate the immediate matching logic for the undef toggled case.
6084     bool SecondTry = false;
6085   AttemptModImm:
6086
6087     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6088       CnstBits = CnstBits.zextOrTrunc(64);
6089       uint64_t CnstVal = CnstBits.getZExtValue();
6090
6091       // Certain magic vector constants (used to express things like NOT
6092       // and NEG) are passed through unmodified.  This allows codegen patterns
6093       // for these operations to match.  Special-purpose patterns will lower
6094       // these immediates to MOVIs if it proves necessary.
6095       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6096         return Op;
6097
6098       // The many faces of MOVI...
6099       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6100         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6101         if (VT.getSizeInBits() == 128) {
6102           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6103                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6104           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6105         }
6106
6107         // Support the V64 version via subregister insertion.
6108         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6109                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6110         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6111       }
6112
6113       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6114         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6115         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6116         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6117                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6118                                   DAG.getConstant(0, dl, MVT::i32));
6119         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6120       }
6121
6122       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6123         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6124         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6125         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6126                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6127                                   DAG.getConstant(8, dl, MVT::i32));
6128         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6129       }
6130
6131       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6132         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6133         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6134         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6135                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6136                                   DAG.getConstant(16, dl, MVT::i32));
6137         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6138       }
6139
6140       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6141         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6142         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6143         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6144                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6145                                   DAG.getConstant(24, dl, MVT::i32));
6146         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6147       }
6148
6149       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6150         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6151         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6152         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6153                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6154                                   DAG.getConstant(0, dl, MVT::i32));
6155         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6156       }
6157
6158       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6159         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6160         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6161         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6162                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6163                                   DAG.getConstant(8, dl, MVT::i32));
6164         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6165       }
6166
6167       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6168         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6169         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6170         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6171                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6172                                   DAG.getConstant(264, dl, MVT::i32));
6173         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6174       }
6175
6176       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6177         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6178         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6179         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6180                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6181                                   DAG.getConstant(272, dl, MVT::i32));
6182         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6183       }
6184
6185       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6186         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6187         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6188         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6189                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6190         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6191       }
6192
6193       // The few faces of FMOV...
6194       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6195         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6196         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6197         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6198                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6199         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6200       }
6201
6202       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6203           VT.getSizeInBits() == 128) {
6204         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6205         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6206                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6207         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6208       }
6209
6210       // The many faces of MVNI...
6211       CnstVal = ~CnstVal;
6212       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6213         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6214         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6215         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6216                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6217                                   DAG.getConstant(0, dl, MVT::i32));
6218         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6219       }
6220
6221       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6222         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6223         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6224         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6225                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6226                                   DAG.getConstant(8, dl, MVT::i32));
6227         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6228       }
6229
6230       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6231         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6232         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6233         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6234                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6235                                   DAG.getConstant(16, dl, MVT::i32));
6236         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6237       }
6238
6239       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6240         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6241         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6242         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6243                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6244                                   DAG.getConstant(24, dl, MVT::i32));
6245         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6246       }
6247
6248       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6249         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6250         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6251         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6252                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6253                                   DAG.getConstant(0, dl, MVT::i32));
6254         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6255       }
6256
6257       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6258         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6259         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6260         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6261                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6262                                   DAG.getConstant(8, dl, MVT::i32));
6263         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6264       }
6265
6266       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6267         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6268         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6269         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6270                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6271                                   DAG.getConstant(264, dl, MVT::i32));
6272         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6273       }
6274
6275       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6276         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6277         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6278         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6279                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6280                                   DAG.getConstant(272, dl, MVT::i32));
6281         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6282       }
6283     }
6284
6285     if (SecondTry)
6286       goto FailedModImm;
6287     SecondTry = true;
6288     CnstBits = UndefBits;
6289     goto AttemptModImm;
6290   }
6291 FailedModImm:
6292
6293   // Scan through the operands to find some interesting properties we can
6294   // exploit:
6295   //   1) If only one value is used, we can use a DUP, or
6296   //   2) if only the low element is not undef, we can just insert that, or
6297   //   3) if only one constant value is used (w/ some non-constant lanes),
6298   //      we can splat the constant value into the whole vector then fill
6299   //      in the non-constant lanes.
6300   //   4) FIXME: If different constant values are used, but we can intelligently
6301   //             select the values we'll be overwriting for the non-constant
6302   //             lanes such that we can directly materialize the vector
6303   //             some other way (MOVI, e.g.), we can be sneaky.
6304   unsigned NumElts = VT.getVectorNumElements();
6305   bool isOnlyLowElement = true;
6306   bool usesOnlyOneValue = true;
6307   bool usesOnlyOneConstantValue = true;
6308   bool isConstant = true;
6309   unsigned NumConstantLanes = 0;
6310   SDValue Value;
6311   SDValue ConstantValue;
6312   for (unsigned i = 0; i < NumElts; ++i) {
6313     SDValue V = Op.getOperand(i);
6314     if (V.isUndef())
6315       continue;
6316     if (i > 0)
6317       isOnlyLowElement = false;
6318     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6319       isConstant = false;
6320
6321     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6322       ++NumConstantLanes;
6323       if (!ConstantValue.getNode())
6324         ConstantValue = V;
6325       else if (ConstantValue != V)
6326         usesOnlyOneConstantValue = false;
6327     }
6328
6329     if (!Value.getNode())
6330       Value = V;
6331     else if (V != Value)
6332       usesOnlyOneValue = false;
6333   }
6334
6335   if (!Value.getNode())
6336     return DAG.getUNDEF(VT);
6337
6338   if (isOnlyLowElement)
6339     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6340
6341   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6342   // i32 and try again.
6343   if (usesOnlyOneValue) {
6344     if (!isConstant) {
6345       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6346           Value.getValueType() != VT)
6347         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6348
6349       // This is actually a DUPLANExx operation, which keeps everything vectory.
6350
6351       // DUPLANE works on 128-bit vectors, widen it if necessary.
6352       SDValue Lane = Value.getOperand(1);
6353       Value = Value.getOperand(0);
6354       if (Value.getValueType().getSizeInBits() == 64)
6355         Value = WidenVector(Value, DAG);
6356
6357       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6358       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6359     }
6360
6361     if (VT.getVectorElementType().isFloatingPoint()) {
6362       SmallVector<SDValue, 8> Ops;
6363       EVT EltTy = VT.getVectorElementType();
6364       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6365               "Unsupported floating-point vector type");
6366       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6367       for (unsigned i = 0; i < NumElts; ++i)
6368         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6369       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6370       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6371       Val = LowerBUILD_VECTOR(Val, DAG);
6372       if (Val.getNode())
6373         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6374     }
6375   }
6376
6377   // If there was only one constant value used and for more than one lane,
6378   // start by splatting that value, then replace the non-constant lanes. This
6379   // is better than the default, which will perform a separate initialization
6380   // for each lane.
6381   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6382     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6383     // Now insert the non-constant lanes.
6384     for (unsigned i = 0; i < NumElts; ++i) {
6385       SDValue V = Op.getOperand(i);
6386       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6387       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6388         // Note that type legalization likely mucked about with the VT of the
6389         // source operand, so we may have to convert it here before inserting.
6390         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6391       }
6392     }
6393     return Val;
6394   }
6395
6396   // If all elements are constants and the case above didn't get hit, fall back
6397   // to the default expansion, which will generate a load from the constant
6398   // pool.
6399   if (isConstant)
6400     return SDValue();
6401
6402   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6403   if (NumElts >= 4) {
6404     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6405       return shuffle;
6406   }
6407
6408   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6409   // know the default expansion would otherwise fall back on something even
6410   // worse. For a vector with one or two non-undef values, that's
6411   // scalar_to_vector for the elements followed by a shuffle (provided the
6412   // shuffle is valid for the target) and materialization element by element
6413   // on the stack followed by a load for everything else.
6414   if (!isConstant && !usesOnlyOneValue) {
6415     SDValue Vec = DAG.getUNDEF(VT);
6416     SDValue Op0 = Op.getOperand(0);
6417     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6418     unsigned i = 0;
6419     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6420     // a) Avoid a RMW dependency on the full vector register, and
6421     // b) Allow the register coalescer to fold away the copy if the
6422     //    value is already in an S or D register.
6423     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6424     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6425     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6426         (ElemSize == 32 || ElemSize == 64)) {
6427       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6428       MachineSDNode *N =
6429           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6430                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6431       Vec = SDValue(N, 0);
6432       ++i;
6433     }
6434     for (; i < NumElts; ++i) {
6435       SDValue V = Op.getOperand(i);
6436       if (V.isUndef())
6437         continue;
6438       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6439       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6440     }
6441     return Vec;
6442   }
6443
6444   // Just use the default expansion. We failed to find a better alternative.
6445   return SDValue();
6446 }
6447
6448 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6449                                                       SelectionDAG &DAG) const {
6450   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6451
6452   // Check for non-constant or out of range lane.
6453   EVT VT = Op.getOperand(0).getValueType();
6454   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6455   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6456     return SDValue();
6457
6458
6459   // Insertion/extraction are legal for V128 types.
6460   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6461       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6462       VT == MVT::v8f16)
6463     return Op;
6464
6465   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6466       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6467     return SDValue();
6468
6469   // For V64 types, we perform insertion by expanding the value
6470   // to a V128 type and perform the insertion on that.
6471   SDLoc DL(Op);
6472   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6473   EVT WideTy = WideVec.getValueType();
6474
6475   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6476                              Op.getOperand(1), Op.getOperand(2));
6477   // Re-narrow the resultant vector.
6478   return NarrowVector(Node, DAG);
6479 }
6480
6481 SDValue
6482 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6483                                                SelectionDAG &DAG) const {
6484   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6485
6486   // Check for non-constant or out of range lane.
6487   EVT VT = Op.getOperand(0).getValueType();
6488   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6489   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6490     return SDValue();
6491
6492
6493   // Insertion/extraction are legal for V128 types.
6494   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6495       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6496       VT == MVT::v8f16)
6497     return Op;
6498
6499   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6500       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6501     return SDValue();
6502
6503   // For V64 types, we perform extraction by expanding the value
6504   // to a V128 type and perform the extraction on that.
6505   SDLoc DL(Op);
6506   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6507   EVT WideTy = WideVec.getValueType();
6508
6509   EVT ExtrTy = WideTy.getVectorElementType();
6510   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6511     ExtrTy = MVT::i32;
6512
6513   // For extractions, we just return the result directly.
6514   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6515                      Op.getOperand(1));
6516 }
6517
6518 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6519                                                       SelectionDAG &DAG) const {
6520   EVT VT = Op.getOperand(0).getValueType();
6521   SDLoc dl(Op);
6522   // Just in case...
6523   if (!VT.isVector())
6524     return SDValue();
6525
6526   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6527   if (!Cst)
6528     return SDValue();
6529   unsigned Val = Cst->getZExtValue();
6530
6531   unsigned Size = Op.getValueType().getSizeInBits();
6532
6533   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6534   if (Val == 0)
6535     return Op;
6536
6537   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6538   // that directly.
6539   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6540     return Op;
6541
6542   return SDValue();
6543 }
6544
6545 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6546                                                EVT VT) const {
6547   if (VT.getVectorNumElements() == 4 &&
6548       (VT.is128BitVector() || VT.is64BitVector())) {
6549     unsigned PFIndexes[4];
6550     for (unsigned i = 0; i != 4; ++i) {
6551       if (M[i] < 0)
6552         PFIndexes[i] = 8;
6553       else
6554         PFIndexes[i] = M[i];
6555     }
6556
6557     // Compute the index in the perfect shuffle table.
6558     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6559                             PFIndexes[2] * 9 + PFIndexes[3];
6560     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6561     unsigned Cost = (PFEntry >> 30);
6562
6563     if (Cost <= 4)
6564       return true;
6565   }
6566
6567   bool DummyBool;
6568   int DummyInt;
6569   unsigned DummyUnsigned;
6570
6571   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6572           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6573           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6574           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6575           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6576           isZIPMask(M, VT, DummyUnsigned) ||
6577           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6578           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6579           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6580           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6581           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6582 }
6583
6584 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6585 /// operand of a vector shift operation, where all the elements of the
6586 /// build_vector must have the same constant integer value.
6587 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6588   // Ignore bit_converts.
6589   while (Op.getOpcode() == ISD::BITCAST)
6590     Op = Op.getOperand(0);
6591   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6592   APInt SplatBits, SplatUndef;
6593   unsigned SplatBitSize;
6594   bool HasAnyUndefs;
6595   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6596                                     HasAnyUndefs, ElementBits) ||
6597       SplatBitSize > ElementBits)
6598     return false;
6599   Cnt = SplatBits.getSExtValue();
6600   return true;
6601 }
6602
6603 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6604 /// operand of a vector shift left operation.  That value must be in the range:
6605 ///   0 <= Value < ElementBits for a left shift; or
6606 ///   0 <= Value <= ElementBits for a long left shift.
6607 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6608   assert(VT.isVector() && "vector shift count is not a vector type");
6609   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6610   if (!getVShiftImm(Op, ElementBits, Cnt))
6611     return false;
6612   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6613 }
6614
6615 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6616 /// operand of a vector shift right operation. The value must be in the range:
6617 ///   1 <= Value <= ElementBits for a right shift; or
6618 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6619   assert(VT.isVector() && "vector shift count is not a vector type");
6620   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6621   if (!getVShiftImm(Op, ElementBits, Cnt))
6622     return false;
6623   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6624 }
6625
6626 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6627                                                       SelectionDAG &DAG) const {
6628   EVT VT = Op.getValueType();
6629   SDLoc DL(Op);
6630   int64_t Cnt;
6631
6632   if (!Op.getOperand(1).getValueType().isVector())
6633     return Op;
6634   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6635
6636   switch (Op.getOpcode()) {
6637   default:
6638     llvm_unreachable("unexpected shift opcode");
6639
6640   case ISD::SHL:
6641     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6642       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6643                          DAG.getConstant(Cnt, DL, MVT::i32));
6644     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6645                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6646                                        MVT::i32),
6647                        Op.getOperand(0), Op.getOperand(1));
6648   case ISD::SRA:
6649   case ISD::SRL:
6650     // Right shift immediate
6651     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6652       unsigned Opc =
6653           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6654       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6655                          DAG.getConstant(Cnt, DL, MVT::i32));
6656     }
6657
6658     // Right shift register.  Note, there is not a shift right register
6659     // instruction, but the shift left register instruction takes a signed
6660     // value, where negative numbers specify a right shift.
6661     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6662                                                 : Intrinsic::aarch64_neon_ushl;
6663     // negate the shift amount
6664     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6665     SDValue NegShiftLeft =
6666         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6667                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6668                     NegShift);
6669     return NegShiftLeft;
6670   }
6671
6672   return SDValue();
6673 }
6674
6675 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6676                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6677                                     const SDLoc &dl, SelectionDAG &DAG) {
6678   EVT SrcVT = LHS.getValueType();
6679   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6680          "function only supposed to emit natural comparisons");
6681
6682   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6683   APInt CnstBits(VT.getSizeInBits(), 0);
6684   APInt UndefBits(VT.getSizeInBits(), 0);
6685   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6686   bool IsZero = IsCnst && (CnstBits == 0);
6687
6688   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6689     switch (CC) {
6690     default:
6691       return SDValue();
6692     case AArch64CC::NE: {
6693       SDValue Fcmeq;
6694       if (IsZero)
6695         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6696       else
6697         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6698       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6699     }
6700     case AArch64CC::EQ:
6701       if (IsZero)
6702         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6703       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6704     case AArch64CC::GE:
6705       if (IsZero)
6706         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6707       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6708     case AArch64CC::GT:
6709       if (IsZero)
6710         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6711       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6712     case AArch64CC::LS:
6713       if (IsZero)
6714         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6715       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6716     case AArch64CC::LT:
6717       if (!NoNans)
6718         return SDValue();
6719     // If we ignore NaNs then we can use to the MI implementation.
6720     // Fallthrough.
6721     case AArch64CC::MI:
6722       if (IsZero)
6723         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6724       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6725     }
6726   }
6727
6728   switch (CC) {
6729   default:
6730     return SDValue();
6731   case AArch64CC::NE: {
6732     SDValue Cmeq;
6733     if (IsZero)
6734       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6735     else
6736       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6737     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6738   }
6739   case AArch64CC::EQ:
6740     if (IsZero)
6741       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6742     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6743   case AArch64CC::GE:
6744     if (IsZero)
6745       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6746     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6747   case AArch64CC::GT:
6748     if (IsZero)
6749       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6750     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6751   case AArch64CC::LE:
6752     if (IsZero)
6753       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6754     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6755   case AArch64CC::LS:
6756     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6757   case AArch64CC::LO:
6758     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6759   case AArch64CC::LT:
6760     if (IsZero)
6761       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6762     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6763   case AArch64CC::HI:
6764     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6765   case AArch64CC::HS:
6766     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6767   }
6768 }
6769
6770 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6771                                            SelectionDAG &DAG) const {
6772   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6773   SDValue LHS = Op.getOperand(0);
6774   SDValue RHS = Op.getOperand(1);
6775   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6776   SDLoc dl(Op);
6777
6778   if (LHS.getValueType().getVectorElementType().isInteger()) {
6779     assert(LHS.getValueType() == RHS.getValueType());
6780     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6781     SDValue Cmp =
6782         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6783     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6784   }
6785
6786   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6787     return SDValue();
6788
6789   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6790          LHS.getValueType().getVectorElementType() == MVT::f64);
6791
6792   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6793   // clean.  Some of them require two branches to implement.
6794   AArch64CC::CondCode CC1, CC2;
6795   bool ShouldInvert;
6796   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6797
6798   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6799   SDValue Cmp =
6800       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6801   if (!Cmp.getNode())
6802     return SDValue();
6803
6804   if (CC2 != AArch64CC::AL) {
6805     SDValue Cmp2 =
6806         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6807     if (!Cmp2.getNode())
6808       return SDValue();
6809
6810     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6811   }
6812
6813   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6814
6815   if (ShouldInvert)
6816     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6817
6818   return Cmp;
6819 }
6820
6821 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6822 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6823 /// specified in the intrinsic calls.
6824 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6825                                                const CallInst &I,
6826                                                unsigned Intrinsic) const {
6827   auto &DL = I.getModule()->getDataLayout();
6828   switch (Intrinsic) {
6829   case Intrinsic::aarch64_neon_ld2:
6830   case Intrinsic::aarch64_neon_ld3:
6831   case Intrinsic::aarch64_neon_ld4:
6832   case Intrinsic::aarch64_neon_ld1x2:
6833   case Intrinsic::aarch64_neon_ld1x3:
6834   case Intrinsic::aarch64_neon_ld1x4:
6835   case Intrinsic::aarch64_neon_ld2lane:
6836   case Intrinsic::aarch64_neon_ld3lane:
6837   case Intrinsic::aarch64_neon_ld4lane:
6838   case Intrinsic::aarch64_neon_ld2r:
6839   case Intrinsic::aarch64_neon_ld3r:
6840   case Intrinsic::aarch64_neon_ld4r: {
6841     Info.opc = ISD::INTRINSIC_W_CHAIN;
6842     // Conservatively set memVT to the entire set of vectors loaded.
6843     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6844     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6845     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6846     Info.offset = 0;
6847     Info.align = 0;
6848     Info.vol = false; // volatile loads with NEON intrinsics not supported
6849     Info.readMem = true;
6850     Info.writeMem = false;
6851     return true;
6852   }
6853   case Intrinsic::aarch64_neon_st2:
6854   case Intrinsic::aarch64_neon_st3:
6855   case Intrinsic::aarch64_neon_st4:
6856   case Intrinsic::aarch64_neon_st1x2:
6857   case Intrinsic::aarch64_neon_st1x3:
6858   case Intrinsic::aarch64_neon_st1x4:
6859   case Intrinsic::aarch64_neon_st2lane:
6860   case Intrinsic::aarch64_neon_st3lane:
6861   case Intrinsic::aarch64_neon_st4lane: {
6862     Info.opc = ISD::INTRINSIC_VOID;
6863     // Conservatively set memVT to the entire set of vectors stored.
6864     unsigned NumElts = 0;
6865     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6866       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6867       if (!ArgTy->isVectorTy())
6868         break;
6869       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6870     }
6871     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6872     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6873     Info.offset = 0;
6874     Info.align = 0;
6875     Info.vol = false; // volatile stores with NEON intrinsics not supported
6876     Info.readMem = false;
6877     Info.writeMem = true;
6878     return true;
6879   }
6880   case Intrinsic::aarch64_ldaxr:
6881   case Intrinsic::aarch64_ldxr: {
6882     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6883     Info.opc = ISD::INTRINSIC_W_CHAIN;
6884     Info.memVT = MVT::getVT(PtrTy->getElementType());
6885     Info.ptrVal = I.getArgOperand(0);
6886     Info.offset = 0;
6887     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6888     Info.vol = true;
6889     Info.readMem = true;
6890     Info.writeMem = false;
6891     return true;
6892   }
6893   case Intrinsic::aarch64_stlxr:
6894   case Intrinsic::aarch64_stxr: {
6895     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6896     Info.opc = ISD::INTRINSIC_W_CHAIN;
6897     Info.memVT = MVT::getVT(PtrTy->getElementType());
6898     Info.ptrVal = I.getArgOperand(1);
6899     Info.offset = 0;
6900     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6901     Info.vol = true;
6902     Info.readMem = false;
6903     Info.writeMem = true;
6904     return true;
6905   }
6906   case Intrinsic::aarch64_ldaxp:
6907   case Intrinsic::aarch64_ldxp: {
6908     Info.opc = ISD::INTRINSIC_W_CHAIN;
6909     Info.memVT = MVT::i128;
6910     Info.ptrVal = I.getArgOperand(0);
6911     Info.offset = 0;
6912     Info.align = 16;
6913     Info.vol = true;
6914     Info.readMem = true;
6915     Info.writeMem = false;
6916     return true;
6917   }
6918   case Intrinsic::aarch64_stlxp:
6919   case Intrinsic::aarch64_stxp: {
6920     Info.opc = ISD::INTRINSIC_W_CHAIN;
6921     Info.memVT = MVT::i128;
6922     Info.ptrVal = I.getArgOperand(2);
6923     Info.offset = 0;
6924     Info.align = 16;
6925     Info.vol = true;
6926     Info.readMem = false;
6927     Info.writeMem = true;
6928     return true;
6929   }
6930   default:
6931     break;
6932   }
6933
6934   return false;
6935 }
6936
6937 // Truncations from 64-bit GPR to 32-bit GPR is free.
6938 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6939   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6940     return false;
6941   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6942   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6943   return NumBits1 > NumBits2;
6944 }
6945 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6946   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6947     return false;
6948   unsigned NumBits1 = VT1.getSizeInBits();
6949   unsigned NumBits2 = VT2.getSizeInBits();
6950   return NumBits1 > NumBits2;
6951 }
6952
6953 /// Check if it is profitable to hoist instruction in then/else to if.
6954 /// Not profitable if I and it's user can form a FMA instruction
6955 /// because we prefer FMSUB/FMADD.
6956 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6957   if (I->getOpcode() != Instruction::FMul)
6958     return true;
6959
6960   if (I->getNumUses() != 1)
6961     return true;
6962
6963   Instruction *User = I->user_back();
6964
6965   if (User &&
6966       !(User->getOpcode() == Instruction::FSub ||
6967         User->getOpcode() == Instruction::FAdd))
6968     return true;
6969
6970   const TargetOptions &Options = getTargetMachine().Options;
6971   const DataLayout &DL = I->getModule()->getDataLayout();
6972   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6973
6974   return !(isFMAFasterThanFMulAndFAdd(VT) &&
6975            isOperationLegalOrCustom(ISD::FMA, VT) &&
6976            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6977             Options.UnsafeFPMath));
6978 }
6979
6980 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6981 // 64-bit GPR.
6982 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6983   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6984     return false;
6985   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6986   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6987   return NumBits1 == 32 && NumBits2 == 64;
6988 }
6989 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6990   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6991     return false;
6992   unsigned NumBits1 = VT1.getSizeInBits();
6993   unsigned NumBits2 = VT2.getSizeInBits();
6994   return NumBits1 == 32 && NumBits2 == 64;
6995 }
6996
6997 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6998   EVT VT1 = Val.getValueType();
6999   if (isZExtFree(VT1, VT2)) {
7000     return true;
7001   }
7002
7003   if (Val.getOpcode() != ISD::LOAD)
7004     return false;
7005
7006   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7007   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7008           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7009           VT1.getSizeInBits() <= 32);
7010 }
7011
7012 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7013   if (isa<FPExtInst>(Ext))
7014     return false;
7015
7016   // Vector types are next free.
7017   if (Ext->getType()->isVectorTy())
7018     return false;
7019
7020   for (const Use &U : Ext->uses()) {
7021     // The extension is free if we can fold it with a left shift in an
7022     // addressing mode or an arithmetic operation: add, sub, and cmp.
7023
7024     // Is there a shift?
7025     const Instruction *Instr = cast<Instruction>(U.getUser());
7026
7027     // Is this a constant shift?
7028     switch (Instr->getOpcode()) {
7029     case Instruction::Shl:
7030       if (!isa<ConstantInt>(Instr->getOperand(1)))
7031         return false;
7032       break;
7033     case Instruction::GetElementPtr: {
7034       gep_type_iterator GTI = gep_type_begin(Instr);
7035       auto &DL = Ext->getModule()->getDataLayout();
7036       std::advance(GTI, U.getOperandNo());
7037       Type *IdxTy = *GTI;
7038       // This extension will end up with a shift because of the scaling factor.
7039       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7040       // Get the shift amount based on the scaling factor:
7041       // log2(sizeof(IdxTy)) - log2(8).
7042       uint64_t ShiftAmt =
7043           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7044       // Is the constant foldable in the shift of the addressing mode?
7045       // I.e., shift amount is between 1 and 4 inclusive.
7046       if (ShiftAmt == 0 || ShiftAmt > 4)
7047         return false;
7048       break;
7049     }
7050     case Instruction::Trunc:
7051       // Check if this is a noop.
7052       // trunc(sext ty1 to ty2) to ty1.
7053       if (Instr->getType() == Ext->getOperand(0)->getType())
7054         continue;
7055     // FALL THROUGH.
7056     default:
7057       return false;
7058     }
7059
7060     // At this point we can use the bfm family, so this extension is free
7061     // for that use.
7062   }
7063   return true;
7064 }
7065
7066 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7067                                           unsigned &RequiredAligment) const {
7068   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7069     return false;
7070   // Cyclone supports unaligned accesses.
7071   RequiredAligment = 0;
7072   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7073   return NumBits == 32 || NumBits == 64;
7074 }
7075
7076 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7077                                           unsigned &RequiredAligment) const {
7078   if (!LoadedType.isSimple() ||
7079       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7080     return false;
7081   // Cyclone supports unaligned accesses.
7082   RequiredAligment = 0;
7083   unsigned NumBits = LoadedType.getSizeInBits();
7084   return NumBits == 32 || NumBits == 64;
7085 }
7086
7087 /// \brief Lower an interleaved load into a ldN intrinsic.
7088 ///
7089 /// E.g. Lower an interleaved load (Factor = 2):
7090 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7091 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7092 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7093 ///
7094 ///      Into:
7095 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7096 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7097 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7098 bool AArch64TargetLowering::lowerInterleavedLoad(
7099     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7100     ArrayRef<unsigned> Indices, unsigned Factor) const {
7101   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7102          "Invalid interleave factor");
7103   assert(!Shuffles.empty() && "Empty shufflevector input");
7104   assert(Shuffles.size() == Indices.size() &&
7105          "Unmatched number of shufflevectors and indices");
7106
7107   const DataLayout &DL = LI->getModule()->getDataLayout();
7108
7109   VectorType *VecTy = Shuffles[0]->getType();
7110   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7111
7112   // Skip if we do not have NEON and skip illegal vector types.
7113   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7114     return false;
7115
7116   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7117   // load integer vectors first and then convert to pointer vectors.
7118   Type *EltTy = VecTy->getVectorElementType();
7119   if (EltTy->isPointerTy())
7120     VecTy =
7121         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7122
7123   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7124   Type *Tys[2] = {VecTy, PtrTy};
7125   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7126                                             Intrinsic::aarch64_neon_ld3,
7127                                             Intrinsic::aarch64_neon_ld4};
7128   Function *LdNFunc =
7129       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7130
7131   IRBuilder<> Builder(LI);
7132   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7133
7134   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7135
7136   // Replace uses of each shufflevector with the corresponding vector loaded
7137   // by ldN.
7138   for (unsigned i = 0; i < Shuffles.size(); i++) {
7139     ShuffleVectorInst *SVI = Shuffles[i];
7140     unsigned Index = Indices[i];
7141
7142     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7143
7144     // Convert the integer vector to pointer vector if the element is pointer.
7145     if (EltTy->isPointerTy())
7146       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7147
7148     SVI->replaceAllUsesWith(SubVec);
7149   }
7150
7151   return true;
7152 }
7153
7154 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7155 ///
7156 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7157 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7158                                    unsigned NumElts) {
7159   SmallVector<Constant *, 16> Mask;
7160   for (unsigned i = 0; i < NumElts; i++)
7161     Mask.push_back(Builder.getInt32(Start + i));
7162
7163   return ConstantVector::get(Mask);
7164 }
7165
7166 /// \brief Lower an interleaved store into a stN intrinsic.
7167 ///
7168 /// E.g. Lower an interleaved store (Factor = 3):
7169 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7170 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7171 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7172 ///
7173 ///      Into:
7174 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7175 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7176 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7177 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7178 ///
7179 /// Note that the new shufflevectors will be removed and we'll only generate one
7180 /// st3 instruction in CodeGen.
7181 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7182                                                   ShuffleVectorInst *SVI,
7183                                                   unsigned Factor) const {
7184   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7185          "Invalid interleave factor");
7186
7187   VectorType *VecTy = SVI->getType();
7188   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7189          "Invalid interleaved store");
7190
7191   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7192   Type *EltTy = VecTy->getVectorElementType();
7193   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7194
7195   const DataLayout &DL = SI->getModule()->getDataLayout();
7196   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7197
7198   // Skip if we do not have NEON and skip illegal vector types.
7199   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7200     return false;
7201
7202   Value *Op0 = SVI->getOperand(0);
7203   Value *Op1 = SVI->getOperand(1);
7204   IRBuilder<> Builder(SI);
7205
7206   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7207   // vectors to integer vectors.
7208   if (EltTy->isPointerTy()) {
7209     Type *IntTy = DL.getIntPtrType(EltTy);
7210     unsigned NumOpElts =
7211         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7212
7213     // Convert to the corresponding integer vector.
7214     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7215     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7216     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7217
7218     SubVecTy = VectorType::get(IntTy, NumSubElts);
7219   }
7220
7221   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7222   Type *Tys[2] = {SubVecTy, PtrTy};
7223   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7224                                              Intrinsic::aarch64_neon_st3,
7225                                              Intrinsic::aarch64_neon_st4};
7226   Function *StNFunc =
7227       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7228
7229   SmallVector<Value *, 5> Ops;
7230
7231   // Split the shufflevector operands into sub vectors for the new stN call.
7232   for (unsigned i = 0; i < Factor; i++)
7233     Ops.push_back(Builder.CreateShuffleVector(
7234         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7235
7236   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7237   Builder.CreateCall(StNFunc, Ops);
7238   return true;
7239 }
7240
7241 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7242                        unsigned AlignCheck) {
7243   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7244           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7245 }
7246
7247 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7248                                                unsigned SrcAlign, bool IsMemset,
7249                                                bool ZeroMemset,
7250                                                bool MemcpyStrSrc,
7251                                                MachineFunction &MF) const {
7252   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7253   // instruction to materialize the v2i64 zero and one store (with restrictive
7254   // addressing mode). Just do two i64 store of zero-registers.
7255   bool Fast;
7256   const Function *F = MF.getFunction();
7257   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7258       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7259       (memOpAlign(SrcAlign, DstAlign, 16) ||
7260        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7261     return MVT::f128;
7262
7263   if (Size >= 8 &&
7264       (memOpAlign(SrcAlign, DstAlign, 8) ||
7265        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7266     return MVT::i64;
7267
7268   if (Size >= 4 &&
7269       (memOpAlign(SrcAlign, DstAlign, 4) ||
7270        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7271     return MVT::i32;
7272
7273   return MVT::Other;
7274 }
7275
7276 // 12-bit optionally shifted immediates are legal for adds.
7277 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7278   // Avoid UB for INT64_MIN.
7279   if (Immed == std::numeric_limits<int64_t>::min())
7280     return false;
7281   // Same encoding for add/sub, just flip the sign.
7282   Immed = std::abs(Immed);
7283   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7284 }
7285
7286 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7287 // immediates is the same as for an add or a sub.
7288 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7289   return isLegalAddImmediate(Immed);
7290 }
7291
7292 /// isLegalAddressingMode - Return true if the addressing mode represented
7293 /// by AM is legal for this target, for a load/store of the specified type.
7294 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7295                                                   const AddrMode &AM, Type *Ty,
7296                                                   unsigned AS) const {
7297   // AArch64 has five basic addressing modes:
7298   //  reg
7299   //  reg + 9-bit signed offset
7300   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7301   //  reg1 + reg2
7302   //  reg + SIZE_IN_BYTES * reg
7303
7304   // No global is ever allowed as a base.
7305   if (AM.BaseGV)
7306     return false;
7307
7308   // No reg+reg+imm addressing.
7309   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7310     return false;
7311
7312   // check reg + imm case:
7313   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7314   uint64_t NumBytes = 0;
7315   if (Ty->isSized()) {
7316     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7317     NumBytes = NumBits / 8;
7318     if (!isPowerOf2_64(NumBits))
7319       NumBytes = 0;
7320   }
7321
7322   if (!AM.Scale) {
7323     int64_t Offset = AM.BaseOffs;
7324
7325     // 9-bit signed offset
7326     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7327       return true;
7328
7329     // 12-bit unsigned offset
7330     unsigned shift = Log2_64(NumBytes);
7331     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7332         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7333         (Offset >> shift) << shift == Offset)
7334       return true;
7335     return false;
7336   }
7337
7338   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7339
7340   return !AM.Scale || AM.Scale == 1 ||
7341          (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7342 }
7343
7344 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7345                                                 const AddrMode &AM, Type *Ty,
7346                                                 unsigned AS) const {
7347   // Scaling factors are not free at all.
7348   // Operands                     | Rt Latency
7349   // -------------------------------------------
7350   // Rt, [Xn, Xm]                 | 4
7351   // -------------------------------------------
7352   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7353   // Rt, [Xn, Wm, <extend> #imm]  |
7354   if (isLegalAddressingMode(DL, AM, Ty, AS))
7355     // Scale represents reg2 * scale, thus account for 1 if
7356     // it is not equal to 0 or 1.
7357     return AM.Scale != 0 && AM.Scale != 1;
7358   return -1;
7359 }
7360
7361 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7362   VT = VT.getScalarType();
7363
7364   if (!VT.isSimple())
7365     return false;
7366
7367   switch (VT.getSimpleVT().SimpleTy) {
7368   case MVT::f32:
7369   case MVT::f64:
7370     return true;
7371   default:
7372     break;
7373   }
7374
7375   return false;
7376 }
7377
7378 const MCPhysReg *
7379 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7380   // LR is a callee-save register, but we must treat it as clobbered by any call
7381   // site. Hence we include LR in the scratch registers, which are in turn added
7382   // as implicit-defs for stackmaps and patchpoints.
7383   static const MCPhysReg ScratchRegs[] = {
7384     AArch64::X16, AArch64::X17, AArch64::LR, 0
7385   };
7386   return ScratchRegs;
7387 }
7388
7389 bool
7390 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7391   EVT VT = N->getValueType(0);
7392     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7393     // it with shift to let it be lowered to UBFX.
7394   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7395       isa<ConstantSDNode>(N->getOperand(1))) {
7396     uint64_t TruncMask = N->getConstantOperandVal(1);
7397     if (isMask_64(TruncMask) &&
7398       N->getOperand(0).getOpcode() == ISD::SRL &&
7399       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7400       return false;
7401   }
7402   return true;
7403 }
7404
7405 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7406                                                               Type *Ty) const {
7407   assert(Ty->isIntegerTy());
7408
7409   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7410   if (BitSize == 0)
7411     return false;
7412
7413   int64_t Val = Imm.getSExtValue();
7414   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7415     return true;
7416
7417   if ((int64_t)Val < 0)
7418     Val = ~Val;
7419   if (BitSize == 32)
7420     Val &= (1LL << 32) - 1;
7421
7422   unsigned LZ = countLeadingZeros((uint64_t)Val);
7423   unsigned Shift = (63 - LZ) / 16;
7424   // MOVZ is free so return true for one or fewer MOVK.
7425   return Shift < 3;
7426 }
7427
7428 /// Turn vector tests of the signbit in the form of:
7429 ///   xor (sra X, elt_size(X)-1), -1
7430 /// into:
7431 ///   cmge X, X, #0
7432 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7433                                          const AArch64Subtarget *Subtarget) {
7434   EVT VT = N->getValueType(0);
7435   if (!Subtarget->hasNEON() || !VT.isVector())
7436     return SDValue();
7437
7438   // There must be a shift right algebraic before the xor, and the xor must be a
7439   // 'not' operation.
7440   SDValue Shift = N->getOperand(0);
7441   SDValue Ones = N->getOperand(1);
7442   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7443       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7444     return SDValue();
7445
7446   // The shift should be smearing the sign bit across each vector element.
7447   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7448   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7449   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7450     return SDValue();
7451
7452   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7453 }
7454
7455 // Generate SUBS and CSEL for integer abs.
7456 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7457   EVT VT = N->getValueType(0);
7458
7459   SDValue N0 = N->getOperand(0);
7460   SDValue N1 = N->getOperand(1);
7461   SDLoc DL(N);
7462
7463   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7464   // and change it to SUB and CSEL.
7465   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7466       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7467       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7468     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7469       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7470         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7471                                   N0.getOperand(0));
7472         // Generate SUBS & CSEL.
7473         SDValue Cmp =
7474             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7475                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7476         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7477                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7478                            SDValue(Cmp.getNode(), 1));
7479       }
7480   return SDValue();
7481 }
7482
7483 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7484                                  TargetLowering::DAGCombinerInfo &DCI,
7485                                  const AArch64Subtarget *Subtarget) {
7486   if (DCI.isBeforeLegalizeOps())
7487     return SDValue();
7488
7489   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7490     return Cmp;
7491
7492   return performIntegerAbsCombine(N, DAG);
7493 }
7494
7495 SDValue
7496 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7497                                      SelectionDAG &DAG,
7498                                      std::vector<SDNode *> *Created) const {
7499   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7500   if (isIntDivCheap(N->getValueType(0), Attr))
7501     return SDValue(N,0); // Lower SDIV as SDIV
7502
7503   // fold (sdiv X, pow2)
7504   EVT VT = N->getValueType(0);
7505   if ((VT != MVT::i32 && VT != MVT::i64) ||
7506       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7507     return SDValue();
7508
7509   SDLoc DL(N);
7510   SDValue N0 = N->getOperand(0);
7511   unsigned Lg2 = Divisor.countTrailingZeros();
7512   SDValue Zero = DAG.getConstant(0, DL, VT);
7513   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7514
7515   // Add (N0 < 0) ? Pow2 - 1 : 0;
7516   SDValue CCVal;
7517   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7518   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7519   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7520
7521   if (Created) {
7522     Created->push_back(Cmp.getNode());
7523     Created->push_back(Add.getNode());
7524     Created->push_back(CSel.getNode());
7525   }
7526
7527   // Divide by pow2.
7528   SDValue SRA =
7529       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7530
7531   // If we're dividing by a positive value, we're done.  Otherwise, we must
7532   // negate the result.
7533   if (Divisor.isNonNegative())
7534     return SRA;
7535
7536   if (Created)
7537     Created->push_back(SRA.getNode());
7538   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7539 }
7540
7541 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7542                                  TargetLowering::DAGCombinerInfo &DCI,
7543                                  const AArch64Subtarget *Subtarget) {
7544   if (DCI.isBeforeLegalizeOps())
7545     return SDValue();
7546
7547   // Multiplication of a power of two plus/minus one can be done more
7548   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7549   // future CPUs have a cheaper MADD instruction, this may need to be
7550   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7551   // 64-bit is 5 cycles, so this is always a win.
7552   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7553     const APInt &Value = C->getAPIntValue();
7554     EVT VT = N->getValueType(0);
7555     SDLoc DL(N);
7556     if (Value.isNonNegative()) {
7557       // (mul x, 2^N + 1) => (add (shl x, N), x)
7558       APInt VM1 = Value - 1;
7559       if (VM1.isPowerOf2()) {
7560         SDValue ShiftedVal =
7561             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7562                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7563         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7564                            N->getOperand(0));
7565       }
7566       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7567       APInt VP1 = Value + 1;
7568       if (VP1.isPowerOf2()) {
7569         SDValue ShiftedVal =
7570             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7571                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7572         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7573                            N->getOperand(0));
7574       }
7575     } else {
7576       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7577       APInt VNP1 = -Value + 1;
7578       if (VNP1.isPowerOf2()) {
7579         SDValue ShiftedVal =
7580             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7581                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7582         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7583                            ShiftedVal);
7584       }
7585       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7586       APInt VNM1 = -Value - 1;
7587       if (VNM1.isPowerOf2()) {
7588         SDValue ShiftedVal =
7589             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7590                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7591         SDValue Add =
7592             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7593         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7594       }
7595     }
7596   }
7597   return SDValue();
7598 }
7599
7600 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7601                                                          SelectionDAG &DAG) {
7602   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7603   // optimize away operation when it's from a constant.
7604   //
7605   // The general transformation is:
7606   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7607   //       AND(VECTOR_CMP(x,y), constant2)
7608   //    constant2 = UNARYOP(constant)
7609
7610   // Early exit if this isn't a vector operation, the operand of the
7611   // unary operation isn't a bitwise AND, or if the sizes of the operations
7612   // aren't the same.
7613   EVT VT = N->getValueType(0);
7614   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7615       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7616       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7617     return SDValue();
7618
7619   // Now check that the other operand of the AND is a constant. We could
7620   // make the transformation for non-constant splats as well, but it's unclear
7621   // that would be a benefit as it would not eliminate any operations, just
7622   // perform one more step in scalar code before moving to the vector unit.
7623   if (BuildVectorSDNode *BV =
7624           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7625     // Bail out if the vector isn't a constant.
7626     if (!BV->isConstant())
7627       return SDValue();
7628
7629     // Everything checks out. Build up the new and improved node.
7630     SDLoc DL(N);
7631     EVT IntVT = BV->getValueType(0);
7632     // Create a new constant of the appropriate type for the transformed
7633     // DAG.
7634     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7635     // The AND node needs bitcasts to/from an integer vector type around it.
7636     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7637     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7638                                  N->getOperand(0)->getOperand(0), MaskConst);
7639     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7640     return Res;
7641   }
7642
7643   return SDValue();
7644 }
7645
7646 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7647                                      const AArch64Subtarget *Subtarget) {
7648   // First try to optimize away the conversion when it's conditionally from
7649   // a constant. Vectors only.
7650   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7651     return Res;
7652
7653   EVT VT = N->getValueType(0);
7654   if (VT != MVT::f32 && VT != MVT::f64)
7655     return SDValue();
7656
7657   // Only optimize when the source and destination types have the same width.
7658   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7659     return SDValue();
7660
7661   // If the result of an integer load is only used by an integer-to-float
7662   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7663   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7664   SDValue N0 = N->getOperand(0);
7665   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7666       // Do not change the width of a volatile load.
7667       !cast<LoadSDNode>(N0)->isVolatile()) {
7668     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7669     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7670                                LN0->getPointerInfo(), LN0->getAlignment(),
7671                                LN0->getMemOperand()->getFlags());
7672
7673     // Make sure successors of the original load stay after it by updating them
7674     // to use the new Chain.
7675     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7676
7677     unsigned Opcode =
7678         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7679     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7680   }
7681
7682   return SDValue();
7683 }
7684
7685 /// Fold a floating-point multiply by power of two into floating-point to
7686 /// fixed-point conversion.
7687 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7688                                      TargetLowering::DAGCombinerInfo &DCI,
7689                                      const AArch64Subtarget *Subtarget) {
7690   if (!Subtarget->hasNEON())
7691     return SDValue();
7692
7693   SDValue Op = N->getOperand(0);
7694   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7695       Op.getOpcode() != ISD::FMUL)
7696     return SDValue();
7697
7698   SDValue ConstVec = Op->getOperand(1);
7699   if (!isa<BuildVectorSDNode>(ConstVec))
7700     return SDValue();
7701
7702   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7703   uint32_t FloatBits = FloatTy.getSizeInBits();
7704   if (FloatBits != 32 && FloatBits != 64)
7705     return SDValue();
7706
7707   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7708   uint32_t IntBits = IntTy.getSizeInBits();
7709   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7710     return SDValue();
7711
7712   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7713   if (IntBits > FloatBits)
7714     return SDValue();
7715
7716   BitVector UndefElements;
7717   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7718   int32_t Bits = IntBits == 64 ? 64 : 32;
7719   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7720   if (C == -1 || C == 0 || C > Bits)
7721     return SDValue();
7722
7723   MVT ResTy;
7724   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7725   switch (NumLanes) {
7726   default:
7727     return SDValue();
7728   case 2:
7729     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7730     break;
7731   case 4:
7732     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7733     break;
7734   }
7735
7736   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7737     return SDValue();
7738
7739   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7740          "Illegal vector type after legalization");
7741
7742   SDLoc DL(N);
7743   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7744   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7745                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7746   SDValue FixConv =
7747       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7748                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7749                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7750   // We can handle smaller integers by generating an extra trunc.
7751   if (IntBits < FloatBits)
7752     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7753
7754   return FixConv;
7755 }
7756
7757 /// Fold a floating-point divide by power of two into fixed-point to
7758 /// floating-point conversion.
7759 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7760                                   const AArch64Subtarget *Subtarget) {
7761   if (!Subtarget->hasNEON())
7762     return SDValue();
7763
7764   SDValue Op = N->getOperand(0);
7765   unsigned Opc = Op->getOpcode();
7766   if (!Op.getValueType().isVector() ||
7767       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7768     return SDValue();
7769
7770   SDValue ConstVec = N->getOperand(1);
7771   if (!isa<BuildVectorSDNode>(ConstVec))
7772     return SDValue();
7773
7774   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7775   int32_t IntBits = IntTy.getSizeInBits();
7776   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7777     return SDValue();
7778
7779   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7780   int32_t FloatBits = FloatTy.getSizeInBits();
7781   if (FloatBits != 32 && FloatBits != 64)
7782     return SDValue();
7783
7784   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7785   if (IntBits > FloatBits)
7786     return SDValue();
7787
7788   BitVector UndefElements;
7789   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7790   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7791   if (C == -1 || C == 0 || C > FloatBits)
7792     return SDValue();
7793
7794   MVT ResTy;
7795   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7796   switch (NumLanes) {
7797   default:
7798     return SDValue();
7799   case 2:
7800     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7801     break;
7802   case 4:
7803     ResTy = MVT::v4i32;
7804     break;
7805   }
7806
7807   SDLoc DL(N);
7808   SDValue ConvInput = Op.getOperand(0);
7809   bool IsSigned = Opc == ISD::SINT_TO_FP;
7810   if (IntBits < FloatBits)
7811     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7812                             ResTy, ConvInput);
7813
7814   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7815                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7816   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7817                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7818                      DAG.getConstant(C, DL, MVT::i32));
7819 }
7820
7821 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7822 /// searches for and classifies those shifts.
7823 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7824                          bool &FromHi) {
7825   if (N.getOpcode() == ISD::SHL)
7826     FromHi = false;
7827   else if (N.getOpcode() == ISD::SRL)
7828     FromHi = true;
7829   else
7830     return false;
7831
7832   if (!isa<ConstantSDNode>(N.getOperand(1)))
7833     return false;
7834
7835   ShiftAmount = N->getConstantOperandVal(1);
7836   Src = N->getOperand(0);
7837   return true;
7838 }
7839
7840 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7841 /// registers viewed as a high/low pair. This function looks for the pattern:
7842 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7843 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7844 /// independent.
7845 static SDValue tryCombineToEXTR(SDNode *N,
7846                                 TargetLowering::DAGCombinerInfo &DCI) {
7847   SelectionDAG &DAG = DCI.DAG;
7848   SDLoc DL(N);
7849   EVT VT = N->getValueType(0);
7850
7851   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7852
7853   if (VT != MVT::i32 && VT != MVT::i64)
7854     return SDValue();
7855
7856   SDValue LHS;
7857   uint32_t ShiftLHS = 0;
7858   bool LHSFromHi = 0;
7859   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7860     return SDValue();
7861
7862   SDValue RHS;
7863   uint32_t ShiftRHS = 0;
7864   bool RHSFromHi = 0;
7865   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7866     return SDValue();
7867
7868   // If they're both trying to come from the high part of the register, they're
7869   // not really an EXTR.
7870   if (LHSFromHi == RHSFromHi)
7871     return SDValue();
7872
7873   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7874     return SDValue();
7875
7876   if (LHSFromHi) {
7877     std::swap(LHS, RHS);
7878     std::swap(ShiftLHS, ShiftRHS);
7879   }
7880
7881   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7882                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7883 }
7884
7885 static SDValue tryCombineToBSL(SDNode *N,
7886                                 TargetLowering::DAGCombinerInfo &DCI) {
7887   EVT VT = N->getValueType(0);
7888   SelectionDAG &DAG = DCI.DAG;
7889   SDLoc DL(N);
7890
7891   if (!VT.isVector())
7892     return SDValue();
7893
7894   SDValue N0 = N->getOperand(0);
7895   if (N0.getOpcode() != ISD::AND)
7896     return SDValue();
7897
7898   SDValue N1 = N->getOperand(1);
7899   if (N1.getOpcode() != ISD::AND)
7900     return SDValue();
7901
7902   // We only have to look for constant vectors here since the general, variable
7903   // case can be handled in TableGen.
7904   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7905   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7906   for (int i = 1; i >= 0; --i)
7907     for (int j = 1; j >= 0; --j) {
7908       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7909       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7910       if (!BVN0 || !BVN1)
7911         continue;
7912
7913       bool FoundMatch = true;
7914       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7915         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7916         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7917         if (!CN0 || !CN1 ||
7918             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7919           FoundMatch = false;
7920           break;
7921         }
7922       }
7923
7924       if (FoundMatch)
7925         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7926                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7927     }
7928
7929   return SDValue();
7930 }
7931
7932 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7933                                 const AArch64Subtarget *Subtarget) {
7934   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7935   SelectionDAG &DAG = DCI.DAG;
7936   EVT VT = N->getValueType(0);
7937
7938   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7939     return SDValue();
7940
7941   if (SDValue Res = tryCombineToEXTR(N, DCI))
7942     return Res;
7943
7944   if (SDValue Res = tryCombineToBSL(N, DCI))
7945     return Res;
7946
7947   return SDValue();
7948 }
7949
7950 static SDValue performSRLCombine(SDNode *N,
7951                                  TargetLowering::DAGCombinerInfo &DCI) {
7952   SelectionDAG &DAG = DCI.DAG;
7953   EVT VT = N->getValueType(0);
7954   if (VT != MVT::i32 && VT != MVT::i64)
7955     return SDValue();
7956
7957   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7958   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7959   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7960   SDValue N0 = N->getOperand(0);
7961   if (N0.getOpcode() == ISD::BSWAP) {
7962     SDLoc DL(N);
7963     SDValue N1 = N->getOperand(1);
7964     SDValue N00 = N0.getOperand(0);
7965     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7966       uint64_t ShiftAmt = C->getZExtValue();
7967       if (VT == MVT::i32 && ShiftAmt == 16 &&
7968           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
7969         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7970       if (VT == MVT::i64 && ShiftAmt == 32 &&
7971           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
7972         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7973     }
7974   }
7975   return SDValue();
7976 }
7977
7978 static SDValue performBitcastCombine(SDNode *N,
7979                                      TargetLowering::DAGCombinerInfo &DCI,
7980                                      SelectionDAG &DAG) {
7981   // Wait 'til after everything is legalized to try this. That way we have
7982   // legal vector types and such.
7983   if (DCI.isBeforeLegalizeOps())
7984     return SDValue();
7985
7986   // Remove extraneous bitcasts around an extract_subvector.
7987   // For example,
7988   //    (v4i16 (bitconvert
7989   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7990   //  becomes
7991   //    (extract_subvector ((v8i16 ...), (i64 4)))
7992
7993   // Only interested in 64-bit vectors as the ultimate result.
7994   EVT VT = N->getValueType(0);
7995   if (!VT.isVector())
7996     return SDValue();
7997   if (VT.getSimpleVT().getSizeInBits() != 64)
7998     return SDValue();
7999   // Is the operand an extract_subvector starting at the beginning or halfway
8000   // point of the vector? A low half may also come through as an
8001   // EXTRACT_SUBREG, so look for that, too.
8002   SDValue Op0 = N->getOperand(0);
8003   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8004       !(Op0->isMachineOpcode() &&
8005         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8006     return SDValue();
8007   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8008   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8009     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8010       return SDValue();
8011   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8012     if (idx != AArch64::dsub)
8013       return SDValue();
8014     // The dsub reference is equivalent to a lane zero subvector reference.
8015     idx = 0;
8016   }
8017   // Look through the bitcast of the input to the extract.
8018   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8019     return SDValue();
8020   SDValue Source = Op0->getOperand(0)->getOperand(0);
8021   // If the source type has twice the number of elements as our destination
8022   // type, we know this is an extract of the high or low half of the vector.
8023   EVT SVT = Source->getValueType(0);
8024   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8025     return SDValue();
8026
8027   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8028
8029   // Create the simplified form to just extract the low or high half of the
8030   // vector directly rather than bothering with the bitcasts.
8031   SDLoc dl(N);
8032   unsigned NumElements = VT.getVectorNumElements();
8033   if (idx) {
8034     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8035     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8036   } else {
8037     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8038     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8039                                       Source, SubReg),
8040                    0);
8041   }
8042 }
8043
8044 static SDValue performConcatVectorsCombine(SDNode *N,
8045                                            TargetLowering::DAGCombinerInfo &DCI,
8046                                            SelectionDAG &DAG) {
8047   SDLoc dl(N);
8048   EVT VT = N->getValueType(0);
8049   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8050
8051   // Optimize concat_vectors of truncated vectors, where the intermediate
8052   // type is illegal, to avoid said illegality,  e.g.,
8053   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8054   //                          (v2i16 (truncate (v2i64)))))
8055   // ->
8056   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8057   //                                    (v4i32 (bitcast (v2i64))),
8058   //                                    <0, 2, 4, 6>)))
8059   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8060   // on both input and result type, so we might generate worse code.
8061   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8062   if (N->getNumOperands() == 2 &&
8063       N0->getOpcode() == ISD::TRUNCATE &&
8064       N1->getOpcode() == ISD::TRUNCATE) {
8065     SDValue N00 = N0->getOperand(0);
8066     SDValue N10 = N1->getOperand(0);
8067     EVT N00VT = N00.getValueType();
8068
8069     if (N00VT == N10.getValueType() &&
8070         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8071         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8072       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8073       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8074       for (size_t i = 0; i < Mask.size(); ++i)
8075         Mask[i] = i * 2;
8076       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8077                          DAG.getVectorShuffle(
8078                              MidVT, dl,
8079                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8080                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8081     }
8082   }
8083
8084   // Wait 'til after everything is legalized to try this. That way we have
8085   // legal vector types and such.
8086   if (DCI.isBeforeLegalizeOps())
8087     return SDValue();
8088
8089   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8090   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8091   // canonicalise to that.
8092   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8093     assert(VT.getVectorElementType().getSizeInBits() == 64);
8094     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8095                        DAG.getConstant(0, dl, MVT::i64));
8096   }
8097
8098   // Canonicalise concat_vectors so that the right-hand vector has as few
8099   // bit-casts as possible before its real operation. The primary matching
8100   // destination for these operations will be the narrowing "2" instructions,
8101   // which depend on the operation being performed on this right-hand vector.
8102   // For example,
8103   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8104   // becomes
8105   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8106
8107   if (N1->getOpcode() != ISD::BITCAST)
8108     return SDValue();
8109   SDValue RHS = N1->getOperand(0);
8110   MVT RHSTy = RHS.getValueType().getSimpleVT();
8111   // If the RHS is not a vector, this is not the pattern we're looking for.
8112   if (!RHSTy.isVector())
8113     return SDValue();
8114
8115   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8116
8117   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8118                                   RHSTy.getVectorNumElements() * 2);
8119   return DAG.getNode(ISD::BITCAST, dl, VT,
8120                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8121                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8122                                  RHS));
8123 }
8124
8125 static SDValue tryCombineFixedPointConvert(SDNode *N,
8126                                            TargetLowering::DAGCombinerInfo &DCI,
8127                                            SelectionDAG &DAG) {
8128   // Wait 'til after everything is legalized to try this. That way we have
8129   // legal vector types and such.
8130   if (DCI.isBeforeLegalizeOps())
8131     return SDValue();
8132   // Transform a scalar conversion of a value from a lane extract into a
8133   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8134   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8135   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8136   //
8137   // The second form interacts better with instruction selection and the
8138   // register allocator to avoid cross-class register copies that aren't
8139   // coalescable due to a lane reference.
8140
8141   // Check the operand and see if it originates from a lane extract.
8142   SDValue Op1 = N->getOperand(1);
8143   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8144     // Yep, no additional predication needed. Perform the transform.
8145     SDValue IID = N->getOperand(0);
8146     SDValue Shift = N->getOperand(2);
8147     SDValue Vec = Op1.getOperand(0);
8148     SDValue Lane = Op1.getOperand(1);
8149     EVT ResTy = N->getValueType(0);
8150     EVT VecResTy;
8151     SDLoc DL(N);
8152
8153     // The vector width should be 128 bits by the time we get here, even
8154     // if it started as 64 bits (the extract_vector handling will have
8155     // done so).
8156     assert(Vec.getValueType().getSizeInBits() == 128 &&
8157            "unexpected vector size on extract_vector_elt!");
8158     if (Vec.getValueType() == MVT::v4i32)
8159       VecResTy = MVT::v4f32;
8160     else if (Vec.getValueType() == MVT::v2i64)
8161       VecResTy = MVT::v2f64;
8162     else
8163       llvm_unreachable("unexpected vector type!");
8164
8165     SDValue Convert =
8166         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8167     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8168   }
8169   return SDValue();
8170 }
8171
8172 // AArch64 high-vector "long" operations are formed by performing the non-high
8173 // version on an extract_subvector of each operand which gets the high half:
8174 //
8175 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8176 //
8177 // However, there are cases which don't have an extract_high explicitly, but
8178 // have another operation that can be made compatible with one for free. For
8179 // example:
8180 //
8181 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8182 //
8183 // This routine does the actual conversion of such DUPs, once outer routines
8184 // have determined that everything else is in order.
8185 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8186 // similarly here.
8187 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8188   switch (N.getOpcode()) {
8189   case AArch64ISD::DUP:
8190   case AArch64ISD::DUPLANE8:
8191   case AArch64ISD::DUPLANE16:
8192   case AArch64ISD::DUPLANE32:
8193   case AArch64ISD::DUPLANE64:
8194   case AArch64ISD::MOVI:
8195   case AArch64ISD::MOVIshift:
8196   case AArch64ISD::MOVIedit:
8197   case AArch64ISD::MOVImsl:
8198   case AArch64ISD::MVNIshift:
8199   case AArch64ISD::MVNImsl:
8200     break;
8201   default:
8202     // FMOV could be supported, but isn't very useful, as it would only occur
8203     // if you passed a bitcast' floating point immediate to an eligible long
8204     // integer op (addl, smull, ...).
8205     return SDValue();
8206   }
8207
8208   MVT NarrowTy = N.getSimpleValueType();
8209   if (!NarrowTy.is64BitVector())
8210     return SDValue();
8211
8212   MVT ElementTy = NarrowTy.getVectorElementType();
8213   unsigned NumElems = NarrowTy.getVectorNumElements();
8214   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8215
8216   SDLoc dl(N);
8217   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8218                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8219                      DAG.getConstant(NumElems, dl, MVT::i64));
8220 }
8221
8222 static bool isEssentiallyExtractSubvector(SDValue N) {
8223   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8224     return true;
8225
8226   return N.getOpcode() == ISD::BITCAST &&
8227          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8228 }
8229
8230 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8231 struct GenericSetCCInfo {
8232   const SDValue *Opnd0;
8233   const SDValue *Opnd1;
8234   ISD::CondCode CC;
8235 };
8236
8237 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8238 struct AArch64SetCCInfo {
8239   const SDValue *Cmp;
8240   AArch64CC::CondCode CC;
8241 };
8242
8243 /// \brief Helper structure to keep track of SetCC information.
8244 union SetCCInfo {
8245   GenericSetCCInfo Generic;
8246   AArch64SetCCInfo AArch64;
8247 };
8248
8249 /// \brief Helper structure to be able to read SetCC information.  If set to
8250 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8251 /// GenericSetCCInfo.
8252 struct SetCCInfoAndKind {
8253   SetCCInfo Info;
8254   bool IsAArch64;
8255 };
8256
8257 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8258 /// an
8259 /// AArch64 lowered one.
8260 /// \p SetCCInfo is filled accordingly.
8261 /// \post SetCCInfo is meanginfull only when this function returns true.
8262 /// \return True when Op is a kind of SET_CC operation.
8263 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8264   // If this is a setcc, this is straight forward.
8265   if (Op.getOpcode() == ISD::SETCC) {
8266     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8267     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8268     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8269     SetCCInfo.IsAArch64 = false;
8270     return true;
8271   }
8272   // Otherwise, check if this is a matching csel instruction.
8273   // In other words:
8274   // - csel 1, 0, cc
8275   // - csel 0, 1, !cc
8276   if (Op.getOpcode() != AArch64ISD::CSEL)
8277     return false;
8278   // Set the information about the operands.
8279   // TODO: we want the operands of the Cmp not the csel
8280   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8281   SetCCInfo.IsAArch64 = true;
8282   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8283       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8284
8285   // Check that the operands matches the constraints:
8286   // (1) Both operands must be constants.
8287   // (2) One must be 1 and the other must be 0.
8288   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8289   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8290
8291   // Check (1).
8292   if (!TValue || !FValue)
8293     return false;
8294
8295   // Check (2).
8296   if (!TValue->isOne()) {
8297     // Update the comparison when we are interested in !cc.
8298     std::swap(TValue, FValue);
8299     SetCCInfo.Info.AArch64.CC =
8300         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8301   }
8302   return TValue->isOne() && FValue->isNullValue();
8303 }
8304
8305 // Returns true if Op is setcc or zext of setcc.
8306 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8307   if (isSetCC(Op, Info))
8308     return true;
8309   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8310     isSetCC(Op->getOperand(0), Info));
8311 }
8312
8313 // The folding we want to perform is:
8314 // (add x, [zext] (setcc cc ...) )
8315 //   -->
8316 // (csel x, (add x, 1), !cc ...)
8317 //
8318 // The latter will get matched to a CSINC instruction.
8319 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8320   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8321   SDValue LHS = Op->getOperand(0);
8322   SDValue RHS = Op->getOperand(1);
8323   SetCCInfoAndKind InfoAndKind;
8324
8325   // If neither operand is a SET_CC, give up.
8326   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8327     std::swap(LHS, RHS);
8328     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8329       return SDValue();
8330   }
8331
8332   // FIXME: This could be generatized to work for FP comparisons.
8333   EVT CmpVT = InfoAndKind.IsAArch64
8334                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8335                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8336   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8337     return SDValue();
8338
8339   SDValue CCVal;
8340   SDValue Cmp;
8341   SDLoc dl(Op);
8342   if (InfoAndKind.IsAArch64) {
8343     CCVal = DAG.getConstant(
8344         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8345         MVT::i32);
8346     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8347   } else
8348     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8349                       *InfoAndKind.Info.Generic.Opnd1,
8350                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8351                       CCVal, DAG, dl);
8352
8353   EVT VT = Op->getValueType(0);
8354   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8355   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8356 }
8357
8358 // The basic add/sub long vector instructions have variants with "2" on the end
8359 // which act on the high-half of their inputs. They are normally matched by
8360 // patterns like:
8361 //
8362 // (add (zeroext (extract_high LHS)),
8363 //      (zeroext (extract_high RHS)))
8364 // -> uaddl2 vD, vN, vM
8365 //
8366 // However, if one of the extracts is something like a duplicate, this
8367 // instruction can still be used profitably. This function puts the DAG into a
8368 // more appropriate form for those patterns to trigger.
8369 static SDValue performAddSubLongCombine(SDNode *N,
8370                                         TargetLowering::DAGCombinerInfo &DCI,
8371                                         SelectionDAG &DAG) {
8372   if (DCI.isBeforeLegalizeOps())
8373     return SDValue();
8374
8375   MVT VT = N->getSimpleValueType(0);
8376   if (!VT.is128BitVector()) {
8377     if (N->getOpcode() == ISD::ADD)
8378       return performSetccAddFolding(N, DAG);
8379     return SDValue();
8380   }
8381
8382   // Make sure both branches are extended in the same way.
8383   SDValue LHS = N->getOperand(0);
8384   SDValue RHS = N->getOperand(1);
8385   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8386        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8387       LHS.getOpcode() != RHS.getOpcode())
8388     return SDValue();
8389
8390   unsigned ExtType = LHS.getOpcode();
8391
8392   // It's not worth doing if at least one of the inputs isn't already an
8393   // extract, but we don't know which it'll be so we have to try both.
8394   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8395     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8396     if (!RHS.getNode())
8397       return SDValue();
8398
8399     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8400   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8401     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8402     if (!LHS.getNode())
8403       return SDValue();
8404
8405     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8406   }
8407
8408   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8409 }
8410
8411 // Massage DAGs which we can use the high-half "long" operations on into
8412 // something isel will recognize better. E.g.
8413 //
8414 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8415 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8416 //                     (extract_high (v2i64 (dup128 scalar)))))
8417 //
8418 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8419                                        TargetLowering::DAGCombinerInfo &DCI,
8420                                        SelectionDAG &DAG) {
8421   if (DCI.isBeforeLegalizeOps())
8422     return SDValue();
8423
8424   SDValue LHS = N->getOperand(1);
8425   SDValue RHS = N->getOperand(2);
8426   assert(LHS.getValueType().is64BitVector() &&
8427          RHS.getValueType().is64BitVector() &&
8428          "unexpected shape for long operation");
8429
8430   // Either node could be a DUP, but it's not worth doing both of them (you'd
8431   // just as well use the non-high version) so look for a corresponding extract
8432   // operation on the other "wing".
8433   if (isEssentiallyExtractSubvector(LHS)) {
8434     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8435     if (!RHS.getNode())
8436       return SDValue();
8437   } else if (isEssentiallyExtractSubvector(RHS)) {
8438     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8439     if (!LHS.getNode())
8440       return SDValue();
8441   }
8442
8443   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8444                      N->getOperand(0), LHS, RHS);
8445 }
8446
8447 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8448   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8449   unsigned ElemBits = ElemTy.getSizeInBits();
8450
8451   int64_t ShiftAmount;
8452   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8453     APInt SplatValue, SplatUndef;
8454     unsigned SplatBitSize;
8455     bool HasAnyUndefs;
8456     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8457                               HasAnyUndefs, ElemBits) ||
8458         SplatBitSize != ElemBits)
8459       return SDValue();
8460
8461     ShiftAmount = SplatValue.getSExtValue();
8462   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8463     ShiftAmount = CVN->getSExtValue();
8464   } else
8465     return SDValue();
8466
8467   unsigned Opcode;
8468   bool IsRightShift;
8469   switch (IID) {
8470   default:
8471     llvm_unreachable("Unknown shift intrinsic");
8472   case Intrinsic::aarch64_neon_sqshl:
8473     Opcode = AArch64ISD::SQSHL_I;
8474     IsRightShift = false;
8475     break;
8476   case Intrinsic::aarch64_neon_uqshl:
8477     Opcode = AArch64ISD::UQSHL_I;
8478     IsRightShift = false;
8479     break;
8480   case Intrinsic::aarch64_neon_srshl:
8481     Opcode = AArch64ISD::SRSHR_I;
8482     IsRightShift = true;
8483     break;
8484   case Intrinsic::aarch64_neon_urshl:
8485     Opcode = AArch64ISD::URSHR_I;
8486     IsRightShift = true;
8487     break;
8488   case Intrinsic::aarch64_neon_sqshlu:
8489     Opcode = AArch64ISD::SQSHLU_I;
8490     IsRightShift = false;
8491     break;
8492   }
8493
8494   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8495     SDLoc dl(N);
8496     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8497                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8498   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8499     SDLoc dl(N);
8500     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8501                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8502   }
8503
8504   return SDValue();
8505 }
8506
8507 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8508 // the intrinsics must be legal and take an i32, this means there's almost
8509 // certainly going to be a zext in the DAG which we can eliminate.
8510 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8511   SDValue AndN = N->getOperand(2);
8512   if (AndN.getOpcode() != ISD::AND)
8513     return SDValue();
8514
8515   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8516   if (!CMask || CMask->getZExtValue() != Mask)
8517     return SDValue();
8518
8519   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8520                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8521 }
8522
8523 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8524                                            SelectionDAG &DAG) {
8525   SDLoc dl(N);
8526   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8527                      DAG.getNode(Opc, dl,
8528                                  N->getOperand(1).getSimpleValueType(),
8529                                  N->getOperand(1)),
8530                      DAG.getConstant(0, dl, MVT::i64));
8531 }
8532
8533 static SDValue performIntrinsicCombine(SDNode *N,
8534                                        TargetLowering::DAGCombinerInfo &DCI,
8535                                        const AArch64Subtarget *Subtarget) {
8536   SelectionDAG &DAG = DCI.DAG;
8537   unsigned IID = getIntrinsicID(N);
8538   switch (IID) {
8539   default:
8540     break;
8541   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8542   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8543     return tryCombineFixedPointConvert(N, DCI, DAG);
8544   case Intrinsic::aarch64_neon_saddv:
8545     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8546   case Intrinsic::aarch64_neon_uaddv:
8547     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8548   case Intrinsic::aarch64_neon_sminv:
8549     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8550   case Intrinsic::aarch64_neon_uminv:
8551     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8552   case Intrinsic::aarch64_neon_smaxv:
8553     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8554   case Intrinsic::aarch64_neon_umaxv:
8555     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8556   case Intrinsic::aarch64_neon_fmax:
8557     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8558                        N->getOperand(1), N->getOperand(2));
8559   case Intrinsic::aarch64_neon_fmin:
8560     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8561                        N->getOperand(1), N->getOperand(2));
8562   case Intrinsic::aarch64_neon_fmaxnm:
8563     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8564                        N->getOperand(1), N->getOperand(2));
8565   case Intrinsic::aarch64_neon_fminnm:
8566     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8567                        N->getOperand(1), N->getOperand(2));
8568   case Intrinsic::aarch64_neon_smull:
8569   case Intrinsic::aarch64_neon_umull:
8570   case Intrinsic::aarch64_neon_pmull:
8571   case Intrinsic::aarch64_neon_sqdmull:
8572     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8573   case Intrinsic::aarch64_neon_sqshl:
8574   case Intrinsic::aarch64_neon_uqshl:
8575   case Intrinsic::aarch64_neon_sqshlu:
8576   case Intrinsic::aarch64_neon_srshl:
8577   case Intrinsic::aarch64_neon_urshl:
8578     return tryCombineShiftImm(IID, N, DAG);
8579   case Intrinsic::aarch64_crc32b:
8580   case Intrinsic::aarch64_crc32cb:
8581     return tryCombineCRC32(0xff, N, DAG);
8582   case Intrinsic::aarch64_crc32h:
8583   case Intrinsic::aarch64_crc32ch:
8584     return tryCombineCRC32(0xffff, N, DAG);
8585   }
8586   return SDValue();
8587 }
8588
8589 static SDValue performExtendCombine(SDNode *N,
8590                                     TargetLowering::DAGCombinerInfo &DCI,
8591                                     SelectionDAG &DAG) {
8592   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8593   // we can convert that DUP into another extract_high (of a bigger DUP), which
8594   // helps the backend to decide that an sabdl2 would be useful, saving a real
8595   // extract_high operation.
8596   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8597       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8598     SDNode *ABDNode = N->getOperand(0).getNode();
8599     unsigned IID = getIntrinsicID(ABDNode);
8600     if (IID == Intrinsic::aarch64_neon_sabd ||
8601         IID == Intrinsic::aarch64_neon_uabd) {
8602       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8603       if (!NewABD.getNode())
8604         return SDValue();
8605
8606       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8607                          NewABD);
8608     }
8609   }
8610
8611   // This is effectively a custom type legalization for AArch64.
8612   //
8613   // Type legalization will split an extend of a small, legal, type to a larger
8614   // illegal type by first splitting the destination type, often creating
8615   // illegal source types, which then get legalized in isel-confusing ways,
8616   // leading to really terrible codegen. E.g.,
8617   //   %result = v8i32 sext v8i8 %value
8618   // becomes
8619   //   %losrc = extract_subreg %value, ...
8620   //   %hisrc = extract_subreg %value, ...
8621   //   %lo = v4i32 sext v4i8 %losrc
8622   //   %hi = v4i32 sext v4i8 %hisrc
8623   // Things go rapidly downhill from there.
8624   //
8625   // For AArch64, the [sz]ext vector instructions can only go up one element
8626   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8627   // take two instructions.
8628   //
8629   // This implies that the most efficient way to do the extend from v8i8
8630   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8631   // the normal splitting to happen for the v8i16->v8i32.
8632
8633   // This is pre-legalization to catch some cases where the default
8634   // type legalization will create ill-tempered code.
8635   if (!DCI.isBeforeLegalizeOps())
8636     return SDValue();
8637
8638   // We're only interested in cleaning things up for non-legal vector types
8639   // here. If both the source and destination are legal, things will just
8640   // work naturally without any fiddling.
8641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8642   EVT ResVT = N->getValueType(0);
8643   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8644     return SDValue();
8645   // If the vector type isn't a simple VT, it's beyond the scope of what
8646   // we're  worried about here. Let legalization do its thing and hope for
8647   // the best.
8648   SDValue Src = N->getOperand(0);
8649   EVT SrcVT = Src->getValueType(0);
8650   if (!ResVT.isSimple() || !SrcVT.isSimple())
8651     return SDValue();
8652
8653   // If the source VT is a 64-bit vector, we can play games and get the
8654   // better results we want.
8655   if (SrcVT.getSizeInBits() != 64)
8656     return SDValue();
8657
8658   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8659   unsigned ElementCount = SrcVT.getVectorNumElements();
8660   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8661   SDLoc DL(N);
8662   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8663
8664   // Now split the rest of the operation into two halves, each with a 64
8665   // bit source.
8666   EVT LoVT, HiVT;
8667   SDValue Lo, Hi;
8668   unsigned NumElements = ResVT.getVectorNumElements();
8669   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8670   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8671                                  ResVT.getVectorElementType(), NumElements / 2);
8672
8673   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8674                                LoVT.getVectorNumElements());
8675   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8676                    DAG.getConstant(0, DL, MVT::i64));
8677   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8678                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8679   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8680   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8681
8682   // Now combine the parts back together so we still have a single result
8683   // like the combiner expects.
8684   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8685 }
8686
8687 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8688 /// value. The load store optimizer pass will merge them to store pair stores.
8689 /// This has better performance than a splat of the scalar followed by a split
8690 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8691 /// followed by an ext.b and two stores.
8692 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8693   SDValue StVal = St->getValue();
8694   EVT VT = StVal.getValueType();
8695
8696   // Don't replace floating point stores, they possibly won't be transformed to
8697   // stp because of the store pair suppress pass.
8698   if (VT.isFloatingPoint())
8699     return SDValue();
8700
8701   // Check for insert vector elements.
8702   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8703     return SDValue();
8704
8705   // We can express a splat as store pair(s) for 2 or 4 elements.
8706   unsigned NumVecElts = VT.getVectorNumElements();
8707   if (NumVecElts != 4 && NumVecElts != 2)
8708     return SDValue();
8709   SDValue SplatVal = StVal.getOperand(1);
8710   unsigned RemainInsertElts = NumVecElts - 1;
8711
8712   // Check that this is a splat.
8713   while (--RemainInsertElts) {
8714     SDValue NextInsertElt = StVal.getOperand(0);
8715     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8716       return SDValue();
8717     if (NextInsertElt.getOperand(1) != SplatVal)
8718       return SDValue();
8719     StVal = NextInsertElt;
8720   }
8721   unsigned OrigAlignment = St->getAlignment();
8722   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8723   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8724
8725   // Create scalar stores. This is at least as good as the code sequence for a
8726   // split unaligned store which is a dup.s, ext.b, and two stores.
8727   // Most of the time the three stores should be replaced by store pair
8728   // instructions (stp).
8729   SDLoc DL(St);
8730   SDValue BasePtr = St->getBasePtr();
8731   SDValue NewST1 =
8732       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8733                    St->getAlignment(), St->getMemOperand()->getFlags());
8734
8735   unsigned Offset = EltOffset;
8736   while (--NumVecElts) {
8737     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8738                                     DAG.getConstant(Offset, DL, MVT::i64));
8739     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8740                           St->getPointerInfo(), Alignment,
8741                           St->getMemOperand()->getFlags());
8742     Offset += EltOffset;
8743   }
8744   return NewST1;
8745 }
8746
8747 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8748                               SelectionDAG &DAG,
8749                               const AArch64Subtarget *Subtarget) {
8750   if (!DCI.isBeforeLegalize())
8751     return SDValue();
8752
8753   StoreSDNode *S = cast<StoreSDNode>(N);
8754   if (S->isVolatile())
8755     return SDValue();
8756
8757   // FIXME: The logic for deciding if an unaligned store should be split should
8758   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8759   // a call to that function here.
8760
8761   if (!Subtarget->isMisaligned128StoreSlow())
8762     return SDValue();
8763
8764   // Don't split at -Oz.
8765   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8766     return SDValue();
8767
8768   SDValue StVal = S->getValue();
8769   EVT VT = StVal.getValueType();
8770
8771   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8772   // those up regresses performance on micro-benchmarks and olden/bh.
8773   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8774     return SDValue();
8775
8776   // Split unaligned 16B stores. They are terrible for performance.
8777   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8778   // extensions can use this to mark that it does not want splitting to happen
8779   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8780   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8781   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8782       S->getAlignment() <= 2)
8783     return SDValue();
8784
8785   // If we get a splat of a scalar convert this vector store to a store of
8786   // scalars. They will be merged into store pairs thereby removing two
8787   // instructions.
8788   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8789     return ReplacedSplat;
8790
8791   SDLoc DL(S);
8792   unsigned NumElts = VT.getVectorNumElements() / 2;
8793   // Split VT into two.
8794   EVT HalfVT =
8795       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8796   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8797                                    DAG.getConstant(0, DL, MVT::i64));
8798   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8799                                    DAG.getConstant(NumElts, DL, MVT::i64));
8800   SDValue BasePtr = S->getBasePtr();
8801   SDValue NewST1 =
8802       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8803                    S->getAlignment(), S->getMemOperand()->getFlags());
8804   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8805                                   DAG.getConstant(8, DL, MVT::i64));
8806   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8807                       S->getPointerInfo(), S->getAlignment(),
8808                       S->getMemOperand()->getFlags());
8809 }
8810
8811 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8812 /// post-increment LD1R.
8813 static SDValue performPostLD1Combine(SDNode *N,
8814                                      TargetLowering::DAGCombinerInfo &DCI,
8815                                      bool IsLaneOp) {
8816   if (DCI.isBeforeLegalizeOps())
8817     return SDValue();
8818
8819   SelectionDAG &DAG = DCI.DAG;
8820   EVT VT = N->getValueType(0);
8821
8822   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8823   SDNode *LD = N->getOperand(LoadIdx).getNode();
8824   // If it is not LOAD, can not do such combine.
8825   if (LD->getOpcode() != ISD::LOAD)
8826     return SDValue();
8827
8828   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8829   EVT MemVT = LoadSDN->getMemoryVT();
8830   // Check if memory operand is the same type as the vector element.
8831   if (MemVT != VT.getVectorElementType())
8832     return SDValue();
8833
8834   // Check if there are other uses. If so, do not combine as it will introduce
8835   // an extra load.
8836   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8837        ++UI) {
8838     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8839       continue;
8840     if (*UI != N)
8841       return SDValue();
8842   }
8843
8844   SDValue Addr = LD->getOperand(1);
8845   SDValue Vector = N->getOperand(0);
8846   // Search for a use of the address operand that is an increment.
8847   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8848        Addr.getNode()->use_end(); UI != UE; ++UI) {
8849     SDNode *User = *UI;
8850     if (User->getOpcode() != ISD::ADD
8851         || UI.getUse().getResNo() != Addr.getResNo())
8852       continue;
8853
8854     // Check that the add is independent of the load.  Otherwise, folding it
8855     // would create a cycle.
8856     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8857       continue;
8858     // Also check that add is not used in the vector operand.  This would also
8859     // create a cycle.
8860     if (User->isPredecessorOf(Vector.getNode()))
8861       continue;
8862
8863     // If the increment is a constant, it must match the memory ref size.
8864     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8865     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8866       uint32_t IncVal = CInc->getZExtValue();
8867       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8868       if (IncVal != NumBytes)
8869         continue;
8870       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8871     }
8872
8873     // Finally, check that the vector doesn't depend on the load.
8874     // Again, this would create a cycle.
8875     // The load depending on the vector is fine, as that's the case for the
8876     // LD1*post we'll eventually generate anyway.
8877     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8878       continue;
8879
8880     SmallVector<SDValue, 8> Ops;
8881     Ops.push_back(LD->getOperand(0));  // Chain
8882     if (IsLaneOp) {
8883       Ops.push_back(Vector);           // The vector to be inserted
8884       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8885     }
8886     Ops.push_back(Addr);
8887     Ops.push_back(Inc);
8888
8889     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8890     SDVTList SDTys = DAG.getVTList(Tys);
8891     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8892     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8893                                            MemVT,
8894                                            LoadSDN->getMemOperand());
8895
8896     // Update the uses.
8897     SDValue NewResults[] = {
8898         SDValue(LD, 0),            // The result of load
8899         SDValue(UpdN.getNode(), 2) // Chain
8900     };
8901     DCI.CombineTo(LD, NewResults);
8902     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8903     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8904
8905     break;
8906   }
8907   return SDValue();
8908 }
8909
8910 /// Simplify \Addr given that the top byte of it is ignored by HW during
8911 /// address translation.
8912 static bool performTBISimplification(SDValue Addr,
8913                                      TargetLowering::DAGCombinerInfo &DCI,
8914                                      SelectionDAG &DAG) {
8915   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8916   APInt KnownZero, KnownOne;
8917   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8918                                         DCI.isBeforeLegalizeOps());
8919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8920   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8921     DCI.CommitTargetLoweringOpt(TLO);
8922     return true;
8923   }
8924   return false;
8925 }
8926
8927 static SDValue performSTORECombine(SDNode *N,
8928                                    TargetLowering::DAGCombinerInfo &DCI,
8929                                    SelectionDAG &DAG,
8930                                    const AArch64Subtarget *Subtarget) {
8931   if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
8932     return Split;
8933
8934   if (Subtarget->supportsAddressTopByteIgnored() &&
8935       performTBISimplification(N->getOperand(2), DCI, DAG))
8936     return SDValue(N, 0);
8937
8938   return SDValue();
8939 }
8940
8941   /// This function handles the log2-shuffle pattern produced by the
8942 /// LoopVectorizer for the across vector reduction. It consists of
8943 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8944 /// are reduced, where s is an induction variable from 0 to
8945 /// log2(NumVectorElements).
8946 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8947                                                      unsigned Op,
8948                                                      SelectionDAG &DAG) {
8949   EVT VTy = OpV->getOperand(0).getValueType();
8950   if (!VTy.isVector())
8951     return SDValue();
8952
8953   int NumVecElts = VTy.getVectorNumElements();
8954   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8955     if (NumVecElts != 4)
8956       return SDValue();
8957   } else {
8958     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8959       return SDValue();
8960   }
8961
8962   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8963   SDValue PreOp = OpV;
8964   // Iterate over each step of the across vector reduction.
8965   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8966     SDValue CurOp = PreOp.getOperand(0);
8967     SDValue Shuffle = PreOp.getOperand(1);
8968     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8969       // Try to swap the 1st and 2nd operand as add and min/max instructions
8970       // are commutative.
8971       CurOp = PreOp.getOperand(1);
8972       Shuffle = PreOp.getOperand(0);
8973       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8974         return SDValue();
8975     }
8976
8977     // Check if the input vector is fed by the operator we want to handle,
8978     // except the last step; the very first input vector is not necessarily
8979     // the same operator we are handling.
8980     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8981       return SDValue();
8982
8983     // Check if it forms one step of the across vector reduction.
8984     // E.g.,
8985     //   %cur = add %1, %0
8986     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8987     //   %pre = add %cur, %shuffle
8988     if (Shuffle.getOperand(0) != CurOp)
8989       return SDValue();
8990
8991     int NumMaskElts = 1 << CurStep;
8992     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8993     // Check mask values in each step.
8994     // We expect the shuffle mask in each step follows a specific pattern
8995     // denoted here by the <M, U> form, where M is a sequence of integers
8996     // starting from NumMaskElts, increasing by 1, and the number integers
8997     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8998     // of undef in U should be NumVecElts - NumMaskElts.
8999     // E.g., for <8 x i16>, mask values in each step should be :
9000     //   step 0 : <1,u,u,u,u,u,u,u>
9001     //   step 1 : <2,3,u,u,u,u,u,u>
9002     //   step 2 : <4,5,6,7,u,u,u,u>
9003     for (int i = 0; i < NumVecElts; ++i)
9004       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9005           (i >= NumMaskElts && !(Mask[i] < 0)))
9006         return SDValue();
9007
9008     PreOp = CurOp;
9009   }
9010   unsigned Opcode;
9011   bool IsIntrinsic = false;
9012
9013   switch (Op) {
9014   default:
9015     llvm_unreachable("Unexpected operator for across vector reduction");
9016   case ISD::ADD:
9017     Opcode = AArch64ISD::UADDV;
9018     break;
9019   case ISD::SMAX:
9020     Opcode = AArch64ISD::SMAXV;
9021     break;
9022   case ISD::UMAX:
9023     Opcode = AArch64ISD::UMAXV;
9024     break;
9025   case ISD::SMIN:
9026     Opcode = AArch64ISD::SMINV;
9027     break;
9028   case ISD::UMIN:
9029     Opcode = AArch64ISD::UMINV;
9030     break;
9031   case ISD::FMAXNUM:
9032     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9033     IsIntrinsic = true;
9034     break;
9035   case ISD::FMINNUM:
9036     Opcode = Intrinsic::aarch64_neon_fminnmv;
9037     IsIntrinsic = true;
9038     break;
9039   }
9040   SDLoc DL(N);
9041
9042   return IsIntrinsic
9043              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9044                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9045              : DAG.getNode(
9046                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9047                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9048                    DAG.getConstant(0, DL, MVT::i64));
9049 }
9050
9051 /// Target-specific DAG combine for the across vector min/max reductions.
9052 /// This function specifically handles the final clean-up step of the vector
9053 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9054 /// pattern, which narrows down and finds the final min/max value from all
9055 /// elements of the vector.
9056 /// For example, for a <16 x i8> vector :
9057 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9058 ///   %smax0 = smax %arr, svn0
9059 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9060 ///   %smax1 = smax %smax0, %svn1
9061 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9062 ///   %smax2 = smax %smax1, svn2
9063 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9064 ///   %sc = setcc %smax2, %svn3, gt
9065 ///   %n0 = extract_vector_elt %sc, #0
9066 ///   %n1 = extract_vector_elt %smax2, #0
9067 ///   %n2 = extract_vector_elt $smax2, #1
9068 ///   %result = select %n0, %n1, n2
9069 ///     becomes :
9070 ///   %1 = smaxv %0
9071 ///   %result = extract_vector_elt %1, 0
9072 static SDValue
9073 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9074                                         const AArch64Subtarget *Subtarget) {
9075   if (!Subtarget->hasNEON())
9076     return SDValue();
9077
9078   SDValue N0 = N->getOperand(0);
9079   SDValue IfTrue = N->getOperand(1);
9080   SDValue IfFalse = N->getOperand(2);
9081
9082   // Check if the SELECT merges up the final result of the min/max
9083   // from a vector.
9084   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9085       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9086       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9087     return SDValue();
9088
9089   // Expect N0 is fed by SETCC.
9090   SDValue SetCC = N0.getOperand(0);
9091   EVT SetCCVT = SetCC.getValueType();
9092   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9093       SetCCVT.getVectorElementType() != MVT::i1)
9094     return SDValue();
9095
9096   SDValue VectorOp = SetCC.getOperand(0);
9097   unsigned Op = VectorOp->getOpcode();
9098   // Check if the input vector is fed by the operator we want to handle.
9099   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9100       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9101     return SDValue();
9102
9103   EVT VTy = VectorOp.getValueType();
9104   if (!VTy.isVector())
9105     return SDValue();
9106
9107   if (VTy.getSizeInBits() < 64)
9108     return SDValue();
9109
9110   EVT EltTy = VTy.getVectorElementType();
9111   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9112     if (EltTy != MVT::f32)
9113       return SDValue();
9114   } else {
9115     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9116       return SDValue();
9117   }
9118
9119   // Check if extracting from the same vector.
9120   // For example,
9121   //   %sc = setcc %vector, %svn1, gt
9122   //   %n0 = extract_vector_elt %sc, #0
9123   //   %n1 = extract_vector_elt %vector, #0
9124   //   %n2 = extract_vector_elt $vector, #1
9125   if (!(VectorOp == IfTrue->getOperand(0) &&
9126         VectorOp == IfFalse->getOperand(0)))
9127     return SDValue();
9128
9129   // Check if the condition code is matched with the operator type.
9130   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9131   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9132       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9133       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9134       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9135       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9136        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9137        CC != ISD::SETGE) ||
9138       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9139        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9140        CC != ISD::SETLE))
9141     return SDValue();
9142
9143   // Expect to check only lane 0 from the vector SETCC.
9144   if (!isNullConstant(N0.getOperand(1)))
9145     return SDValue();
9146
9147   // Expect to extract the true value from lane 0.
9148   if (!isNullConstant(IfTrue.getOperand(1)))
9149     return SDValue();
9150
9151   // Expect to extract the false value from lane 1.
9152   if (!isOneConstant(IfFalse.getOperand(1)))
9153     return SDValue();
9154
9155   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9156 }
9157
9158 /// Target-specific DAG combine for the across vector add reduction.
9159 /// This function specifically handles the final clean-up step of the vector
9160 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9161 /// pattern, which adds all elements of a vector together.
9162 /// For example, for a <4 x i32> vector :
9163 ///   %1 = vector_shuffle %0, <2,3,u,u>
9164 ///   %2 = add %0, %1
9165 ///   %3 = vector_shuffle %2, <1,u,u,u>
9166 ///   %4 = add %2, %3
9167 ///   %result = extract_vector_elt %4, 0
9168 /// becomes :
9169 ///   %0 = uaddv %0
9170 ///   %result = extract_vector_elt %0, 0
9171 static SDValue
9172 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9173                                      const AArch64Subtarget *Subtarget) {
9174   if (!Subtarget->hasNEON())
9175     return SDValue();
9176   SDValue N0 = N->getOperand(0);
9177   SDValue N1 = N->getOperand(1);
9178
9179   // Check if the input vector is fed by the ADD.
9180   if (N0->getOpcode() != ISD::ADD)
9181     return SDValue();
9182
9183   // The vector extract idx must constant zero because we only expect the final
9184   // result of the reduction is placed in lane 0.
9185   if (!isNullConstant(N1))
9186     return SDValue();
9187
9188   EVT VTy = N0.getValueType();
9189   if (!VTy.isVector())
9190     return SDValue();
9191
9192   EVT EltTy = VTy.getVectorElementType();
9193   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9194     return SDValue();
9195
9196   if (VTy.getSizeInBits() < 64)
9197     return SDValue();
9198
9199   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9200 }
9201
9202 /// Target-specific DAG combine function for NEON load/store intrinsics
9203 /// to merge base address updates.
9204 static SDValue performNEONPostLDSTCombine(SDNode *N,
9205                                           TargetLowering::DAGCombinerInfo &DCI,
9206                                           SelectionDAG &DAG) {
9207   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9208     return SDValue();
9209
9210   unsigned AddrOpIdx = N->getNumOperands() - 1;
9211   SDValue Addr = N->getOperand(AddrOpIdx);
9212
9213   // Search for a use of the address operand that is an increment.
9214   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9215        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9216     SDNode *User = *UI;
9217     if (User->getOpcode() != ISD::ADD ||
9218         UI.getUse().getResNo() != Addr.getResNo())
9219       continue;
9220
9221     // Check that the add is independent of the load/store.  Otherwise, folding
9222     // it would create a cycle.
9223     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9224       continue;
9225
9226     // Find the new opcode for the updating load/store.
9227     bool IsStore = false;
9228     bool IsLaneOp = false;
9229     bool IsDupOp = false;
9230     unsigned NewOpc = 0;
9231     unsigned NumVecs = 0;
9232     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9233     switch (IntNo) {
9234     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9235     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9236       NumVecs = 2; break;
9237     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9238       NumVecs = 3; break;
9239     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9240       NumVecs = 4; break;
9241     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9242       NumVecs = 2; IsStore = true; break;
9243     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9244       NumVecs = 3; IsStore = true; break;
9245     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9246       NumVecs = 4; IsStore = true; break;
9247     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9248       NumVecs = 2; break;
9249     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9250       NumVecs = 3; break;
9251     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9252       NumVecs = 4; break;
9253     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9254       NumVecs = 2; IsStore = true; break;
9255     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9256       NumVecs = 3; IsStore = true; break;
9257     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9258       NumVecs = 4; IsStore = true; break;
9259     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9260       NumVecs = 2; IsDupOp = true; break;
9261     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9262       NumVecs = 3; IsDupOp = true; break;
9263     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9264       NumVecs = 4; IsDupOp = true; break;
9265     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9266       NumVecs = 2; IsLaneOp = true; break;
9267     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9268       NumVecs = 3; IsLaneOp = true; break;
9269     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9270       NumVecs = 4; IsLaneOp = true; break;
9271     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9272       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9273     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9274       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9275     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9276       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9277     }
9278
9279     EVT VecTy;
9280     if (IsStore)
9281       VecTy = N->getOperand(2).getValueType();
9282     else
9283       VecTy = N->getValueType(0);
9284
9285     // If the increment is a constant, it must match the memory ref size.
9286     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9287     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9288       uint32_t IncVal = CInc->getZExtValue();
9289       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9290       if (IsLaneOp || IsDupOp)
9291         NumBytes /= VecTy.getVectorNumElements();
9292       if (IncVal != NumBytes)
9293         continue;
9294       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9295     }
9296     SmallVector<SDValue, 8> Ops;
9297     Ops.push_back(N->getOperand(0)); // Incoming chain
9298     // Load lane and store have vector list as input.
9299     if (IsLaneOp || IsStore)
9300       for (unsigned i = 2; i < AddrOpIdx; ++i)
9301         Ops.push_back(N->getOperand(i));
9302     Ops.push_back(Addr); // Base register
9303     Ops.push_back(Inc);
9304
9305     // Return Types.
9306     EVT Tys[6];
9307     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9308     unsigned n;
9309     for (n = 0; n < NumResultVecs; ++n)
9310       Tys[n] = VecTy;
9311     Tys[n++] = MVT::i64;  // Type of write back register
9312     Tys[n] = MVT::Other;  // Type of the chain
9313     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9314
9315     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9316     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9317                                            MemInt->getMemoryVT(),
9318                                            MemInt->getMemOperand());
9319
9320     // Update the uses.
9321     std::vector<SDValue> NewResults;
9322     for (unsigned i = 0; i < NumResultVecs; ++i) {
9323       NewResults.push_back(SDValue(UpdN.getNode(), i));
9324     }
9325     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9326     DCI.CombineTo(N, NewResults);
9327     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9328
9329     break;
9330   }
9331   return SDValue();
9332 }
9333
9334 // Checks to see if the value is the prescribed width and returns information
9335 // about its extension mode.
9336 static
9337 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9338   ExtType = ISD::NON_EXTLOAD;
9339   switch(V.getNode()->getOpcode()) {
9340   default:
9341     return false;
9342   case ISD::LOAD: {
9343     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9344     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9345        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9346       ExtType = LoadNode->getExtensionType();
9347       return true;
9348     }
9349     return false;
9350   }
9351   case ISD::AssertSext: {
9352     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9353     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9354        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9355       ExtType = ISD::SEXTLOAD;
9356       return true;
9357     }
9358     return false;
9359   }
9360   case ISD::AssertZext: {
9361     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9362     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9363        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9364       ExtType = ISD::ZEXTLOAD;
9365       return true;
9366     }
9367     return false;
9368   }
9369   case ISD::Constant:
9370   case ISD::TargetConstant: {
9371     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9372            1LL << (width - 1);
9373   }
9374   }
9375
9376   return true;
9377 }
9378
9379 // This function does a whole lot of voodoo to determine if the tests are
9380 // equivalent without and with a mask. Essentially what happens is that given a
9381 // DAG resembling:
9382 //
9383 //  +-------------+ +-------------+ +-------------+ +-------------+
9384 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9385 //  +-------------+ +-------------+ +-------------+ +-------------+
9386 //           |           |           |               |
9387 //           V           V           |    +----------+
9388 //          +-------------+  +----+  |    |
9389 //          |     ADD     |  |0xff|  |    |
9390 //          +-------------+  +----+  |    |
9391 //                  |           |    |    |
9392 //                  V           V    |    |
9393 //                 +-------------+   |    |
9394 //                 |     AND     |   |    |
9395 //                 +-------------+   |    |
9396 //                      |            |    |
9397 //                      +-----+      |    |
9398 //                            |      |    |
9399 //                            V      V    V
9400 //                           +-------------+
9401 //                           |     CMP     |
9402 //                           +-------------+
9403 //
9404 // The AND node may be safely removed for some combinations of inputs. In
9405 // particular we need to take into account the extension type of the Input,
9406 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9407 // width of the input (this can work for any width inputs, the above graph is
9408 // specific to 8 bits.
9409 //
9410 // The specific equations were worked out by generating output tables for each
9411 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9412 // problem was simplified by working with 4 bit inputs, which means we only
9413 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9414 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9415 // patterns present in both extensions (0,7). For every distinct set of
9416 // AddConstant and CompConstants bit patterns we can consider the masked and
9417 // unmasked versions to be equivalent if the result of this function is true for
9418 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9419 //
9420 //   sub      w8, w0, w1
9421 //   and      w10, w8, #0x0f
9422 //   cmp      w8, w2
9423 //   cset     w9, AArch64CC
9424 //   cmp      w10, w2
9425 //   cset     w11, AArch64CC
9426 //   cmp      w9, w11
9427 //   cset     w0, eq
9428 //   ret
9429 //
9430 // Since the above function shows when the outputs are equivalent it defines
9431 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9432 // would be expensive to run during compiles. The equations below were written
9433 // in a test harness that confirmed they gave equivalent outputs to the above
9434 // for all inputs function, so they can be used determine if the removal is
9435 // legal instead.
9436 //
9437 // isEquivalentMaskless() is the code for testing if the AND can be removed
9438 // factored out of the DAG recognition as the DAG can take several forms.
9439
9440 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9441                                  ISD::LoadExtType ExtType, int AddConstant,
9442                                  int CompConstant) {
9443   // By being careful about our equations and only writing the in term
9444   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9445   // make them generally applicable to all bit widths.
9446   int MaxUInt = (1 << width);
9447
9448   // For the purposes of these comparisons sign extending the type is
9449   // equivalent to zero extending the add and displacing it by half the integer
9450   // width. Provided we are careful and make sure our equations are valid over
9451   // the whole range we can just adjust the input and avoid writing equations
9452   // for sign extended inputs.
9453   if (ExtType == ISD::SEXTLOAD)
9454     AddConstant -= (1 << (width-1));
9455
9456   switch(CC) {
9457   case AArch64CC::LE:
9458   case AArch64CC::GT: {
9459     if ((AddConstant == 0) ||
9460         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9461         (AddConstant >= 0 && CompConstant < 0) ||
9462         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9463       return true;
9464   } break;
9465   case AArch64CC::LT:
9466   case AArch64CC::GE: {
9467     if ((AddConstant == 0) ||
9468         (AddConstant >= 0 && CompConstant <= 0) ||
9469         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9470       return true;
9471   } break;
9472   case AArch64CC::HI:
9473   case AArch64CC::LS: {
9474     if ((AddConstant >= 0 && CompConstant < 0) ||
9475        (AddConstant <= 0 && CompConstant >= -1 &&
9476         CompConstant < AddConstant + MaxUInt))
9477       return true;
9478   } break;
9479   case AArch64CC::PL:
9480   case AArch64CC::MI: {
9481     if ((AddConstant == 0) ||
9482         (AddConstant > 0 && CompConstant <= 0) ||
9483         (AddConstant < 0 && CompConstant <= AddConstant))
9484       return true;
9485   } break;
9486   case AArch64CC::LO:
9487   case AArch64CC::HS: {
9488     if ((AddConstant >= 0 && CompConstant <= 0) ||
9489         (AddConstant <= 0 && CompConstant >= 0 &&
9490          CompConstant <= AddConstant + MaxUInt))
9491       return true;
9492   } break;
9493   case AArch64CC::EQ:
9494   case AArch64CC::NE: {
9495     if ((AddConstant > 0 && CompConstant < 0) ||
9496         (AddConstant < 0 && CompConstant >= 0 &&
9497          CompConstant < AddConstant + MaxUInt) ||
9498         (AddConstant >= 0 && CompConstant >= 0 &&
9499          CompConstant >= AddConstant) ||
9500         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9501
9502       return true;
9503   } break;
9504   case AArch64CC::VS:
9505   case AArch64CC::VC:
9506   case AArch64CC::AL:
9507   case AArch64CC::NV:
9508     return true;
9509   case AArch64CC::Invalid:
9510     break;
9511   }
9512
9513   return false;
9514 }
9515
9516 static
9517 SDValue performCONDCombine(SDNode *N,
9518                            TargetLowering::DAGCombinerInfo &DCI,
9519                            SelectionDAG &DAG, unsigned CCIndex,
9520                            unsigned CmpIndex) {
9521   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9522   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9523   unsigned CondOpcode = SubsNode->getOpcode();
9524
9525   if (CondOpcode != AArch64ISD::SUBS)
9526     return SDValue();
9527
9528   // There is a SUBS feeding this condition. Is it fed by a mask we can
9529   // use?
9530
9531   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9532   unsigned MaskBits = 0;
9533
9534   if (AndNode->getOpcode() != ISD::AND)
9535     return SDValue();
9536
9537   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9538     uint32_t CNV = CN->getZExtValue();
9539     if (CNV == 255)
9540       MaskBits = 8;
9541     else if (CNV == 65535)
9542       MaskBits = 16;
9543   }
9544
9545   if (!MaskBits)
9546     return SDValue();
9547
9548   SDValue AddValue = AndNode->getOperand(0);
9549
9550   if (AddValue.getOpcode() != ISD::ADD)
9551     return SDValue();
9552
9553   // The basic dag structure is correct, grab the inputs and validate them.
9554
9555   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9556   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9557   SDValue SubsInputValue = SubsNode->getOperand(1);
9558
9559   // The mask is present and the provenance of all the values is a smaller type,
9560   // lets see if the mask is superfluous.
9561
9562   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9563       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9564     return SDValue();
9565
9566   ISD::LoadExtType ExtType;
9567
9568   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9569       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9570       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9571     return SDValue();
9572
9573   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9574                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9575                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9576     return SDValue();
9577
9578   // The AND is not necessary, remove it.
9579
9580   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9581                                SubsNode->getValueType(1));
9582   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9583
9584   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9585   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9586
9587   return SDValue(N, 0);
9588 }
9589
9590 // Optimize compare with zero and branch.
9591 static SDValue performBRCONDCombine(SDNode *N,
9592                                     TargetLowering::DAGCombinerInfo &DCI,
9593                                     SelectionDAG &DAG) {
9594   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9595     N = NV.getNode();
9596   SDValue Chain = N->getOperand(0);
9597   SDValue Dest = N->getOperand(1);
9598   SDValue CCVal = N->getOperand(2);
9599   SDValue Cmp = N->getOperand(3);
9600
9601   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9602   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9603   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9604     return SDValue();
9605
9606   unsigned CmpOpc = Cmp.getOpcode();
9607   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9608     return SDValue();
9609
9610   // Only attempt folding if there is only one use of the flag and no use of the
9611   // value.
9612   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9613     return SDValue();
9614
9615   SDValue LHS = Cmp.getOperand(0);
9616   SDValue RHS = Cmp.getOperand(1);
9617
9618   assert(LHS.getValueType() == RHS.getValueType() &&
9619          "Expected the value type to be the same for both operands!");
9620   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9621     return SDValue();
9622
9623   if (isNullConstant(LHS))
9624     std::swap(LHS, RHS);
9625
9626   if (!isNullConstant(RHS))
9627     return SDValue();
9628
9629   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9630       LHS.getOpcode() == ISD::SRL)
9631     return SDValue();
9632
9633   // Fold the compare into the branch instruction.
9634   SDValue BR;
9635   if (CC == AArch64CC::EQ)
9636     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9637   else
9638     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9639
9640   // Do not add new nodes to DAG combiner worklist.
9641   DCI.CombineTo(N, BR, false);
9642
9643   return SDValue();
9644 }
9645
9646 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9647 // as well as whether the test should be inverted.  This code is required to
9648 // catch these cases (as opposed to standard dag combines) because
9649 // AArch64ISD::TBZ is matched during legalization.
9650 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9651                                  SelectionDAG &DAG) {
9652
9653   if (!Op->hasOneUse())
9654     return Op;
9655
9656   // We don't handle undef/constant-fold cases below, as they should have
9657   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9658   // etc.)
9659
9660   // (tbz (trunc x), b) -> (tbz x, b)
9661   // This case is just here to enable more of the below cases to be caught.
9662   if (Op->getOpcode() == ISD::TRUNCATE &&
9663       Bit < Op->getValueType(0).getSizeInBits()) {
9664     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9665   }
9666
9667   if (Op->getNumOperands() != 2)
9668     return Op;
9669
9670   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9671   if (!C)
9672     return Op;
9673
9674   switch (Op->getOpcode()) {
9675   default:
9676     return Op;
9677
9678   // (tbz (and x, m), b) -> (tbz x, b)
9679   case ISD::AND:
9680     if ((C->getZExtValue() >> Bit) & 1)
9681       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9682     return Op;
9683
9684   // (tbz (shl x, c), b) -> (tbz x, b-c)
9685   case ISD::SHL:
9686     if (C->getZExtValue() <= Bit &&
9687         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9688       Bit = Bit - C->getZExtValue();
9689       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9690     }
9691     return Op;
9692
9693   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9694   case ISD::SRA:
9695     Bit = Bit + C->getZExtValue();
9696     if (Bit >= Op->getValueType(0).getSizeInBits())
9697       Bit = Op->getValueType(0).getSizeInBits() - 1;
9698     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9699
9700   // (tbz (srl x, c), b) -> (tbz x, b+c)
9701   case ISD::SRL:
9702     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9703       Bit = Bit + C->getZExtValue();
9704       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9705     }
9706     return Op;
9707
9708   // (tbz (xor x, -1), b) -> (tbnz x, b)
9709   case ISD::XOR:
9710     if ((C->getZExtValue() >> Bit) & 1)
9711       Invert = !Invert;
9712     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9713   }
9714 }
9715
9716 // Optimize test single bit zero/non-zero and branch.
9717 static SDValue performTBZCombine(SDNode *N,
9718                                  TargetLowering::DAGCombinerInfo &DCI,
9719                                  SelectionDAG &DAG) {
9720   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9721   bool Invert = false;
9722   SDValue TestSrc = N->getOperand(1);
9723   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9724
9725   if (TestSrc == NewTestSrc)
9726     return SDValue();
9727
9728   unsigned NewOpc = N->getOpcode();
9729   if (Invert) {
9730     if (NewOpc == AArch64ISD::TBZ)
9731       NewOpc = AArch64ISD::TBNZ;
9732     else {
9733       assert(NewOpc == AArch64ISD::TBNZ);
9734       NewOpc = AArch64ISD::TBZ;
9735     }
9736   }
9737
9738   SDLoc DL(N);
9739   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9740                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9741 }
9742
9743 // vselect (v1i1 setcc) ->
9744 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9745 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9746 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9747 // such VSELECT.
9748 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9749   SDValue N0 = N->getOperand(0);
9750   EVT CCVT = N0.getValueType();
9751
9752   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9753       CCVT.getVectorElementType() != MVT::i1)
9754     return SDValue();
9755
9756   EVT ResVT = N->getValueType(0);
9757   EVT CmpVT = N0.getOperand(0).getValueType();
9758   // Only combine when the result type is of the same size as the compared
9759   // operands.
9760   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9761     return SDValue();
9762
9763   SDValue IfTrue = N->getOperand(1);
9764   SDValue IfFalse = N->getOperand(2);
9765   SDValue SetCC =
9766       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9767                    N0.getOperand(0), N0.getOperand(1),
9768                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9769   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9770                      IfTrue, IfFalse);
9771 }
9772
9773 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9774 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9775 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9776 /// with a vector one followed by a DUP shuffle on the result.
9777 static SDValue performSelectCombine(SDNode *N,
9778                                     TargetLowering::DAGCombinerInfo &DCI) {
9779   SelectionDAG &DAG = DCI.DAG;
9780   SDValue N0 = N->getOperand(0);
9781   EVT ResVT = N->getValueType(0);
9782
9783   if (N0.getOpcode() != ISD::SETCC)
9784     return SDValue();
9785
9786   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9787   // scalar SetCCResultType. We also don't expect vectors, because we assume
9788   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9789   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9790          "Scalar-SETCC feeding SELECT has unexpected result type!");
9791
9792   // If NumMaskElts == 0, the comparison is larger than select result. The
9793   // largest real NEON comparison is 64-bits per lane, which means the result is
9794   // at most 32-bits and an illegal vector. Just bail out for now.
9795   EVT SrcVT = N0.getOperand(0).getValueType();
9796
9797   // Don't try to do this optimization when the setcc itself has i1 operands.
9798   // There are no legal vectors of i1, so this would be pointless.
9799   if (SrcVT == MVT::i1)
9800     return SDValue();
9801
9802   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9803   if (!ResVT.isVector() || NumMaskElts == 0)
9804     return SDValue();
9805
9806   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9807   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9808
9809   // Also bail out if the vector CCVT isn't the same size as ResVT.
9810   // This can happen if the SETCC operand size doesn't divide the ResVT size
9811   // (e.g., f64 vs v3f32).
9812   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9813     return SDValue();
9814
9815   // Make sure we didn't create illegal types, if we're not supposed to.
9816   assert(DCI.isBeforeLegalize() ||
9817          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9818
9819   // First perform a vector comparison, where lane 0 is the one we're interested
9820   // in.
9821   SDLoc DL(N0);
9822   SDValue LHS =
9823       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9824   SDValue RHS =
9825       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9826   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9827
9828   // Now duplicate the comparison mask we want across all other lanes.
9829   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9830   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
9831   Mask = DAG.getNode(ISD::BITCAST, DL,
9832                      ResVT.changeVectorElementTypeToInteger(), Mask);
9833
9834   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9835 }
9836
9837 /// Get rid of unnecessary NVCASTs (that don't change the type).
9838 static SDValue performNVCASTCombine(SDNode *N) {
9839   if (N->getValueType(0) == N->getOperand(0).getValueType())
9840     return N->getOperand(0);
9841
9842   return SDValue();
9843 }
9844
9845 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9846                                                  DAGCombinerInfo &DCI) const {
9847   SelectionDAG &DAG = DCI.DAG;
9848   switch (N->getOpcode()) {
9849   default:
9850     break;
9851   case ISD::ADD:
9852   case ISD::SUB:
9853     return performAddSubLongCombine(N, DCI, DAG);
9854   case ISD::XOR:
9855     return performXorCombine(N, DAG, DCI, Subtarget);
9856   case ISD::MUL:
9857     return performMulCombine(N, DAG, DCI, Subtarget);
9858   case ISD::SINT_TO_FP:
9859   case ISD::UINT_TO_FP:
9860     return performIntToFpCombine(N, DAG, Subtarget);
9861   case ISD::FP_TO_SINT:
9862   case ISD::FP_TO_UINT:
9863     return performFpToIntCombine(N, DAG, DCI, Subtarget);
9864   case ISD::FDIV:
9865     return performFDivCombine(N, DAG, Subtarget);
9866   case ISD::OR:
9867     return performORCombine(N, DCI, Subtarget);
9868   case ISD::SRL:
9869     return performSRLCombine(N, DCI);
9870   case ISD::INTRINSIC_WO_CHAIN:
9871     return performIntrinsicCombine(N, DCI, Subtarget);
9872   case ISD::ANY_EXTEND:
9873   case ISD::ZERO_EXTEND:
9874   case ISD::SIGN_EXTEND:
9875     return performExtendCombine(N, DCI, DAG);
9876   case ISD::BITCAST:
9877     return performBitcastCombine(N, DCI, DAG);
9878   case ISD::CONCAT_VECTORS:
9879     return performConcatVectorsCombine(N, DCI, DAG);
9880   case ISD::SELECT: {
9881     SDValue RV = performSelectCombine(N, DCI);
9882     if (!RV.getNode())
9883       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9884     return RV;
9885   }
9886   case ISD::VSELECT:
9887     return performVSelectCombine(N, DCI.DAG);
9888   case ISD::LOAD:
9889     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9890       return SDValue(N, 0);
9891     break;
9892   case ISD::STORE:
9893     return performSTORECombine(N, DCI, DAG, Subtarget);
9894   case AArch64ISD::BRCOND:
9895     return performBRCONDCombine(N, DCI, DAG);
9896   case AArch64ISD::TBNZ:
9897   case AArch64ISD::TBZ:
9898     return performTBZCombine(N, DCI, DAG);
9899   case AArch64ISD::CSEL:
9900     return performCONDCombine(N, DCI, DAG, 2, 3);
9901   case AArch64ISD::DUP:
9902     return performPostLD1Combine(N, DCI, false);
9903   case AArch64ISD::NVCAST:
9904     return performNVCASTCombine(N);
9905   case ISD::INSERT_VECTOR_ELT:
9906     return performPostLD1Combine(N, DCI, true);
9907   case ISD::EXTRACT_VECTOR_ELT:
9908     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9909   case ISD::INTRINSIC_VOID:
9910   case ISD::INTRINSIC_W_CHAIN:
9911     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9912     case Intrinsic::aarch64_neon_ld2:
9913     case Intrinsic::aarch64_neon_ld3:
9914     case Intrinsic::aarch64_neon_ld4:
9915     case Intrinsic::aarch64_neon_ld1x2:
9916     case Intrinsic::aarch64_neon_ld1x3:
9917     case Intrinsic::aarch64_neon_ld1x4:
9918     case Intrinsic::aarch64_neon_ld2lane:
9919     case Intrinsic::aarch64_neon_ld3lane:
9920     case Intrinsic::aarch64_neon_ld4lane:
9921     case Intrinsic::aarch64_neon_ld2r:
9922     case Intrinsic::aarch64_neon_ld3r:
9923     case Intrinsic::aarch64_neon_ld4r:
9924     case Intrinsic::aarch64_neon_st2:
9925     case Intrinsic::aarch64_neon_st3:
9926     case Intrinsic::aarch64_neon_st4:
9927     case Intrinsic::aarch64_neon_st1x2:
9928     case Intrinsic::aarch64_neon_st1x3:
9929     case Intrinsic::aarch64_neon_st1x4:
9930     case Intrinsic::aarch64_neon_st2lane:
9931     case Intrinsic::aarch64_neon_st3lane:
9932     case Intrinsic::aarch64_neon_st4lane:
9933       return performNEONPostLDSTCombine(N, DCI, DAG);
9934     default:
9935       break;
9936     }
9937   }
9938   return SDValue();
9939 }
9940
9941 // Check if the return value is used as only a return value, as otherwise
9942 // we can't perform a tail-call. In particular, we need to check for
9943 // target ISD nodes that are returns and any other "odd" constructs
9944 // that the generic analysis code won't necessarily catch.
9945 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9946                                                SDValue &Chain) const {
9947   if (N->getNumValues() != 1)
9948     return false;
9949   if (!N->hasNUsesOfValue(1, 0))
9950     return false;
9951
9952   SDValue TCChain = Chain;
9953   SDNode *Copy = *N->use_begin();
9954   if (Copy->getOpcode() == ISD::CopyToReg) {
9955     // If the copy has a glue operand, we conservatively assume it isn't safe to
9956     // perform a tail call.
9957     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9958         MVT::Glue)
9959       return false;
9960     TCChain = Copy->getOperand(0);
9961   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9962     return false;
9963
9964   bool HasRet = false;
9965   for (SDNode *Node : Copy->uses()) {
9966     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9967       return false;
9968     HasRet = true;
9969   }
9970
9971   if (!HasRet)
9972     return false;
9973
9974   Chain = TCChain;
9975   return true;
9976 }
9977
9978 // Return whether the an instruction can potentially be optimized to a tail
9979 // call. This will cause the optimizers to attempt to move, or duplicate,
9980 // return instructions to help enable tail call optimizations for this
9981 // instruction.
9982 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9983   return CI->isTailCall();
9984 }
9985
9986 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9987                                                    SDValue &Offset,
9988                                                    ISD::MemIndexedMode &AM,
9989                                                    bool &IsInc,
9990                                                    SelectionDAG &DAG) const {
9991   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9992     return false;
9993
9994   Base = Op->getOperand(0);
9995   // All of the indexed addressing mode instructions take a signed
9996   // 9 bit immediate offset.
9997   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9998     int64_t RHSC = (int64_t)RHS->getZExtValue();
9999     if (RHSC >= 256 || RHSC <= -256)
10000       return false;
10001     IsInc = (Op->getOpcode() == ISD::ADD);
10002     Offset = Op->getOperand(1);
10003     return true;
10004   }
10005   return false;
10006 }
10007
10008 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10009                                                       SDValue &Offset,
10010                                                       ISD::MemIndexedMode &AM,
10011                                                       SelectionDAG &DAG) const {
10012   EVT VT;
10013   SDValue Ptr;
10014   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10015     VT = LD->getMemoryVT();
10016     Ptr = LD->getBasePtr();
10017   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10018     VT = ST->getMemoryVT();
10019     Ptr = ST->getBasePtr();
10020   } else
10021     return false;
10022
10023   bool IsInc;
10024   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10025     return false;
10026   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10027   return true;
10028 }
10029
10030 bool AArch64TargetLowering::getPostIndexedAddressParts(
10031     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10032     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10033   EVT VT;
10034   SDValue Ptr;
10035   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10036     VT = LD->getMemoryVT();
10037     Ptr = LD->getBasePtr();
10038   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10039     VT = ST->getMemoryVT();
10040     Ptr = ST->getBasePtr();
10041   } else
10042     return false;
10043
10044   bool IsInc;
10045   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10046     return false;
10047   // Post-indexing updates the base, so it's not a valid transform
10048   // if that's not the same as the load's pointer.
10049   if (Ptr != Base)
10050     return false;
10051   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10052   return true;
10053 }
10054
10055 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10056                                   SelectionDAG &DAG) {
10057   SDLoc DL(N);
10058   SDValue Op = N->getOperand(0);
10059
10060   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10061     return;
10062
10063   Op = SDValue(
10064       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10065                          DAG.getUNDEF(MVT::i32), Op,
10066                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10067       0);
10068   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10069   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10070 }
10071
10072 static void ReplaceReductionResults(SDNode *N,
10073                                     SmallVectorImpl<SDValue> &Results,
10074                                     SelectionDAG &DAG, unsigned InterOp,
10075                                     unsigned AcrossOp) {
10076   EVT LoVT, HiVT;
10077   SDValue Lo, Hi;
10078   SDLoc dl(N);
10079   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10080   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10081   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10082   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10083   Results.push_back(SplitVal);
10084 }
10085
10086 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10087                                        SmallVectorImpl<SDValue> & Results,
10088                                        SelectionDAG &DAG) {
10089   assert(N->getValueType(0) == MVT::i128 &&
10090          "AtomicCmpSwap on types less than 128 should be legal");
10091   SDValue Ops[] = {N->getOperand(1),
10092                    N->getOperand(2)->getOperand(0),
10093                    N->getOperand(2)->getOperand(1),
10094                    N->getOperand(3)->getOperand(0),
10095                    N->getOperand(3)->getOperand(1),
10096                    N->getOperand(0)};
10097   SDNode *CmpSwap = DAG.getMachineNode(
10098       AArch64::CMP_SWAP_128, SDLoc(N),
10099       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10100
10101   MachineFunction &MF = DAG.getMachineFunction();
10102   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10103   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10104   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10105
10106   Results.push_back(SDValue(CmpSwap, 0));
10107   Results.push_back(SDValue(CmpSwap, 1));
10108   Results.push_back(SDValue(CmpSwap, 3));
10109 }
10110
10111 void AArch64TargetLowering::ReplaceNodeResults(
10112     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10113   switch (N->getOpcode()) {
10114   default:
10115     llvm_unreachable("Don't know how to custom expand this");
10116   case ISD::BITCAST:
10117     ReplaceBITCASTResults(N, Results, DAG);
10118     return;
10119   case AArch64ISD::SADDV:
10120     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10121     return;
10122   case AArch64ISD::UADDV:
10123     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10124     return;
10125   case AArch64ISD::SMINV:
10126     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10127     return;
10128   case AArch64ISD::UMINV:
10129     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10130     return;
10131   case AArch64ISD::SMAXV:
10132     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10133     return;
10134   case AArch64ISD::UMAXV:
10135     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10136     return;
10137   case ISD::FP_TO_UINT:
10138   case ISD::FP_TO_SINT:
10139     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10140     // Let normal code take care of it by not adding anything to Results.
10141     return;
10142   case ISD::ATOMIC_CMP_SWAP:
10143     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10144     return;
10145   }
10146 }
10147
10148 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10149   if (!Subtarget->isTargetAndroid())
10150     return true;
10151   return TargetLowering::useLoadStackGuardNode();
10152 }
10153
10154 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10155   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10156   // reciprocal if there are three or more FDIVs.
10157   return 3;
10158 }
10159
10160 TargetLoweringBase::LegalizeTypeAction
10161 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10162   MVT SVT = VT.getSimpleVT();
10163   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10164   // v4i16, v2i32 instead of to promote.
10165   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10166       || SVT == MVT::v1f32)
10167     return TypeWidenVector;
10168
10169   return TargetLoweringBase::getPreferredVectorAction(VT);
10170 }
10171
10172 // Loads and stores less than 128-bits are already atomic; ones above that
10173 // are doomed anyway, so defer to the default libcall and blame the OS when
10174 // things go wrong.
10175 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10176   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10177   return Size == 128;
10178 }
10179
10180 // Loads and stores less than 128-bits are already atomic; ones above that
10181 // are doomed anyway, so defer to the default libcall and blame the OS when
10182 // things go wrong.
10183 TargetLowering::AtomicExpansionKind
10184 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10185   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10186   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10187 }
10188
10189 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10190 TargetLowering::AtomicExpansionKind
10191 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10192   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10193   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10194 }
10195
10196 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10197     AtomicCmpXchgInst *AI) const {
10198   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10199   // implement cmpxchg without spilling. If the address being exchanged is also
10200   // on the stack and close enough to the spill slot, this can lead to a
10201   // situation where the monitor always gets cleared and the atomic operation
10202   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10203   return getTargetMachine().getOptLevel() != 0;
10204 }
10205
10206 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10207                                              AtomicOrdering Ord) const {
10208   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10209   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10210   bool IsAcquire = isAcquireOrStronger(Ord);
10211
10212   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10213   // intrinsic must return {i64, i64} and we have to recombine them into a
10214   // single i128 here.
10215   if (ValTy->getPrimitiveSizeInBits() == 128) {
10216     Intrinsic::ID Int =
10217         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10218     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10219
10220     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10221     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10222
10223     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10224     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10225     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10226     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10227     return Builder.CreateOr(
10228         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10229   }
10230
10231   Type *Tys[] = { Addr->getType() };
10232   Intrinsic::ID Int =
10233       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10234   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10235
10236   return Builder.CreateTruncOrBitCast(
10237       Builder.CreateCall(Ldxr, Addr),
10238       cast<PointerType>(Addr->getType())->getElementType());
10239 }
10240
10241 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10242     IRBuilder<> &Builder) const {
10243   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10244   Builder.CreateCall(
10245       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10246 }
10247
10248 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10249                                                    Value *Val, Value *Addr,
10250                                                    AtomicOrdering Ord) const {
10251   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10252   bool IsRelease = isReleaseOrStronger(Ord);
10253
10254   // Since the intrinsics must have legal type, the i128 intrinsics take two
10255   // parameters: "i64, i64". We must marshal Val into the appropriate form
10256   // before the call.
10257   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10258     Intrinsic::ID Int =
10259         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10260     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10261     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10262
10263     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10264     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10265     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10266     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10267   }
10268
10269   Intrinsic::ID Int =
10270       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10271   Type *Tys[] = { Addr->getType() };
10272   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10273
10274   return Builder.CreateCall(Stxr,
10275                             {Builder.CreateZExtOrBitCast(
10276                                  Val, Stxr->getFunctionType()->getParamType(0)),
10277                              Addr});
10278 }
10279
10280 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10281     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10282   return Ty->isArrayTy();
10283 }
10284
10285 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10286                                                             EVT) const {
10287   return false;
10288 }
10289
10290 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10291   if (!Subtarget->isTargetAndroid())
10292     return TargetLowering::getIRStackGuard(IRB);
10293
10294   // Android provides a fixed TLS slot for the stack cookie. See the definition
10295   // of TLS_SLOT_STACK_GUARD in
10296   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10297   const unsigned TlsOffset = 0x28;
10298   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10299   Function *ThreadPointerFunc =
10300       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10301   return IRB.CreatePointerCast(
10302       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10303       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10304 }
10305
10306 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10307   if (!Subtarget->isTargetAndroid())
10308     return TargetLowering::getSafeStackPointerLocation(IRB);
10309
10310   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10311   // definition of TLS_SLOT_SAFESTACK in
10312   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10313   const unsigned TlsOffset = 0x48;
10314   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10315   Function *ThreadPointerFunc =
10316       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10317   return IRB.CreatePointerCast(
10318       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10319       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10320 }
10321
10322 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10323   // Update IsSplitCSR in AArch64unctionInfo.
10324   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10325   AFI->setIsSplitCSR(true);
10326 }
10327
10328 void AArch64TargetLowering::insertCopiesSplitCSR(
10329     MachineBasicBlock *Entry,
10330     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10331   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10332   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10333   if (!IStart)
10334     return;
10335
10336   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10337   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10338   MachineBasicBlock::iterator MBBI = Entry->begin();
10339   for (const MCPhysReg *I = IStart; *I; ++I) {
10340     const TargetRegisterClass *RC = nullptr;
10341     if (AArch64::GPR64RegClass.contains(*I))
10342       RC = &AArch64::GPR64RegClass;
10343     else if (AArch64::FPR64RegClass.contains(*I))
10344       RC = &AArch64::FPR64RegClass;
10345     else
10346       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10347
10348     unsigned NewVR = MRI->createVirtualRegister(RC);
10349     // Create copy from CSR to a virtual register.
10350     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10351     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10352     // nounwind. If we want to generalize this later, we may need to emit
10353     // CFI pseudo-instructions.
10354     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10355                Attribute::NoUnwind) &&
10356            "Function should be nounwind in insertCopiesSplitCSR!");
10357     Entry->addLiveIn(*I);
10358     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10359         .addReg(*I);
10360
10361     // Insert the copy-back instructions right before the terminator.
10362     for (auto *Exit : Exits)
10363       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10364               TII->get(TargetOpcode::COPY), *I)
10365           .addReg(NewVR);
10366   }
10367 }
10368
10369 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10370   // Integer division on AArch64 is expensive. However, when aggressively
10371   // optimizing for code size, we prefer to use a div instruction, as it is
10372   // usually smaller than the alternative sequence.
10373   // The exception to this is vector division. Since AArch64 doesn't have vector
10374   // integer division, leaving the division as-is is a loss even in terms of
10375   // size, because it will have to be scalarized, while the alternative code
10376   // sequence can be performed in vector form.
10377   bool OptSize =
10378       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10379   return OptSize && !VT.isVector();
10380 }