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 /// Value type used for condition codes.
57 static const MVT MVT_CC = MVT::i32;
58 
59 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60                                              const AArch64Subtarget &STI)
61     : TargetLowering(TM), Subtarget(&STI) {
62 
63   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64   // we have to make something up. Arbitrarily, choose ZeroOrOne.
65   setBooleanContents(ZeroOrOneBooleanContent);
66   // When comparing vectors the result sets the different elements in the
67   // vector to all-one or all-zero.
68   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
69 
70   // Set up the register classes.
71   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
73 
74   if (Subtarget->hasFPARMv8()) {
75     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
79   }
80 
81   if (Subtarget->hasNEON()) {
82     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84     // Someone set us up the NEON.
85     addDRTypeForNEON(MVT::v2f32);
86     addDRTypeForNEON(MVT::v8i8);
87     addDRTypeForNEON(MVT::v4i16);
88     addDRTypeForNEON(MVT::v2i32);
89     addDRTypeForNEON(MVT::v1i64);
90     addDRTypeForNEON(MVT::v1f64);
91     addDRTypeForNEON(MVT::v4f16);
92 
93     addQRTypeForNEON(MVT::v4f32);
94     addQRTypeForNEON(MVT::v2f64);
95     addQRTypeForNEON(MVT::v16i8);
96     addQRTypeForNEON(MVT::v8i16);
97     addQRTypeForNEON(MVT::v4i32);
98     addQRTypeForNEON(MVT::v2i64);
99     addQRTypeForNEON(MVT::v8f16);
100   }
101 
102   // Compute derived properties from the register classes
103   computeRegisterProperties(Subtarget->getRegisterInfo());
104 
105   // Provide all sorts of operation actions
106   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108   setOperationAction(ISD::SETCC, MVT::i32, Custom);
109   setOperationAction(ISD::SETCC, MVT::i64, Custom);
110   setOperationAction(ISD::SETCC, MVT::f32, Custom);
111   setOperationAction(ISD::SETCC, MVT::f64, Custom);
112   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117   setOperationAction(ISD::SELECT, MVT::i32, Custom);
118   setOperationAction(ISD::SELECT, MVT::i64, Custom);
119   setOperationAction(ISD::SELECT, MVT::f32, Custom);
120   setOperationAction(ISD::SELECT, MVT::f64, Custom);
121   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
127 
128   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
131 
132   setOperationAction(ISD::FREM, MVT::f32, Expand);
133   setOperationAction(ISD::FREM, MVT::f64, Expand);
134   setOperationAction(ISD::FREM, MVT::f80, Expand);
135 
136   // Custom lowering hooks are needed for XOR
137   // to fold it into CSINC/CSINV.
138   setOperationAction(ISD::XOR, MVT::i32, Custom);
139   setOperationAction(ISD::XOR, MVT::i64, Custom);
140 
141   // Virtually no operation on f128 is legal, but LLVM can't expand them when
142   // there's a valid register class, so we need custom operations in most cases.
143   setOperationAction(ISD::FABS, MVT::f128, Expand);
144   setOperationAction(ISD::FADD, MVT::f128, Custom);
145   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146   setOperationAction(ISD::FCOS, MVT::f128, Expand);
147   setOperationAction(ISD::FDIV, MVT::f128, Custom);
148   setOperationAction(ISD::FMA, MVT::f128, Expand);
149   setOperationAction(ISD::FMUL, MVT::f128, Custom);
150   setOperationAction(ISD::FNEG, MVT::f128, Expand);
151   setOperationAction(ISD::FPOW, MVT::f128, Expand);
152   setOperationAction(ISD::FREM, MVT::f128, Expand);
153   setOperationAction(ISD::FRINT, MVT::f128, Expand);
154   setOperationAction(ISD::FSIN, MVT::f128, Expand);
155   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157   setOperationAction(ISD::FSUB, MVT::f128, Custom);
158   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159   setOperationAction(ISD::SETCC, MVT::f128, Custom);
160   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161   setOperationAction(ISD::SELECT, MVT::f128, Custom);
162   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
164 
165   // Lowering for many of the conversions is actually specified by the non-f128
166   // type. The LowerXXX function will be trivial when f128 isn't involved.
167   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
181 
182   // Variable arguments.
183   setOperationAction(ISD::VASTART, MVT::Other, Custom);
184   setOperationAction(ISD::VAARG, MVT::Other, Custom);
185   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186   setOperationAction(ISD::VAEND, MVT::Other, Expand);
187 
188   // Variable-sized objects.
189   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
192 
193   // Constant pool entries
194   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
195 
196   // BlockAddress
197   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
198 
199   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200   setOperationAction(ISD::ADDC, MVT::i32, Custom);
201   setOperationAction(ISD::ADDE, MVT::i32, Custom);
202   setOperationAction(ISD::SUBC, MVT::i32, Custom);
203   setOperationAction(ISD::SUBE, MVT::i32, Custom);
204   setOperationAction(ISD::ADDC, MVT::i64, Custom);
205   setOperationAction(ISD::ADDE, MVT::i64, Custom);
206   setOperationAction(ISD::SUBC, MVT::i64, Custom);
207   setOperationAction(ISD::SUBE, MVT::i64, Custom);
208 
209   // AArch64 lacks both left-rotate and popcount instructions.
210   setOperationAction(ISD::ROTL, MVT::i32, Expand);
211   setOperationAction(ISD::ROTL, MVT::i64, Expand);
212   for (MVT VT : MVT::vector_valuetypes()) {
213     setOperationAction(ISD::ROTL, VT, Expand);
214     setOperationAction(ISD::ROTR, VT, Expand);
215   }
216 
217   // AArch64 doesn't have {U|S}MUL_LOHI.
218   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
220 
221 
222   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
224 
225   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
227   for (MVT VT : MVT::vector_valuetypes()) {
228     setOperationAction(ISD::SDIVREM, VT, Expand);
229     setOperationAction(ISD::UDIVREM, VT, Expand);
230   }
231   setOperationAction(ISD::SREM, MVT::i32, Expand);
232   setOperationAction(ISD::SREM, MVT::i64, Expand);
233   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235   setOperationAction(ISD::UREM, MVT::i32, Expand);
236   setOperationAction(ISD::UREM, MVT::i64, Expand);
237 
238   // Custom lower Add/Sub/Mul with overflow.
239   setOperationAction(ISD::SADDO, MVT::i32, Custom);
240   setOperationAction(ISD::SADDO, MVT::i64, Custom);
241   setOperationAction(ISD::UADDO, MVT::i32, Custom);
242   setOperationAction(ISD::UADDO, MVT::i64, Custom);
243   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245   setOperationAction(ISD::USUBO, MVT::i32, Custom);
246   setOperationAction(ISD::USUBO, MVT::i64, Custom);
247   setOperationAction(ISD::SMULO, MVT::i32, Custom);
248   setOperationAction(ISD::SMULO, MVT::i64, Custom);
249   setOperationAction(ISD::UMULO, MVT::i32, Custom);
250   setOperationAction(ISD::UMULO, MVT::i64, Custom);
251 
252   setOperationAction(ISD::FSIN, MVT::f32, Expand);
253   setOperationAction(ISD::FSIN, MVT::f64, Expand);
254   setOperationAction(ISD::FCOS, MVT::f32, Expand);
255   setOperationAction(ISD::FCOS, MVT::f64, Expand);
256   setOperationAction(ISD::FPOW, MVT::f32, Expand);
257   setOperationAction(ISD::FPOW, MVT::f64, Expand);
258   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
260 
261   // f16 is a storage-only type, always promote it to f32.
262   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
263   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
264   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
265   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
266   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
267   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
268   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
269   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
270   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
271   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
272   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
273   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
274   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
275   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
276   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
277   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
278   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
279   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
280   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
281   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
282   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
283   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
284   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
285   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
286   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
287   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
288   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
289   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
290   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
291   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
292   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
293   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
294   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
295   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
296 
297   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
298   // known to be safe.
299   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
311 
312   // Expand all other v4f16 operations.
313   // FIXME: We could generate better code by promoting some operations to
314   // a pair of v4f32s
315   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
341 
342 
343   // v8f16 is also a storage-only type, so expand it.
344   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
375 
376   // AArch64 has implementations of a lot of rounding-like FP operations.
377   for (MVT Ty : {MVT::f32, MVT::f64}) {
378     setOperationAction(ISD::FFLOOR, Ty, Legal);
379     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380     setOperationAction(ISD::FCEIL, Ty, Legal);
381     setOperationAction(ISD::FRINT, Ty, Legal);
382     setOperationAction(ISD::FTRUNC, Ty, Legal);
383     setOperationAction(ISD::FROUND, Ty, Legal);
384     setOperationAction(ISD::FMINNUM, Ty, Legal);
385     setOperationAction(ISD::FMAXNUM, Ty, Legal);
386     setOperationAction(ISD::FMINNAN, Ty, Legal);
387     setOperationAction(ISD::FMAXNAN, Ty, Legal);
388   }
389 
390   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
391 
392   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
393 
394   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395   // This requires the Performance Monitors extension.
396   if (Subtarget->hasPerfMon())
397     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
398 
399   if (Subtarget->isTargetMachO()) {
400     // For iOS, we don't want to the normal expansion of a libcall to
401     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
402     // traffic.
403     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
405   } else {
406     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
408   }
409 
410   // Make floating-point constants legal for the large code model, so they don't
411   // become loads from the constant pool.
412   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
415   }
416 
417   // AArch64 does not have floating-point extending loads, i1 sign-extending
418   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
419   for (MVT VT : MVT::fp_valuetypes()) {
420     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
424   }
425   for (MVT VT : MVT::integer_valuetypes())
426     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
427 
428   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
435 
436   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
438 
439   // Indexed loads and stores are supported.
440   for (unsigned im = (unsigned)ISD::PRE_INC;
441        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442     setIndexedLoadAction(im, MVT::i8, Legal);
443     setIndexedLoadAction(im, MVT::i16, Legal);
444     setIndexedLoadAction(im, MVT::i32, Legal);
445     setIndexedLoadAction(im, MVT::i64, Legal);
446     setIndexedLoadAction(im, MVT::f64, Legal);
447     setIndexedLoadAction(im, MVT::f32, Legal);
448     setIndexedLoadAction(im, MVT::f16, Legal);
449     setIndexedStoreAction(im, MVT::i8, Legal);
450     setIndexedStoreAction(im, MVT::i16, Legal);
451     setIndexedStoreAction(im, MVT::i32, Legal);
452     setIndexedStoreAction(im, MVT::i64, Legal);
453     setIndexedStoreAction(im, MVT::f64, Legal);
454     setIndexedStoreAction(im, MVT::f32, Legal);
455     setIndexedStoreAction(im, MVT::f16, Legal);
456   }
457 
458   // Trap.
459   setOperationAction(ISD::TRAP, MVT::Other, Legal);
460 
461   // We combine OR nodes for bitfield operations.
462   setTargetDAGCombine(ISD::OR);
463 
464   // Vector add and sub nodes may conceal a high-half opportunity.
465   // Also, try to fold ADD into CSINC/CSINV..
466   setTargetDAGCombine(ISD::ADD);
467   setTargetDAGCombine(ISD::SUB);
468   setTargetDAGCombine(ISD::SRL);
469   setTargetDAGCombine(ISD::XOR);
470   setTargetDAGCombine(ISD::SINT_TO_FP);
471   setTargetDAGCombine(ISD::UINT_TO_FP);
472 
473   setTargetDAGCombine(ISD::FP_TO_SINT);
474   setTargetDAGCombine(ISD::FP_TO_UINT);
475   setTargetDAGCombine(ISD::FDIV);
476 
477   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478 
479   setTargetDAGCombine(ISD::ANY_EXTEND);
480   setTargetDAGCombine(ISD::ZERO_EXTEND);
481   setTargetDAGCombine(ISD::SIGN_EXTEND);
482   setTargetDAGCombine(ISD::BITCAST);
483   setTargetDAGCombine(ISD::CONCAT_VECTORS);
484   setTargetDAGCombine(ISD::STORE);
485   if (Subtarget->supportsAddressTopByteIgnored())
486     setTargetDAGCombine(ISD::LOAD);
487 
488   setTargetDAGCombine(ISD::MUL);
489 
490   setTargetDAGCombine(ISD::SELECT);
491   setTargetDAGCombine(ISD::VSELECT);
492 
493   setTargetDAGCombine(ISD::INTRINSIC_VOID);
494   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
496   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
497 
498   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
501 
502   setStackPointerRegisterToSaveRestore(AArch64::SP);
503 
504   setSchedulingPreference(Sched::Hybrid);
505 
506   // Enable TBZ/TBNZ
507   MaskAndBranchFoldingIsLegal = true;
508   EnableExtLdPromotion = true;
509 
510   // Set required alignment.
511   setMinFunctionAlignment(2);
512   // Set preferred alignments.
513   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514   setPrefLoopAlignment(STI.getPrefLoopAlignment());
515 
516   // Only change the limit for entries in a jump table if specified by
517   // the subtarget, but not at the command line.
518   unsigned MaxJT = STI.getMaximumJumpTableSize();
519   if (MaxJT && getMaximumJumpTableSize() == 0)
520     setMaximumJumpTableSize(MaxJT);
521 
522   setHasExtractBitsInsn(true);
523 
524   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
525 
526   if (Subtarget->hasNEON()) {
527     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528     // silliness like this:
529     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
554 
555     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
560 
561     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
562 
563     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564     // elements smaller than i32, so promote the input to i32 first.
565     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
569     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570     // -> v8f16 conversions.
571     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
575     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
580     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
581     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
584 
585     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
586     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
587 
588     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
589     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
590     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
591     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
592     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
593     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
594     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
595     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
596 
597     // AArch64 doesn't have MUL.2d:
598     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
599     // Custom handling for some quad-vector types to detect MULL.
600     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
601     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
602     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
603 
604     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
605     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
606     // Likewise, narrowing and extending vector loads/stores aren't handled
607     // directly.
608     for (MVT VT : MVT::vector_valuetypes()) {
609       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
610 
611       setOperationAction(ISD::MULHS, VT, Expand);
612       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
613       setOperationAction(ISD::MULHU, VT, Expand);
614       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
615 
616       setOperationAction(ISD::BSWAP, VT, Expand);
617 
618       for (MVT InnerVT : MVT::vector_valuetypes()) {
619         setTruncStoreAction(VT, InnerVT, Expand);
620         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
621         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
622         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
623       }
624     }
625 
626     // AArch64 has implementations of a lot of rounding-like FP operations.
627     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
628       setOperationAction(ISD::FFLOOR, Ty, Legal);
629       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
630       setOperationAction(ISD::FCEIL, Ty, Legal);
631       setOperationAction(ISD::FRINT, Ty, Legal);
632       setOperationAction(ISD::FTRUNC, Ty, Legal);
633       setOperationAction(ISD::FROUND, Ty, Legal);
634     }
635   }
636 
637   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
638 }
639 
640 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
641   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
642     setOperationAction(ISD::LOAD, VT, Promote);
643     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
644 
645     setOperationAction(ISD::STORE, VT, Promote);
646     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
647   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
648     setOperationAction(ISD::LOAD, VT, Promote);
649     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
650 
651     setOperationAction(ISD::STORE, VT, Promote);
652     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
653   }
654 
655   // Mark vector float intrinsics as expand.
656   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
657     setOperationAction(ISD::FSIN, VT, Expand);
658     setOperationAction(ISD::FCOS, VT, Expand);
659     setOperationAction(ISD::FPOWI, VT, Expand);
660     setOperationAction(ISD::FPOW, VT, Expand);
661     setOperationAction(ISD::FLOG, VT, Expand);
662     setOperationAction(ISD::FLOG2, VT, Expand);
663     setOperationAction(ISD::FLOG10, VT, Expand);
664     setOperationAction(ISD::FEXP, VT, Expand);
665     setOperationAction(ISD::FEXP2, VT, Expand);
666 
667     // But we do support custom-lowering for FCOPYSIGN.
668     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
669   }
670 
671   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
672   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
673   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
674   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
675   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
676   setOperationAction(ISD::SRA, VT, Custom);
677   setOperationAction(ISD::SRL, VT, Custom);
678   setOperationAction(ISD::SHL, VT, Custom);
679   setOperationAction(ISD::AND, VT, Custom);
680   setOperationAction(ISD::OR, VT, Custom);
681   setOperationAction(ISD::SETCC, VT, Custom);
682   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
683 
684   setOperationAction(ISD::SELECT, VT, Expand);
685   setOperationAction(ISD::SELECT_CC, VT, Expand);
686   setOperationAction(ISD::VSELECT, VT, Expand);
687   for (MVT InnerVT : MVT::all_valuetypes())
688     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
689 
690   // CNT supports only B element sizes.
691   if (VT != MVT::v8i8 && VT != MVT::v16i8)
692     setOperationAction(ISD::CTPOP, VT, Expand);
693 
694   setOperationAction(ISD::UDIV, VT, Expand);
695   setOperationAction(ISD::SDIV, VT, Expand);
696   setOperationAction(ISD::UREM, VT, Expand);
697   setOperationAction(ISD::SREM, VT, Expand);
698   setOperationAction(ISD::FREM, VT, Expand);
699 
700   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
701   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
702 
703   // [SU][MIN|MAX] are available for all NEON types apart from i64.
704   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
705     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
706       setOperationAction(Opcode, VT, Legal);
707 
708   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
709   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
710     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
711                             ISD::FMINNUM, ISD::FMAXNUM})
712       setOperationAction(Opcode, VT, Legal);
713 
714   if (Subtarget->isLittleEndian()) {
715     for (unsigned im = (unsigned)ISD::PRE_INC;
716          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
717       setIndexedLoadAction(im, VT, Legal);
718       setIndexedStoreAction(im, VT, Legal);
719     }
720   }
721 }
722 
723 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
724   addRegisterClass(VT, &AArch64::FPR64RegClass);
725   addTypeForNEON(VT, MVT::v2i32);
726 }
727 
728 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
729   addRegisterClass(VT, &AArch64::FPR128RegClass);
730   addTypeForNEON(VT, MVT::v4i32);
731 }
732 
733 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
734                                               EVT VT) const {
735   if (!VT.isVector())
736     return MVT::i32;
737   return VT.changeVectorElementTypeToInteger();
738 }
739 
740 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
741 /// Mask are known to be either zero or one and return them in the
742 /// KnownZero/KnownOne bitsets.
743 void AArch64TargetLowering::computeKnownBitsForTargetNode(
744     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
745     const SelectionDAG &DAG, unsigned Depth) const {
746   switch (Op.getOpcode()) {
747   default:
748     break;
749   case AArch64ISD::CSEL: {
750     APInt KnownZero2, KnownOne2;
751     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
752     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
753     KnownZero &= KnownZero2;
754     KnownOne &= KnownOne2;
755     break;
756   }
757   case ISD::INTRINSIC_W_CHAIN: {
758     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
759     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
760     switch (IntID) {
761     default: return;
762     case Intrinsic::aarch64_ldaxr:
763     case Intrinsic::aarch64_ldxr: {
764       unsigned BitWidth = KnownOne.getBitWidth();
765       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
766       unsigned MemBits = VT.getScalarSizeInBits();
767       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
768       return;
769     }
770     }
771     break;
772   }
773   case ISD::INTRINSIC_WO_CHAIN:
774   case ISD::INTRINSIC_VOID: {
775     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
776     switch (IntNo) {
777     default:
778       break;
779     case Intrinsic::aarch64_neon_umaxv:
780     case Intrinsic::aarch64_neon_uminv: {
781       // Figure out the datatype of the vector operand. The UMINV instruction
782       // will zero extend the result, so we can mark as known zero all the
783       // bits larger than the element datatype. 32-bit or larget doesn't need
784       // this as those are legal types and will be handled by isel directly.
785       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
786       unsigned BitWidth = KnownZero.getBitWidth();
787       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
788         assert(BitWidth >= 8 && "Unexpected width!");
789         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
790         KnownZero |= Mask;
791       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
792         assert(BitWidth >= 16 && "Unexpected width!");
793         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
794         KnownZero |= Mask;
795       }
796       break;
797     } break;
798     }
799   }
800   }
801 }
802 
803 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
804                                                   EVT) const {
805   return MVT::i64;
806 }
807 
808 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
809                                                            unsigned AddrSpace,
810                                                            unsigned Align,
811                                                            bool *Fast) const {
812   if (Subtarget->requiresStrictAlign())
813     return false;
814 
815   if (Fast) {
816     // Some CPUs are fine with unaligned stores except for 128-bit ones.
817     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
818             // See comments in performSTORECombine() for more details about
819             // these conditions.
820 
821             // Code that uses clang vector extensions can mark that it
822             // wants unaligned accesses to be treated as fast by
823             // underspecifying alignment to be 1 or 2.
824             Align <= 2 ||
825 
826             // Disregard v2i64. Memcpy lowering produces those and splitting
827             // them regresses performance on micro-benchmarks and olden/bh.
828             VT == MVT::v2i64;
829   }
830   return true;
831 }
832 
833 FastISel *
834 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
835                                       const TargetLibraryInfo *libInfo) const {
836   return AArch64::createFastISel(funcInfo, libInfo);
837 }
838 
839 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
840   switch ((AArch64ISD::NodeType)Opcode) {
841   case AArch64ISD::FIRST_NUMBER:      break;
842   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
843   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
844   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
845   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
846   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
847   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
848   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
849   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
850   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
851   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
852   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
853   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
854   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
855   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
856   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
857   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
858   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
859   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
860   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
861   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
862   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
863   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
864   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
865   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
866   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
867   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
868   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
869   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
870   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
871   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
872   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
873   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
874   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
875   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
876   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
877   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
878   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
879   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
880   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
881   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
882   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
883   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
884   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
885   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
886   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
887   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
888   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
889   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
890   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
891   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
892   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
893   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
894   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
895   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
896   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
897   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
898   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
899   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
900   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
901   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
902   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
903   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
904   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
905   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
906   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
907   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
908   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
909   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
910   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
911   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
912   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
913   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
914   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
915   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
916   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
917   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
918   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
919   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
920   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
921   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
922   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
923   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
924   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
925   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
926   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
927   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
928   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
929   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
930   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
931   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
932   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
933   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
934   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
935   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
936   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
937   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
938   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
939   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
940   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
941   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
942   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
943   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
944   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
945   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
946   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
947   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
948   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
949   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
950   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
951   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
952   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
953   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
954   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
955   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
956   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
957   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
958   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
959   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
960   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
961   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
962   }
963   return nullptr;
964 }
965 
966 MachineBasicBlock *
967 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
968                                     MachineBasicBlock *MBB) const {
969   // We materialise the F128CSEL pseudo-instruction as some control flow and a
970   // phi node:
971 
972   // OrigBB:
973   //     [... previous instrs leading to comparison ...]
974   //     b.ne TrueBB
975   //     b EndBB
976   // TrueBB:
977   //     ; Fallthrough
978   // EndBB:
979   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
980 
981   MachineFunction *MF = MBB->getParent();
982   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
983   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
984   DebugLoc DL = MI.getDebugLoc();
985   MachineFunction::iterator It = ++MBB->getIterator();
986 
987   unsigned DestReg = MI.getOperand(0).getReg();
988   unsigned IfTrueReg = MI.getOperand(1).getReg();
989   unsigned IfFalseReg = MI.getOperand(2).getReg();
990   unsigned CondCode = MI.getOperand(3).getImm();
991   bool NZCVKilled = MI.getOperand(4).isKill();
992 
993   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
994   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
995   MF->insert(It, TrueBB);
996   MF->insert(It, EndBB);
997 
998   // Transfer rest of current basic-block to EndBB
999   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1000                 MBB->end());
1001   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1002 
1003   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1004   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1005   MBB->addSuccessor(TrueBB);
1006   MBB->addSuccessor(EndBB);
1007 
1008   // TrueBB falls through to the end.
1009   TrueBB->addSuccessor(EndBB);
1010 
1011   if (!NZCVKilled) {
1012     TrueBB->addLiveIn(AArch64::NZCV);
1013     EndBB->addLiveIn(AArch64::NZCV);
1014   }
1015 
1016   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1017       .addReg(IfTrueReg)
1018       .addMBB(TrueBB)
1019       .addReg(IfFalseReg)
1020       .addMBB(MBB);
1021 
1022   MI.eraseFromParent();
1023   return EndBB;
1024 }
1025 
1026 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1027     MachineInstr &MI, MachineBasicBlock *BB) const {
1028   switch (MI.getOpcode()) {
1029   default:
1030 #ifndef NDEBUG
1031     MI.dump();
1032 #endif
1033     llvm_unreachable("Unexpected instruction for custom inserter!");
1034 
1035   case AArch64::F128CSEL:
1036     return EmitF128CSEL(MI, BB);
1037 
1038   case TargetOpcode::STACKMAP:
1039   case TargetOpcode::PATCHPOINT:
1040     return emitPatchPoint(MI, BB);
1041   }
1042 }
1043 
1044 //===----------------------------------------------------------------------===//
1045 // AArch64 Lowering private implementation.
1046 //===----------------------------------------------------------------------===//
1047 
1048 //===----------------------------------------------------------------------===//
1049 // Lowering Code
1050 //===----------------------------------------------------------------------===//
1051 
1052 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1053 /// CC
1054 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1055   switch (CC) {
1056   default:
1057     llvm_unreachable("Unknown condition code!");
1058   case ISD::SETNE:
1059     return AArch64CC::NE;
1060   case ISD::SETEQ:
1061     return AArch64CC::EQ;
1062   case ISD::SETGT:
1063     return AArch64CC::GT;
1064   case ISD::SETGE:
1065     return AArch64CC::GE;
1066   case ISD::SETLT:
1067     return AArch64CC::LT;
1068   case ISD::SETLE:
1069     return AArch64CC::LE;
1070   case ISD::SETUGT:
1071     return AArch64CC::HI;
1072   case ISD::SETUGE:
1073     return AArch64CC::HS;
1074   case ISD::SETULT:
1075     return AArch64CC::LO;
1076   case ISD::SETULE:
1077     return AArch64CC::LS;
1078   }
1079 }
1080 
1081 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1082 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1083                                   AArch64CC::CondCode &CondCode,
1084                                   AArch64CC::CondCode &CondCode2) {
1085   CondCode2 = AArch64CC::AL;
1086   switch (CC) {
1087   default:
1088     llvm_unreachable("Unknown FP condition!");
1089   case ISD::SETEQ:
1090   case ISD::SETOEQ:
1091     CondCode = AArch64CC::EQ;
1092     break;
1093   case ISD::SETGT:
1094   case ISD::SETOGT:
1095     CondCode = AArch64CC::GT;
1096     break;
1097   case ISD::SETGE:
1098   case ISD::SETOGE:
1099     CondCode = AArch64CC::GE;
1100     break;
1101   case ISD::SETOLT:
1102     CondCode = AArch64CC::MI;
1103     break;
1104   case ISD::SETOLE:
1105     CondCode = AArch64CC::LS;
1106     break;
1107   case ISD::SETONE:
1108     CondCode = AArch64CC::MI;
1109     CondCode2 = AArch64CC::GT;
1110     break;
1111   case ISD::SETO:
1112     CondCode = AArch64CC::VC;
1113     break;
1114   case ISD::SETUO:
1115     CondCode = AArch64CC::VS;
1116     break;
1117   case ISD::SETUEQ:
1118     CondCode = AArch64CC::EQ;
1119     CondCode2 = AArch64CC::VS;
1120     break;
1121   case ISD::SETUGT:
1122     CondCode = AArch64CC::HI;
1123     break;
1124   case ISD::SETUGE:
1125     CondCode = AArch64CC::PL;
1126     break;
1127   case ISD::SETLT:
1128   case ISD::SETULT:
1129     CondCode = AArch64CC::LT;
1130     break;
1131   case ISD::SETLE:
1132   case ISD::SETULE:
1133     CondCode = AArch64CC::LE;
1134     break;
1135   case ISD::SETNE:
1136   case ISD::SETUNE:
1137     CondCode = AArch64CC::NE;
1138     break;
1139   }
1140 }
1141 
1142 /// Convert a DAG fp condition code to an AArch64 CC.
1143 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1144 /// should be AND'ed instead of OR'ed.
1145 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1146                                      AArch64CC::CondCode &CondCode,
1147                                      AArch64CC::CondCode &CondCode2) {
1148   CondCode2 = AArch64CC::AL;
1149   switch (CC) {
1150   default:
1151     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1152     assert(CondCode2 == AArch64CC::AL);
1153     break;
1154   case ISD::SETONE:
1155     // (a one b)
1156     // == ((a olt b) || (a ogt b))
1157     // == ((a ord b) && (a une b))
1158     CondCode = AArch64CC::VC;
1159     CondCode2 = AArch64CC::NE;
1160     break;
1161   case ISD::SETUEQ:
1162     // (a ueq b)
1163     // == ((a uno b) || (a oeq b))
1164     // == ((a ule b) && (a uge b))
1165     CondCode = AArch64CC::PL;
1166     CondCode2 = AArch64CC::LE;
1167     break;
1168   }
1169 }
1170 
1171 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1172 /// CC usable with the vector instructions. Fewer operations are available
1173 /// without a real NZCV register, so we have to use less efficient combinations
1174 /// to get the same effect.
1175 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1176                                         AArch64CC::CondCode &CondCode,
1177                                         AArch64CC::CondCode &CondCode2,
1178                                         bool &Invert) {
1179   Invert = false;
1180   switch (CC) {
1181   default:
1182     // Mostly the scalar mappings work fine.
1183     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1184     break;
1185   case ISD::SETUO:
1186     Invert = true;
1187     LLVM_FALLTHROUGH;
1188   case ISD::SETO:
1189     CondCode = AArch64CC::MI;
1190     CondCode2 = AArch64CC::GE;
1191     break;
1192   case ISD::SETUEQ:
1193   case ISD::SETULT:
1194   case ISD::SETULE:
1195   case ISD::SETUGT:
1196   case ISD::SETUGE:
1197     // All of the compare-mask comparisons are ordered, but we can switch
1198     // between the two by a double inversion. E.g. ULE == !OGT.
1199     Invert = true;
1200     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1201     break;
1202   }
1203 }
1204 
1205 static bool isLegalArithImmed(uint64_t C) {
1206   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1207   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1208 }
1209 
1210 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1211                               const SDLoc &dl, SelectionDAG &DAG) {
1212   EVT VT = LHS.getValueType();
1213 
1214   if (VT.isFloatingPoint()) {
1215     assert(VT != MVT::f128);
1216     if (VT == MVT::f16) {
1217       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1218       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1219       VT = MVT::f32;
1220     }
1221     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1222   }
1223 
1224   // The CMP instruction is just an alias for SUBS, and representing it as
1225   // SUBS means that it's possible to get CSE with subtract operations.
1226   // A later phase can perform the optimization of setting the destination
1227   // register to WZR/XZR if it ends up being unused.
1228   unsigned Opcode = AArch64ISD::SUBS;
1229 
1230   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1231       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1232     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1233     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1234     // can be set differently by this operation. It comes down to whether
1235     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1236     // everything is fine. If not then the optimization is wrong. Thus general
1237     // comparisons are only valid if op2 != 0.
1238 
1239     // So, finally, the only LLVM-native comparisons that don't mention C and V
1240     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1241     // the absence of information about op2.
1242     Opcode = AArch64ISD::ADDS;
1243     RHS = RHS.getOperand(1);
1244   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1245              !isUnsignedIntSetCC(CC)) {
1246     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1247     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1248     // of the signed comparisons.
1249     Opcode = AArch64ISD::ANDS;
1250     RHS = LHS.getOperand(1);
1251     LHS = LHS.getOperand(0);
1252   }
1253 
1254   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1255       .getValue(1);
1256 }
1257 
1258 /// \defgroup AArch64CCMP CMP;CCMP matching
1259 ///
1260 /// These functions deal with the formation of CMP;CCMP;... sequences.
1261 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1262 /// a comparison. They set the NZCV flags to a predefined value if their
1263 /// predicate is false. This allows to express arbitrary conjunctions, for
1264 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1265 /// expressed as:
1266 ///   cmp A
1267 ///   ccmp B, inv(CB), CA
1268 ///   check for CB flags
1269 ///
1270 /// In general we can create code for arbitrary "... (and (and A B) C)"
1271 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1272 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1273 /// negation operations:
1274 /// We can negate the results of a single comparison by inverting the flags
1275 /// used when the predicate fails and inverting the flags tested in the next
1276 /// instruction; We can also negate the results of the whole previous
1277 /// conditional compare sequence by inverting the flags tested in the next
1278 /// instruction. However there is no way to negate the result of a partial
1279 /// sequence.
1280 ///
1281 /// Therefore on encountering an "or" expression we can negate the subtree on
1282 /// one side and have to be able to push the negate to the leafs of the subtree
1283 /// on the other side (see also the comments in code). As complete example:
1284 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1285 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1286 /// is transformed to
1287 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1288 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1289 /// and implemented as:
1290 ///   cmp C
1291 ///   ccmp D, inv(CD), CC
1292 ///   ccmp A, CA, inv(CD)
1293 ///   ccmp B, CB, inv(CA)
1294 ///   check for CB flags
1295 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1296 /// by conditional compare sequences.
1297 /// @{
1298 
1299 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1300 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1301                                          ISD::CondCode CC, SDValue CCOp,
1302                                          AArch64CC::CondCode Predicate,
1303                                          AArch64CC::CondCode OutCC,
1304                                          const SDLoc &DL, SelectionDAG &DAG) {
1305   unsigned Opcode = 0;
1306   if (LHS.getValueType().isFloatingPoint()) {
1307     assert(LHS.getValueType() != MVT::f128);
1308     if (LHS.getValueType() == MVT::f16) {
1309       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1310       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1311     }
1312     Opcode = AArch64ISD::FCCMP;
1313   } else if (RHS.getOpcode() == ISD::SUB) {
1314     SDValue SubOp0 = RHS.getOperand(0);
1315     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1316       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1317       Opcode = AArch64ISD::CCMN;
1318       RHS = RHS.getOperand(1);
1319     }
1320   }
1321   if (Opcode == 0)
1322     Opcode = AArch64ISD::CCMP;
1323 
1324   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1325   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1326   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1327   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1328   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1329 }
1330 
1331 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1332 /// CanPushNegate is set to true if we can push a negate operation through
1333 /// the tree in a was that we are left with AND operations and negate operations
1334 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1335 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1336 /// brought into such a form.
1337 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1338                                          unsigned Depth = 0) {
1339   if (!Val.hasOneUse())
1340     return false;
1341   unsigned Opcode = Val->getOpcode();
1342   if (Opcode == ISD::SETCC) {
1343     if (Val->getOperand(0).getValueType() == MVT::f128)
1344       return false;
1345     CanNegate = true;
1346     return true;
1347   }
1348   // Protect against exponential runtime and stack overflow.
1349   if (Depth > 6)
1350     return false;
1351   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1352     SDValue O0 = Val->getOperand(0);
1353     SDValue O1 = Val->getOperand(1);
1354     bool CanNegateL;
1355     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1356       return false;
1357     bool CanNegateR;
1358     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1359       return false;
1360 
1361     if (Opcode == ISD::OR) {
1362       // For an OR expression we need to be able to negate at least one side or
1363       // we cannot do the transformation at all.
1364       if (!CanNegateL && !CanNegateR)
1365         return false;
1366       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1367       // can negate the x and y subtrees.
1368       CanNegate = CanNegateL && CanNegateR;
1369     } else {
1370       // If the operands are OR expressions then we finally need to negate their
1371       // outputs, we can only do that for the operand with emitted last by
1372       // negating OutCC, not for both operands.
1373       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1374       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1375       if (NeedsNegOutL && NeedsNegOutR)
1376         return false;
1377       // We cannot negate an AND operation (it would become an OR),
1378       CanNegate = false;
1379     }
1380     return true;
1381   }
1382   return false;
1383 }
1384 
1385 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1386 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1387 /// Tries to transform the given i1 producing node @p Val to a series compare
1388 /// and conditional compare operations. @returns an NZCV flags producing node
1389 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1390 /// transformation was not possible.
1391 /// On recursive invocations @p PushNegate may be set to true to have negation
1392 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1393 /// for the comparisons in the current subtree; @p Depth limits the search
1394 /// depth to avoid stack overflow.
1395 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1396     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1397     AArch64CC::CondCode Predicate) {
1398   // We're at a tree leaf, produce a conditional comparison operation.
1399   unsigned Opcode = Val->getOpcode();
1400   if (Opcode == ISD::SETCC) {
1401     SDValue LHS = Val->getOperand(0);
1402     SDValue RHS = Val->getOperand(1);
1403     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1404     bool isInteger = LHS.getValueType().isInteger();
1405     if (Negate)
1406       CC = getSetCCInverse(CC, isInteger);
1407     SDLoc DL(Val);
1408     // Determine OutCC and handle FP special case.
1409     if (isInteger) {
1410       OutCC = changeIntCCToAArch64CC(CC);
1411     } else {
1412       assert(LHS.getValueType().isFloatingPoint());
1413       AArch64CC::CondCode ExtraCC;
1414       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1415       // Some floating point conditions can't be tested with a single condition
1416       // code. Construct an additional comparison in this case.
1417       if (ExtraCC != AArch64CC::AL) {
1418         SDValue ExtraCmp;
1419         if (!CCOp.getNode())
1420           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1421         else
1422           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1423                                                ExtraCC, DL, DAG);
1424         CCOp = ExtraCmp;
1425         Predicate = ExtraCC;
1426       }
1427     }
1428 
1429     // Produce a normal comparison if we are first in the chain
1430     if (!CCOp)
1431       return emitComparison(LHS, RHS, CC, DL, DAG);
1432     // Otherwise produce a ccmp.
1433     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1434                                      DAG);
1435   }
1436   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1437          "Valid conjunction/disjunction tree");
1438 
1439   // Check if both sides can be transformed.
1440   SDValue LHS = Val->getOperand(0);
1441   SDValue RHS = Val->getOperand(1);
1442 
1443   // In case of an OR we need to negate our operands and the result.
1444   // (A v B) <=> not(not(A) ^ not(B))
1445   bool NegateOpsAndResult = Opcode == ISD::OR;
1446   // We can negate the results of all previous operations by inverting the
1447   // predicate flags giving us a free negation for one side. The other side
1448   // must be negatable by itself.
1449   if (NegateOpsAndResult) {
1450     // See which side we can negate.
1451     bool CanNegateL;
1452     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1453     assert(isValidL && "Valid conjunction/disjunction tree");
1454     (void)isValidL;
1455 
1456 #ifndef NDEBUG
1457     bool CanNegateR;
1458     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1459     assert(isValidR && "Valid conjunction/disjunction tree");
1460     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1461 #endif
1462 
1463     // Order the side which we cannot negate to RHS so we can emit it first.
1464     if (!CanNegateL)
1465       std::swap(LHS, RHS);
1466   } else {
1467     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1468     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1469            "Valid conjunction/disjunction tree");
1470     // Order the side where we need to negate the output flags to RHS so it
1471     // gets emitted first.
1472     if (NeedsNegOutL)
1473       std::swap(LHS, RHS);
1474   }
1475 
1476   // Emit RHS. If we want to negate the tree we only need to push a negate
1477   // through if we are already in a PushNegate case, otherwise we can negate
1478   // the "flags to test" afterwards.
1479   AArch64CC::CondCode RHSCC;
1480   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1481                                                    CCOp, Predicate);
1482   if (NegateOpsAndResult && !Negate)
1483     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1484   // Emit LHS. We may need to negate it.
1485   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1486                                                    NegateOpsAndResult, CmpR,
1487                                                    RHSCC);
1488   // If we transformed an OR to and AND then we have to negate the result
1489   // (or absorb the Negate parameter).
1490   if (NegateOpsAndResult && !Negate)
1491     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1492   return CmpL;
1493 }
1494 
1495 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1496 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1497 /// \see emitConjunctionDisjunctionTreeRec().
1498 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1499                                               AArch64CC::CondCode &OutCC) {
1500   bool CanNegate;
1501   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1502     return SDValue();
1503 
1504   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1505                                            AArch64CC::AL);
1506 }
1507 
1508 /// @}
1509 
1510 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1511                              SDValue &AArch64cc, SelectionDAG &DAG,
1512                              const SDLoc &dl) {
1513   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1514     EVT VT = RHS.getValueType();
1515     uint64_t C = RHSC->getZExtValue();
1516     if (!isLegalArithImmed(C)) {
1517       // Constant does not fit, try adjusting it by one?
1518       switch (CC) {
1519       default:
1520         break;
1521       case ISD::SETLT:
1522       case ISD::SETGE:
1523         if ((VT == MVT::i32 && C != 0x80000000 &&
1524              isLegalArithImmed((uint32_t)(C - 1))) ||
1525             (VT == MVT::i64 && C != 0x80000000ULL &&
1526              isLegalArithImmed(C - 1ULL))) {
1527           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1528           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1529           RHS = DAG.getConstant(C, dl, VT);
1530         }
1531         break;
1532       case ISD::SETULT:
1533       case ISD::SETUGE:
1534         if ((VT == MVT::i32 && C != 0 &&
1535              isLegalArithImmed((uint32_t)(C - 1))) ||
1536             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1537           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1538           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1539           RHS = DAG.getConstant(C, dl, VT);
1540         }
1541         break;
1542       case ISD::SETLE:
1543       case ISD::SETGT:
1544         if ((VT == MVT::i32 && C != INT32_MAX &&
1545              isLegalArithImmed((uint32_t)(C + 1))) ||
1546             (VT == MVT::i64 && C != INT64_MAX &&
1547              isLegalArithImmed(C + 1ULL))) {
1548           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1549           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1550           RHS = DAG.getConstant(C, dl, VT);
1551         }
1552         break;
1553       case ISD::SETULE:
1554       case ISD::SETUGT:
1555         if ((VT == MVT::i32 && C != UINT32_MAX &&
1556              isLegalArithImmed((uint32_t)(C + 1))) ||
1557             (VT == MVT::i64 && C != UINT64_MAX &&
1558              isLegalArithImmed(C + 1ULL))) {
1559           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1560           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1561           RHS = DAG.getConstant(C, dl, VT);
1562         }
1563         break;
1564       }
1565     }
1566   }
1567   SDValue Cmp;
1568   AArch64CC::CondCode AArch64CC;
1569   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1570     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1571 
1572     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1573     // For the i8 operand, the largest immediate is 255, so this can be easily
1574     // encoded in the compare instruction. For the i16 operand, however, the
1575     // largest immediate cannot be encoded in the compare.
1576     // Therefore, use a sign extending load and cmn to avoid materializing the
1577     // -1 constant. For example,
1578     // movz w1, #65535
1579     // ldrh w0, [x0, #0]
1580     // cmp w0, w1
1581     // >
1582     // ldrsh w0, [x0, #0]
1583     // cmn w0, #1
1584     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1585     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1586     // ensure both the LHS and RHS are truly zero extended and to make sure the
1587     // transformation is profitable.
1588     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1589         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1590         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1591         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1592       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1593       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1594         SDValue SExt =
1595             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1596                         DAG.getValueType(MVT::i16));
1597         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1598                                                    RHS.getValueType()),
1599                              CC, dl, DAG);
1600         AArch64CC = changeIntCCToAArch64CC(CC);
1601       }
1602     }
1603 
1604     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1605       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1606         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1607           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1608       }
1609     }
1610   }
1611 
1612   if (!Cmp) {
1613     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1614     AArch64CC = changeIntCCToAArch64CC(CC);
1615   }
1616   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1617   return Cmp;
1618 }
1619 
1620 static std::pair<SDValue, SDValue>
1621 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1622   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1623          "Unsupported value type");
1624   SDValue Value, Overflow;
1625   SDLoc DL(Op);
1626   SDValue LHS = Op.getOperand(0);
1627   SDValue RHS = Op.getOperand(1);
1628   unsigned Opc = 0;
1629   switch (Op.getOpcode()) {
1630   default:
1631     llvm_unreachable("Unknown overflow instruction!");
1632   case ISD::SADDO:
1633     Opc = AArch64ISD::ADDS;
1634     CC = AArch64CC::VS;
1635     break;
1636   case ISD::UADDO:
1637     Opc = AArch64ISD::ADDS;
1638     CC = AArch64CC::HS;
1639     break;
1640   case ISD::SSUBO:
1641     Opc = AArch64ISD::SUBS;
1642     CC = AArch64CC::VS;
1643     break;
1644   case ISD::USUBO:
1645     Opc = AArch64ISD::SUBS;
1646     CC = AArch64CC::LO;
1647     break;
1648   // Multiply needs a little bit extra work.
1649   case ISD::SMULO:
1650   case ISD::UMULO: {
1651     CC = AArch64CC::NE;
1652     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1653     if (Op.getValueType() == MVT::i32) {
1654       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1655       // For a 32 bit multiply with overflow check we want the instruction
1656       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1657       // need to generate the following pattern:
1658       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1659       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1660       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1661       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1662       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1663                                 DAG.getConstant(0, DL, MVT::i64));
1664       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1665       // operation. We need to clear out the upper 32 bits, because we used a
1666       // widening multiply that wrote all 64 bits. In the end this should be a
1667       // noop.
1668       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1669       if (IsSigned) {
1670         // The signed overflow check requires more than just a simple check for
1671         // any bit set in the upper 32 bits of the result. These bits could be
1672         // just the sign bits of a negative number. To perform the overflow
1673         // check we have to arithmetic shift right the 32nd bit of the result by
1674         // 31 bits. Then we compare the result to the upper 32 bits.
1675         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1676                                         DAG.getConstant(32, DL, MVT::i64));
1677         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1678         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1679                                         DAG.getConstant(31, DL, MVT::i64));
1680         // It is important that LowerBits is last, otherwise the arithmetic
1681         // shift will not be folded into the compare (SUBS).
1682         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1683         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1684                        .getValue(1);
1685       } else {
1686         // The overflow check for unsigned multiply is easy. We only need to
1687         // check if any of the upper 32 bits are set. This can be done with a
1688         // CMP (shifted register). For that we need to generate the following
1689         // pattern:
1690         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1691         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1692                                         DAG.getConstant(32, DL, MVT::i64));
1693         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1694         Overflow =
1695             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1696                         DAG.getConstant(0, DL, MVT::i64),
1697                         UpperBits).getValue(1);
1698       }
1699       break;
1700     }
1701     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1702     // For the 64 bit multiply
1703     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1704     if (IsSigned) {
1705       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1706       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1707                                       DAG.getConstant(63, DL, MVT::i64));
1708       // It is important that LowerBits is last, otherwise the arithmetic
1709       // shift will not be folded into the compare (SUBS).
1710       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1711       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1712                      .getValue(1);
1713     } else {
1714       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1715       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1716       Overflow =
1717           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1718                       DAG.getConstant(0, DL, MVT::i64),
1719                       UpperBits).getValue(1);
1720     }
1721     break;
1722   }
1723   } // switch (...)
1724 
1725   if (Opc) {
1726     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1727 
1728     // Emit the AArch64 operation with overflow check.
1729     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1730     Overflow = Value.getValue(1);
1731   }
1732   return std::make_pair(Value, Overflow);
1733 }
1734 
1735 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1736                                              RTLIB::Libcall Call) const {
1737   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1738   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1739 }
1740 
1741 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1742   SDValue Sel = Op.getOperand(0);
1743   SDValue Other = Op.getOperand(1);
1744 
1745   // If neither operand is a SELECT_CC, give up.
1746   if (Sel.getOpcode() != ISD::SELECT_CC)
1747     std::swap(Sel, Other);
1748   if (Sel.getOpcode() != ISD::SELECT_CC)
1749     return Op;
1750 
1751   // The folding we want to perform is:
1752   // (xor x, (select_cc a, b, cc, 0, -1) )
1753   //   -->
1754   // (csel x, (xor x, -1), cc ...)
1755   //
1756   // The latter will get matched to a CSINV instruction.
1757 
1758   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1759   SDValue LHS = Sel.getOperand(0);
1760   SDValue RHS = Sel.getOperand(1);
1761   SDValue TVal = Sel.getOperand(2);
1762   SDValue FVal = Sel.getOperand(3);
1763   SDLoc dl(Sel);
1764 
1765   // FIXME: This could be generalized to non-integer comparisons.
1766   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1767     return Op;
1768 
1769   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1770   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1771 
1772   // The values aren't constants, this isn't the pattern we're looking for.
1773   if (!CFVal || !CTVal)
1774     return Op;
1775 
1776   // We can commute the SELECT_CC by inverting the condition.  This
1777   // might be needed to make this fit into a CSINV pattern.
1778   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1779     std::swap(TVal, FVal);
1780     std::swap(CTVal, CFVal);
1781     CC = ISD::getSetCCInverse(CC, true);
1782   }
1783 
1784   // If the constants line up, perform the transform!
1785   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1786     SDValue CCVal;
1787     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1788 
1789     FVal = Other;
1790     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1791                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1792 
1793     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1794                        CCVal, Cmp);
1795   }
1796 
1797   return Op;
1798 }
1799 
1800 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1801   EVT VT = Op.getValueType();
1802 
1803   // Let legalize expand this if it isn't a legal type yet.
1804   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1805     return SDValue();
1806 
1807   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1808 
1809   unsigned Opc;
1810   bool ExtraOp = false;
1811   switch (Op.getOpcode()) {
1812   default:
1813     llvm_unreachable("Invalid code");
1814   case ISD::ADDC:
1815     Opc = AArch64ISD::ADDS;
1816     break;
1817   case ISD::SUBC:
1818     Opc = AArch64ISD::SUBS;
1819     break;
1820   case ISD::ADDE:
1821     Opc = AArch64ISD::ADCS;
1822     ExtraOp = true;
1823     break;
1824   case ISD::SUBE:
1825     Opc = AArch64ISD::SBCS;
1826     ExtraOp = true;
1827     break;
1828   }
1829 
1830   if (!ExtraOp)
1831     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1832   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1833                      Op.getOperand(2));
1834 }
1835 
1836 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1837   // Let legalize expand this if it isn't a legal type yet.
1838   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1839     return SDValue();
1840 
1841   SDLoc dl(Op);
1842   AArch64CC::CondCode CC;
1843   // The actual operation that sets the overflow or carry flag.
1844   SDValue Value, Overflow;
1845   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1846 
1847   // We use 0 and 1 as false and true values.
1848   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1849   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1850 
1851   // We use an inverted condition, because the conditional select is inverted
1852   // too. This will allow it to be selected to a single instruction:
1853   // CSINC Wd, WZR, WZR, invert(cond).
1854   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1855   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1856                          CCVal, Overflow);
1857 
1858   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1859   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1860 }
1861 
1862 // Prefetch operands are:
1863 // 1: Address to prefetch
1864 // 2: bool isWrite
1865 // 3: int locality (0 = no locality ... 3 = extreme locality)
1866 // 4: bool isDataCache
1867 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1868   SDLoc DL(Op);
1869   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1870   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1871   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1872 
1873   bool IsStream = !Locality;
1874   // When the locality number is set
1875   if (Locality) {
1876     // The front-end should have filtered out the out-of-range values
1877     assert(Locality <= 3 && "Prefetch locality out-of-range");
1878     // The locality degree is the opposite of the cache speed.
1879     // Put the number the other way around.
1880     // The encoding starts at 0 for level 1
1881     Locality = 3 - Locality;
1882   }
1883 
1884   // built the mask value encoding the expected behavior.
1885   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1886                    (!IsData << 3) |     // IsDataCache bit
1887                    (Locality << 1) |    // Cache level bits
1888                    (unsigned)IsStream;  // Stream bit
1889   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1890                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1891 }
1892 
1893 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1894                                               SelectionDAG &DAG) const {
1895   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1896 
1897   RTLIB::Libcall LC;
1898   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1899 
1900   return LowerF128Call(Op, DAG, LC);
1901 }
1902 
1903 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1904                                              SelectionDAG &DAG) const {
1905   if (Op.getOperand(0).getValueType() != MVT::f128) {
1906     // It's legal except when f128 is involved
1907     return Op;
1908   }
1909 
1910   RTLIB::Libcall LC;
1911   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1912 
1913   // FP_ROUND node has a second operand indicating whether it is known to be
1914   // precise. That doesn't take part in the LibCall so we can't directly use
1915   // LowerF128Call.
1916   SDValue SrcVal = Op.getOperand(0);
1917   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1918                      SDLoc(Op)).first;
1919 }
1920 
1921 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1922   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1923   // Any additional optimization in this function should be recorded
1924   // in the cost tables.
1925   EVT InVT = Op.getOperand(0).getValueType();
1926   EVT VT = Op.getValueType();
1927   unsigned NumElts = InVT.getVectorNumElements();
1928 
1929   // f16 vectors are promoted to f32 before a conversion.
1930   if (InVT.getVectorElementType() == MVT::f16) {
1931     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1932     SDLoc dl(Op);
1933     return DAG.getNode(
1934         Op.getOpcode(), dl, Op.getValueType(),
1935         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1936   }
1937 
1938   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1939     SDLoc dl(Op);
1940     SDValue Cv =
1941         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1942                     Op.getOperand(0));
1943     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1944   }
1945 
1946   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1947     SDLoc dl(Op);
1948     MVT ExtVT =
1949         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1950                          VT.getVectorNumElements());
1951     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1952     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1953   }
1954 
1955   // Type changing conversions are illegal.
1956   return Op;
1957 }
1958 
1959 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1960                                               SelectionDAG &DAG) const {
1961   if (Op.getOperand(0).getValueType().isVector())
1962     return LowerVectorFP_TO_INT(Op, DAG);
1963 
1964   // f16 conversions are promoted to f32.
1965   if (Op.getOperand(0).getValueType() == MVT::f16) {
1966     SDLoc dl(Op);
1967     return DAG.getNode(
1968         Op.getOpcode(), dl, Op.getValueType(),
1969         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1970   }
1971 
1972   if (Op.getOperand(0).getValueType() != MVT::f128) {
1973     // It's legal except when f128 is involved
1974     return Op;
1975   }
1976 
1977   RTLIB::Libcall LC;
1978   if (Op.getOpcode() == ISD::FP_TO_SINT)
1979     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1980   else
1981     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1982 
1983   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1984   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1985 }
1986 
1987 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1988   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1989   // Any additional optimization in this function should be recorded
1990   // in the cost tables.
1991   EVT VT = Op.getValueType();
1992   SDLoc dl(Op);
1993   SDValue In = Op.getOperand(0);
1994   EVT InVT = In.getValueType();
1995 
1996   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1997     MVT CastVT =
1998         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1999                          InVT.getVectorNumElements());
2000     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2001     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2002   }
2003 
2004   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2005     unsigned CastOpc =
2006         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2007     EVT CastVT = VT.changeVectorElementTypeToInteger();
2008     In = DAG.getNode(CastOpc, dl, CastVT, In);
2009     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2010   }
2011 
2012   return Op;
2013 }
2014 
2015 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2016                                             SelectionDAG &DAG) const {
2017   if (Op.getValueType().isVector())
2018     return LowerVectorINT_TO_FP(Op, DAG);
2019 
2020   // f16 conversions are promoted to f32.
2021   if (Op.getValueType() == MVT::f16) {
2022     SDLoc dl(Op);
2023     return DAG.getNode(
2024         ISD::FP_ROUND, dl, MVT::f16,
2025         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2026         DAG.getIntPtrConstant(0, dl));
2027   }
2028 
2029   // i128 conversions are libcalls.
2030   if (Op.getOperand(0).getValueType() == MVT::i128)
2031     return SDValue();
2032 
2033   // Other conversions are legal, unless it's to the completely software-based
2034   // fp128.
2035   if (Op.getValueType() != MVT::f128)
2036     return Op;
2037 
2038   RTLIB::Libcall LC;
2039   if (Op.getOpcode() == ISD::SINT_TO_FP)
2040     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2041   else
2042     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2043 
2044   return LowerF128Call(Op, DAG, LC);
2045 }
2046 
2047 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2048                                             SelectionDAG &DAG) const {
2049   // For iOS, we want to call an alternative entry point: __sincos_stret,
2050   // which returns the values in two S / D registers.
2051   SDLoc dl(Op);
2052   SDValue Arg = Op.getOperand(0);
2053   EVT ArgVT = Arg.getValueType();
2054   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2055 
2056   ArgListTy Args;
2057   ArgListEntry Entry;
2058 
2059   Entry.Node = Arg;
2060   Entry.Ty = ArgTy;
2061   Entry.isSExt = false;
2062   Entry.isZExt = false;
2063   Args.push_back(Entry);
2064 
2065   const char *LibcallName =
2066       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2067   SDValue Callee =
2068       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2069 
2070   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2071   TargetLowering::CallLoweringInfo CLI(DAG);
2072   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2073     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2074 
2075   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2076   return CallResult.first;
2077 }
2078 
2079 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2080   if (Op.getValueType() != MVT::f16)
2081     return SDValue();
2082 
2083   assert(Op.getOperand(0).getValueType() == MVT::i16);
2084   SDLoc DL(Op);
2085 
2086   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2087   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2088   return SDValue(
2089       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2090                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2091       0);
2092 }
2093 
2094 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2095   if (OrigVT.getSizeInBits() >= 64)
2096     return OrigVT;
2097 
2098   assert(OrigVT.isSimple() && "Expecting a simple value type");
2099 
2100   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2101   switch (OrigSimpleTy) {
2102   default: llvm_unreachable("Unexpected Vector Type");
2103   case MVT::v2i8:
2104   case MVT::v2i16:
2105      return MVT::v2i32;
2106   case MVT::v4i8:
2107     return  MVT::v4i16;
2108   }
2109 }
2110 
2111 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2112                                                  const EVT &OrigTy,
2113                                                  const EVT &ExtTy,
2114                                                  unsigned ExtOpcode) {
2115   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2116   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2117   // 64-bits we need to insert a new extension so that it will be 64-bits.
2118   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2119   if (OrigTy.getSizeInBits() >= 64)
2120     return N;
2121 
2122   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2123   EVT NewVT = getExtensionTo64Bits(OrigTy);
2124 
2125   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2126 }
2127 
2128 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2129                                    bool isSigned) {
2130   EVT VT = N->getValueType(0);
2131 
2132   if (N->getOpcode() != ISD::BUILD_VECTOR)
2133     return false;
2134 
2135   for (const SDValue &Elt : N->op_values()) {
2136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2137       unsigned EltSize = VT.getScalarSizeInBits();
2138       unsigned HalfSize = EltSize / 2;
2139       if (isSigned) {
2140         if (!isIntN(HalfSize, C->getSExtValue()))
2141           return false;
2142       } else {
2143         if (!isUIntN(HalfSize, C->getZExtValue()))
2144           return false;
2145       }
2146       continue;
2147     }
2148     return false;
2149   }
2150 
2151   return true;
2152 }
2153 
2154 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2155   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2156     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2157                                              N->getOperand(0)->getValueType(0),
2158                                              N->getValueType(0),
2159                                              N->getOpcode());
2160 
2161   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2162   EVT VT = N->getValueType(0);
2163   SDLoc dl(N);
2164   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2165   unsigned NumElts = VT.getVectorNumElements();
2166   MVT TruncVT = MVT::getIntegerVT(EltSize);
2167   SmallVector<SDValue, 8> Ops;
2168   for (unsigned i = 0; i != NumElts; ++i) {
2169     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2170     const APInt &CInt = C->getAPIntValue();
2171     // Element types smaller than 32 bits are not legal, so use i32 elements.
2172     // The values are implicitly truncated so sext vs. zext doesn't matter.
2173     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2174   }
2175   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2176 }
2177 
2178 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2179   if (N->getOpcode() == ISD::SIGN_EXTEND)
2180     return true;
2181   if (isExtendedBUILD_VECTOR(N, DAG, true))
2182     return true;
2183   return false;
2184 }
2185 
2186 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2187   if (N->getOpcode() == ISD::ZERO_EXTEND)
2188     return true;
2189   if (isExtendedBUILD_VECTOR(N, DAG, false))
2190     return true;
2191   return false;
2192 }
2193 
2194 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2195   unsigned Opcode = N->getOpcode();
2196   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2197     SDNode *N0 = N->getOperand(0).getNode();
2198     SDNode *N1 = N->getOperand(1).getNode();
2199     return N0->hasOneUse() && N1->hasOneUse() &&
2200       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2201   }
2202   return false;
2203 }
2204 
2205 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2206   unsigned Opcode = N->getOpcode();
2207   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2208     SDNode *N0 = N->getOperand(0).getNode();
2209     SDNode *N1 = N->getOperand(1).getNode();
2210     return N0->hasOneUse() && N1->hasOneUse() &&
2211       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2212   }
2213   return false;
2214 }
2215 
2216 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2217   // Multiplications are only custom-lowered for 128-bit vectors so that
2218   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2219   EVT VT = Op.getValueType();
2220   assert(VT.is128BitVector() && VT.isInteger() &&
2221          "unexpected type for custom-lowering ISD::MUL");
2222   SDNode *N0 = Op.getOperand(0).getNode();
2223   SDNode *N1 = Op.getOperand(1).getNode();
2224   unsigned NewOpc = 0;
2225   bool isMLA = false;
2226   bool isN0SExt = isSignExtended(N0, DAG);
2227   bool isN1SExt = isSignExtended(N1, DAG);
2228   if (isN0SExt && isN1SExt)
2229     NewOpc = AArch64ISD::SMULL;
2230   else {
2231     bool isN0ZExt = isZeroExtended(N0, DAG);
2232     bool isN1ZExt = isZeroExtended(N1, DAG);
2233     if (isN0ZExt && isN1ZExt)
2234       NewOpc = AArch64ISD::UMULL;
2235     else if (isN1SExt || isN1ZExt) {
2236       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2237       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2238       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2239         NewOpc = AArch64ISD::SMULL;
2240         isMLA = true;
2241       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2242         NewOpc =  AArch64ISD::UMULL;
2243         isMLA = true;
2244       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2245         std::swap(N0, N1);
2246         NewOpc =  AArch64ISD::UMULL;
2247         isMLA = true;
2248       }
2249     }
2250 
2251     if (!NewOpc) {
2252       if (VT == MVT::v2i64)
2253         // Fall through to expand this.  It is not legal.
2254         return SDValue();
2255       else
2256         // Other vector multiplications are legal.
2257         return Op;
2258     }
2259   }
2260 
2261   // Legalize to a S/UMULL instruction
2262   SDLoc DL(Op);
2263   SDValue Op0;
2264   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2265   if (!isMLA) {
2266     Op0 = skipExtensionForVectorMULL(N0, DAG);
2267     assert(Op0.getValueType().is64BitVector() &&
2268            Op1.getValueType().is64BitVector() &&
2269            "unexpected types for extended operands to VMULL");
2270     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2271   }
2272   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2273   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2274   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2275   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2276   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2277   EVT Op1VT = Op1.getValueType();
2278   return DAG.getNode(N0->getOpcode(), DL, VT,
2279                      DAG.getNode(NewOpc, DL, VT,
2280                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2281                      DAG.getNode(NewOpc, DL, VT,
2282                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2283 }
2284 
2285 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2286                                                      SelectionDAG &DAG) const {
2287   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2288   SDLoc dl(Op);
2289   switch (IntNo) {
2290   default: return SDValue();    // Don't custom lower most intrinsics.
2291   case Intrinsic::thread_pointer: {
2292     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2293     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2294   }
2295   case Intrinsic::aarch64_neon_smax:
2296     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2297                        Op.getOperand(1), Op.getOperand(2));
2298   case Intrinsic::aarch64_neon_umax:
2299     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2300                        Op.getOperand(1), Op.getOperand(2));
2301   case Intrinsic::aarch64_neon_smin:
2302     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2303                        Op.getOperand(1), Op.getOperand(2));
2304   case Intrinsic::aarch64_neon_umin:
2305     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2306                        Op.getOperand(1), Op.getOperand(2));
2307   }
2308 }
2309 
2310 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2311                                               SelectionDAG &DAG) const {
2312   switch (Op.getOpcode()) {
2313   default:
2314     llvm_unreachable("unimplemented operand");
2315     return SDValue();
2316   case ISD::BITCAST:
2317     return LowerBITCAST(Op, DAG);
2318   case ISD::GlobalAddress:
2319     return LowerGlobalAddress(Op, DAG);
2320   case ISD::GlobalTLSAddress:
2321     return LowerGlobalTLSAddress(Op, DAG);
2322   case ISD::SETCC:
2323     return LowerSETCC(Op, DAG);
2324   case ISD::BR_CC:
2325     return LowerBR_CC(Op, DAG);
2326   case ISD::SELECT:
2327     return LowerSELECT(Op, DAG);
2328   case ISD::SELECT_CC:
2329     return LowerSELECT_CC(Op, DAG);
2330   case ISD::JumpTable:
2331     return LowerJumpTable(Op, DAG);
2332   case ISD::ConstantPool:
2333     return LowerConstantPool(Op, DAG);
2334   case ISD::BlockAddress:
2335     return LowerBlockAddress(Op, DAG);
2336   case ISD::VASTART:
2337     return LowerVASTART(Op, DAG);
2338   case ISD::VACOPY:
2339     return LowerVACOPY(Op, DAG);
2340   case ISD::VAARG:
2341     return LowerVAARG(Op, DAG);
2342   case ISD::ADDC:
2343   case ISD::ADDE:
2344   case ISD::SUBC:
2345   case ISD::SUBE:
2346     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2347   case ISD::SADDO:
2348   case ISD::UADDO:
2349   case ISD::SSUBO:
2350   case ISD::USUBO:
2351   case ISD::SMULO:
2352   case ISD::UMULO:
2353     return LowerXALUO(Op, DAG);
2354   case ISD::FADD:
2355     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2356   case ISD::FSUB:
2357     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2358   case ISD::FMUL:
2359     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2360   case ISD::FDIV:
2361     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2362   case ISD::FP_ROUND:
2363     return LowerFP_ROUND(Op, DAG);
2364   case ISD::FP_EXTEND:
2365     return LowerFP_EXTEND(Op, DAG);
2366   case ISD::FRAMEADDR:
2367     return LowerFRAMEADDR(Op, DAG);
2368   case ISD::RETURNADDR:
2369     return LowerRETURNADDR(Op, DAG);
2370   case ISD::INSERT_VECTOR_ELT:
2371     return LowerINSERT_VECTOR_ELT(Op, DAG);
2372   case ISD::EXTRACT_VECTOR_ELT:
2373     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2374   case ISD::BUILD_VECTOR:
2375     return LowerBUILD_VECTOR(Op, DAG);
2376   case ISD::VECTOR_SHUFFLE:
2377     return LowerVECTOR_SHUFFLE(Op, DAG);
2378   case ISD::EXTRACT_SUBVECTOR:
2379     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2380   case ISD::SRA:
2381   case ISD::SRL:
2382   case ISD::SHL:
2383     return LowerVectorSRA_SRL_SHL(Op, DAG);
2384   case ISD::SHL_PARTS:
2385     return LowerShiftLeftParts(Op, DAG);
2386   case ISD::SRL_PARTS:
2387   case ISD::SRA_PARTS:
2388     return LowerShiftRightParts(Op, DAG);
2389   case ISD::CTPOP:
2390     return LowerCTPOP(Op, DAG);
2391   case ISD::FCOPYSIGN:
2392     return LowerFCOPYSIGN(Op, DAG);
2393   case ISD::AND:
2394     return LowerVectorAND(Op, DAG);
2395   case ISD::OR:
2396     return LowerVectorOR(Op, DAG);
2397   case ISD::XOR:
2398     return LowerXOR(Op, DAG);
2399   case ISD::PREFETCH:
2400     return LowerPREFETCH(Op, DAG);
2401   case ISD::SINT_TO_FP:
2402   case ISD::UINT_TO_FP:
2403     return LowerINT_TO_FP(Op, DAG);
2404   case ISD::FP_TO_SINT:
2405   case ISD::FP_TO_UINT:
2406     return LowerFP_TO_INT(Op, DAG);
2407   case ISD::FSINCOS:
2408     return LowerFSINCOS(Op, DAG);
2409   case ISD::MUL:
2410     return LowerMUL(Op, DAG);
2411   case ISD::INTRINSIC_WO_CHAIN:
2412     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2413   }
2414 }
2415 
2416 //===----------------------------------------------------------------------===//
2417 //                      Calling Convention Implementation
2418 //===----------------------------------------------------------------------===//
2419 
2420 #include "AArch64GenCallingConv.inc"
2421 
2422 /// Selects the correct CCAssignFn for a given CallingConvention value.
2423 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2424                                                      bool IsVarArg) const {
2425   switch (CC) {
2426   default:
2427     llvm_unreachable("Unsupported calling convention.");
2428   case CallingConv::WebKit_JS:
2429     return CC_AArch64_WebKit_JS;
2430   case CallingConv::GHC:
2431     return CC_AArch64_GHC;
2432   case CallingConv::C:
2433   case CallingConv::Fast:
2434   case CallingConv::PreserveMost:
2435   case CallingConv::CXX_FAST_TLS:
2436   case CallingConv::Swift:
2437     if (!Subtarget->isTargetDarwin())
2438       return CC_AArch64_AAPCS;
2439     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2440   }
2441 }
2442 
2443 CCAssignFn *
2444 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2445   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2446                                       : RetCC_AArch64_AAPCS;
2447 }
2448 
2449 SDValue AArch64TargetLowering::LowerFormalArguments(
2450     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2451     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2452     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2453   MachineFunction &MF = DAG.getMachineFunction();
2454   MachineFrameInfo &MFI = MF.getFrameInfo();
2455 
2456   // Assign locations to all of the incoming arguments.
2457   SmallVector<CCValAssign, 16> ArgLocs;
2458   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2459                  *DAG.getContext());
2460 
2461   // At this point, Ins[].VT may already be promoted to i32. To correctly
2462   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2463   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2464   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2465   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2466   // LocVT.
2467   unsigned NumArgs = Ins.size();
2468   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2469   unsigned CurArgIdx = 0;
2470   for (unsigned i = 0; i != NumArgs; ++i) {
2471     MVT ValVT = Ins[i].VT;
2472     if (Ins[i].isOrigArg()) {
2473       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2474       CurArgIdx = Ins[i].getOrigArgIndex();
2475 
2476       // Get type of the original argument.
2477       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2478                                   /*AllowUnknown*/ true);
2479       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2480       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2481       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2482         ValVT = MVT::i8;
2483       else if (ActualMVT == MVT::i16)
2484         ValVT = MVT::i16;
2485     }
2486     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2487     bool Res =
2488         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2489     assert(!Res && "Call operand has unhandled type");
2490     (void)Res;
2491   }
2492   assert(ArgLocs.size() == Ins.size());
2493   SmallVector<SDValue, 16> ArgValues;
2494   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2495     CCValAssign &VA = ArgLocs[i];
2496 
2497     if (Ins[i].Flags.isByVal()) {
2498       // Byval is used for HFAs in the PCS, but the system should work in a
2499       // non-compliant manner for larger structs.
2500       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2501       int Size = Ins[i].Flags.getByValSize();
2502       unsigned NumRegs = (Size + 7) / 8;
2503 
2504       // FIXME: This works on big-endian for composite byvals, which are the common
2505       // case. It should also work for fundamental types too.
2506       unsigned FrameIdx =
2507         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2508       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2509       InVals.push_back(FrameIdxN);
2510 
2511       continue;
2512     }
2513 
2514     if (VA.isRegLoc()) {
2515       // Arguments stored in registers.
2516       EVT RegVT = VA.getLocVT();
2517 
2518       SDValue ArgValue;
2519       const TargetRegisterClass *RC;
2520 
2521       if (RegVT == MVT::i32)
2522         RC = &AArch64::GPR32RegClass;
2523       else if (RegVT == MVT::i64)
2524         RC = &AArch64::GPR64RegClass;
2525       else if (RegVT == MVT::f16)
2526         RC = &AArch64::FPR16RegClass;
2527       else if (RegVT == MVT::f32)
2528         RC = &AArch64::FPR32RegClass;
2529       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2530         RC = &AArch64::FPR64RegClass;
2531       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2532         RC = &AArch64::FPR128RegClass;
2533       else
2534         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2535 
2536       // Transform the arguments in physical registers into virtual ones.
2537       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2538       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2539 
2540       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2541       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2542       // truncate to the right size.
2543       switch (VA.getLocInfo()) {
2544       default:
2545         llvm_unreachable("Unknown loc info!");
2546       case CCValAssign::Full:
2547         break;
2548       case CCValAssign::BCvt:
2549         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2550         break;
2551       case CCValAssign::AExt:
2552       case CCValAssign::SExt:
2553       case CCValAssign::ZExt:
2554         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2555         // nodes after our lowering.
2556         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2557         break;
2558       }
2559 
2560       InVals.push_back(ArgValue);
2561 
2562     } else { // VA.isRegLoc()
2563       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2564       unsigned ArgOffset = VA.getLocMemOffset();
2565       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2566 
2567       uint32_t BEAlign = 0;
2568       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2569           !Ins[i].Flags.isInConsecutiveRegs())
2570         BEAlign = 8 - ArgSize;
2571 
2572       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2573 
2574       // Create load nodes to retrieve arguments from the stack.
2575       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2576       SDValue ArgValue;
2577 
2578       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2579       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2580       MVT MemVT = VA.getValVT();
2581 
2582       switch (VA.getLocInfo()) {
2583       default:
2584         break;
2585       case CCValAssign::BCvt:
2586         MemVT = VA.getLocVT();
2587         break;
2588       case CCValAssign::SExt:
2589         ExtType = ISD::SEXTLOAD;
2590         break;
2591       case CCValAssign::ZExt:
2592         ExtType = ISD::ZEXTLOAD;
2593         break;
2594       case CCValAssign::AExt:
2595         ExtType = ISD::EXTLOAD;
2596         break;
2597       }
2598 
2599       ArgValue = DAG.getExtLoad(
2600           ExtType, DL, VA.getLocVT(), Chain, FIN,
2601           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2602           MemVT);
2603 
2604       InVals.push_back(ArgValue);
2605     }
2606   }
2607 
2608   // varargs
2609   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2610   if (isVarArg) {
2611     if (!Subtarget->isTargetDarwin()) {
2612       // The AAPCS variadic function ABI is identical to the non-variadic
2613       // one. As a result there may be more arguments in registers and we should
2614       // save them for future reference.
2615       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2616     }
2617 
2618     // This will point to the next argument passed via stack.
2619     unsigned StackOffset = CCInfo.getNextStackOffset();
2620     // We currently pass all varargs at 8-byte alignment.
2621     StackOffset = ((StackOffset + 7) & ~7);
2622     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2623   }
2624 
2625   unsigned StackArgSize = CCInfo.getNextStackOffset();
2626   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2627   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2628     // This is a non-standard ABI so by fiat I say we're allowed to make full
2629     // use of the stack area to be popped, which must be aligned to 16 bytes in
2630     // any case:
2631     StackArgSize = alignTo(StackArgSize, 16);
2632 
2633     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2634     // a multiple of 16.
2635     FuncInfo->setArgumentStackToRestore(StackArgSize);
2636 
2637     // This realignment carries over to the available bytes below. Our own
2638     // callers will guarantee the space is free by giving an aligned value to
2639     // CALLSEQ_START.
2640   }
2641   // Even if we're not expected to free up the space, it's useful to know how
2642   // much is there while considering tail calls (because we can reuse it).
2643   FuncInfo->setBytesInStackArgArea(StackArgSize);
2644 
2645   return Chain;
2646 }
2647 
2648 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2649                                                 SelectionDAG &DAG,
2650                                                 const SDLoc &DL,
2651                                                 SDValue &Chain) const {
2652   MachineFunction &MF = DAG.getMachineFunction();
2653   MachineFrameInfo &MFI = MF.getFrameInfo();
2654   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2655   auto PtrVT = getPointerTy(DAG.getDataLayout());
2656 
2657   SmallVector<SDValue, 8> MemOps;
2658 
2659   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2660                                           AArch64::X3, AArch64::X4, AArch64::X5,
2661                                           AArch64::X6, AArch64::X7 };
2662   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2663   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2664 
2665   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2666   int GPRIdx = 0;
2667   if (GPRSaveSize != 0) {
2668     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2669 
2670     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2671 
2672     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2673       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2674       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2675       SDValue Store = DAG.getStore(
2676           Val.getValue(1), DL, Val, FIN,
2677           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2678       MemOps.push_back(Store);
2679       FIN =
2680           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2681     }
2682   }
2683   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2684   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2685 
2686   if (Subtarget->hasFPARMv8()) {
2687     static const MCPhysReg FPRArgRegs[] = {
2688         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2689         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2690     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2691     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2692 
2693     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2694     int FPRIdx = 0;
2695     if (FPRSaveSize != 0) {
2696       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2697 
2698       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2699 
2700       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2701         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2702         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2703 
2704         SDValue Store = DAG.getStore(
2705             Val.getValue(1), DL, Val, FIN,
2706             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2707         MemOps.push_back(Store);
2708         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2709                           DAG.getConstant(16, DL, PtrVT));
2710       }
2711     }
2712     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2713     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2714   }
2715 
2716   if (!MemOps.empty()) {
2717     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2718   }
2719 }
2720 
2721 /// LowerCallResult - Lower the result values of a call into the
2722 /// appropriate copies out of appropriate physical registers.
2723 SDValue AArch64TargetLowering::LowerCallResult(
2724     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2725     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2726     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2727     SDValue ThisVal) const {
2728   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2729                           ? RetCC_AArch64_WebKit_JS
2730                           : RetCC_AArch64_AAPCS;
2731   // Assign locations to each value returned by this call.
2732   SmallVector<CCValAssign, 16> RVLocs;
2733   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2734                  *DAG.getContext());
2735   CCInfo.AnalyzeCallResult(Ins, RetCC);
2736 
2737   // Copy all of the result registers out of their specified physreg.
2738   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2739     CCValAssign VA = RVLocs[i];
2740 
2741     // Pass 'this' value directly from the argument to return value, to avoid
2742     // reg unit interference
2743     if (i == 0 && isThisReturn) {
2744       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2745              "unexpected return calling convention register assignment");
2746       InVals.push_back(ThisVal);
2747       continue;
2748     }
2749 
2750     SDValue Val =
2751         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2752     Chain = Val.getValue(1);
2753     InFlag = Val.getValue(2);
2754 
2755     switch (VA.getLocInfo()) {
2756     default:
2757       llvm_unreachable("Unknown loc info!");
2758     case CCValAssign::Full:
2759       break;
2760     case CCValAssign::BCvt:
2761       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2762       break;
2763     }
2764 
2765     InVals.push_back(Val);
2766   }
2767 
2768   return Chain;
2769 }
2770 
2771 /// Return true if the calling convention is one that we can guarantee TCO for.
2772 static bool canGuaranteeTCO(CallingConv::ID CC) {
2773   return CC == CallingConv::Fast;
2774 }
2775 
2776 /// Return true if we might ever do TCO for calls with this calling convention.
2777 static bool mayTailCallThisCC(CallingConv::ID CC) {
2778   switch (CC) {
2779   case CallingConv::C:
2780   case CallingConv::PreserveMost:
2781   case CallingConv::Swift:
2782     return true;
2783   default:
2784     return canGuaranteeTCO(CC);
2785   }
2786 }
2787 
2788 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2789     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2790     const SmallVectorImpl<ISD::OutputArg> &Outs,
2791     const SmallVectorImpl<SDValue> &OutVals,
2792     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2793   if (!mayTailCallThisCC(CalleeCC))
2794     return false;
2795 
2796   MachineFunction &MF = DAG.getMachineFunction();
2797   const Function *CallerF = MF.getFunction();
2798   CallingConv::ID CallerCC = CallerF->getCallingConv();
2799   bool CCMatch = CallerCC == CalleeCC;
2800 
2801   // Byval parameters hand the function a pointer directly into the stack area
2802   // we want to reuse during a tail call. Working around this *is* possible (see
2803   // X86) but less efficient and uglier in LowerCall.
2804   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2805                                     e = CallerF->arg_end();
2806        i != e; ++i)
2807     if (i->hasByValAttr())
2808       return false;
2809 
2810   if (getTargetMachine().Options.GuaranteedTailCallOpt)
2811     return canGuaranteeTCO(CalleeCC) && CCMatch;
2812 
2813   // Externally-defined functions with weak linkage should not be
2814   // tail-called on AArch64 when the OS does not support dynamic
2815   // pre-emption of symbols, as the AAELF spec requires normal calls
2816   // to undefined weak functions to be replaced with a NOP or jump to the
2817   // next instruction. The behaviour of branch instructions in this
2818   // situation (as used for tail calls) is implementation-defined, so we
2819   // cannot rely on the linker replacing the tail call with a return.
2820   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2821     const GlobalValue *GV = G->getGlobal();
2822     const Triple &TT = getTargetMachine().getTargetTriple();
2823     if (GV->hasExternalWeakLinkage() &&
2824         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2825       return false;
2826   }
2827 
2828   // Now we search for cases where we can use a tail call without changing the
2829   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2830   // concept.
2831 
2832   // I want anyone implementing a new calling convention to think long and hard
2833   // about this assert.
2834   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2835          "Unexpected variadic calling convention");
2836 
2837   LLVMContext &C = *DAG.getContext();
2838   if (isVarArg && !Outs.empty()) {
2839     // At least two cases here: if caller is fastcc then we can't have any
2840     // memory arguments (we'd be expected to clean up the stack afterwards). If
2841     // caller is C then we could potentially use its argument area.
2842 
2843     // FIXME: for now we take the most conservative of these in both cases:
2844     // disallow all variadic memory operands.
2845     SmallVector<CCValAssign, 16> ArgLocs;
2846     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2847 
2848     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2849     for (const CCValAssign &ArgLoc : ArgLocs)
2850       if (!ArgLoc.isRegLoc())
2851         return false;
2852   }
2853 
2854   // Check that the call results are passed in the same way.
2855   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2856                                   CCAssignFnForCall(CalleeCC, isVarArg),
2857                                   CCAssignFnForCall(CallerCC, isVarArg)))
2858     return false;
2859   // The callee has to preserve all registers the caller needs to preserve.
2860   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2861   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2862   if (!CCMatch) {
2863     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2864     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2865       return false;
2866   }
2867 
2868   // Nothing more to check if the callee is taking no arguments
2869   if (Outs.empty())
2870     return true;
2871 
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2874 
2875   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2876 
2877   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2878 
2879   // If the stack arguments for this call do not fit into our own save area then
2880   // the call cannot be made tail.
2881   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2882     return false;
2883 
2884   const MachineRegisterInfo &MRI = MF.getRegInfo();
2885   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2886     return false;
2887 
2888   return true;
2889 }
2890 
2891 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2892                                                    SelectionDAG &DAG,
2893                                                    MachineFrameInfo &MFI,
2894                                                    int ClobberedFI) const {
2895   SmallVector<SDValue, 8> ArgChains;
2896   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2897   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2898 
2899   // Include the original chain at the beginning of the list. When this is
2900   // used by target LowerCall hooks, this helps legalize find the
2901   // CALLSEQ_BEGIN node.
2902   ArgChains.push_back(Chain);
2903 
2904   // Add a chain value for each stack argument corresponding
2905   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2906                             UE = DAG.getEntryNode().getNode()->use_end();
2907        U != UE; ++U)
2908     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2909       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2910         if (FI->getIndex() < 0) {
2911           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2912           int64_t InLastByte = InFirstByte;
2913           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2914 
2915           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2916               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2917             ArgChains.push_back(SDValue(L, 1));
2918         }
2919 
2920   // Build a tokenfactor for all the chains.
2921   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2922 }
2923 
2924 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2925                                                    bool TailCallOpt) const {
2926   return CallCC == CallingConv::Fast && TailCallOpt;
2927 }
2928 
2929 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2930 /// and add input and output parameter nodes.
2931 SDValue
2932 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2933                                  SmallVectorImpl<SDValue> &InVals) const {
2934   SelectionDAG &DAG = CLI.DAG;
2935   SDLoc &DL = CLI.DL;
2936   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2937   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2938   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2939   SDValue Chain = CLI.Chain;
2940   SDValue Callee = CLI.Callee;
2941   bool &IsTailCall = CLI.IsTailCall;
2942   CallingConv::ID CallConv = CLI.CallConv;
2943   bool IsVarArg = CLI.IsVarArg;
2944 
2945   MachineFunction &MF = DAG.getMachineFunction();
2946   bool IsThisReturn = false;
2947 
2948   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2949   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2950   bool IsSibCall = false;
2951 
2952   if (IsTailCall) {
2953     // Check if it's really possible to do a tail call.
2954     IsTailCall = isEligibleForTailCallOptimization(
2955         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2956     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2957       report_fatal_error("failed to perform tail call elimination on a call "
2958                          "site marked musttail");
2959 
2960     // A sibling call is one where we're under the usual C ABI and not planning
2961     // to change that but can still do a tail call:
2962     if (!TailCallOpt && IsTailCall)
2963       IsSibCall = true;
2964 
2965     if (IsTailCall)
2966       ++NumTailCalls;
2967   }
2968 
2969   // Analyze operands of the call, assigning locations to each operand.
2970   SmallVector<CCValAssign, 16> ArgLocs;
2971   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2972                  *DAG.getContext());
2973 
2974   if (IsVarArg) {
2975     // Handle fixed and variable vector arguments differently.
2976     // Variable vector arguments always go into memory.
2977     unsigned NumArgs = Outs.size();
2978 
2979     for (unsigned i = 0; i != NumArgs; ++i) {
2980       MVT ArgVT = Outs[i].VT;
2981       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2982       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2983                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2984       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2985       assert(!Res && "Call operand has unhandled type");
2986       (void)Res;
2987     }
2988   } else {
2989     // At this point, Outs[].VT may already be promoted to i32. To correctly
2990     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2991     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2992     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2993     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2994     // LocVT.
2995     unsigned NumArgs = Outs.size();
2996     for (unsigned i = 0; i != NumArgs; ++i) {
2997       MVT ValVT = Outs[i].VT;
2998       // Get type of the original argument.
2999       EVT ActualVT = getValueType(DAG.getDataLayout(),
3000                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3001                                   /*AllowUnknown*/ true);
3002       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3003       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3004       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3005       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3006         ValVT = MVT::i8;
3007       else if (ActualMVT == MVT::i16)
3008         ValVT = MVT::i16;
3009 
3010       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3011       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3012       assert(!Res && "Call operand has unhandled type");
3013       (void)Res;
3014     }
3015   }
3016 
3017   // Get a count of how many bytes are to be pushed on the stack.
3018   unsigned NumBytes = CCInfo.getNextStackOffset();
3019 
3020   if (IsSibCall) {
3021     // Since we're not changing the ABI to make this a tail call, the memory
3022     // operands are already available in the caller's incoming argument space.
3023     NumBytes = 0;
3024   }
3025 
3026   // FPDiff is the byte offset of the call's argument area from the callee's.
3027   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3028   // by this amount for a tail call. In a sibling call it must be 0 because the
3029   // caller will deallocate the entire stack and the callee still expects its
3030   // arguments to begin at SP+0. Completely unused for non-tail calls.
3031   int FPDiff = 0;
3032 
3033   if (IsTailCall && !IsSibCall) {
3034     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3035 
3036     // Since callee will pop argument stack as a tail call, we must keep the
3037     // popped size 16-byte aligned.
3038     NumBytes = alignTo(NumBytes, 16);
3039 
3040     // FPDiff will be negative if this tail call requires more space than we
3041     // would automatically have in our incoming argument space. Positive if we
3042     // can actually shrink the stack.
3043     FPDiff = NumReusableBytes - NumBytes;
3044 
3045     // The stack pointer must be 16-byte aligned at all times it's used for a
3046     // memory operation, which in practice means at *all* times and in
3047     // particular across call boundaries. Therefore our own arguments started at
3048     // a 16-byte aligned SP and the delta applied for the tail call should
3049     // satisfy the same constraint.
3050     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3051   }
3052 
3053   // Adjust the stack pointer for the new arguments...
3054   // These operations are automatically eliminated by the prolog/epilog pass
3055   if (!IsSibCall)
3056     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3057                                                               true),
3058                                  DL);
3059 
3060   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3061                                         getPointerTy(DAG.getDataLayout()));
3062 
3063   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3064   SmallVector<SDValue, 8> MemOpChains;
3065   auto PtrVT = getPointerTy(DAG.getDataLayout());
3066 
3067   // Walk the register/memloc assignments, inserting copies/loads.
3068   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3069        ++i, ++realArgIdx) {
3070     CCValAssign &VA = ArgLocs[i];
3071     SDValue Arg = OutVals[realArgIdx];
3072     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3073 
3074     // Promote the value if needed.
3075     switch (VA.getLocInfo()) {
3076     default:
3077       llvm_unreachable("Unknown loc info!");
3078     case CCValAssign::Full:
3079       break;
3080     case CCValAssign::SExt:
3081       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3082       break;
3083     case CCValAssign::ZExt:
3084       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3085       break;
3086     case CCValAssign::AExt:
3087       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3088         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3089         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3090         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3091       }
3092       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3093       break;
3094     case CCValAssign::BCvt:
3095       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3096       break;
3097     case CCValAssign::FPExt:
3098       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3099       break;
3100     }
3101 
3102     if (VA.isRegLoc()) {
3103       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3104         assert(VA.getLocVT() == MVT::i64 &&
3105                "unexpected calling convention register assignment");
3106         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3107                "unexpected use of 'returned'");
3108         IsThisReturn = true;
3109       }
3110       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3111     } else {
3112       assert(VA.isMemLoc());
3113 
3114       SDValue DstAddr;
3115       MachinePointerInfo DstInfo;
3116 
3117       // FIXME: This works on big-endian for composite byvals, which are the
3118       // common case. It should also work for fundamental types too.
3119       uint32_t BEAlign = 0;
3120       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3121                                         : VA.getValVT().getSizeInBits();
3122       OpSize = (OpSize + 7) / 8;
3123       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3124           !Flags.isInConsecutiveRegs()) {
3125         if (OpSize < 8)
3126           BEAlign = 8 - OpSize;
3127       }
3128       unsigned LocMemOffset = VA.getLocMemOffset();
3129       int32_t Offset = LocMemOffset + BEAlign;
3130       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3131       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3132 
3133       if (IsTailCall) {
3134         Offset = Offset + FPDiff;
3135         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3136 
3137         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3138         DstInfo =
3139             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3140 
3141         // Make sure any stack arguments overlapping with where we're storing
3142         // are loaded before this eventual operation. Otherwise they'll be
3143         // clobbered.
3144         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3145       } else {
3146         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3147 
3148         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3149         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3150                                                LocMemOffset);
3151       }
3152 
3153       if (Outs[i].Flags.isByVal()) {
3154         SDValue SizeNode =
3155             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3156         SDValue Cpy = DAG.getMemcpy(
3157             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3158             /*isVol = */ false, /*AlwaysInline = */ false,
3159             /*isTailCall = */ false,
3160             DstInfo, MachinePointerInfo());
3161 
3162         MemOpChains.push_back(Cpy);
3163       } else {
3164         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3165         // promoted to a legal register type i32, we should truncate Arg back to
3166         // i1/i8/i16.
3167         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3168             VA.getValVT() == MVT::i16)
3169           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3170 
3171         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3172         MemOpChains.push_back(Store);
3173       }
3174     }
3175   }
3176 
3177   if (!MemOpChains.empty())
3178     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3179 
3180   // Build a sequence of copy-to-reg nodes chained together with token chain
3181   // and flag operands which copy the outgoing args into the appropriate regs.
3182   SDValue InFlag;
3183   for (auto &RegToPass : RegsToPass) {
3184     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3185                              RegToPass.second, InFlag);
3186     InFlag = Chain.getValue(1);
3187   }
3188 
3189   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3190   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3191   // node so that legalize doesn't hack it.
3192   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3193       Subtarget->isTargetMachO()) {
3194     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3195       const GlobalValue *GV = G->getGlobal();
3196       bool InternalLinkage = GV->hasInternalLinkage();
3197       if (InternalLinkage)
3198         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3199       else {
3200         Callee =
3201             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3202         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3203       }
3204     } else if (ExternalSymbolSDNode *S =
3205                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3206       const char *Sym = S->getSymbol();
3207       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3208       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3209     }
3210   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3211     const GlobalValue *GV = G->getGlobal();
3212     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3213   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3214     const char *Sym = S->getSymbol();
3215     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3216   }
3217 
3218   // We don't usually want to end the call-sequence here because we would tidy
3219   // the frame up *after* the call, however in the ABI-changing tail-call case
3220   // we've carefully laid out the parameters so that when sp is reset they'll be
3221   // in the correct location.
3222   if (IsTailCall && !IsSibCall) {
3223     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3224                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3225     InFlag = Chain.getValue(1);
3226   }
3227 
3228   std::vector<SDValue> Ops;
3229   Ops.push_back(Chain);
3230   Ops.push_back(Callee);
3231 
3232   if (IsTailCall) {
3233     // Each tail call may have to adjust the stack by a different amount, so
3234     // this information must travel along with the operation for eventual
3235     // consumption by emitEpilogue.
3236     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3237   }
3238 
3239   // Add argument registers to the end of the list so that they are known live
3240   // into the call.
3241   for (auto &RegToPass : RegsToPass)
3242     Ops.push_back(DAG.getRegister(RegToPass.first,
3243                                   RegToPass.second.getValueType()));
3244 
3245   // Add a register mask operand representing the call-preserved registers.
3246   const uint32_t *Mask;
3247   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3248   if (IsThisReturn) {
3249     // For 'this' returns, use the X0-preserving mask if applicable
3250     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3251     if (!Mask) {
3252       IsThisReturn = false;
3253       Mask = TRI->getCallPreservedMask(MF, CallConv);
3254     }
3255   } else
3256     Mask = TRI->getCallPreservedMask(MF, CallConv);
3257 
3258   assert(Mask && "Missing call preserved mask for calling convention");
3259   Ops.push_back(DAG.getRegisterMask(Mask));
3260 
3261   if (InFlag.getNode())
3262     Ops.push_back(InFlag);
3263 
3264   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3265 
3266   // If we're doing a tall call, use a TC_RETURN here rather than an
3267   // actual call instruction.
3268   if (IsTailCall) {
3269     MF.getFrameInfo().setHasTailCall();
3270     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3271   }
3272 
3273   // Returns a chain and a flag for retval copy to use.
3274   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3275   InFlag = Chain.getValue(1);
3276 
3277   uint64_t CalleePopBytes =
3278       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3279 
3280   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3281                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3282                              InFlag, DL);
3283   if (!Ins.empty())
3284     InFlag = Chain.getValue(1);
3285 
3286   // Handle result values, copying them out of physregs into vregs that we
3287   // return.
3288   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3289                          InVals, IsThisReturn,
3290                          IsThisReturn ? OutVals[0] : SDValue());
3291 }
3292 
3293 bool AArch64TargetLowering::CanLowerReturn(
3294     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3295     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3296   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3297                           ? RetCC_AArch64_WebKit_JS
3298                           : RetCC_AArch64_AAPCS;
3299   SmallVector<CCValAssign, 16> RVLocs;
3300   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3301   return CCInfo.CheckReturn(Outs, RetCC);
3302 }
3303 
3304 SDValue
3305 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3306                                    bool isVarArg,
3307                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3308                                    const SmallVectorImpl<SDValue> &OutVals,
3309                                    const SDLoc &DL, SelectionDAG &DAG) const {
3310   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3311                           ? RetCC_AArch64_WebKit_JS
3312                           : RetCC_AArch64_AAPCS;
3313   SmallVector<CCValAssign, 16> RVLocs;
3314   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3315                  *DAG.getContext());
3316   CCInfo.AnalyzeReturn(Outs, RetCC);
3317 
3318   // Copy the result values into the output registers.
3319   SDValue Flag;
3320   SmallVector<SDValue, 4> RetOps(1, Chain);
3321   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3322        ++i, ++realRVLocIdx) {
3323     CCValAssign &VA = RVLocs[i];
3324     assert(VA.isRegLoc() && "Can only return in registers!");
3325     SDValue Arg = OutVals[realRVLocIdx];
3326 
3327     switch (VA.getLocInfo()) {
3328     default:
3329       llvm_unreachable("Unknown loc info!");
3330     case CCValAssign::Full:
3331       if (Outs[i].ArgVT == MVT::i1) {
3332         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3333         // value. This is strictly redundant on Darwin (which uses "zeroext
3334         // i1"), but will be optimised out before ISel.
3335         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3336         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3337       }
3338       break;
3339     case CCValAssign::BCvt:
3340       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3341       break;
3342     }
3343 
3344     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3345     Flag = Chain.getValue(1);
3346     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3347   }
3348   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3349   const MCPhysReg *I =
3350       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3351   if (I) {
3352     for (; *I; ++I) {
3353       if (AArch64::GPR64RegClass.contains(*I))
3354         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3355       else if (AArch64::FPR64RegClass.contains(*I))
3356         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3357       else
3358         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3359     }
3360   }
3361 
3362   RetOps[0] = Chain; // Update chain.
3363 
3364   // Add the flag if we have it.
3365   if (Flag.getNode())
3366     RetOps.push_back(Flag);
3367 
3368   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3369 }
3370 
3371 //===----------------------------------------------------------------------===//
3372 //  Other Lowering Code
3373 //===----------------------------------------------------------------------===//
3374 
3375 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3376                                                   SelectionDAG &DAG) const {
3377   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3378   SDLoc DL(Op);
3379   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3380   const GlobalValue *GV = GN->getGlobal();
3381   unsigned char OpFlags =
3382       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3383 
3384   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3385          "unexpected offset in global node");
3386 
3387   // This also catched the large code model case for Darwin.
3388   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3389     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3390     // FIXME: Once remat is capable of dealing with instructions with register
3391     // operands, expand this into two nodes instead of using a wrapper node.
3392     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3393   }
3394 
3395   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3396     const unsigned char MO_NC = AArch64II::MO_NC;
3397     return DAG.getNode(
3398         AArch64ISD::WrapperLarge, DL, PtrVT,
3399         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3400         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3401         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3402         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3403   } else {
3404     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3405     // the only correct model on Darwin.
3406     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3407                                             OpFlags | AArch64II::MO_PAGE);
3408     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3409     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3410 
3411     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3412     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3413   }
3414 }
3415 
3416 /// \brief Convert a TLS address reference into the correct sequence of loads
3417 /// and calls to compute the variable's address (for Darwin, currently) and
3418 /// return an SDValue containing the final node.
3419 
3420 /// Darwin only has one TLS scheme which must be capable of dealing with the
3421 /// fully general situation, in the worst case. This means:
3422 ///     + "extern __thread" declaration.
3423 ///     + Defined in a possibly unknown dynamic library.
3424 ///
3425 /// The general system is that each __thread variable has a [3 x i64] descriptor
3426 /// which contains information used by the runtime to calculate the address. The
3427 /// only part of this the compiler needs to know about is the first xword, which
3428 /// contains a function pointer that must be called with the address of the
3429 /// entire descriptor in "x0".
3430 ///
3431 /// Since this descriptor may be in a different unit, in general even the
3432 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3433 /// is:
3434 ///     adrp x0, _var@TLVPPAGE
3435 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3436 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3437 ///                                      ; the function pointer
3438 ///     blr x1                           ; Uses descriptor address in x0
3439 ///     ; Address of _var is now in x0.
3440 ///
3441 /// If the address of _var's descriptor *is* known to the linker, then it can
3442 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3443 /// a slight efficiency gain.
3444 SDValue
3445 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3446                                                    SelectionDAG &DAG) const {
3447   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3448 
3449   SDLoc DL(Op);
3450   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3451   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3452 
3453   SDValue TLVPAddr =
3454       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3455   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3456 
3457   // The first entry in the descriptor is a function pointer that we must call
3458   // to obtain the address of the variable.
3459   SDValue Chain = DAG.getEntryNode();
3460   SDValue FuncTLVGet = DAG.getLoad(
3461       MVT::i64, DL, Chain, DescAddr,
3462       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3463       /* Alignment = */ 8,
3464       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3465           MachineMemOperand::MODereferenceable);
3466   Chain = FuncTLVGet.getValue(1);
3467 
3468   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3469   MFI.setAdjustsStack(true);
3470 
3471   // TLS calls preserve all registers except those that absolutely must be
3472   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3473   // silly).
3474   const uint32_t *Mask =
3475       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3476 
3477   // Finally, we can make the call. This is just a degenerate version of a
3478   // normal AArch64 call node: x0 takes the address of the descriptor, and
3479   // returns the address of the variable in this thread.
3480   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3481   Chain =
3482       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3483                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3484                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3485   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3486 }
3487 
3488 /// When accessing thread-local variables under either the general-dynamic or
3489 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3490 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3491 /// is a function pointer to carry out the resolution.
3492 ///
3493 /// The sequence is:
3494 ///    adrp  x0, :tlsdesc:var
3495 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3496 ///    add   x0, x0, #:tlsdesc_lo12:var
3497 ///    .tlsdesccall var
3498 ///    blr   x1
3499 ///    (TPIDR_EL0 offset now in x0)
3500 ///
3501 ///  The above sequence must be produced unscheduled, to enable the linker to
3502 ///  optimize/relax this sequence.
3503 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3504 ///  above sequence, and expanded really late in the compilation flow, to ensure
3505 ///  the sequence is produced as per above.
3506 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3507                                                       const SDLoc &DL,
3508                                                       SelectionDAG &DAG) const {
3509   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3510 
3511   SDValue Chain = DAG.getEntryNode();
3512   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3513 
3514   Chain =
3515       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3516   SDValue Glue = Chain.getValue(1);
3517 
3518   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3519 }
3520 
3521 SDValue
3522 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3523                                                 SelectionDAG &DAG) const {
3524   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3525   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3526          "ELF TLS only supported in small memory model");
3527   // Different choices can be made for the maximum size of the TLS area for a
3528   // module. For the small address model, the default TLS size is 16MiB and the
3529   // maximum TLS size is 4GiB.
3530   // FIXME: add -mtls-size command line option and make it control the 16MiB
3531   // vs. 4GiB code sequence generation.
3532   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3533 
3534   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3535 
3536   if (DAG.getTarget().Options.EmulatedTLS)
3537     return LowerToTLSEmulatedModel(GA, DAG);
3538 
3539   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3540     if (Model == TLSModel::LocalDynamic)
3541       Model = TLSModel::GeneralDynamic;
3542   }
3543 
3544   SDValue TPOff;
3545   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3546   SDLoc DL(Op);
3547   const GlobalValue *GV = GA->getGlobal();
3548 
3549   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3550 
3551   if (Model == TLSModel::LocalExec) {
3552     SDValue HiVar = DAG.getTargetGlobalAddress(
3553         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3554     SDValue LoVar = DAG.getTargetGlobalAddress(
3555         GV, DL, PtrVT, 0,
3556         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3557 
3558     SDValue TPWithOff_lo =
3559         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3560                                    HiVar,
3561                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3562                 0);
3563     SDValue TPWithOff =
3564         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3565                                    LoVar,
3566                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3567                 0);
3568     return TPWithOff;
3569   } else if (Model == TLSModel::InitialExec) {
3570     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3571     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3572   } else if (Model == TLSModel::LocalDynamic) {
3573     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3574     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3575     // the beginning of the module's TLS region, followed by a DTPREL offset
3576     // calculation.
3577 
3578     // These accesses will need deduplicating if there's more than one.
3579     AArch64FunctionInfo *MFI =
3580         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3581     MFI->incNumLocalDynamicTLSAccesses();
3582 
3583     // The call needs a relocation too for linker relaxation. It doesn't make
3584     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3585     // the address.
3586     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3587                                                   AArch64II::MO_TLS);
3588 
3589     // Now we can calculate the offset from TPIDR_EL0 to this module's
3590     // thread-local area.
3591     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3592 
3593     // Now use :dtprel_whatever: operations to calculate this variable's offset
3594     // in its thread-storage area.
3595     SDValue HiVar = DAG.getTargetGlobalAddress(
3596         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3597     SDValue LoVar = DAG.getTargetGlobalAddress(
3598         GV, DL, MVT::i64, 0,
3599         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3600 
3601     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3602                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3603                     0);
3604     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3605                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3606                     0);
3607   } else if (Model == TLSModel::GeneralDynamic) {
3608     // The call needs a relocation too for linker relaxation. It doesn't make
3609     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3610     // the address.
3611     SDValue SymAddr =
3612         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3613 
3614     // Finally we can make a call to calculate the offset from tpidr_el0.
3615     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3616   } else
3617     llvm_unreachable("Unsupported ELF TLS access model");
3618 
3619   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3620 }
3621 
3622 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3623                                                      SelectionDAG &DAG) const {
3624   if (Subtarget->isTargetDarwin())
3625     return LowerDarwinGlobalTLSAddress(Op, DAG);
3626   else if (Subtarget->isTargetELF())
3627     return LowerELFGlobalTLSAddress(Op, DAG);
3628 
3629   llvm_unreachable("Unexpected platform trying to use TLS");
3630 }
3631 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3632   SDValue Chain = Op.getOperand(0);
3633   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3634   SDValue LHS = Op.getOperand(2);
3635   SDValue RHS = Op.getOperand(3);
3636   SDValue Dest = Op.getOperand(4);
3637   SDLoc dl(Op);
3638 
3639   // Handle f128 first, since lowering it will result in comparing the return
3640   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3641   // is expecting to deal with.
3642   if (LHS.getValueType() == MVT::f128) {
3643     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3644 
3645     // If softenSetCCOperands returned a scalar, we need to compare the result
3646     // against zero to select between true and false values.
3647     if (!RHS.getNode()) {
3648       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3649       CC = ISD::SETNE;
3650     }
3651   }
3652 
3653   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3654   // instruction.
3655   unsigned Opc = LHS.getOpcode();
3656   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3657       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3658        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3659     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3660            "Unexpected condition code.");
3661     // Only lower legal XALUO ops.
3662     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3663       return SDValue();
3664 
3665     // The actual operation with overflow check.
3666     AArch64CC::CondCode OFCC;
3667     SDValue Value, Overflow;
3668     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3669 
3670     if (CC == ISD::SETNE)
3671       OFCC = getInvertedCondCode(OFCC);
3672     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3673 
3674     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3675                        Overflow);
3676   }
3677 
3678   if (LHS.getValueType().isInteger()) {
3679     assert((LHS.getValueType() == RHS.getValueType()) &&
3680            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3681 
3682     // If the RHS of the comparison is zero, we can potentially fold this
3683     // to a specialized branch.
3684     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3685     if (RHSC && RHSC->getZExtValue() == 0) {
3686       if (CC == ISD::SETEQ) {
3687         // See if we can use a TBZ to fold in an AND as well.
3688         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3689         // out of bounds, a late MI-layer pass rewrites branches.
3690         // 403.gcc is an example that hits this case.
3691         if (LHS.getOpcode() == ISD::AND &&
3692             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3693             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3694           SDValue Test = LHS.getOperand(0);
3695           uint64_t Mask = LHS.getConstantOperandVal(1);
3696           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3697                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3698                              Dest);
3699         }
3700 
3701         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3702       } else if (CC == ISD::SETNE) {
3703         // See if we can use a TBZ to fold in an AND as well.
3704         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3705         // out of bounds, a late MI-layer pass rewrites branches.
3706         // 403.gcc is an example that hits this case.
3707         if (LHS.getOpcode() == ISD::AND &&
3708             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3709             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3710           SDValue Test = LHS.getOperand(0);
3711           uint64_t Mask = LHS.getConstantOperandVal(1);
3712           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3713                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3714                              Dest);
3715         }
3716 
3717         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3718       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3719         // Don't combine AND since emitComparison converts the AND to an ANDS
3720         // (a.k.a. TST) and the test in the test bit and branch instruction
3721         // becomes redundant.  This would also increase register pressure.
3722         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3723         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3724                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3725       }
3726     }
3727     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3728         LHS.getOpcode() != ISD::AND) {
3729       // Don't combine AND since emitComparison converts the AND to an ANDS
3730       // (a.k.a. TST) and the test in the test bit and branch instruction
3731       // becomes redundant.  This would also increase register pressure.
3732       uint64_t Mask = LHS.getValueSizeInBits() - 1;
3733       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3734                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3735     }
3736 
3737     SDValue CCVal;
3738     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3739     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3740                        Cmp);
3741   }
3742 
3743   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3744 
3745   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3746   // clean.  Some of them require two branches to implement.
3747   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3748   AArch64CC::CondCode CC1, CC2;
3749   changeFPCCToAArch64CC(CC, CC1, CC2);
3750   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3751   SDValue BR1 =
3752       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3753   if (CC2 != AArch64CC::AL) {
3754     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3755     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3756                        Cmp);
3757   }
3758 
3759   return BR1;
3760 }
3761 
3762 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3763                                               SelectionDAG &DAG) const {
3764   EVT VT = Op.getValueType();
3765   SDLoc DL(Op);
3766 
3767   SDValue In1 = Op.getOperand(0);
3768   SDValue In2 = Op.getOperand(1);
3769   EVT SrcVT = In2.getValueType();
3770 
3771   if (SrcVT.bitsLT(VT))
3772     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3773   else if (SrcVT.bitsGT(VT))
3774     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3775 
3776   EVT VecVT;
3777   EVT EltVT;
3778   uint64_t EltMask;
3779   SDValue VecVal1, VecVal2;
3780   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3781     EltVT = MVT::i32;
3782     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3783     EltMask = 0x80000000ULL;
3784 
3785     if (!VT.isVector()) {
3786       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3787                                           DAG.getUNDEF(VecVT), In1);
3788       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3789                                           DAG.getUNDEF(VecVT), In2);
3790     } else {
3791       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3792       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3793     }
3794   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3795     EltVT = MVT::i64;
3796     VecVT = MVT::v2i64;
3797 
3798     // We want to materialize a mask with the high bit set, but the AdvSIMD
3799     // immediate moves cannot materialize that in a single instruction for
3800     // 64-bit elements. Instead, materialize zero and then negate it.
3801     EltMask = 0;
3802 
3803     if (!VT.isVector()) {
3804       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3805                                           DAG.getUNDEF(VecVT), In1);
3806       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3807                                           DAG.getUNDEF(VecVT), In2);
3808     } else {
3809       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3810       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3811     }
3812   } else {
3813     llvm_unreachable("Invalid type for copysign!");
3814   }
3815 
3816   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3817 
3818   // If we couldn't materialize the mask above, then the mask vector will be
3819   // the zero vector, and we need to negate it here.
3820   if (VT == MVT::f64 || VT == MVT::v2f64) {
3821     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3822     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3823     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3824   }
3825 
3826   SDValue Sel =
3827       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3828 
3829   if (VT == MVT::f32)
3830     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3831   else if (VT == MVT::f64)
3832     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3833   else
3834     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3835 }
3836 
3837 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3838   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3839           Attribute::NoImplicitFloat))
3840     return SDValue();
3841 
3842   if (!Subtarget->hasNEON())
3843     return SDValue();
3844 
3845   // While there is no integer popcount instruction, it can
3846   // be more efficiently lowered to the following sequence that uses
3847   // AdvSIMD registers/instructions as long as the copies to/from
3848   // the AdvSIMD registers are cheap.
3849   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3850   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3851   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3852   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3853   SDValue Val = Op.getOperand(0);
3854   SDLoc DL(Op);
3855   EVT VT = Op.getValueType();
3856 
3857   if (VT == MVT::i32)
3858     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3859   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3860 
3861   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3862   SDValue UaddLV = DAG.getNode(
3863       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3864       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3865 
3866   if (VT == MVT::i64)
3867     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3868   return UaddLV;
3869 }
3870 
3871 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3872 
3873   if (Op.getValueType().isVector())
3874     return LowerVSETCC(Op, DAG);
3875 
3876   SDValue LHS = Op.getOperand(0);
3877   SDValue RHS = Op.getOperand(1);
3878   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3879   SDLoc dl(Op);
3880 
3881   // We chose ZeroOrOneBooleanContents, so use zero and one.
3882   EVT VT = Op.getValueType();
3883   SDValue TVal = DAG.getConstant(1, dl, VT);
3884   SDValue FVal = DAG.getConstant(0, dl, VT);
3885 
3886   // Handle f128 first, since one possible outcome is a normal integer
3887   // comparison which gets picked up by the next if statement.
3888   if (LHS.getValueType() == MVT::f128) {
3889     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3890 
3891     // If softenSetCCOperands returned a scalar, use it.
3892     if (!RHS.getNode()) {
3893       assert(LHS.getValueType() == Op.getValueType() &&
3894              "Unexpected setcc expansion!");
3895       return LHS;
3896     }
3897   }
3898 
3899   if (LHS.getValueType().isInteger()) {
3900     SDValue CCVal;
3901     SDValue Cmp =
3902         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3903 
3904     // Note that we inverted the condition above, so we reverse the order of
3905     // the true and false operands here.  This will allow the setcc to be
3906     // matched to a single CSINC instruction.
3907     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3908   }
3909 
3910   // Now we know we're dealing with FP values.
3911   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3912 
3913   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3914   // and do the comparison.
3915   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3916 
3917   AArch64CC::CondCode CC1, CC2;
3918   changeFPCCToAArch64CC(CC, CC1, CC2);
3919   if (CC2 == AArch64CC::AL) {
3920     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3921     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3922 
3923     // Note that we inverted the condition above, so we reverse the order of
3924     // the true and false operands here.  This will allow the setcc to be
3925     // matched to a single CSINC instruction.
3926     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3927   } else {
3928     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3929     // totally clean.  Some of them require two CSELs to implement.  As is in
3930     // this case, we emit the first CSEL and then emit a second using the output
3931     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3932 
3933     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3934     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3935     SDValue CS1 =
3936         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3937 
3938     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3939     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3940   }
3941 }
3942 
3943 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3944                                               SDValue RHS, SDValue TVal,
3945                                               SDValue FVal, const SDLoc &dl,
3946                                               SelectionDAG &DAG) const {
3947   // Handle f128 first, because it will result in a comparison of some RTLIB
3948   // call result against zero.
3949   if (LHS.getValueType() == MVT::f128) {
3950     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3951 
3952     // If softenSetCCOperands returned a scalar, we need to compare the result
3953     // against zero to select between true and false values.
3954     if (!RHS.getNode()) {
3955       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3956       CC = ISD::SETNE;
3957     }
3958   }
3959 
3960   // Also handle f16, for which we need to do a f32 comparison.
3961   if (LHS.getValueType() == MVT::f16) {
3962     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3963     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3964   }
3965 
3966   // Next, handle integers.
3967   if (LHS.getValueType().isInteger()) {
3968     assert((LHS.getValueType() == RHS.getValueType()) &&
3969            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3970 
3971     unsigned Opcode = AArch64ISD::CSEL;
3972 
3973     // If both the TVal and the FVal are constants, see if we can swap them in
3974     // order to for a CSINV or CSINC out of them.
3975     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3976     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3977 
3978     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3979       std::swap(TVal, FVal);
3980       std::swap(CTVal, CFVal);
3981       CC = ISD::getSetCCInverse(CC, true);
3982     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3983       std::swap(TVal, FVal);
3984       std::swap(CTVal, CFVal);
3985       CC = ISD::getSetCCInverse(CC, true);
3986     } else if (TVal.getOpcode() == ISD::XOR) {
3987       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3988       // with a CSINV rather than a CSEL.
3989       if (isAllOnesConstant(TVal.getOperand(1))) {
3990         std::swap(TVal, FVal);
3991         std::swap(CTVal, CFVal);
3992         CC = ISD::getSetCCInverse(CC, true);
3993       }
3994     } else if (TVal.getOpcode() == ISD::SUB) {
3995       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3996       // that we can match with a CSNEG rather than a CSEL.
3997       if (isNullConstant(TVal.getOperand(0))) {
3998         std::swap(TVal, FVal);
3999         std::swap(CTVal, CFVal);
4000         CC = ISD::getSetCCInverse(CC, true);
4001       }
4002     } else if (CTVal && CFVal) {
4003       const int64_t TrueVal = CTVal->getSExtValue();
4004       const int64_t FalseVal = CFVal->getSExtValue();
4005       bool Swap = false;
4006 
4007       // If both TVal and FVal are constants, see if FVal is the
4008       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4009       // instead of a CSEL in that case.
4010       if (TrueVal == ~FalseVal) {
4011         Opcode = AArch64ISD::CSINV;
4012       } else if (TrueVal == -FalseVal) {
4013         Opcode = AArch64ISD::CSNEG;
4014       } else if (TVal.getValueType() == MVT::i32) {
4015         // If our operands are only 32-bit wide, make sure we use 32-bit
4016         // arithmetic for the check whether we can use CSINC. This ensures that
4017         // the addition in the check will wrap around properly in case there is
4018         // an overflow (which would not be the case if we do the check with
4019         // 64-bit arithmetic).
4020         const uint32_t TrueVal32 = CTVal->getZExtValue();
4021         const uint32_t FalseVal32 = CFVal->getZExtValue();
4022 
4023         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4024           Opcode = AArch64ISD::CSINC;
4025 
4026           if (TrueVal32 > FalseVal32) {
4027             Swap = true;
4028           }
4029         }
4030         // 64-bit check whether we can use CSINC.
4031       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4032         Opcode = AArch64ISD::CSINC;
4033 
4034         if (TrueVal > FalseVal) {
4035           Swap = true;
4036         }
4037       }
4038 
4039       // Swap TVal and FVal if necessary.
4040       if (Swap) {
4041         std::swap(TVal, FVal);
4042         std::swap(CTVal, CFVal);
4043         CC = ISD::getSetCCInverse(CC, true);
4044       }
4045 
4046       if (Opcode != AArch64ISD::CSEL) {
4047         // Drop FVal since we can get its value by simply inverting/negating
4048         // TVal.
4049         FVal = TVal;
4050       }
4051     }
4052 
4053     // Avoid materializing a constant when possible by reusing a known value in
4054     // a register.  However, don't perform this optimization if the known value
4055     // is one, zero or negative one.  We can always materialize these values
4056     // using CSINC, CSEL and CSINV with wzr/xzr as the FVal, respectively.
4057     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4058     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4059         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4060       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4061       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4062       // "a != C ? x : a" to avoid materializing C.
4063       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4064         TVal = LHS;
4065       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4066         FVal = LHS;
4067     }
4068 
4069     SDValue CCVal;
4070     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4071 
4072     EVT VT = TVal.getValueType();
4073     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4074   }
4075 
4076   // Now we know we're dealing with FP values.
4077   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4078   assert(LHS.getValueType() == RHS.getValueType());
4079   EVT VT = TVal.getValueType();
4080   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4081 
4082   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4083   // clean.  Some of them require two CSELs to implement.
4084   AArch64CC::CondCode CC1, CC2;
4085   changeFPCCToAArch64CC(CC, CC1, CC2);
4086   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4087   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4088 
4089   // If we need a second CSEL, emit it, using the output of the first as the
4090   // RHS.  We're effectively OR'ing the two CC's together.
4091   if (CC2 != AArch64CC::AL) {
4092     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4093     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4094   }
4095 
4096   // Otherwise, return the output of the first CSEL.
4097   return CS1;
4098 }
4099 
4100 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4101                                               SelectionDAG &DAG) const {
4102   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4103   SDValue LHS = Op.getOperand(0);
4104   SDValue RHS = Op.getOperand(1);
4105   SDValue TVal = Op.getOperand(2);
4106   SDValue FVal = Op.getOperand(3);
4107   SDLoc DL(Op);
4108   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4109 }
4110 
4111 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4112                                            SelectionDAG &DAG) const {
4113   SDValue CCVal = Op->getOperand(0);
4114   SDValue TVal = Op->getOperand(1);
4115   SDValue FVal = Op->getOperand(2);
4116   SDLoc DL(Op);
4117 
4118   unsigned Opc = CCVal.getOpcode();
4119   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4120   // instruction.
4121   if (CCVal.getResNo() == 1 &&
4122       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4123        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4124     // Only lower legal XALUO ops.
4125     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4126       return SDValue();
4127 
4128     AArch64CC::CondCode OFCC;
4129     SDValue Value, Overflow;
4130     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4131     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4132 
4133     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4134                        CCVal, Overflow);
4135   }
4136 
4137   // Lower it the same way as we would lower a SELECT_CC node.
4138   ISD::CondCode CC;
4139   SDValue LHS, RHS;
4140   if (CCVal.getOpcode() == ISD::SETCC) {
4141     LHS = CCVal.getOperand(0);
4142     RHS = CCVal.getOperand(1);
4143     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4144   } else {
4145     LHS = CCVal;
4146     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4147     CC = ISD::SETNE;
4148   }
4149   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4150 }
4151 
4152 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4153                                               SelectionDAG &DAG) const {
4154   // Jump table entries as PC relative offsets. No additional tweaking
4155   // is necessary here. Just get the address of the jump table.
4156   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4157   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4158   SDLoc DL(Op);
4159 
4160   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4161       !Subtarget->isTargetMachO()) {
4162     const unsigned char MO_NC = AArch64II::MO_NC;
4163     return DAG.getNode(
4164         AArch64ISD::WrapperLarge, DL, PtrVT,
4165         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4166         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4167         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4168         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4169                                AArch64II::MO_G0 | MO_NC));
4170   }
4171 
4172   SDValue Hi =
4173       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4174   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4175                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4176   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4177   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4178 }
4179 
4180 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4181                                                  SelectionDAG &DAG) const {
4182   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4183   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4184   SDLoc DL(Op);
4185 
4186   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4187     // Use the GOT for the large code model on iOS.
4188     if (Subtarget->isTargetMachO()) {
4189       SDValue GotAddr = DAG.getTargetConstantPool(
4190           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4191           AArch64II::MO_GOT);
4192       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4193     }
4194 
4195     const unsigned char MO_NC = AArch64II::MO_NC;
4196     return DAG.getNode(
4197         AArch64ISD::WrapperLarge, DL, PtrVT,
4198         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4199                                   CP->getOffset(), AArch64II::MO_G3),
4200         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4201                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4202         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4203                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4204         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4205                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4206   } else {
4207     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4208     // ELF, the only valid one on Darwin.
4209     SDValue Hi =
4210         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4211                                   CP->getOffset(), AArch64II::MO_PAGE);
4212     SDValue Lo = DAG.getTargetConstantPool(
4213         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4214         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4215 
4216     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4217     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4218   }
4219 }
4220 
4221 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4222                                                SelectionDAG &DAG) const {
4223   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4224   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4225   SDLoc DL(Op);
4226   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4227       !Subtarget->isTargetMachO()) {
4228     const unsigned char MO_NC = AArch64II::MO_NC;
4229     return DAG.getNode(
4230         AArch64ISD::WrapperLarge, DL, PtrVT,
4231         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4232         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4233         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4234         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4235   } else {
4236     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4237     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4238                                                              AArch64II::MO_NC);
4239     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4240     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4241   }
4242 }
4243 
4244 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4245                                                  SelectionDAG &DAG) const {
4246   AArch64FunctionInfo *FuncInfo =
4247       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4248 
4249   SDLoc DL(Op);
4250   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4251                                  getPointerTy(DAG.getDataLayout()));
4252   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4253   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4254                       MachinePointerInfo(SV));
4255 }
4256 
4257 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4258                                                 SelectionDAG &DAG) const {
4259   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4260   // Standard, section B.3.
4261   MachineFunction &MF = DAG.getMachineFunction();
4262   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4263   auto PtrVT = getPointerTy(DAG.getDataLayout());
4264   SDLoc DL(Op);
4265 
4266   SDValue Chain = Op.getOperand(0);
4267   SDValue VAList = Op.getOperand(1);
4268   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4269   SmallVector<SDValue, 4> MemOps;
4270 
4271   // void *__stack at offset 0
4272   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4273   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4274                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4275 
4276   // void *__gr_top at offset 8
4277   int GPRSize = FuncInfo->getVarArgsGPRSize();
4278   if (GPRSize > 0) {
4279     SDValue GRTop, GRTopAddr;
4280 
4281     GRTopAddr =
4282         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4283 
4284     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4285     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4286                         DAG.getConstant(GPRSize, DL, PtrVT));
4287 
4288     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4289                                   MachinePointerInfo(SV, 8),
4290                                   /* Alignment = */ 8));
4291   }
4292 
4293   // void *__vr_top at offset 16
4294   int FPRSize = FuncInfo->getVarArgsFPRSize();
4295   if (FPRSize > 0) {
4296     SDValue VRTop, VRTopAddr;
4297     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4298                             DAG.getConstant(16, DL, PtrVT));
4299 
4300     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4301     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4302                         DAG.getConstant(FPRSize, DL, PtrVT));
4303 
4304     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4305                                   MachinePointerInfo(SV, 16),
4306                                   /* Alignment = */ 8));
4307   }
4308 
4309   // int __gr_offs at offset 24
4310   SDValue GROffsAddr =
4311       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4312   MemOps.push_back(DAG.getStore(
4313       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4314       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4315 
4316   // int __vr_offs at offset 28
4317   SDValue VROffsAddr =
4318       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4319   MemOps.push_back(DAG.getStore(
4320       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4321       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4322 
4323   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4324 }
4325 
4326 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4327                                             SelectionDAG &DAG) const {
4328   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4329                                      : LowerAAPCS_VASTART(Op, DAG);
4330 }
4331 
4332 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4333                                            SelectionDAG &DAG) const {
4334   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4335   // pointer.
4336   SDLoc DL(Op);
4337   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4338   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4339   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4340 
4341   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4342                        Op.getOperand(2),
4343                        DAG.getConstant(VaListSize, DL, MVT::i32),
4344                        8, false, false, false, MachinePointerInfo(DestSV),
4345                        MachinePointerInfo(SrcSV));
4346 }
4347 
4348 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4349   assert(Subtarget->isTargetDarwin() &&
4350          "automatic va_arg instruction only works on Darwin");
4351 
4352   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4353   EVT VT = Op.getValueType();
4354   SDLoc DL(Op);
4355   SDValue Chain = Op.getOperand(0);
4356   SDValue Addr = Op.getOperand(1);
4357   unsigned Align = Op.getConstantOperandVal(3);
4358   auto PtrVT = getPointerTy(DAG.getDataLayout());
4359 
4360   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4361   Chain = VAList.getValue(1);
4362 
4363   if (Align > 8) {
4364     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4365     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4366                          DAG.getConstant(Align - 1, DL, PtrVT));
4367     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4368                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4369   }
4370 
4371   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4372   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4373 
4374   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4375   // up to 64 bits.  At the very least, we have to increase the striding of the
4376   // vaargs list to match this, and for FP values we need to introduce
4377   // FP_ROUND nodes as well.
4378   if (VT.isInteger() && !VT.isVector())
4379     ArgSize = 8;
4380   bool NeedFPTrunc = false;
4381   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4382     ArgSize = 8;
4383     NeedFPTrunc = true;
4384   }
4385 
4386   // Increment the pointer, VAList, to the next vaarg
4387   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4388                                DAG.getConstant(ArgSize, DL, PtrVT));
4389   // Store the incremented VAList to the legalized pointer
4390   SDValue APStore =
4391       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4392 
4393   // Load the actual argument out of the pointer VAList
4394   if (NeedFPTrunc) {
4395     // Load the value as an f64.
4396     SDValue WideFP =
4397         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4398     // Round the value down to an f32.
4399     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4400                                    DAG.getIntPtrConstant(1, DL));
4401     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4402     // Merge the rounded value with the chain output of the load.
4403     return DAG.getMergeValues(Ops, DL);
4404   }
4405 
4406   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4407 }
4408 
4409 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4410                                               SelectionDAG &DAG) const {
4411   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4412   MFI.setFrameAddressIsTaken(true);
4413 
4414   EVT VT = Op.getValueType();
4415   SDLoc DL(Op);
4416   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4417   SDValue FrameAddr =
4418       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4419   while (Depth--)
4420     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4421                             MachinePointerInfo());
4422   return FrameAddr;
4423 }
4424 
4425 // FIXME? Maybe this could be a TableGen attribute on some registers and
4426 // this table could be generated automatically from RegInfo.
4427 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4428                                                   SelectionDAG &DAG) const {
4429   unsigned Reg = StringSwitch<unsigned>(RegName)
4430                        .Case("sp", AArch64::SP)
4431                        .Default(0);
4432   if (Reg)
4433     return Reg;
4434   report_fatal_error(Twine("Invalid register name \""
4435                               + StringRef(RegName)  + "\"."));
4436 }
4437 
4438 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4439                                                SelectionDAG &DAG) const {
4440   MachineFunction &MF = DAG.getMachineFunction();
4441   MachineFrameInfo &MFI = MF.getFrameInfo();
4442   MFI.setReturnAddressIsTaken(true);
4443 
4444   EVT VT = Op.getValueType();
4445   SDLoc DL(Op);
4446   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4447   if (Depth) {
4448     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4449     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4450     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4451                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4452                        MachinePointerInfo());
4453   }
4454 
4455   // Return LR, which contains the return address. Mark it an implicit live-in.
4456   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4457   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4458 }
4459 
4460 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4461 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4462 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4463                                                     SelectionDAG &DAG) const {
4464   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4465   EVT VT = Op.getValueType();
4466   unsigned VTBits = VT.getSizeInBits();
4467   SDLoc dl(Op);
4468   SDValue ShOpLo = Op.getOperand(0);
4469   SDValue ShOpHi = Op.getOperand(1);
4470   SDValue ShAmt = Op.getOperand(2);
4471   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4472 
4473   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4474 
4475   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4476                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4477   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4478 
4479   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4480   // is "undef". We wanted 0, so CSEL it directly.
4481   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4482                                ISD::SETEQ, dl, DAG);
4483   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4484   HiBitsForLo =
4485       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4486                   HiBitsForLo, CCVal, Cmp);
4487 
4488   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4489                                    DAG.getConstant(VTBits, dl, MVT::i64));
4490 
4491   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4492   SDValue LoForNormalShift =
4493       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4494 
4495   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4496                        dl, DAG);
4497   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4498   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4499   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4500                            LoForNormalShift, CCVal, Cmp);
4501 
4502   // AArch64 shifts larger than the register width are wrapped rather than
4503   // clamped, so we can't just emit "hi >> x".
4504   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4505   SDValue HiForBigShift =
4506       Opc == ISD::SRA
4507           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4508                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4509           : DAG.getConstant(0, dl, VT);
4510   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4511                            HiForNormalShift, CCVal, Cmp);
4512 
4513   SDValue Ops[2] = { Lo, Hi };
4514   return DAG.getMergeValues(Ops, dl);
4515 }
4516 
4517 
4518 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4519 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4520 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4521                                                    SelectionDAG &DAG) const {
4522   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4523   EVT VT = Op.getValueType();
4524   unsigned VTBits = VT.getSizeInBits();
4525   SDLoc dl(Op);
4526   SDValue ShOpLo = Op.getOperand(0);
4527   SDValue ShOpHi = Op.getOperand(1);
4528   SDValue ShAmt = Op.getOperand(2);
4529 
4530   assert(Op.getOpcode() == ISD::SHL_PARTS);
4531   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4532                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4533   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4534 
4535   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4536   // is "undef". We wanted 0, so CSEL it directly.
4537   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4538                                ISD::SETEQ, dl, DAG);
4539   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4540   LoBitsForHi =
4541       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4542                   LoBitsForHi, CCVal, Cmp);
4543 
4544   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4545                                    DAG.getConstant(VTBits, dl, MVT::i64));
4546   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4547   SDValue HiForNormalShift =
4548       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4549 
4550   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4551 
4552   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4553                        dl, DAG);
4554   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4555   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4556                            HiForNormalShift, CCVal, Cmp);
4557 
4558   // AArch64 shifts of larger than register sizes are wrapped rather than
4559   // clamped, so we can't just emit "lo << a" if a is too big.
4560   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4561   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4562   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4563                            LoForNormalShift, CCVal, Cmp);
4564 
4565   SDValue Ops[2] = { Lo, Hi };
4566   return DAG.getMergeValues(Ops, dl);
4567 }
4568 
4569 bool AArch64TargetLowering::isOffsetFoldingLegal(
4570     const GlobalAddressSDNode *GA) const {
4571   // The AArch64 target doesn't support folding offsets into global addresses.
4572   return false;
4573 }
4574 
4575 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4576   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4577   // FIXME: We should be able to handle f128 as well with a clever lowering.
4578   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4579     return true;
4580 
4581   if (VT == MVT::f64)
4582     return AArch64_AM::getFP64Imm(Imm) != -1;
4583   else if (VT == MVT::f32)
4584     return AArch64_AM::getFP32Imm(Imm) != -1;
4585   return false;
4586 }
4587 
4588 //===----------------------------------------------------------------------===//
4589 //                          AArch64 Optimization Hooks
4590 //===----------------------------------------------------------------------===//
4591 
4592 //===----------------------------------------------------------------------===//
4593 //                          AArch64 Inline Assembly Support
4594 //===----------------------------------------------------------------------===//
4595 
4596 // Table of Constraints
4597 // TODO: This is the current set of constraints supported by ARM for the
4598 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4599 //
4600 // r - A general register
4601 // w - An FP/SIMD register of some size in the range v0-v31
4602 // x - An FP/SIMD register of some size in the range v0-v15
4603 // I - Constant that can be used with an ADD instruction
4604 // J - Constant that can be used with a SUB instruction
4605 // K - Constant that can be used with a 32-bit logical instruction
4606 // L - Constant that can be used with a 64-bit logical instruction
4607 // M - Constant that can be used as a 32-bit MOV immediate
4608 // N - Constant that can be used as a 64-bit MOV immediate
4609 // Q - A memory reference with base register and no offset
4610 // S - A symbolic address
4611 // Y - Floating point constant zero
4612 // Z - Integer constant zero
4613 //
4614 //   Note that general register operands will be output using their 64-bit x
4615 // register name, whatever the size of the variable, unless the asm operand
4616 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4617 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4618 // %q modifier.
4619 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4620   // At this point, we have to lower this constraint to something else, so we
4621   // lower it to an "r" or "w". However, by doing this we will force the result
4622   // to be in register, while the X constraint is much more permissive.
4623   //
4624   // Although we are correct (we are free to emit anything, without
4625   // constraints), we might break use cases that would expect us to be more
4626   // efficient and emit something else.
4627   if (!Subtarget->hasFPARMv8())
4628     return "r";
4629 
4630   if (ConstraintVT.isFloatingPoint())
4631     return "w";
4632 
4633   if (ConstraintVT.isVector() &&
4634      (ConstraintVT.getSizeInBits() == 64 ||
4635       ConstraintVT.getSizeInBits() == 128))
4636     return "w";
4637 
4638   return "r";
4639 }
4640 
4641 /// getConstraintType - Given a constraint letter, return the type of
4642 /// constraint it is for this target.
4643 AArch64TargetLowering::ConstraintType
4644 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4645   if (Constraint.size() == 1) {
4646     switch (Constraint[0]) {
4647     default:
4648       break;
4649     case 'z':
4650       return C_Other;
4651     case 'x':
4652     case 'w':
4653       return C_RegisterClass;
4654     // An address with a single base register. Due to the way we
4655     // currently handle addresses it is the same as 'r'.
4656     case 'Q':
4657       return C_Memory;
4658     }
4659   }
4660   return TargetLowering::getConstraintType(Constraint);
4661 }
4662 
4663 /// Examine constraint type and operand type and determine a weight value.
4664 /// This object must already have been set up with the operand type
4665 /// and the current alternative constraint selected.
4666 TargetLowering::ConstraintWeight
4667 AArch64TargetLowering::getSingleConstraintMatchWeight(
4668     AsmOperandInfo &info, const char *constraint) const {
4669   ConstraintWeight weight = CW_Invalid;
4670   Value *CallOperandVal = info.CallOperandVal;
4671   // If we don't have a value, we can't do a match,
4672   // but allow it at the lowest weight.
4673   if (!CallOperandVal)
4674     return CW_Default;
4675   Type *type = CallOperandVal->getType();
4676   // Look at the constraint type.
4677   switch (*constraint) {
4678   default:
4679     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4680     break;
4681   case 'x':
4682   case 'w':
4683     if (type->isFloatingPointTy() || type->isVectorTy())
4684       weight = CW_Register;
4685     break;
4686   case 'z':
4687     weight = CW_Constant;
4688     break;
4689   }
4690   return weight;
4691 }
4692 
4693 std::pair<unsigned, const TargetRegisterClass *>
4694 AArch64TargetLowering::getRegForInlineAsmConstraint(
4695     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4696   if (Constraint.size() == 1) {
4697     switch (Constraint[0]) {
4698     case 'r':
4699       if (VT.getSizeInBits() == 64)
4700         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4701       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4702     case 'w':
4703       if (VT.getSizeInBits() == 32)
4704         return std::make_pair(0U, &AArch64::FPR32RegClass);
4705       if (VT.getSizeInBits() == 64)
4706         return std::make_pair(0U, &AArch64::FPR64RegClass);
4707       if (VT.getSizeInBits() == 128)
4708         return std::make_pair(0U, &AArch64::FPR128RegClass);
4709       break;
4710     // The instructions that this constraint is designed for can
4711     // only take 128-bit registers so just use that regclass.
4712     case 'x':
4713       if (VT.getSizeInBits() == 128)
4714         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4715       break;
4716     }
4717   }
4718   if (StringRef("{cc}").equals_lower(Constraint))
4719     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4720 
4721   // Use the default implementation in TargetLowering to convert the register
4722   // constraint into a member of a register class.
4723   std::pair<unsigned, const TargetRegisterClass *> Res;
4724   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4725 
4726   // Not found as a standard register?
4727   if (!Res.second) {
4728     unsigned Size = Constraint.size();
4729     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4730         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4731       int RegNo;
4732       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4733       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4734         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4735         // By default we'll emit v0-v31 for this unless there's a modifier where
4736         // we'll emit the correct register as well.
4737         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4738           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4739           Res.second = &AArch64::FPR64RegClass;
4740         } else {
4741           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4742           Res.second = &AArch64::FPR128RegClass;
4743         }
4744       }
4745     }
4746   }
4747 
4748   return Res;
4749 }
4750 
4751 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4752 /// vector.  If it is invalid, don't add anything to Ops.
4753 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4754     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4755     SelectionDAG &DAG) const {
4756   SDValue Result;
4757 
4758   // Currently only support length 1 constraints.
4759   if (Constraint.length() != 1)
4760     return;
4761 
4762   char ConstraintLetter = Constraint[0];
4763   switch (ConstraintLetter) {
4764   default:
4765     break;
4766 
4767   // This set of constraints deal with valid constants for various instructions.
4768   // Validate and return a target constant for them if we can.
4769   case 'z': {
4770     // 'z' maps to xzr or wzr so it needs an input of 0.
4771     if (!isNullConstant(Op))
4772       return;
4773 
4774     if (Op.getValueType() == MVT::i64)
4775       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4776     else
4777       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4778     break;
4779   }
4780 
4781   case 'I':
4782   case 'J':
4783   case 'K':
4784   case 'L':
4785   case 'M':
4786   case 'N':
4787     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4788     if (!C)
4789       return;
4790 
4791     // Grab the value and do some validation.
4792     uint64_t CVal = C->getZExtValue();
4793     switch (ConstraintLetter) {
4794     // The I constraint applies only to simple ADD or SUB immediate operands:
4795     // i.e. 0 to 4095 with optional shift by 12
4796     // The J constraint applies only to ADD or SUB immediates that would be
4797     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4798     // instruction [or vice versa], in other words -1 to -4095 with optional
4799     // left shift by 12.
4800     case 'I':
4801       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4802         break;
4803       return;
4804     case 'J': {
4805       uint64_t NVal = -C->getSExtValue();
4806       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4807         CVal = C->getSExtValue();
4808         break;
4809       }
4810       return;
4811     }
4812     // The K and L constraints apply *only* to logical immediates, including
4813     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4814     // been removed and MOV should be used). So these constraints have to
4815     // distinguish between bit patterns that are valid 32-bit or 64-bit
4816     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4817     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4818     // versa.
4819     case 'K':
4820       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4821         break;
4822       return;
4823     case 'L':
4824       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4825         break;
4826       return;
4827     // The M and N constraints are a superset of K and L respectively, for use
4828     // with the MOV (immediate) alias. As well as the logical immediates they
4829     // also match 32 or 64-bit immediates that can be loaded either using a
4830     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4831     // (M) or 64-bit 0x1234000000000000 (N) etc.
4832     // As a note some of this code is liberally stolen from the asm parser.
4833     case 'M': {
4834       if (!isUInt<32>(CVal))
4835         return;
4836       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4837         break;
4838       if ((CVal & 0xFFFF) == CVal)
4839         break;
4840       if ((CVal & 0xFFFF0000ULL) == CVal)
4841         break;
4842       uint64_t NCVal = ~(uint32_t)CVal;
4843       if ((NCVal & 0xFFFFULL) == NCVal)
4844         break;
4845       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4846         break;
4847       return;
4848     }
4849     case 'N': {
4850       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4851         break;
4852       if ((CVal & 0xFFFFULL) == CVal)
4853         break;
4854       if ((CVal & 0xFFFF0000ULL) == CVal)
4855         break;
4856       if ((CVal & 0xFFFF00000000ULL) == CVal)
4857         break;
4858       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4859         break;
4860       uint64_t NCVal = ~CVal;
4861       if ((NCVal & 0xFFFFULL) == NCVal)
4862         break;
4863       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4864         break;
4865       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4866         break;
4867       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4868         break;
4869       return;
4870     }
4871     default:
4872       return;
4873     }
4874 
4875     // All assembler immediates are 64-bit integers.
4876     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4877     break;
4878   }
4879 
4880   if (Result.getNode()) {
4881     Ops.push_back(Result);
4882     return;
4883   }
4884 
4885   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4886 }
4887 
4888 //===----------------------------------------------------------------------===//
4889 //                     AArch64 Advanced SIMD Support
4890 //===----------------------------------------------------------------------===//
4891 
4892 /// WidenVector - Given a value in the V64 register class, produce the
4893 /// equivalent value in the V128 register class.
4894 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4895   EVT VT = V64Reg.getValueType();
4896   unsigned NarrowSize = VT.getVectorNumElements();
4897   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4898   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4899   SDLoc DL(V64Reg);
4900 
4901   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4902                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4903 }
4904 
4905 /// getExtFactor - Determine the adjustment factor for the position when
4906 /// generating an "extract from vector registers" instruction.
4907 static unsigned getExtFactor(SDValue &V) {
4908   EVT EltType = V.getValueType().getVectorElementType();
4909   return EltType.getSizeInBits() / 8;
4910 }
4911 
4912 /// NarrowVector - Given a value in the V128 register class, produce the
4913 /// equivalent value in the V64 register class.
4914 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4915   EVT VT = V128Reg.getValueType();
4916   unsigned WideSize = VT.getVectorNumElements();
4917   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4918   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4919   SDLoc DL(V128Reg);
4920 
4921   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4922 }
4923 
4924 // Gather data to see if the operation can be modelled as a
4925 // shuffle in combination with VEXTs.
4926 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4927                                                   SelectionDAG &DAG) const {
4928   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4929   SDLoc dl(Op);
4930   EVT VT = Op.getValueType();
4931   unsigned NumElts = VT.getVectorNumElements();
4932 
4933   struct ShuffleSourceInfo {
4934     SDValue Vec;
4935     unsigned MinElt;
4936     unsigned MaxElt;
4937 
4938     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4939     // be compatible with the shuffle we intend to construct. As a result
4940     // ShuffleVec will be some sliding window into the original Vec.
4941     SDValue ShuffleVec;
4942 
4943     // Code should guarantee that element i in Vec starts at element "WindowBase
4944     // + i * WindowScale in ShuffleVec".
4945     int WindowBase;
4946     int WindowScale;
4947 
4948     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4949     ShuffleSourceInfo(SDValue Vec)
4950         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4951           WindowScale(1) {}
4952   };
4953 
4954   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4955   // node.
4956   SmallVector<ShuffleSourceInfo, 2> Sources;
4957   for (unsigned i = 0; i < NumElts; ++i) {
4958     SDValue V = Op.getOperand(i);
4959     if (V.isUndef())
4960       continue;
4961     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4962              !isa<ConstantSDNode>(V.getOperand(1))) {
4963       // A shuffle can only come from building a vector from various
4964       // elements of other vectors, provided their indices are constant.
4965       return SDValue();
4966     }
4967 
4968     // Add this element source to the list if it's not already there.
4969     SDValue SourceVec = V.getOperand(0);
4970     auto Source = find(Sources, SourceVec);
4971     if (Source == Sources.end())
4972       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4973 
4974     // Update the minimum and maximum lane number seen.
4975     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4976     Source->MinElt = std::min(Source->MinElt, EltNo);
4977     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4978   }
4979 
4980   // Currently only do something sane when at most two source vectors
4981   // are involved.
4982   if (Sources.size() > 2)
4983     return SDValue();
4984 
4985   // Find out the smallest element size among result and two sources, and use
4986   // it as element size to build the shuffle_vector.
4987   EVT SmallestEltTy = VT.getVectorElementType();
4988   for (auto &Source : Sources) {
4989     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4990     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4991       SmallestEltTy = SrcEltTy;
4992     }
4993   }
4994   unsigned ResMultiplier =
4995       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
4996   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4997   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4998 
4999   // If the source vector is too wide or too narrow, we may nevertheless be able
5000   // to construct a compatible shuffle either by concatenating it with UNDEF or
5001   // extracting a suitable range of elements.
5002   for (auto &Src : Sources) {
5003     EVT SrcVT = Src.ShuffleVec.getValueType();
5004 
5005     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5006       continue;
5007 
5008     // This stage of the search produces a source with the same element type as
5009     // the original, but with a total width matching the BUILD_VECTOR output.
5010     EVT EltVT = SrcVT.getVectorElementType();
5011     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5012     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5013 
5014     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5015       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5016       // We can pad out the smaller vector for free, so if it's part of a
5017       // shuffle...
5018       Src.ShuffleVec =
5019           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5020                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5021       continue;
5022     }
5023 
5024     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5025 
5026     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5027       // Span too large for a VEXT to cope
5028       return SDValue();
5029     }
5030 
5031     if (Src.MinElt >= NumSrcElts) {
5032       // The extraction can just take the second half
5033       Src.ShuffleVec =
5034           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5035                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5036       Src.WindowBase = -NumSrcElts;
5037     } else if (Src.MaxElt < NumSrcElts) {
5038       // The extraction can just take the first half
5039       Src.ShuffleVec =
5040           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5041                       DAG.getConstant(0, dl, MVT::i64));
5042     } else {
5043       // An actual VEXT is needed
5044       SDValue VEXTSrc1 =
5045           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5046                       DAG.getConstant(0, dl, MVT::i64));
5047       SDValue VEXTSrc2 =
5048           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5049                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5050       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5051 
5052       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5053                                    VEXTSrc2,
5054                                    DAG.getConstant(Imm, dl, MVT::i32));
5055       Src.WindowBase = -Src.MinElt;
5056     }
5057   }
5058 
5059   // Another possible incompatibility occurs from the vector element types. We
5060   // can fix this by bitcasting the source vectors to the same type we intend
5061   // for the shuffle.
5062   for (auto &Src : Sources) {
5063     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5064     if (SrcEltTy == SmallestEltTy)
5065       continue;
5066     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5067     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5068     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5069     Src.WindowBase *= Src.WindowScale;
5070   }
5071 
5072   // Final sanity check before we try to actually produce a shuffle.
5073   DEBUG(
5074     for (auto Src : Sources)
5075       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5076   );
5077 
5078   // The stars all align, our next step is to produce the mask for the shuffle.
5079   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5080   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5081   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5082     SDValue Entry = Op.getOperand(i);
5083     if (Entry.isUndef())
5084       continue;
5085 
5086     auto Src = find(Sources, Entry.getOperand(0));
5087     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5088 
5089     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5090     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5091     // segment.
5092     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5093     int BitsDefined =
5094         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5095     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5096 
5097     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5098     // starting at the appropriate offset.
5099     int *LaneMask = &Mask[i * ResMultiplier];
5100 
5101     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5102     ExtractBase += NumElts * (Src - Sources.begin());
5103     for (int j = 0; j < LanesDefined; ++j)
5104       LaneMask[j] = ExtractBase + j;
5105   }
5106 
5107   // Final check before we try to produce nonsense...
5108   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5109     return SDValue();
5110 
5111   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5112   for (unsigned i = 0; i < Sources.size(); ++i)
5113     ShuffleOps[i] = Sources[i].ShuffleVec;
5114 
5115   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5116                                          ShuffleOps[1], Mask);
5117   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5118 }
5119 
5120 // check if an EXT instruction can handle the shuffle mask when the
5121 // vector sources of the shuffle are the same.
5122 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5123   unsigned NumElts = VT.getVectorNumElements();
5124 
5125   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5126   if (M[0] < 0)
5127     return false;
5128 
5129   Imm = M[0];
5130 
5131   // If this is a VEXT shuffle, the immediate value is the index of the first
5132   // element.  The other shuffle indices must be the successive elements after
5133   // the first one.
5134   unsigned ExpectedElt = Imm;
5135   for (unsigned i = 1; i < NumElts; ++i) {
5136     // Increment the expected index.  If it wraps around, just follow it
5137     // back to index zero and keep going.
5138     ++ExpectedElt;
5139     if (ExpectedElt == NumElts)
5140       ExpectedElt = 0;
5141 
5142     if (M[i] < 0)
5143       continue; // ignore UNDEF indices
5144     if (ExpectedElt != static_cast<unsigned>(M[i]))
5145       return false;
5146   }
5147 
5148   return true;
5149 }
5150 
5151 // check if an EXT instruction can handle the shuffle mask when the
5152 // vector sources of the shuffle are different.
5153 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5154                       unsigned &Imm) {
5155   // Look for the first non-undef element.
5156   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5157 
5158   // Benefit form APInt to handle overflow when calculating expected element.
5159   unsigned NumElts = VT.getVectorNumElements();
5160   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5161   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5162   // The following shuffle indices must be the successive elements after the
5163   // first real element.
5164   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5165       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5166   if (FirstWrongElt != M.end())
5167     return false;
5168 
5169   // The index of an EXT is the first element if it is not UNDEF.
5170   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5171   // value of the first element.  E.g.
5172   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5173   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5174   // ExpectedElt is the last mask index plus 1.
5175   Imm = ExpectedElt.getZExtValue();
5176 
5177   // There are two difference cases requiring to reverse input vectors.
5178   // For example, for vector <4 x i32> we have the following cases,
5179   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5180   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5181   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5182   // to reverse two input vectors.
5183   if (Imm < NumElts)
5184     ReverseEXT = true;
5185   else
5186     Imm -= NumElts;
5187 
5188   return true;
5189 }
5190 
5191 /// isREVMask - Check if a vector shuffle corresponds to a REV
5192 /// instruction with the specified blocksize.  (The order of the elements
5193 /// within each block of the vector is reversed.)
5194 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5195   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5196          "Only possible block sizes for REV are: 16, 32, 64");
5197 
5198   unsigned EltSz = VT.getScalarSizeInBits();
5199   if (EltSz == 64)
5200     return false;
5201 
5202   unsigned NumElts = VT.getVectorNumElements();
5203   unsigned BlockElts = M[0] + 1;
5204   // If the first shuffle index is UNDEF, be optimistic.
5205   if (M[0] < 0)
5206     BlockElts = BlockSize / EltSz;
5207 
5208   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5209     return false;
5210 
5211   for (unsigned i = 0; i < NumElts; ++i) {
5212     if (M[i] < 0)
5213       continue; // ignore UNDEF indices
5214     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5215       return false;
5216   }
5217 
5218   return true;
5219 }
5220 
5221 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5222   unsigned NumElts = VT.getVectorNumElements();
5223   WhichResult = (M[0] == 0 ? 0 : 1);
5224   unsigned Idx = WhichResult * NumElts / 2;
5225   for (unsigned i = 0; i != NumElts; i += 2) {
5226     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5227         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5228       return false;
5229     Idx += 1;
5230   }
5231 
5232   return true;
5233 }
5234 
5235 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5236   unsigned NumElts = VT.getVectorNumElements();
5237   WhichResult = (M[0] == 0 ? 0 : 1);
5238   for (unsigned i = 0; i != NumElts; ++i) {
5239     if (M[i] < 0)
5240       continue; // ignore UNDEF indices
5241     if ((unsigned)M[i] != 2 * i + WhichResult)
5242       return false;
5243   }
5244 
5245   return true;
5246 }
5247 
5248 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5249   unsigned NumElts = VT.getVectorNumElements();
5250   WhichResult = (M[0] == 0 ? 0 : 1);
5251   for (unsigned i = 0; i < NumElts; i += 2) {
5252     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5253         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5254       return false;
5255   }
5256   return true;
5257 }
5258 
5259 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5260 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5261 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5262 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5263   unsigned NumElts = VT.getVectorNumElements();
5264   WhichResult = (M[0] == 0 ? 0 : 1);
5265   unsigned Idx = WhichResult * NumElts / 2;
5266   for (unsigned i = 0; i != NumElts; i += 2) {
5267     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5268         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5269       return false;
5270     Idx += 1;
5271   }
5272 
5273   return true;
5274 }
5275 
5276 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5277 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5278 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5279 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5280   unsigned Half = VT.getVectorNumElements() / 2;
5281   WhichResult = (M[0] == 0 ? 0 : 1);
5282   for (unsigned j = 0; j != 2; ++j) {
5283     unsigned Idx = WhichResult;
5284     for (unsigned i = 0; i != Half; ++i) {
5285       int MIdx = M[i + j * Half];
5286       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5287         return false;
5288       Idx += 2;
5289     }
5290   }
5291 
5292   return true;
5293 }
5294 
5295 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5296 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5297 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5298 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5299   unsigned NumElts = VT.getVectorNumElements();
5300   WhichResult = (M[0] == 0 ? 0 : 1);
5301   for (unsigned i = 0; i < NumElts; i += 2) {
5302     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5303         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5304       return false;
5305   }
5306   return true;
5307 }
5308 
5309 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5310                       bool &DstIsLeft, int &Anomaly) {
5311   if (M.size() != static_cast<size_t>(NumInputElements))
5312     return false;
5313 
5314   int NumLHSMatch = 0, NumRHSMatch = 0;
5315   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5316 
5317   for (int i = 0; i < NumInputElements; ++i) {
5318     if (M[i] == -1) {
5319       ++NumLHSMatch;
5320       ++NumRHSMatch;
5321       continue;
5322     }
5323 
5324     if (M[i] == i)
5325       ++NumLHSMatch;
5326     else
5327       LastLHSMismatch = i;
5328 
5329     if (M[i] == i + NumInputElements)
5330       ++NumRHSMatch;
5331     else
5332       LastRHSMismatch = i;
5333   }
5334 
5335   if (NumLHSMatch == NumInputElements - 1) {
5336     DstIsLeft = true;
5337     Anomaly = LastLHSMismatch;
5338     return true;
5339   } else if (NumRHSMatch == NumInputElements - 1) {
5340     DstIsLeft = false;
5341     Anomaly = LastRHSMismatch;
5342     return true;
5343   }
5344 
5345   return false;
5346 }
5347 
5348 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5349   if (VT.getSizeInBits() != 128)
5350     return false;
5351 
5352   unsigned NumElts = VT.getVectorNumElements();
5353 
5354   for (int I = 0, E = NumElts / 2; I != E; I++) {
5355     if (Mask[I] != I)
5356       return false;
5357   }
5358 
5359   int Offset = NumElts / 2;
5360   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5361     if (Mask[I] != I + SplitLHS * Offset)
5362       return false;
5363   }
5364 
5365   return true;
5366 }
5367 
5368 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5369   SDLoc DL(Op);
5370   EVT VT = Op.getValueType();
5371   SDValue V0 = Op.getOperand(0);
5372   SDValue V1 = Op.getOperand(1);
5373   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5374 
5375   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5376       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5377     return SDValue();
5378 
5379   bool SplitV0 = V0.getValueSizeInBits() == 128;
5380 
5381   if (!isConcatMask(Mask, VT, SplitV0))
5382     return SDValue();
5383 
5384   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5385                                 VT.getVectorNumElements() / 2);
5386   if (SplitV0) {
5387     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5388                      DAG.getConstant(0, DL, MVT::i64));
5389   }
5390   if (V1.getValueSizeInBits() == 128) {
5391     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5392                      DAG.getConstant(0, DL, MVT::i64));
5393   }
5394   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5395 }
5396 
5397 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5398 /// the specified operations to build the shuffle.
5399 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5400                                       SDValue RHS, SelectionDAG &DAG,
5401                                       const SDLoc &dl) {
5402   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5403   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5404   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5405 
5406   enum {
5407     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5408     OP_VREV,
5409     OP_VDUP0,
5410     OP_VDUP1,
5411     OP_VDUP2,
5412     OP_VDUP3,
5413     OP_VEXT1,
5414     OP_VEXT2,
5415     OP_VEXT3,
5416     OP_VUZPL, // VUZP, left result
5417     OP_VUZPR, // VUZP, right result
5418     OP_VZIPL, // VZIP, left result
5419     OP_VZIPR, // VZIP, right result
5420     OP_VTRNL, // VTRN, left result
5421     OP_VTRNR  // VTRN, right result
5422   };
5423 
5424   if (OpNum == OP_COPY) {
5425     if (LHSID == (1 * 9 + 2) * 9 + 3)
5426       return LHS;
5427     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5428     return RHS;
5429   }
5430 
5431   SDValue OpLHS, OpRHS;
5432   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5433   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5434   EVT VT = OpLHS.getValueType();
5435 
5436   switch (OpNum) {
5437   default:
5438     llvm_unreachable("Unknown shuffle opcode!");
5439   case OP_VREV:
5440     // VREV divides the vector in half and swaps within the half.
5441     if (VT.getVectorElementType() == MVT::i32 ||
5442         VT.getVectorElementType() == MVT::f32)
5443       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5444     // vrev <4 x i16> -> REV32
5445     if (VT.getVectorElementType() == MVT::i16 ||
5446         VT.getVectorElementType() == MVT::f16)
5447       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5448     // vrev <4 x i8> -> REV16
5449     assert(VT.getVectorElementType() == MVT::i8);
5450     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5451   case OP_VDUP0:
5452   case OP_VDUP1:
5453   case OP_VDUP2:
5454   case OP_VDUP3: {
5455     EVT EltTy = VT.getVectorElementType();
5456     unsigned Opcode;
5457     if (EltTy == MVT::i8)
5458       Opcode = AArch64ISD::DUPLANE8;
5459     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5460       Opcode = AArch64ISD::DUPLANE16;
5461     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5462       Opcode = AArch64ISD::DUPLANE32;
5463     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5464       Opcode = AArch64ISD::DUPLANE64;
5465     else
5466       llvm_unreachable("Invalid vector element type?");
5467 
5468     if (VT.getSizeInBits() == 64)
5469       OpLHS = WidenVector(OpLHS, DAG);
5470     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5471     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5472   }
5473   case OP_VEXT1:
5474   case OP_VEXT2:
5475   case OP_VEXT3: {
5476     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5477     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5478                        DAG.getConstant(Imm, dl, MVT::i32));
5479   }
5480   case OP_VUZPL:
5481     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5482                        OpRHS);
5483   case OP_VUZPR:
5484     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5485                        OpRHS);
5486   case OP_VZIPL:
5487     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5488                        OpRHS);
5489   case OP_VZIPR:
5490     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5491                        OpRHS);
5492   case OP_VTRNL:
5493     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5494                        OpRHS);
5495   case OP_VTRNR:
5496     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5497                        OpRHS);
5498   }
5499 }
5500 
5501 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5502                            SelectionDAG &DAG) {
5503   // Check to see if we can use the TBL instruction.
5504   SDValue V1 = Op.getOperand(0);
5505   SDValue V2 = Op.getOperand(1);
5506   SDLoc DL(Op);
5507 
5508   EVT EltVT = Op.getValueType().getVectorElementType();
5509   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5510 
5511   SmallVector<SDValue, 8> TBLMask;
5512   for (int Val : ShuffleMask) {
5513     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5514       unsigned Offset = Byte + Val * BytesPerElt;
5515       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5516     }
5517   }
5518 
5519   MVT IndexVT = MVT::v8i8;
5520   unsigned IndexLen = 8;
5521   if (Op.getValueSizeInBits() == 128) {
5522     IndexVT = MVT::v16i8;
5523     IndexLen = 16;
5524   }
5525 
5526   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5527   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5528 
5529   SDValue Shuffle;
5530   if (V2.getNode()->isUndef()) {
5531     if (IndexLen == 8)
5532       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5533     Shuffle = DAG.getNode(
5534         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5535         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5536         DAG.getBuildVector(IndexVT, DL,
5537                            makeArrayRef(TBLMask.data(), IndexLen)));
5538   } else {
5539     if (IndexLen == 8) {
5540       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5541       Shuffle = DAG.getNode(
5542           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5543           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5544           DAG.getBuildVector(IndexVT, DL,
5545                              makeArrayRef(TBLMask.data(), IndexLen)));
5546     } else {
5547       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5548       // cannot currently represent the register constraints on the input
5549       // table registers.
5550       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5551       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5552       //                   IndexLen));
5553       Shuffle = DAG.getNode(
5554           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5555           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5556           V2Cst, DAG.getBuildVector(IndexVT, DL,
5557                                     makeArrayRef(TBLMask.data(), IndexLen)));
5558     }
5559   }
5560   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5561 }
5562 
5563 static unsigned getDUPLANEOp(EVT EltType) {
5564   if (EltType == MVT::i8)
5565     return AArch64ISD::DUPLANE8;
5566   if (EltType == MVT::i16 || EltType == MVT::f16)
5567     return AArch64ISD::DUPLANE16;
5568   if (EltType == MVT::i32 || EltType == MVT::f32)
5569     return AArch64ISD::DUPLANE32;
5570   if (EltType == MVT::i64 || EltType == MVT::f64)
5571     return AArch64ISD::DUPLANE64;
5572 
5573   llvm_unreachable("Invalid vector element type?");
5574 }
5575 
5576 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5577                                                    SelectionDAG &DAG) const {
5578   SDLoc dl(Op);
5579   EVT VT = Op.getValueType();
5580 
5581   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5582 
5583   // Convert shuffles that are directly supported on NEON to target-specific
5584   // DAG nodes, instead of keeping them as shuffles and matching them again
5585   // during code selection.  This is more efficient and avoids the possibility
5586   // of inconsistencies between legalization and selection.
5587   ArrayRef<int> ShuffleMask = SVN->getMask();
5588 
5589   SDValue V1 = Op.getOperand(0);
5590   SDValue V2 = Op.getOperand(1);
5591 
5592   if (SVN->isSplat()) {
5593     int Lane = SVN->getSplatIndex();
5594     // If this is undef splat, generate it via "just" vdup, if possible.
5595     if (Lane == -1)
5596       Lane = 0;
5597 
5598     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5599       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5600                          V1.getOperand(0));
5601     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5602     // constant. If so, we can just reference the lane's definition directly.
5603     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5604         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5605       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5606 
5607     // Otherwise, duplicate from the lane of the input vector.
5608     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5609 
5610     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5611     // to make a vector of the same size as this SHUFFLE. We can ignore the
5612     // extract entirely, and canonicalise the concat using WidenVector.
5613     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5614       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5615       V1 = V1.getOperand(0);
5616     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5617       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5618       Lane -= Idx * VT.getVectorNumElements() / 2;
5619       V1 = WidenVector(V1.getOperand(Idx), DAG);
5620     } else if (VT.getSizeInBits() == 64)
5621       V1 = WidenVector(V1, DAG);
5622 
5623     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5624   }
5625 
5626   if (isREVMask(ShuffleMask, VT, 64))
5627     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5628   if (isREVMask(ShuffleMask, VT, 32))
5629     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5630   if (isREVMask(ShuffleMask, VT, 16))
5631     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5632 
5633   bool ReverseEXT = false;
5634   unsigned Imm;
5635   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5636     if (ReverseEXT)
5637       std::swap(V1, V2);
5638     Imm *= getExtFactor(V1);
5639     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5640                        DAG.getConstant(Imm, dl, MVT::i32));
5641   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5642     Imm *= getExtFactor(V1);
5643     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5644                        DAG.getConstant(Imm, dl, MVT::i32));
5645   }
5646 
5647   unsigned WhichResult;
5648   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5649     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5650     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5651   }
5652   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5653     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5654     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5655   }
5656   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5657     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5658     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5659   }
5660 
5661   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5662     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5663     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5664   }
5665   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5666     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5667     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5668   }
5669   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5670     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5671     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5672   }
5673 
5674   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5675     return Concat;
5676 
5677   bool DstIsLeft;
5678   int Anomaly;
5679   int NumInputElements = V1.getValueType().getVectorNumElements();
5680   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5681     SDValue DstVec = DstIsLeft ? V1 : V2;
5682     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5683 
5684     SDValue SrcVec = V1;
5685     int SrcLane = ShuffleMask[Anomaly];
5686     if (SrcLane >= NumInputElements) {
5687       SrcVec = V2;
5688       SrcLane -= VT.getVectorNumElements();
5689     }
5690     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5691 
5692     EVT ScalarVT = VT.getVectorElementType();
5693 
5694     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5695       ScalarVT = MVT::i32;
5696 
5697     return DAG.getNode(
5698         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5699         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5700         DstLaneV);
5701   }
5702 
5703   // If the shuffle is not directly supported and it has 4 elements, use
5704   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5705   unsigned NumElts = VT.getVectorNumElements();
5706   if (NumElts == 4) {
5707     unsigned PFIndexes[4];
5708     for (unsigned i = 0; i != 4; ++i) {
5709       if (ShuffleMask[i] < 0)
5710         PFIndexes[i] = 8;
5711       else
5712         PFIndexes[i] = ShuffleMask[i];
5713     }
5714 
5715     // Compute the index in the perfect shuffle table.
5716     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5717                             PFIndexes[2] * 9 + PFIndexes[3];
5718     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5719     unsigned Cost = (PFEntry >> 30);
5720 
5721     if (Cost <= 4)
5722       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5723   }
5724 
5725   return GenerateTBL(Op, ShuffleMask, DAG);
5726 }
5727 
5728 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5729                                APInt &UndefBits) {
5730   EVT VT = BVN->getValueType(0);
5731   APInt SplatBits, SplatUndef;
5732   unsigned SplatBitSize;
5733   bool HasAnyUndefs;
5734   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5735     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5736 
5737     for (unsigned i = 0; i < NumSplats; ++i) {
5738       CnstBits <<= SplatBitSize;
5739       UndefBits <<= SplatBitSize;
5740       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5741       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5742     }
5743 
5744     return true;
5745   }
5746 
5747   return false;
5748 }
5749 
5750 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5751                                               SelectionDAG &DAG) const {
5752   BuildVectorSDNode *BVN =
5753       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5754   SDValue LHS = Op.getOperand(0);
5755   SDLoc dl(Op);
5756   EVT VT = Op.getValueType();
5757 
5758   if (!BVN)
5759     return Op;
5760 
5761   APInt CnstBits(VT.getSizeInBits(), 0);
5762   APInt UndefBits(VT.getSizeInBits(), 0);
5763   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5764     // We only have BIC vector immediate instruction, which is and-not.
5765     CnstBits = ~CnstBits;
5766 
5767     // We make use of a little bit of goto ickiness in order to avoid having to
5768     // duplicate the immediate matching logic for the undef toggled case.
5769     bool SecondTry = false;
5770   AttemptModImm:
5771 
5772     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5773       CnstBits = CnstBits.zextOrTrunc(64);
5774       uint64_t CnstVal = CnstBits.getZExtValue();
5775 
5776       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5777         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5778         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5779         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5780                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5781                                   DAG.getConstant(0, dl, MVT::i32));
5782         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5783       }
5784 
5785       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5786         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5787         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5788         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5789                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5790                                   DAG.getConstant(8, dl, MVT::i32));
5791         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5792       }
5793 
5794       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5795         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5796         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5797         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5798                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5799                                   DAG.getConstant(16, dl, MVT::i32));
5800         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5801       }
5802 
5803       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5804         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5805         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5806         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5807                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5808                                   DAG.getConstant(24, dl, MVT::i32));
5809         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5810       }
5811 
5812       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5813         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5814         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5815         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5816                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5817                                   DAG.getConstant(0, dl, MVT::i32));
5818         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5819       }
5820 
5821       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5822         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5823         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5824         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5825                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5826                                   DAG.getConstant(8, dl, MVT::i32));
5827         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5828       }
5829     }
5830 
5831     if (SecondTry)
5832       goto FailedModImm;
5833     SecondTry = true;
5834     CnstBits = ~UndefBits;
5835     goto AttemptModImm;
5836   }
5837 
5838 // We can always fall back to a non-immediate AND.
5839 FailedModImm:
5840   return Op;
5841 }
5842 
5843 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5844 // consists of only the same constant int value, returned in reference arg
5845 // ConstVal
5846 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5847                                      uint64_t &ConstVal) {
5848   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5849   if (!Bvec)
5850     return false;
5851   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5852   if (!FirstElt)
5853     return false;
5854   EVT VT = Bvec->getValueType(0);
5855   unsigned NumElts = VT.getVectorNumElements();
5856   for (unsigned i = 1; i < NumElts; ++i)
5857     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5858       return false;
5859   ConstVal = FirstElt->getZExtValue();
5860   return true;
5861 }
5862 
5863 static unsigned getIntrinsicID(const SDNode *N) {
5864   unsigned Opcode = N->getOpcode();
5865   switch (Opcode) {
5866   default:
5867     return Intrinsic::not_intrinsic;
5868   case ISD::INTRINSIC_WO_CHAIN: {
5869     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5870     if (IID < Intrinsic::num_intrinsics)
5871       return IID;
5872     return Intrinsic::not_intrinsic;
5873   }
5874   }
5875 }
5876 
5877 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5878 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5879 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5880 // Also, logical shift right -> sri, with the same structure.
5881 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5882   EVT VT = N->getValueType(0);
5883 
5884   if (!VT.isVector())
5885     return SDValue();
5886 
5887   SDLoc DL(N);
5888 
5889   // Is the first op an AND?
5890   const SDValue And = N->getOperand(0);
5891   if (And.getOpcode() != ISD::AND)
5892     return SDValue();
5893 
5894   // Is the second op an shl or lshr?
5895   SDValue Shift = N->getOperand(1);
5896   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5897   // or AArch64ISD::VLSHR vector, #shift
5898   unsigned ShiftOpc = Shift.getOpcode();
5899   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5900     return SDValue();
5901   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5902 
5903   // Is the shift amount constant?
5904   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5905   if (!C2node)
5906     return SDValue();
5907 
5908   // Is the and mask vector all constant?
5909   uint64_t C1;
5910   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5911     return SDValue();
5912 
5913   // Is C1 == ~C2, taking into account how much one can shift elements of a
5914   // particular size?
5915   uint64_t C2 = C2node->getZExtValue();
5916   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
5917   if (C2 > ElemSizeInBits)
5918     return SDValue();
5919   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5920   if ((C1 & ElemMask) != (~C2 & ElemMask))
5921     return SDValue();
5922 
5923   SDValue X = And.getOperand(0);
5924   SDValue Y = Shift.getOperand(0);
5925 
5926   unsigned Intrin =
5927       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5928   SDValue ResultSLI =
5929       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5930                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5931                   Shift.getOperand(1));
5932 
5933   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5934   DEBUG(N->dump(&DAG));
5935   DEBUG(dbgs() << "into: \n");
5936   DEBUG(ResultSLI->dump(&DAG));
5937 
5938   ++NumShiftInserts;
5939   return ResultSLI;
5940 }
5941 
5942 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5943                                              SelectionDAG &DAG) const {
5944   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5945   if (EnableAArch64SlrGeneration) {
5946     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
5947       return Res;
5948   }
5949 
5950   BuildVectorSDNode *BVN =
5951       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5952   SDValue LHS = Op.getOperand(1);
5953   SDLoc dl(Op);
5954   EVT VT = Op.getValueType();
5955 
5956   // OR commutes, so try swapping the operands.
5957   if (!BVN) {
5958     LHS = Op.getOperand(0);
5959     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5960   }
5961   if (!BVN)
5962     return Op;
5963 
5964   APInt CnstBits(VT.getSizeInBits(), 0);
5965   APInt UndefBits(VT.getSizeInBits(), 0);
5966   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5967     // We make use of a little bit of goto ickiness in order to avoid having to
5968     // duplicate the immediate matching logic for the undef toggled case.
5969     bool SecondTry = false;
5970   AttemptModImm:
5971 
5972     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5973       CnstBits = CnstBits.zextOrTrunc(64);
5974       uint64_t CnstVal = CnstBits.getZExtValue();
5975 
5976       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5977         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5978         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5979         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5980                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5981                                   DAG.getConstant(0, dl, MVT::i32));
5982         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5983       }
5984 
5985       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5986         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5987         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5988         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5989                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5990                                   DAG.getConstant(8, dl, MVT::i32));
5991         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5992       }
5993 
5994       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5995         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5996         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5997         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5998                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5999                                   DAG.getConstant(16, dl, MVT::i32));
6000         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6001       }
6002 
6003       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6004         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6005         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6006         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6007                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6008                                   DAG.getConstant(24, dl, MVT::i32));
6009         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6010       }
6011 
6012       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6013         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6014         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6015         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6016                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6017                                   DAG.getConstant(0, dl, MVT::i32));
6018         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6019       }
6020 
6021       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6022         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6023         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6024         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6025                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6026                                   DAG.getConstant(8, dl, MVT::i32));
6027         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6028       }
6029     }
6030 
6031     if (SecondTry)
6032       goto FailedModImm;
6033     SecondTry = true;
6034     CnstBits = UndefBits;
6035     goto AttemptModImm;
6036   }
6037 
6038 // We can always fall back to a non-immediate OR.
6039 FailedModImm:
6040   return Op;
6041 }
6042 
6043 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6044 // be truncated to fit element width.
6045 static SDValue NormalizeBuildVector(SDValue Op,
6046                                     SelectionDAG &DAG) {
6047   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6048   SDLoc dl(Op);
6049   EVT VT = Op.getValueType();
6050   EVT EltTy= VT.getVectorElementType();
6051 
6052   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6053     return Op;
6054 
6055   SmallVector<SDValue, 16> Ops;
6056   for (SDValue Lane : Op->ops()) {
6057     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6058       APInt LowBits(EltTy.getSizeInBits(),
6059                     CstLane->getZExtValue());
6060       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6061     }
6062     Ops.push_back(Lane);
6063   }
6064   return DAG.getBuildVector(VT, dl, Ops);
6065 }
6066 
6067 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6068                                                  SelectionDAG &DAG) const {
6069   SDLoc dl(Op);
6070   EVT VT = Op.getValueType();
6071   Op = NormalizeBuildVector(Op, DAG);
6072   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6073 
6074   APInt CnstBits(VT.getSizeInBits(), 0);
6075   APInt UndefBits(VT.getSizeInBits(), 0);
6076   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6077     // We make use of a little bit of goto ickiness in order to avoid having to
6078     // duplicate the immediate matching logic for the undef toggled case.
6079     bool SecondTry = false;
6080   AttemptModImm:
6081 
6082     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6083       CnstBits = CnstBits.zextOrTrunc(64);
6084       uint64_t CnstVal = CnstBits.getZExtValue();
6085 
6086       // Certain magic vector constants (used to express things like NOT
6087       // and NEG) are passed through unmodified.  This allows codegen patterns
6088       // for these operations to match.  Special-purpose patterns will lower
6089       // these immediates to MOVIs if it proves necessary.
6090       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6091         return Op;
6092 
6093       // The many faces of MOVI...
6094       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6095         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6096         if (VT.getSizeInBits() == 128) {
6097           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6098                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6099           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6100         }
6101 
6102         // Support the V64 version via subregister insertion.
6103         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6104                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6105         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6106       }
6107 
6108       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6109         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6110         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6111         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6112                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6113                                   DAG.getConstant(0, dl, MVT::i32));
6114         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6115       }
6116 
6117       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6118         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6119         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6120         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6121                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6122                                   DAG.getConstant(8, dl, MVT::i32));
6123         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6124       }
6125 
6126       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6127         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6128         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6129         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6130                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6131                                   DAG.getConstant(16, dl, MVT::i32));
6132         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6133       }
6134 
6135       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6136         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6137         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6138         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6139                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6140                                   DAG.getConstant(24, dl, MVT::i32));
6141         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6142       }
6143 
6144       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6145         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6146         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6147         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6148                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6149                                   DAG.getConstant(0, dl, MVT::i32));
6150         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6151       }
6152 
6153       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6154         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6155         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6156         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6157                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6158                                   DAG.getConstant(8, dl, MVT::i32));
6159         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6160       }
6161 
6162       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6163         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6164         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6165         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6166                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6167                                   DAG.getConstant(264, dl, MVT::i32));
6168         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6169       }
6170 
6171       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6172         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6173         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6174         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6175                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6176                                   DAG.getConstant(272, dl, MVT::i32));
6177         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6178       }
6179 
6180       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6181         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6182         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6183         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6184                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6185         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6186       }
6187 
6188       // The few faces of FMOV...
6189       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6190         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6191         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6192         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6193                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6194         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6195       }
6196 
6197       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6198           VT.getSizeInBits() == 128) {
6199         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6200         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6201                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6202         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6203       }
6204 
6205       // The many faces of MVNI...
6206       CnstVal = ~CnstVal;
6207       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6208         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6209         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6210         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6211                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6212                                   DAG.getConstant(0, dl, MVT::i32));
6213         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6214       }
6215 
6216       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6217         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6218         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6219         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6220                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6221                                   DAG.getConstant(8, dl, MVT::i32));
6222         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6223       }
6224 
6225       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6226         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6227         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6228         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6229                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6230                                   DAG.getConstant(16, dl, MVT::i32));
6231         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6232       }
6233 
6234       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6235         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6236         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6237         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6238                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6239                                   DAG.getConstant(24, dl, MVT::i32));
6240         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6241       }
6242 
6243       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6244         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6245         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6246         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6247                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6248                                   DAG.getConstant(0, dl, MVT::i32));
6249         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6250       }
6251 
6252       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6253         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6254         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6255         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6256                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6257                                   DAG.getConstant(8, dl, MVT::i32));
6258         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6259       }
6260 
6261       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6262         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6263         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6264         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6265                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6266                                   DAG.getConstant(264, dl, MVT::i32));
6267         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6268       }
6269 
6270       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6271         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6272         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6273         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6274                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6275                                   DAG.getConstant(272, dl, MVT::i32));
6276         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6277       }
6278     }
6279 
6280     if (SecondTry)
6281       goto FailedModImm;
6282     SecondTry = true;
6283     CnstBits = UndefBits;
6284     goto AttemptModImm;
6285   }
6286 FailedModImm:
6287 
6288   // Scan through the operands to find some interesting properties we can
6289   // exploit:
6290   //   1) If only one value is used, we can use a DUP, or
6291   //   2) if only the low element is not undef, we can just insert that, or
6292   //   3) if only one constant value is used (w/ some non-constant lanes),
6293   //      we can splat the constant value into the whole vector then fill
6294   //      in the non-constant lanes.
6295   //   4) FIXME: If different constant values are used, but we can intelligently
6296   //             select the values we'll be overwriting for the non-constant
6297   //             lanes such that we can directly materialize the vector
6298   //             some other way (MOVI, e.g.), we can be sneaky.
6299   unsigned NumElts = VT.getVectorNumElements();
6300   bool isOnlyLowElement = true;
6301   bool usesOnlyOneValue = true;
6302   bool usesOnlyOneConstantValue = true;
6303   bool isConstant = true;
6304   unsigned NumConstantLanes = 0;
6305   SDValue Value;
6306   SDValue ConstantValue;
6307   for (unsigned i = 0; i < NumElts; ++i) {
6308     SDValue V = Op.getOperand(i);
6309     if (V.isUndef())
6310       continue;
6311     if (i > 0)
6312       isOnlyLowElement = false;
6313     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6314       isConstant = false;
6315 
6316     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6317       ++NumConstantLanes;
6318       if (!ConstantValue.getNode())
6319         ConstantValue = V;
6320       else if (ConstantValue != V)
6321         usesOnlyOneConstantValue = false;
6322     }
6323 
6324     if (!Value.getNode())
6325       Value = V;
6326     else if (V != Value)
6327       usesOnlyOneValue = false;
6328   }
6329 
6330   if (!Value.getNode())
6331     return DAG.getUNDEF(VT);
6332 
6333   if (isOnlyLowElement)
6334     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6335 
6336   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6337   // i32 and try again.
6338   if (usesOnlyOneValue) {
6339     if (!isConstant) {
6340       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6341           Value.getValueType() != VT)
6342         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6343 
6344       // This is actually a DUPLANExx operation, which keeps everything vectory.
6345 
6346       // DUPLANE works on 128-bit vectors, widen it if necessary.
6347       SDValue Lane = Value.getOperand(1);
6348       Value = Value.getOperand(0);
6349       if (Value.getValueSizeInBits() == 64)
6350         Value = WidenVector(Value, DAG);
6351 
6352       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6353       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6354     }
6355 
6356     if (VT.getVectorElementType().isFloatingPoint()) {
6357       SmallVector<SDValue, 8> Ops;
6358       EVT EltTy = VT.getVectorElementType();
6359       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6360               "Unsupported floating-point vector type");
6361       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6362       for (unsigned i = 0; i < NumElts; ++i)
6363         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6364       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6365       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6366       Val = LowerBUILD_VECTOR(Val, DAG);
6367       if (Val.getNode())
6368         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6369     }
6370   }
6371 
6372   // If there was only one constant value used and for more than one lane,
6373   // start by splatting that value, then replace the non-constant lanes. This
6374   // is better than the default, which will perform a separate initialization
6375   // for each lane.
6376   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6377     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6378     // Now insert the non-constant lanes.
6379     for (unsigned i = 0; i < NumElts; ++i) {
6380       SDValue V = Op.getOperand(i);
6381       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6382       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6383         // Note that type legalization likely mucked about with the VT of the
6384         // source operand, so we may have to convert it here before inserting.
6385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6386       }
6387     }
6388     return Val;
6389   }
6390 
6391   // If all elements are constants and the case above didn't get hit, fall back
6392   // to the default expansion, which will generate a load from the constant
6393   // pool.
6394   if (isConstant)
6395     return SDValue();
6396 
6397   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6398   if (NumElts >= 4) {
6399     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6400       return shuffle;
6401   }
6402 
6403   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6404   // know the default expansion would otherwise fall back on something even
6405   // worse. For a vector with one or two non-undef values, that's
6406   // scalar_to_vector for the elements followed by a shuffle (provided the
6407   // shuffle is valid for the target) and materialization element by element
6408   // on the stack followed by a load for everything else.
6409   if (!isConstant && !usesOnlyOneValue) {
6410     SDValue Vec = DAG.getUNDEF(VT);
6411     SDValue Op0 = Op.getOperand(0);
6412     unsigned ElemSize = VT.getScalarSizeInBits();
6413     unsigned i = 0;
6414     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6415     // a) Avoid a RMW dependency on the full vector register, and
6416     // b) Allow the register coalescer to fold away the copy if the
6417     //    value is already in an S or D register.
6418     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6419     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6420     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6421         (ElemSize == 32 || ElemSize == 64)) {
6422       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6423       MachineSDNode *N =
6424           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6425                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6426       Vec = SDValue(N, 0);
6427       ++i;
6428     }
6429     for (; i < NumElts; ++i) {
6430       SDValue V = Op.getOperand(i);
6431       if (V.isUndef())
6432         continue;
6433       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6434       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6435     }
6436     return Vec;
6437   }
6438 
6439   // Just use the default expansion. We failed to find a better alternative.
6440   return SDValue();
6441 }
6442 
6443 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6444                                                       SelectionDAG &DAG) const {
6445   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6446 
6447   // Check for non-constant or out of range lane.
6448   EVT VT = Op.getOperand(0).getValueType();
6449   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6450   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6451     return SDValue();
6452 
6453 
6454   // Insertion/extraction are legal for V128 types.
6455   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6456       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6457       VT == MVT::v8f16)
6458     return Op;
6459 
6460   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6461       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6462     return SDValue();
6463 
6464   // For V64 types, we perform insertion by expanding the value
6465   // to a V128 type and perform the insertion on that.
6466   SDLoc DL(Op);
6467   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6468   EVT WideTy = WideVec.getValueType();
6469 
6470   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6471                              Op.getOperand(1), Op.getOperand(2));
6472   // Re-narrow the resultant vector.
6473   return NarrowVector(Node, DAG);
6474 }
6475 
6476 SDValue
6477 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6478                                                SelectionDAG &DAG) const {
6479   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6480 
6481   // Check for non-constant or out of range lane.
6482   EVT VT = Op.getOperand(0).getValueType();
6483   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6484   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6485     return SDValue();
6486 
6487 
6488   // Insertion/extraction are legal for V128 types.
6489   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6490       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6491       VT == MVT::v8f16)
6492     return Op;
6493 
6494   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6495       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6496     return SDValue();
6497 
6498   // For V64 types, we perform extraction by expanding the value
6499   // to a V128 type and perform the extraction on that.
6500   SDLoc DL(Op);
6501   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6502   EVT WideTy = WideVec.getValueType();
6503 
6504   EVT ExtrTy = WideTy.getVectorElementType();
6505   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6506     ExtrTy = MVT::i32;
6507 
6508   // For extractions, we just return the result directly.
6509   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6510                      Op.getOperand(1));
6511 }
6512 
6513 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6514                                                       SelectionDAG &DAG) const {
6515   EVT VT = Op.getOperand(0).getValueType();
6516   SDLoc dl(Op);
6517   // Just in case...
6518   if (!VT.isVector())
6519     return SDValue();
6520 
6521   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6522   if (!Cst)
6523     return SDValue();
6524   unsigned Val = Cst->getZExtValue();
6525 
6526   unsigned Size = Op.getValueSizeInBits();
6527 
6528   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6529   if (Val == 0)
6530     return Op;
6531 
6532   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6533   // that directly.
6534   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6535     return Op;
6536 
6537   return SDValue();
6538 }
6539 
6540 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6541                                                EVT VT) const {
6542   if (VT.getVectorNumElements() == 4 &&
6543       (VT.is128BitVector() || VT.is64BitVector())) {
6544     unsigned PFIndexes[4];
6545     for (unsigned i = 0; i != 4; ++i) {
6546       if (M[i] < 0)
6547         PFIndexes[i] = 8;
6548       else
6549         PFIndexes[i] = M[i];
6550     }
6551 
6552     // Compute the index in the perfect shuffle table.
6553     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6554                             PFIndexes[2] * 9 + PFIndexes[3];
6555     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6556     unsigned Cost = (PFEntry >> 30);
6557 
6558     if (Cost <= 4)
6559       return true;
6560   }
6561 
6562   bool DummyBool;
6563   int DummyInt;
6564   unsigned DummyUnsigned;
6565 
6566   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6567           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6568           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6569           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6570           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6571           isZIPMask(M, VT, DummyUnsigned) ||
6572           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6573           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6574           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6575           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6576           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6577 }
6578 
6579 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6580 /// operand of a vector shift operation, where all the elements of the
6581 /// build_vector must have the same constant integer value.
6582 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6583   // Ignore bit_converts.
6584   while (Op.getOpcode() == ISD::BITCAST)
6585     Op = Op.getOperand(0);
6586   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6587   APInt SplatBits, SplatUndef;
6588   unsigned SplatBitSize;
6589   bool HasAnyUndefs;
6590   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6591                                     HasAnyUndefs, ElementBits) ||
6592       SplatBitSize > ElementBits)
6593     return false;
6594   Cnt = SplatBits.getSExtValue();
6595   return true;
6596 }
6597 
6598 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6599 /// operand of a vector shift left operation.  That value must be in the range:
6600 ///   0 <= Value < ElementBits for a left shift; or
6601 ///   0 <= Value <= ElementBits for a long left shift.
6602 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6603   assert(VT.isVector() && "vector shift count is not a vector type");
6604   int64_t ElementBits = VT.getScalarSizeInBits();
6605   if (!getVShiftImm(Op, ElementBits, Cnt))
6606     return false;
6607   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6608 }
6609 
6610 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6611 /// operand of a vector shift right operation. The value must be in the range:
6612 ///   1 <= Value <= ElementBits for a right shift; or
6613 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6614   assert(VT.isVector() && "vector shift count is not a vector type");
6615   int64_t ElementBits = VT.getScalarSizeInBits();
6616   if (!getVShiftImm(Op, ElementBits, Cnt))
6617     return false;
6618   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6619 }
6620 
6621 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6622                                                       SelectionDAG &DAG) const {
6623   EVT VT = Op.getValueType();
6624   SDLoc DL(Op);
6625   int64_t Cnt;
6626 
6627   if (!Op.getOperand(1).getValueType().isVector())
6628     return Op;
6629   unsigned EltSize = VT.getScalarSizeInBits();
6630 
6631   switch (Op.getOpcode()) {
6632   default:
6633     llvm_unreachable("unexpected shift opcode");
6634 
6635   case ISD::SHL:
6636     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6637       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6638                          DAG.getConstant(Cnt, DL, MVT::i32));
6639     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6640                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6641                                        MVT::i32),
6642                        Op.getOperand(0), Op.getOperand(1));
6643   case ISD::SRA:
6644   case ISD::SRL:
6645     // Right shift immediate
6646     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6647       unsigned Opc =
6648           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6649       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6650                          DAG.getConstant(Cnt, DL, MVT::i32));
6651     }
6652 
6653     // Right shift register.  Note, there is not a shift right register
6654     // instruction, but the shift left register instruction takes a signed
6655     // value, where negative numbers specify a right shift.
6656     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6657                                                 : Intrinsic::aarch64_neon_ushl;
6658     // negate the shift amount
6659     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6660     SDValue NegShiftLeft =
6661         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6662                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6663                     NegShift);
6664     return NegShiftLeft;
6665   }
6666 
6667   return SDValue();
6668 }
6669 
6670 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6671                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6672                                     const SDLoc &dl, SelectionDAG &DAG) {
6673   EVT SrcVT = LHS.getValueType();
6674   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6675          "function only supposed to emit natural comparisons");
6676 
6677   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6678   APInt CnstBits(VT.getSizeInBits(), 0);
6679   APInt UndefBits(VT.getSizeInBits(), 0);
6680   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6681   bool IsZero = IsCnst && (CnstBits == 0);
6682 
6683   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6684     switch (CC) {
6685     default:
6686       return SDValue();
6687     case AArch64CC::NE: {
6688       SDValue Fcmeq;
6689       if (IsZero)
6690         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6691       else
6692         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6693       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6694     }
6695     case AArch64CC::EQ:
6696       if (IsZero)
6697         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6698       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6699     case AArch64CC::GE:
6700       if (IsZero)
6701         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6702       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6703     case AArch64CC::GT:
6704       if (IsZero)
6705         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6706       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6707     case AArch64CC::LS:
6708       if (IsZero)
6709         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6710       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6711     case AArch64CC::LT:
6712       if (!NoNans)
6713         return SDValue();
6714       // If we ignore NaNs then we can use to the MI implementation.
6715       LLVM_FALLTHROUGH;
6716     case AArch64CC::MI:
6717       if (IsZero)
6718         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6719       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6720     }
6721   }
6722 
6723   switch (CC) {
6724   default:
6725     return SDValue();
6726   case AArch64CC::NE: {
6727     SDValue Cmeq;
6728     if (IsZero)
6729       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6730     else
6731       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6732     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6733   }
6734   case AArch64CC::EQ:
6735     if (IsZero)
6736       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6737     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6738   case AArch64CC::GE:
6739     if (IsZero)
6740       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6741     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6742   case AArch64CC::GT:
6743     if (IsZero)
6744       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6745     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6746   case AArch64CC::LE:
6747     if (IsZero)
6748       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6749     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6750   case AArch64CC::LS:
6751     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6752   case AArch64CC::LO:
6753     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6754   case AArch64CC::LT:
6755     if (IsZero)
6756       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6757     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6758   case AArch64CC::HI:
6759     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6760   case AArch64CC::HS:
6761     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6762   }
6763 }
6764 
6765 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6766                                            SelectionDAG &DAG) const {
6767   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6768   SDValue LHS = Op.getOperand(0);
6769   SDValue RHS = Op.getOperand(1);
6770   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6771   SDLoc dl(Op);
6772 
6773   if (LHS.getValueType().getVectorElementType().isInteger()) {
6774     assert(LHS.getValueType() == RHS.getValueType());
6775     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6776     SDValue Cmp =
6777         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6778     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6779   }
6780 
6781   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6782     return SDValue();
6783 
6784   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6785          LHS.getValueType().getVectorElementType() == MVT::f64);
6786 
6787   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6788   // clean.  Some of them require two branches to implement.
6789   AArch64CC::CondCode CC1, CC2;
6790   bool ShouldInvert;
6791   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6792 
6793   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6794   SDValue Cmp =
6795       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6796   if (!Cmp.getNode())
6797     return SDValue();
6798 
6799   if (CC2 != AArch64CC::AL) {
6800     SDValue Cmp2 =
6801         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6802     if (!Cmp2.getNode())
6803       return SDValue();
6804 
6805     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6806   }
6807 
6808   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6809 
6810   if (ShouldInvert)
6811     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6812 
6813   return Cmp;
6814 }
6815 
6816 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6817 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6818 /// specified in the intrinsic calls.
6819 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6820                                                const CallInst &I,
6821                                                unsigned Intrinsic) const {
6822   auto &DL = I.getModule()->getDataLayout();
6823   switch (Intrinsic) {
6824   case Intrinsic::aarch64_neon_ld2:
6825   case Intrinsic::aarch64_neon_ld3:
6826   case Intrinsic::aarch64_neon_ld4:
6827   case Intrinsic::aarch64_neon_ld1x2:
6828   case Intrinsic::aarch64_neon_ld1x3:
6829   case Intrinsic::aarch64_neon_ld1x4:
6830   case Intrinsic::aarch64_neon_ld2lane:
6831   case Intrinsic::aarch64_neon_ld3lane:
6832   case Intrinsic::aarch64_neon_ld4lane:
6833   case Intrinsic::aarch64_neon_ld2r:
6834   case Intrinsic::aarch64_neon_ld3r:
6835   case Intrinsic::aarch64_neon_ld4r: {
6836     Info.opc = ISD::INTRINSIC_W_CHAIN;
6837     // Conservatively set memVT to the entire set of vectors loaded.
6838     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6839     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6840     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6841     Info.offset = 0;
6842     Info.align = 0;
6843     Info.vol = false; // volatile loads with NEON intrinsics not supported
6844     Info.readMem = true;
6845     Info.writeMem = false;
6846     return true;
6847   }
6848   case Intrinsic::aarch64_neon_st2:
6849   case Intrinsic::aarch64_neon_st3:
6850   case Intrinsic::aarch64_neon_st4:
6851   case Intrinsic::aarch64_neon_st1x2:
6852   case Intrinsic::aarch64_neon_st1x3:
6853   case Intrinsic::aarch64_neon_st1x4:
6854   case Intrinsic::aarch64_neon_st2lane:
6855   case Intrinsic::aarch64_neon_st3lane:
6856   case Intrinsic::aarch64_neon_st4lane: {
6857     Info.opc = ISD::INTRINSIC_VOID;
6858     // Conservatively set memVT to the entire set of vectors stored.
6859     unsigned NumElts = 0;
6860     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6861       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6862       if (!ArgTy->isVectorTy())
6863         break;
6864       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6865     }
6866     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6867     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6868     Info.offset = 0;
6869     Info.align = 0;
6870     Info.vol = false; // volatile stores with NEON intrinsics not supported
6871     Info.readMem = false;
6872     Info.writeMem = true;
6873     return true;
6874   }
6875   case Intrinsic::aarch64_ldaxr:
6876   case Intrinsic::aarch64_ldxr: {
6877     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6878     Info.opc = ISD::INTRINSIC_W_CHAIN;
6879     Info.memVT = MVT::getVT(PtrTy->getElementType());
6880     Info.ptrVal = I.getArgOperand(0);
6881     Info.offset = 0;
6882     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6883     Info.vol = true;
6884     Info.readMem = true;
6885     Info.writeMem = false;
6886     return true;
6887   }
6888   case Intrinsic::aarch64_stlxr:
6889   case Intrinsic::aarch64_stxr: {
6890     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6891     Info.opc = ISD::INTRINSIC_W_CHAIN;
6892     Info.memVT = MVT::getVT(PtrTy->getElementType());
6893     Info.ptrVal = I.getArgOperand(1);
6894     Info.offset = 0;
6895     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6896     Info.vol = true;
6897     Info.readMem = false;
6898     Info.writeMem = true;
6899     return true;
6900   }
6901   case Intrinsic::aarch64_ldaxp:
6902   case Intrinsic::aarch64_ldxp: {
6903     Info.opc = ISD::INTRINSIC_W_CHAIN;
6904     Info.memVT = MVT::i128;
6905     Info.ptrVal = I.getArgOperand(0);
6906     Info.offset = 0;
6907     Info.align = 16;
6908     Info.vol = true;
6909     Info.readMem = true;
6910     Info.writeMem = false;
6911     return true;
6912   }
6913   case Intrinsic::aarch64_stlxp:
6914   case Intrinsic::aarch64_stxp: {
6915     Info.opc = ISD::INTRINSIC_W_CHAIN;
6916     Info.memVT = MVT::i128;
6917     Info.ptrVal = I.getArgOperand(2);
6918     Info.offset = 0;
6919     Info.align = 16;
6920     Info.vol = true;
6921     Info.readMem = false;
6922     Info.writeMem = true;
6923     return true;
6924   }
6925   default:
6926     break;
6927   }
6928 
6929   return false;
6930 }
6931 
6932 // Truncations from 64-bit GPR to 32-bit GPR is free.
6933 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6934   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6935     return false;
6936   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6937   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6938   return NumBits1 > NumBits2;
6939 }
6940 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6941   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6942     return false;
6943   unsigned NumBits1 = VT1.getSizeInBits();
6944   unsigned NumBits2 = VT2.getSizeInBits();
6945   return NumBits1 > NumBits2;
6946 }
6947 
6948 /// Check if it is profitable to hoist instruction in then/else to if.
6949 /// Not profitable if I and it's user can form a FMA instruction
6950 /// because we prefer FMSUB/FMADD.
6951 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6952   if (I->getOpcode() != Instruction::FMul)
6953     return true;
6954 
6955   if (I->getNumUses() != 1)
6956     return true;
6957 
6958   Instruction *User = I->user_back();
6959 
6960   if (User &&
6961       !(User->getOpcode() == Instruction::FSub ||
6962         User->getOpcode() == Instruction::FAdd))
6963     return true;
6964 
6965   const TargetOptions &Options = getTargetMachine().Options;
6966   const DataLayout &DL = I->getModule()->getDataLayout();
6967   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6968 
6969   return !(isFMAFasterThanFMulAndFAdd(VT) &&
6970            isOperationLegalOrCustom(ISD::FMA, VT) &&
6971            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6972             Options.UnsafeFPMath));
6973 }
6974 
6975 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6976 // 64-bit GPR.
6977 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6978   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6979     return false;
6980   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6981   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6982   return NumBits1 == 32 && NumBits2 == 64;
6983 }
6984 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6985   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6986     return false;
6987   unsigned NumBits1 = VT1.getSizeInBits();
6988   unsigned NumBits2 = VT2.getSizeInBits();
6989   return NumBits1 == 32 && NumBits2 == 64;
6990 }
6991 
6992 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6993   EVT VT1 = Val.getValueType();
6994   if (isZExtFree(VT1, VT2)) {
6995     return true;
6996   }
6997 
6998   if (Val.getOpcode() != ISD::LOAD)
6999     return false;
7000 
7001   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7002   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7003           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7004           VT1.getSizeInBits() <= 32);
7005 }
7006 
7007 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7008   if (isa<FPExtInst>(Ext))
7009     return false;
7010 
7011   // Vector types are next free.
7012   if (Ext->getType()->isVectorTy())
7013     return false;
7014 
7015   for (const Use &U : Ext->uses()) {
7016     // The extension is free if we can fold it with a left shift in an
7017     // addressing mode or an arithmetic operation: add, sub, and cmp.
7018 
7019     // Is there a shift?
7020     const Instruction *Instr = cast<Instruction>(U.getUser());
7021 
7022     // Is this a constant shift?
7023     switch (Instr->getOpcode()) {
7024     case Instruction::Shl:
7025       if (!isa<ConstantInt>(Instr->getOperand(1)))
7026         return false;
7027       break;
7028     case Instruction::GetElementPtr: {
7029       gep_type_iterator GTI = gep_type_begin(Instr);
7030       auto &DL = Ext->getModule()->getDataLayout();
7031       std::advance(GTI, U.getOperandNo());
7032       Type *IdxTy = *GTI;
7033       // This extension will end up with a shift because of the scaling factor.
7034       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7035       // Get the shift amount based on the scaling factor:
7036       // log2(sizeof(IdxTy)) - log2(8).
7037       uint64_t ShiftAmt =
7038           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7039       // Is the constant foldable in the shift of the addressing mode?
7040       // I.e., shift amount is between 1 and 4 inclusive.
7041       if (ShiftAmt == 0 || ShiftAmt > 4)
7042         return false;
7043       break;
7044     }
7045     case Instruction::Trunc:
7046       // Check if this is a noop.
7047       // trunc(sext ty1 to ty2) to ty1.
7048       if (Instr->getType() == Ext->getOperand(0)->getType())
7049         continue;
7050       LLVM_FALLTHROUGH;
7051     default:
7052       return false;
7053     }
7054 
7055     // At this point we can use the bfm family, so this extension is free
7056     // for that use.
7057   }
7058   return true;
7059 }
7060 
7061 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7062                                           unsigned &RequiredAligment) const {
7063   if (!LoadedType.isSimple() ||
7064       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7065     return false;
7066   // Cyclone supports unaligned accesses.
7067   RequiredAligment = 0;
7068   unsigned NumBits = LoadedType.getSizeInBits();
7069   return NumBits == 32 || NumBits == 64;
7070 }
7071 
7072 /// \brief Lower an interleaved load into a ldN intrinsic.
7073 ///
7074 /// E.g. Lower an interleaved load (Factor = 2):
7075 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7076 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7077 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7078 ///
7079 ///      Into:
7080 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7081 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7082 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7083 bool AArch64TargetLowering::lowerInterleavedLoad(
7084     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7085     ArrayRef<unsigned> Indices, unsigned Factor) const {
7086   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7087          "Invalid interleave factor");
7088   assert(!Shuffles.empty() && "Empty shufflevector input");
7089   assert(Shuffles.size() == Indices.size() &&
7090          "Unmatched number of shufflevectors and indices");
7091 
7092   const DataLayout &DL = LI->getModule()->getDataLayout();
7093 
7094   VectorType *VecTy = Shuffles[0]->getType();
7095   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7096 
7097   // Skip if we do not have NEON and skip illegal vector types.
7098   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7099     return false;
7100 
7101   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7102   // load integer vectors first and then convert to pointer vectors.
7103   Type *EltTy = VecTy->getVectorElementType();
7104   if (EltTy->isPointerTy())
7105     VecTy =
7106         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7107 
7108   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7109   Type *Tys[2] = {VecTy, PtrTy};
7110   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7111                                             Intrinsic::aarch64_neon_ld3,
7112                                             Intrinsic::aarch64_neon_ld4};
7113   Function *LdNFunc =
7114       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7115 
7116   IRBuilder<> Builder(LI);
7117   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7118 
7119   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7120 
7121   // Replace uses of each shufflevector with the corresponding vector loaded
7122   // by ldN.
7123   for (unsigned i = 0; i < Shuffles.size(); i++) {
7124     ShuffleVectorInst *SVI = Shuffles[i];
7125     unsigned Index = Indices[i];
7126 
7127     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7128 
7129     // Convert the integer vector to pointer vector if the element is pointer.
7130     if (EltTy->isPointerTy())
7131       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7132 
7133     SVI->replaceAllUsesWith(SubVec);
7134   }
7135 
7136   return true;
7137 }
7138 
7139 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7140 ///
7141 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7142 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7143                                    unsigned NumElts) {
7144   SmallVector<Constant *, 16> Mask;
7145   for (unsigned i = 0; i < NumElts; i++)
7146     Mask.push_back(Builder.getInt32(Start + i));
7147 
7148   return ConstantVector::get(Mask);
7149 }
7150 
7151 /// \brief Lower an interleaved store into a stN intrinsic.
7152 ///
7153 /// E.g. Lower an interleaved store (Factor = 3):
7154 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7155 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7156 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7157 ///
7158 ///      Into:
7159 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7160 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7161 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7162 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7163 ///
7164 /// Note that the new shufflevectors will be removed and we'll only generate one
7165 /// st3 instruction in CodeGen.
7166 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7167                                                   ShuffleVectorInst *SVI,
7168                                                   unsigned Factor) const {
7169   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7170          "Invalid interleave factor");
7171 
7172   VectorType *VecTy = SVI->getType();
7173   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7174          "Invalid interleaved store");
7175 
7176   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7177   Type *EltTy = VecTy->getVectorElementType();
7178   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7179 
7180   const DataLayout &DL = SI->getModule()->getDataLayout();
7181   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7182 
7183   // Skip if we do not have NEON and skip illegal vector types.
7184   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7185     return false;
7186 
7187   Value *Op0 = SVI->getOperand(0);
7188   Value *Op1 = SVI->getOperand(1);
7189   IRBuilder<> Builder(SI);
7190 
7191   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7192   // vectors to integer vectors.
7193   if (EltTy->isPointerTy()) {
7194     Type *IntTy = DL.getIntPtrType(EltTy);
7195     unsigned NumOpElts =
7196         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7197 
7198     // Convert to the corresponding integer vector.
7199     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7200     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7201     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7202 
7203     SubVecTy = VectorType::get(IntTy, NumSubElts);
7204   }
7205 
7206   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7207   Type *Tys[2] = {SubVecTy, PtrTy};
7208   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7209                                              Intrinsic::aarch64_neon_st3,
7210                                              Intrinsic::aarch64_neon_st4};
7211   Function *StNFunc =
7212       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7213 
7214   SmallVector<Value *, 5> Ops;
7215 
7216   // Split the shufflevector operands into sub vectors for the new stN call.
7217   for (unsigned i = 0; i < Factor; i++)
7218     Ops.push_back(Builder.CreateShuffleVector(
7219         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7220 
7221   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7222   Builder.CreateCall(StNFunc, Ops);
7223   return true;
7224 }
7225 
7226 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7227                        unsigned AlignCheck) {
7228   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7229           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7230 }
7231 
7232 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7233                                                unsigned SrcAlign, bool IsMemset,
7234                                                bool ZeroMemset,
7235                                                bool MemcpyStrSrc,
7236                                                MachineFunction &MF) const {
7237   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7238   // instruction to materialize the v2i64 zero and one store (with restrictive
7239   // addressing mode). Just do two i64 store of zero-registers.
7240   bool Fast;
7241   const Function *F = MF.getFunction();
7242   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7243       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7244       (memOpAlign(SrcAlign, DstAlign, 16) ||
7245        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7246     return MVT::f128;
7247 
7248   if (Size >= 8 &&
7249       (memOpAlign(SrcAlign, DstAlign, 8) ||
7250        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7251     return MVT::i64;
7252 
7253   if (Size >= 4 &&
7254       (memOpAlign(SrcAlign, DstAlign, 4) ||
7255        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7256     return MVT::i32;
7257 
7258   return MVT::Other;
7259 }
7260 
7261 // 12-bit optionally shifted immediates are legal for adds.
7262 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7263   // Avoid UB for INT64_MIN.
7264   if (Immed == std::numeric_limits<int64_t>::min())
7265     return false;
7266   // Same encoding for add/sub, just flip the sign.
7267   Immed = std::abs(Immed);
7268   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7269 }
7270 
7271 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7272 // immediates is the same as for an add or a sub.
7273 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7274   return isLegalAddImmediate(Immed);
7275 }
7276 
7277 /// isLegalAddressingMode - Return true if the addressing mode represented
7278 /// by AM is legal for this target, for a load/store of the specified type.
7279 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7280                                                   const AddrMode &AM, Type *Ty,
7281                                                   unsigned AS) const {
7282   // AArch64 has five basic addressing modes:
7283   //  reg
7284   //  reg + 9-bit signed offset
7285   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7286   //  reg1 + reg2
7287   //  reg + SIZE_IN_BYTES * reg
7288 
7289   // No global is ever allowed as a base.
7290   if (AM.BaseGV)
7291     return false;
7292 
7293   // No reg+reg+imm addressing.
7294   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7295     return false;
7296 
7297   // check reg + imm case:
7298   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7299   uint64_t NumBytes = 0;
7300   if (Ty->isSized()) {
7301     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7302     NumBytes = NumBits / 8;
7303     if (!isPowerOf2_64(NumBits))
7304       NumBytes = 0;
7305   }
7306 
7307   if (!AM.Scale) {
7308     int64_t Offset = AM.BaseOffs;
7309 
7310     // 9-bit signed offset
7311     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7312       return true;
7313 
7314     // 12-bit unsigned offset
7315     unsigned shift = Log2_64(NumBytes);
7316     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7317         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7318         (Offset >> shift) << shift == Offset)
7319       return true;
7320     return false;
7321   }
7322 
7323   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7324 
7325   return !AM.Scale || AM.Scale == 1 ||
7326          (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7327 }
7328 
7329 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7330                                                 const AddrMode &AM, Type *Ty,
7331                                                 unsigned AS) const {
7332   // Scaling factors are not free at all.
7333   // Operands                     | Rt Latency
7334   // -------------------------------------------
7335   // Rt, [Xn, Xm]                 | 4
7336   // -------------------------------------------
7337   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7338   // Rt, [Xn, Wm, <extend> #imm]  |
7339   if (isLegalAddressingMode(DL, AM, Ty, AS))
7340     // Scale represents reg2 * scale, thus account for 1 if
7341     // it is not equal to 0 or 1.
7342     return AM.Scale != 0 && AM.Scale != 1;
7343   return -1;
7344 }
7345 
7346 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7347   VT = VT.getScalarType();
7348 
7349   if (!VT.isSimple())
7350     return false;
7351 
7352   switch (VT.getSimpleVT().SimpleTy) {
7353   case MVT::f32:
7354   case MVT::f64:
7355     return true;
7356   default:
7357     break;
7358   }
7359 
7360   return false;
7361 }
7362 
7363 const MCPhysReg *
7364 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7365   // LR is a callee-save register, but we must treat it as clobbered by any call
7366   // site. Hence we include LR in the scratch registers, which are in turn added
7367   // as implicit-defs for stackmaps and patchpoints.
7368   static const MCPhysReg ScratchRegs[] = {
7369     AArch64::X16, AArch64::X17, AArch64::LR, 0
7370   };
7371   return ScratchRegs;
7372 }
7373 
7374 bool
7375 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7376   EVT VT = N->getValueType(0);
7377     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7378     // it with shift to let it be lowered to UBFX.
7379   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7380       isa<ConstantSDNode>(N->getOperand(1))) {
7381     uint64_t TruncMask = N->getConstantOperandVal(1);
7382     if (isMask_64(TruncMask) &&
7383       N->getOperand(0).getOpcode() == ISD::SRL &&
7384       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7385       return false;
7386   }
7387   return true;
7388 }
7389 
7390 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7391                                                               Type *Ty) const {
7392   assert(Ty->isIntegerTy());
7393 
7394   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7395   if (BitSize == 0)
7396     return false;
7397 
7398   int64_t Val = Imm.getSExtValue();
7399   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7400     return true;
7401 
7402   if ((int64_t)Val < 0)
7403     Val = ~Val;
7404   if (BitSize == 32)
7405     Val &= (1LL << 32) - 1;
7406 
7407   unsigned LZ = countLeadingZeros((uint64_t)Val);
7408   unsigned Shift = (63 - LZ) / 16;
7409   // MOVZ is free so return true for one or fewer MOVK.
7410   return Shift < 3;
7411 }
7412 
7413 /// Turn vector tests of the signbit in the form of:
7414 ///   xor (sra X, elt_size(X)-1), -1
7415 /// into:
7416 ///   cmge X, X, #0
7417 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7418                                          const AArch64Subtarget *Subtarget) {
7419   EVT VT = N->getValueType(0);
7420   if (!Subtarget->hasNEON() || !VT.isVector())
7421     return SDValue();
7422 
7423   // There must be a shift right algebraic before the xor, and the xor must be a
7424   // 'not' operation.
7425   SDValue Shift = N->getOperand(0);
7426   SDValue Ones = N->getOperand(1);
7427   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7428       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7429     return SDValue();
7430 
7431   // The shift should be smearing the sign bit across each vector element.
7432   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7433   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7434   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7435     return SDValue();
7436 
7437   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7438 }
7439 
7440 // Generate SUBS and CSEL for integer abs.
7441 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7442   EVT VT = N->getValueType(0);
7443 
7444   SDValue N0 = N->getOperand(0);
7445   SDValue N1 = N->getOperand(1);
7446   SDLoc DL(N);
7447 
7448   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7449   // and change it to SUB and CSEL.
7450   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7451       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7452       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7453     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7454       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7455         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7456                                   N0.getOperand(0));
7457         // Generate SUBS & CSEL.
7458         SDValue Cmp =
7459             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7460                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7461         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7462                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7463                            SDValue(Cmp.getNode(), 1));
7464       }
7465   return SDValue();
7466 }
7467 
7468 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7469                                  TargetLowering::DAGCombinerInfo &DCI,
7470                                  const AArch64Subtarget *Subtarget) {
7471   if (DCI.isBeforeLegalizeOps())
7472     return SDValue();
7473 
7474   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7475     return Cmp;
7476 
7477   return performIntegerAbsCombine(N, DAG);
7478 }
7479 
7480 SDValue
7481 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7482                                      SelectionDAG &DAG,
7483                                      std::vector<SDNode *> *Created) const {
7484   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7485   if (isIntDivCheap(N->getValueType(0), Attr))
7486     return SDValue(N,0); // Lower SDIV as SDIV
7487 
7488   // fold (sdiv X, pow2)
7489   EVT VT = N->getValueType(0);
7490   if ((VT != MVT::i32 && VT != MVT::i64) ||
7491       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7492     return SDValue();
7493 
7494   SDLoc DL(N);
7495   SDValue N0 = N->getOperand(0);
7496   unsigned Lg2 = Divisor.countTrailingZeros();
7497   SDValue Zero = DAG.getConstant(0, DL, VT);
7498   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7499 
7500   // Add (N0 < 0) ? Pow2 - 1 : 0;
7501   SDValue CCVal;
7502   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7503   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7504   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7505 
7506   if (Created) {
7507     Created->push_back(Cmp.getNode());
7508     Created->push_back(Add.getNode());
7509     Created->push_back(CSel.getNode());
7510   }
7511 
7512   // Divide by pow2.
7513   SDValue SRA =
7514       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7515 
7516   // If we're dividing by a positive value, we're done.  Otherwise, we must
7517   // negate the result.
7518   if (Divisor.isNonNegative())
7519     return SRA;
7520 
7521   if (Created)
7522     Created->push_back(SRA.getNode());
7523   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7524 }
7525 
7526 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7527                                  TargetLowering::DAGCombinerInfo &DCI,
7528                                  const AArch64Subtarget *Subtarget) {
7529   if (DCI.isBeforeLegalizeOps())
7530     return SDValue();
7531 
7532   // Multiplication of a power of two plus/minus one can be done more
7533   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7534   // future CPUs have a cheaper MADD instruction, this may need to be
7535   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7536   // 64-bit is 5 cycles, so this is always a win.
7537   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7538     const APInt &Value = C->getAPIntValue();
7539     EVT VT = N->getValueType(0);
7540     SDLoc DL(N);
7541     if (Value.isNonNegative()) {
7542       // (mul x, 2^N + 1) => (add (shl x, N), x)
7543       APInt VM1 = Value - 1;
7544       if (VM1.isPowerOf2()) {
7545         SDValue ShiftedVal =
7546             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7547                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7548         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7549                            N->getOperand(0));
7550       }
7551       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7552       APInt VP1 = Value + 1;
7553       if (VP1.isPowerOf2()) {
7554         SDValue ShiftedVal =
7555             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7556                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7557         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7558                            N->getOperand(0));
7559       }
7560     } else {
7561       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7562       APInt VNP1 = -Value + 1;
7563       if (VNP1.isPowerOf2()) {
7564         SDValue ShiftedVal =
7565             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7566                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7567         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7568                            ShiftedVal);
7569       }
7570       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7571       APInt VNM1 = -Value - 1;
7572       if (VNM1.isPowerOf2()) {
7573         SDValue ShiftedVal =
7574             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7575                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7576         SDValue Add =
7577             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7578         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7579       }
7580     }
7581   }
7582   return SDValue();
7583 }
7584 
7585 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7586                                                          SelectionDAG &DAG) {
7587   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7588   // optimize away operation when it's from a constant.
7589   //
7590   // The general transformation is:
7591   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7592   //       AND(VECTOR_CMP(x,y), constant2)
7593   //    constant2 = UNARYOP(constant)
7594 
7595   // Early exit if this isn't a vector operation, the operand of the
7596   // unary operation isn't a bitwise AND, or if the sizes of the operations
7597   // aren't the same.
7598   EVT VT = N->getValueType(0);
7599   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7600       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7601       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7602     return SDValue();
7603 
7604   // Now check that the other operand of the AND is a constant. We could
7605   // make the transformation for non-constant splats as well, but it's unclear
7606   // that would be a benefit as it would not eliminate any operations, just
7607   // perform one more step in scalar code before moving to the vector unit.
7608   if (BuildVectorSDNode *BV =
7609           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7610     // Bail out if the vector isn't a constant.
7611     if (!BV->isConstant())
7612       return SDValue();
7613 
7614     // Everything checks out. Build up the new and improved node.
7615     SDLoc DL(N);
7616     EVT IntVT = BV->getValueType(0);
7617     // Create a new constant of the appropriate type for the transformed
7618     // DAG.
7619     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7620     // The AND node needs bitcasts to/from an integer vector type around it.
7621     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7622     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7623                                  N->getOperand(0)->getOperand(0), MaskConst);
7624     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7625     return Res;
7626   }
7627 
7628   return SDValue();
7629 }
7630 
7631 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7632                                      const AArch64Subtarget *Subtarget) {
7633   // First try to optimize away the conversion when it's conditionally from
7634   // a constant. Vectors only.
7635   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7636     return Res;
7637 
7638   EVT VT = N->getValueType(0);
7639   if (VT != MVT::f32 && VT != MVT::f64)
7640     return SDValue();
7641 
7642   // Only optimize when the source and destination types have the same width.
7643   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7644     return SDValue();
7645 
7646   // If the result of an integer load is only used by an integer-to-float
7647   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7648   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7649   SDValue N0 = N->getOperand(0);
7650   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7651       // Do not change the width of a volatile load.
7652       !cast<LoadSDNode>(N0)->isVolatile()) {
7653     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7654     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7655                                LN0->getPointerInfo(), LN0->getAlignment(),
7656                                LN0->getMemOperand()->getFlags());
7657 
7658     // Make sure successors of the original load stay after it by updating them
7659     // to use the new Chain.
7660     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7661 
7662     unsigned Opcode =
7663         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7664     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7665   }
7666 
7667   return SDValue();
7668 }
7669 
7670 /// Fold a floating-point multiply by power of two into floating-point to
7671 /// fixed-point conversion.
7672 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7673                                      TargetLowering::DAGCombinerInfo &DCI,
7674                                      const AArch64Subtarget *Subtarget) {
7675   if (!Subtarget->hasNEON())
7676     return SDValue();
7677 
7678   SDValue Op = N->getOperand(0);
7679   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7680       Op.getOpcode() != ISD::FMUL)
7681     return SDValue();
7682 
7683   SDValue ConstVec = Op->getOperand(1);
7684   if (!isa<BuildVectorSDNode>(ConstVec))
7685     return SDValue();
7686 
7687   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7688   uint32_t FloatBits = FloatTy.getSizeInBits();
7689   if (FloatBits != 32 && FloatBits != 64)
7690     return SDValue();
7691 
7692   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7693   uint32_t IntBits = IntTy.getSizeInBits();
7694   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7695     return SDValue();
7696 
7697   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7698   if (IntBits > FloatBits)
7699     return SDValue();
7700 
7701   BitVector UndefElements;
7702   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7703   int32_t Bits = IntBits == 64 ? 64 : 32;
7704   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7705   if (C == -1 || C == 0 || C > Bits)
7706     return SDValue();
7707 
7708   MVT ResTy;
7709   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7710   switch (NumLanes) {
7711   default:
7712     return SDValue();
7713   case 2:
7714     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7715     break;
7716   case 4:
7717     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7718     break;
7719   }
7720 
7721   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7722     return SDValue();
7723 
7724   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7725          "Illegal vector type after legalization");
7726 
7727   SDLoc DL(N);
7728   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7729   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7730                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7731   SDValue FixConv =
7732       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7733                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7734                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7735   // We can handle smaller integers by generating an extra trunc.
7736   if (IntBits < FloatBits)
7737     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7738 
7739   return FixConv;
7740 }
7741 
7742 /// Fold a floating-point divide by power of two into fixed-point to
7743 /// floating-point conversion.
7744 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7745                                   TargetLowering::DAGCombinerInfo &DCI,
7746                                   const AArch64Subtarget *Subtarget) {
7747   if (!Subtarget->hasNEON())
7748     return SDValue();
7749 
7750   SDValue Op = N->getOperand(0);
7751   unsigned Opc = Op->getOpcode();
7752   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7753       !Op.getOperand(0).getValueType().isSimple() ||
7754       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7755     return SDValue();
7756 
7757   SDValue ConstVec = N->getOperand(1);
7758   if (!isa<BuildVectorSDNode>(ConstVec))
7759     return SDValue();
7760 
7761   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7762   int32_t IntBits = IntTy.getSizeInBits();
7763   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7764     return SDValue();
7765 
7766   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7767   int32_t FloatBits = FloatTy.getSizeInBits();
7768   if (FloatBits != 32 && FloatBits != 64)
7769     return SDValue();
7770 
7771   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7772   if (IntBits > FloatBits)
7773     return SDValue();
7774 
7775   BitVector UndefElements;
7776   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7777   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7778   if (C == -1 || C == 0 || C > FloatBits)
7779     return SDValue();
7780 
7781   MVT ResTy;
7782   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7783   switch (NumLanes) {
7784   default:
7785     return SDValue();
7786   case 2:
7787     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7788     break;
7789   case 4:
7790     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7791     break;
7792   }
7793 
7794   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7795     return SDValue();
7796 
7797   SDLoc DL(N);
7798   SDValue ConvInput = Op.getOperand(0);
7799   bool IsSigned = Opc == ISD::SINT_TO_FP;
7800   if (IntBits < FloatBits)
7801     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7802                             ResTy, ConvInput);
7803 
7804   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7805                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7806   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7807                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7808                      DAG.getConstant(C, DL, MVT::i32));
7809 }
7810 
7811 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7812 /// searches for and classifies those shifts.
7813 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7814                          bool &FromHi) {
7815   if (N.getOpcode() == ISD::SHL)
7816     FromHi = false;
7817   else if (N.getOpcode() == ISD::SRL)
7818     FromHi = true;
7819   else
7820     return false;
7821 
7822   if (!isa<ConstantSDNode>(N.getOperand(1)))
7823     return false;
7824 
7825   ShiftAmount = N->getConstantOperandVal(1);
7826   Src = N->getOperand(0);
7827   return true;
7828 }
7829 
7830 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7831 /// registers viewed as a high/low pair. This function looks for the pattern:
7832 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7833 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7834 /// independent.
7835 static SDValue tryCombineToEXTR(SDNode *N,
7836                                 TargetLowering::DAGCombinerInfo &DCI) {
7837   SelectionDAG &DAG = DCI.DAG;
7838   SDLoc DL(N);
7839   EVT VT = N->getValueType(0);
7840 
7841   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7842 
7843   if (VT != MVT::i32 && VT != MVT::i64)
7844     return SDValue();
7845 
7846   SDValue LHS;
7847   uint32_t ShiftLHS = 0;
7848   bool LHSFromHi = 0;
7849   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7850     return SDValue();
7851 
7852   SDValue RHS;
7853   uint32_t ShiftRHS = 0;
7854   bool RHSFromHi = 0;
7855   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7856     return SDValue();
7857 
7858   // If they're both trying to come from the high part of the register, they're
7859   // not really an EXTR.
7860   if (LHSFromHi == RHSFromHi)
7861     return SDValue();
7862 
7863   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7864     return SDValue();
7865 
7866   if (LHSFromHi) {
7867     std::swap(LHS, RHS);
7868     std::swap(ShiftLHS, ShiftRHS);
7869   }
7870 
7871   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7872                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7873 }
7874 
7875 static SDValue tryCombineToBSL(SDNode *N,
7876                                 TargetLowering::DAGCombinerInfo &DCI) {
7877   EVT VT = N->getValueType(0);
7878   SelectionDAG &DAG = DCI.DAG;
7879   SDLoc DL(N);
7880 
7881   if (!VT.isVector())
7882     return SDValue();
7883 
7884   SDValue N0 = N->getOperand(0);
7885   if (N0.getOpcode() != ISD::AND)
7886     return SDValue();
7887 
7888   SDValue N1 = N->getOperand(1);
7889   if (N1.getOpcode() != ISD::AND)
7890     return SDValue();
7891 
7892   // We only have to look for constant vectors here since the general, variable
7893   // case can be handled in TableGen.
7894   unsigned Bits = VT.getScalarSizeInBits();
7895   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7896   for (int i = 1; i >= 0; --i)
7897     for (int j = 1; j >= 0; --j) {
7898       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7899       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7900       if (!BVN0 || !BVN1)
7901         continue;
7902 
7903       bool FoundMatch = true;
7904       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7905         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7906         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7907         if (!CN0 || !CN1 ||
7908             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7909           FoundMatch = false;
7910           break;
7911         }
7912       }
7913 
7914       if (FoundMatch)
7915         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7916                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7917     }
7918 
7919   return SDValue();
7920 }
7921 
7922 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7923                                 const AArch64Subtarget *Subtarget) {
7924   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7925   SelectionDAG &DAG = DCI.DAG;
7926   EVT VT = N->getValueType(0);
7927 
7928   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7929     return SDValue();
7930 
7931   if (SDValue Res = tryCombineToEXTR(N, DCI))
7932     return Res;
7933 
7934   if (SDValue Res = tryCombineToBSL(N, DCI))
7935     return Res;
7936 
7937   return SDValue();
7938 }
7939 
7940 static SDValue performSRLCombine(SDNode *N,
7941                                  TargetLowering::DAGCombinerInfo &DCI) {
7942   SelectionDAG &DAG = DCI.DAG;
7943   EVT VT = N->getValueType(0);
7944   if (VT != MVT::i32 && VT != MVT::i64)
7945     return SDValue();
7946 
7947   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7948   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7949   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7950   SDValue N0 = N->getOperand(0);
7951   if (N0.getOpcode() == ISD::BSWAP) {
7952     SDLoc DL(N);
7953     SDValue N1 = N->getOperand(1);
7954     SDValue N00 = N0.getOperand(0);
7955     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7956       uint64_t ShiftAmt = C->getZExtValue();
7957       if (VT == MVT::i32 && ShiftAmt == 16 &&
7958           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
7959         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7960       if (VT == MVT::i64 && ShiftAmt == 32 &&
7961           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
7962         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7963     }
7964   }
7965   return SDValue();
7966 }
7967 
7968 static SDValue performBitcastCombine(SDNode *N,
7969                                      TargetLowering::DAGCombinerInfo &DCI,
7970                                      SelectionDAG &DAG) {
7971   // Wait 'til after everything is legalized to try this. That way we have
7972   // legal vector types and such.
7973   if (DCI.isBeforeLegalizeOps())
7974     return SDValue();
7975 
7976   // Remove extraneous bitcasts around an extract_subvector.
7977   // For example,
7978   //    (v4i16 (bitconvert
7979   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7980   //  becomes
7981   //    (extract_subvector ((v8i16 ...), (i64 4)))
7982 
7983   // Only interested in 64-bit vectors as the ultimate result.
7984   EVT VT = N->getValueType(0);
7985   if (!VT.isVector())
7986     return SDValue();
7987   if (VT.getSimpleVT().getSizeInBits() != 64)
7988     return SDValue();
7989   // Is the operand an extract_subvector starting at the beginning or halfway
7990   // point of the vector? A low half may also come through as an
7991   // EXTRACT_SUBREG, so look for that, too.
7992   SDValue Op0 = N->getOperand(0);
7993   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7994       !(Op0->isMachineOpcode() &&
7995         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7996     return SDValue();
7997   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7998   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7999     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8000       return SDValue();
8001   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8002     if (idx != AArch64::dsub)
8003       return SDValue();
8004     // The dsub reference is equivalent to a lane zero subvector reference.
8005     idx = 0;
8006   }
8007   // Look through the bitcast of the input to the extract.
8008   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8009     return SDValue();
8010   SDValue Source = Op0->getOperand(0)->getOperand(0);
8011   // If the source type has twice the number of elements as our destination
8012   // type, we know this is an extract of the high or low half of the vector.
8013   EVT SVT = Source->getValueType(0);
8014   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8015     return SDValue();
8016 
8017   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8018 
8019   // Create the simplified form to just extract the low or high half of the
8020   // vector directly rather than bothering with the bitcasts.
8021   SDLoc dl(N);
8022   unsigned NumElements = VT.getVectorNumElements();
8023   if (idx) {
8024     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8025     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8026   } else {
8027     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8028     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8029                                       Source, SubReg),
8030                    0);
8031   }
8032 }
8033 
8034 static SDValue performConcatVectorsCombine(SDNode *N,
8035                                            TargetLowering::DAGCombinerInfo &DCI,
8036                                            SelectionDAG &DAG) {
8037   SDLoc dl(N);
8038   EVT VT = N->getValueType(0);
8039   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8040 
8041   // Optimize concat_vectors of truncated vectors, where the intermediate
8042   // type is illegal, to avoid said illegality,  e.g.,
8043   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8044   //                          (v2i16 (truncate (v2i64)))))
8045   // ->
8046   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8047   //                                    (v4i32 (bitcast (v2i64))),
8048   //                                    <0, 2, 4, 6>)))
8049   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8050   // on both input and result type, so we might generate worse code.
8051   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8052   if (N->getNumOperands() == 2 &&
8053       N0->getOpcode() == ISD::TRUNCATE &&
8054       N1->getOpcode() == ISD::TRUNCATE) {
8055     SDValue N00 = N0->getOperand(0);
8056     SDValue N10 = N1->getOperand(0);
8057     EVT N00VT = N00.getValueType();
8058 
8059     if (N00VT == N10.getValueType() &&
8060         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8061         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8062       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8063       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8064       for (size_t i = 0; i < Mask.size(); ++i)
8065         Mask[i] = i * 2;
8066       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8067                          DAG.getVectorShuffle(
8068                              MidVT, dl,
8069                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8070                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8071     }
8072   }
8073 
8074   // Wait 'til after everything is legalized to try this. That way we have
8075   // legal vector types and such.
8076   if (DCI.isBeforeLegalizeOps())
8077     return SDValue();
8078 
8079   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8080   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8081   // canonicalise to that.
8082   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8083     assert(VT.getScalarSizeInBits() == 64);
8084     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8085                        DAG.getConstant(0, dl, MVT::i64));
8086   }
8087 
8088   // Canonicalise concat_vectors so that the right-hand vector has as few
8089   // bit-casts as possible before its real operation. The primary matching
8090   // destination for these operations will be the narrowing "2" instructions,
8091   // which depend on the operation being performed on this right-hand vector.
8092   // For example,
8093   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8094   // becomes
8095   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8096 
8097   if (N1->getOpcode() != ISD::BITCAST)
8098     return SDValue();
8099   SDValue RHS = N1->getOperand(0);
8100   MVT RHSTy = RHS.getValueType().getSimpleVT();
8101   // If the RHS is not a vector, this is not the pattern we're looking for.
8102   if (!RHSTy.isVector())
8103     return SDValue();
8104 
8105   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8106 
8107   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8108                                   RHSTy.getVectorNumElements() * 2);
8109   return DAG.getNode(ISD::BITCAST, dl, VT,
8110                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8111                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8112                                  RHS));
8113 }
8114 
8115 static SDValue tryCombineFixedPointConvert(SDNode *N,
8116                                            TargetLowering::DAGCombinerInfo &DCI,
8117                                            SelectionDAG &DAG) {
8118   // Wait 'til after everything is legalized to try this. That way we have
8119   // legal vector types and such.
8120   if (DCI.isBeforeLegalizeOps())
8121     return SDValue();
8122   // Transform a scalar conversion of a value from a lane extract into a
8123   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8124   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8125   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8126   //
8127   // The second form interacts better with instruction selection and the
8128   // register allocator to avoid cross-class register copies that aren't
8129   // coalescable due to a lane reference.
8130 
8131   // Check the operand and see if it originates from a lane extract.
8132   SDValue Op1 = N->getOperand(1);
8133   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8134     // Yep, no additional predication needed. Perform the transform.
8135     SDValue IID = N->getOperand(0);
8136     SDValue Shift = N->getOperand(2);
8137     SDValue Vec = Op1.getOperand(0);
8138     SDValue Lane = Op1.getOperand(1);
8139     EVT ResTy = N->getValueType(0);
8140     EVT VecResTy;
8141     SDLoc DL(N);
8142 
8143     // The vector width should be 128 bits by the time we get here, even
8144     // if it started as 64 bits (the extract_vector handling will have
8145     // done so).
8146     assert(Vec.getValueSizeInBits() == 128 &&
8147            "unexpected vector size on extract_vector_elt!");
8148     if (Vec.getValueType() == MVT::v4i32)
8149       VecResTy = MVT::v4f32;
8150     else if (Vec.getValueType() == MVT::v2i64)
8151       VecResTy = MVT::v2f64;
8152     else
8153       llvm_unreachable("unexpected vector type!");
8154 
8155     SDValue Convert =
8156         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8157     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8158   }
8159   return SDValue();
8160 }
8161 
8162 // AArch64 high-vector "long" operations are formed by performing the non-high
8163 // version on an extract_subvector of each operand which gets the high half:
8164 //
8165 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8166 //
8167 // However, there are cases which don't have an extract_high explicitly, but
8168 // have another operation that can be made compatible with one for free. For
8169 // example:
8170 //
8171 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8172 //
8173 // This routine does the actual conversion of such DUPs, once outer routines
8174 // have determined that everything else is in order.
8175 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8176 // similarly here.
8177 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8178   switch (N.getOpcode()) {
8179   case AArch64ISD::DUP:
8180   case AArch64ISD::DUPLANE8:
8181   case AArch64ISD::DUPLANE16:
8182   case AArch64ISD::DUPLANE32:
8183   case AArch64ISD::DUPLANE64:
8184   case AArch64ISD::MOVI:
8185   case AArch64ISD::MOVIshift:
8186   case AArch64ISD::MOVIedit:
8187   case AArch64ISD::MOVImsl:
8188   case AArch64ISD::MVNIshift:
8189   case AArch64ISD::MVNImsl:
8190     break;
8191   default:
8192     // FMOV could be supported, but isn't very useful, as it would only occur
8193     // if you passed a bitcast' floating point immediate to an eligible long
8194     // integer op (addl, smull, ...).
8195     return SDValue();
8196   }
8197 
8198   MVT NarrowTy = N.getSimpleValueType();
8199   if (!NarrowTy.is64BitVector())
8200     return SDValue();
8201 
8202   MVT ElementTy = NarrowTy.getVectorElementType();
8203   unsigned NumElems = NarrowTy.getVectorNumElements();
8204   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8205 
8206   SDLoc dl(N);
8207   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8208                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8209                      DAG.getConstant(NumElems, dl, MVT::i64));
8210 }
8211 
8212 static bool isEssentiallyExtractSubvector(SDValue N) {
8213   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8214     return true;
8215 
8216   return N.getOpcode() == ISD::BITCAST &&
8217          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8218 }
8219 
8220 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8221 struct GenericSetCCInfo {
8222   const SDValue *Opnd0;
8223   const SDValue *Opnd1;
8224   ISD::CondCode CC;
8225 };
8226 
8227 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8228 struct AArch64SetCCInfo {
8229   const SDValue *Cmp;
8230   AArch64CC::CondCode CC;
8231 };
8232 
8233 /// \brief Helper structure to keep track of SetCC information.
8234 union SetCCInfo {
8235   GenericSetCCInfo Generic;
8236   AArch64SetCCInfo AArch64;
8237 };
8238 
8239 /// \brief Helper structure to be able to read SetCC information.  If set to
8240 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8241 /// GenericSetCCInfo.
8242 struct SetCCInfoAndKind {
8243   SetCCInfo Info;
8244   bool IsAArch64;
8245 };
8246 
8247 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8248 /// an
8249 /// AArch64 lowered one.
8250 /// \p SetCCInfo is filled accordingly.
8251 /// \post SetCCInfo is meanginfull only when this function returns true.
8252 /// \return True when Op is a kind of SET_CC operation.
8253 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8254   // If this is a setcc, this is straight forward.
8255   if (Op.getOpcode() == ISD::SETCC) {
8256     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8257     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8258     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8259     SetCCInfo.IsAArch64 = false;
8260     return true;
8261   }
8262   // Otherwise, check if this is a matching csel instruction.
8263   // In other words:
8264   // - csel 1, 0, cc
8265   // - csel 0, 1, !cc
8266   if (Op.getOpcode() != AArch64ISD::CSEL)
8267     return false;
8268   // Set the information about the operands.
8269   // TODO: we want the operands of the Cmp not the csel
8270   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8271   SetCCInfo.IsAArch64 = true;
8272   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8273       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8274 
8275   // Check that the operands matches the constraints:
8276   // (1) Both operands must be constants.
8277   // (2) One must be 1 and the other must be 0.
8278   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8279   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8280 
8281   // Check (1).
8282   if (!TValue || !FValue)
8283     return false;
8284 
8285   // Check (2).
8286   if (!TValue->isOne()) {
8287     // Update the comparison when we are interested in !cc.
8288     std::swap(TValue, FValue);
8289     SetCCInfo.Info.AArch64.CC =
8290         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8291   }
8292   return TValue->isOne() && FValue->isNullValue();
8293 }
8294 
8295 // Returns true if Op is setcc or zext of setcc.
8296 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8297   if (isSetCC(Op, Info))
8298     return true;
8299   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8300     isSetCC(Op->getOperand(0), Info));
8301 }
8302 
8303 // The folding we want to perform is:
8304 // (add x, [zext] (setcc cc ...) )
8305 //   -->
8306 // (csel x, (add x, 1), !cc ...)
8307 //
8308 // The latter will get matched to a CSINC instruction.
8309 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8310   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8311   SDValue LHS = Op->getOperand(0);
8312   SDValue RHS = Op->getOperand(1);
8313   SetCCInfoAndKind InfoAndKind;
8314 
8315   // If neither operand is a SET_CC, give up.
8316   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8317     std::swap(LHS, RHS);
8318     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8319       return SDValue();
8320   }
8321 
8322   // FIXME: This could be generatized to work for FP comparisons.
8323   EVT CmpVT = InfoAndKind.IsAArch64
8324                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8325                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8326   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8327     return SDValue();
8328 
8329   SDValue CCVal;
8330   SDValue Cmp;
8331   SDLoc dl(Op);
8332   if (InfoAndKind.IsAArch64) {
8333     CCVal = DAG.getConstant(
8334         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8335         MVT::i32);
8336     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8337   } else
8338     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8339                       *InfoAndKind.Info.Generic.Opnd1,
8340                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8341                       CCVal, DAG, dl);
8342 
8343   EVT VT = Op->getValueType(0);
8344   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8345   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8346 }
8347 
8348 // The basic add/sub long vector instructions have variants with "2" on the end
8349 // which act on the high-half of their inputs. They are normally matched by
8350 // patterns like:
8351 //
8352 // (add (zeroext (extract_high LHS)),
8353 //      (zeroext (extract_high RHS)))
8354 // -> uaddl2 vD, vN, vM
8355 //
8356 // However, if one of the extracts is something like a duplicate, this
8357 // instruction can still be used profitably. This function puts the DAG into a
8358 // more appropriate form for those patterns to trigger.
8359 static SDValue performAddSubLongCombine(SDNode *N,
8360                                         TargetLowering::DAGCombinerInfo &DCI,
8361                                         SelectionDAG &DAG) {
8362   if (DCI.isBeforeLegalizeOps())
8363     return SDValue();
8364 
8365   MVT VT = N->getSimpleValueType(0);
8366   if (!VT.is128BitVector()) {
8367     if (N->getOpcode() == ISD::ADD)
8368       return performSetccAddFolding(N, DAG);
8369     return SDValue();
8370   }
8371 
8372   // Make sure both branches are extended in the same way.
8373   SDValue LHS = N->getOperand(0);
8374   SDValue RHS = N->getOperand(1);
8375   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8376        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8377       LHS.getOpcode() != RHS.getOpcode())
8378     return SDValue();
8379 
8380   unsigned ExtType = LHS.getOpcode();
8381 
8382   // It's not worth doing if at least one of the inputs isn't already an
8383   // extract, but we don't know which it'll be so we have to try both.
8384   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8385     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8386     if (!RHS.getNode())
8387       return SDValue();
8388 
8389     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8390   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8391     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8392     if (!LHS.getNode())
8393       return SDValue();
8394 
8395     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8396   }
8397 
8398   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8399 }
8400 
8401 // Massage DAGs which we can use the high-half "long" operations on into
8402 // something isel will recognize better. E.g.
8403 //
8404 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8405 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8406 //                     (extract_high (v2i64 (dup128 scalar)))))
8407 //
8408 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8409                                        TargetLowering::DAGCombinerInfo &DCI,
8410                                        SelectionDAG &DAG) {
8411   if (DCI.isBeforeLegalizeOps())
8412     return SDValue();
8413 
8414   SDValue LHS = N->getOperand(1);
8415   SDValue RHS = N->getOperand(2);
8416   assert(LHS.getValueType().is64BitVector() &&
8417          RHS.getValueType().is64BitVector() &&
8418          "unexpected shape for long operation");
8419 
8420   // Either node could be a DUP, but it's not worth doing both of them (you'd
8421   // just as well use the non-high version) so look for a corresponding extract
8422   // operation on the other "wing".
8423   if (isEssentiallyExtractSubvector(LHS)) {
8424     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8425     if (!RHS.getNode())
8426       return SDValue();
8427   } else if (isEssentiallyExtractSubvector(RHS)) {
8428     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8429     if (!LHS.getNode())
8430       return SDValue();
8431   }
8432 
8433   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8434                      N->getOperand(0), LHS, RHS);
8435 }
8436 
8437 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8438   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8439   unsigned ElemBits = ElemTy.getSizeInBits();
8440 
8441   int64_t ShiftAmount;
8442   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8443     APInt SplatValue, SplatUndef;
8444     unsigned SplatBitSize;
8445     bool HasAnyUndefs;
8446     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8447                               HasAnyUndefs, ElemBits) ||
8448         SplatBitSize != ElemBits)
8449       return SDValue();
8450 
8451     ShiftAmount = SplatValue.getSExtValue();
8452   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8453     ShiftAmount = CVN->getSExtValue();
8454   } else
8455     return SDValue();
8456 
8457   unsigned Opcode;
8458   bool IsRightShift;
8459   switch (IID) {
8460   default:
8461     llvm_unreachable("Unknown shift intrinsic");
8462   case Intrinsic::aarch64_neon_sqshl:
8463     Opcode = AArch64ISD::SQSHL_I;
8464     IsRightShift = false;
8465     break;
8466   case Intrinsic::aarch64_neon_uqshl:
8467     Opcode = AArch64ISD::UQSHL_I;
8468     IsRightShift = false;
8469     break;
8470   case Intrinsic::aarch64_neon_srshl:
8471     Opcode = AArch64ISD::SRSHR_I;
8472     IsRightShift = true;
8473     break;
8474   case Intrinsic::aarch64_neon_urshl:
8475     Opcode = AArch64ISD::URSHR_I;
8476     IsRightShift = true;
8477     break;
8478   case Intrinsic::aarch64_neon_sqshlu:
8479     Opcode = AArch64ISD::SQSHLU_I;
8480     IsRightShift = false;
8481     break;
8482   }
8483 
8484   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8485     SDLoc dl(N);
8486     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8487                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8488   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8489     SDLoc dl(N);
8490     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8491                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8492   }
8493 
8494   return SDValue();
8495 }
8496 
8497 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8498 // the intrinsics must be legal and take an i32, this means there's almost
8499 // certainly going to be a zext in the DAG which we can eliminate.
8500 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8501   SDValue AndN = N->getOperand(2);
8502   if (AndN.getOpcode() != ISD::AND)
8503     return SDValue();
8504 
8505   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8506   if (!CMask || CMask->getZExtValue() != Mask)
8507     return SDValue();
8508 
8509   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8510                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8511 }
8512 
8513 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8514                                            SelectionDAG &DAG) {
8515   SDLoc dl(N);
8516   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8517                      DAG.getNode(Opc, dl,
8518                                  N->getOperand(1).getSimpleValueType(),
8519                                  N->getOperand(1)),
8520                      DAG.getConstant(0, dl, MVT::i64));
8521 }
8522 
8523 static SDValue performIntrinsicCombine(SDNode *N,
8524                                        TargetLowering::DAGCombinerInfo &DCI,
8525                                        const AArch64Subtarget *Subtarget) {
8526   SelectionDAG &DAG = DCI.DAG;
8527   unsigned IID = getIntrinsicID(N);
8528   switch (IID) {
8529   default:
8530     break;
8531   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8532   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8533     return tryCombineFixedPointConvert(N, DCI, DAG);
8534   case Intrinsic::aarch64_neon_saddv:
8535     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8536   case Intrinsic::aarch64_neon_uaddv:
8537     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8538   case Intrinsic::aarch64_neon_sminv:
8539     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8540   case Intrinsic::aarch64_neon_uminv:
8541     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8542   case Intrinsic::aarch64_neon_smaxv:
8543     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8544   case Intrinsic::aarch64_neon_umaxv:
8545     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8546   case Intrinsic::aarch64_neon_fmax:
8547     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8548                        N->getOperand(1), N->getOperand(2));
8549   case Intrinsic::aarch64_neon_fmin:
8550     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8551                        N->getOperand(1), N->getOperand(2));
8552   case Intrinsic::aarch64_neon_fmaxnm:
8553     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8554                        N->getOperand(1), N->getOperand(2));
8555   case Intrinsic::aarch64_neon_fminnm:
8556     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8557                        N->getOperand(1), N->getOperand(2));
8558   case Intrinsic::aarch64_neon_smull:
8559   case Intrinsic::aarch64_neon_umull:
8560   case Intrinsic::aarch64_neon_pmull:
8561   case Intrinsic::aarch64_neon_sqdmull:
8562     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8563   case Intrinsic::aarch64_neon_sqshl:
8564   case Intrinsic::aarch64_neon_uqshl:
8565   case Intrinsic::aarch64_neon_sqshlu:
8566   case Intrinsic::aarch64_neon_srshl:
8567   case Intrinsic::aarch64_neon_urshl:
8568     return tryCombineShiftImm(IID, N, DAG);
8569   case Intrinsic::aarch64_crc32b:
8570   case Intrinsic::aarch64_crc32cb:
8571     return tryCombineCRC32(0xff, N, DAG);
8572   case Intrinsic::aarch64_crc32h:
8573   case Intrinsic::aarch64_crc32ch:
8574     return tryCombineCRC32(0xffff, N, DAG);
8575   }
8576   return SDValue();
8577 }
8578 
8579 static SDValue performExtendCombine(SDNode *N,
8580                                     TargetLowering::DAGCombinerInfo &DCI,
8581                                     SelectionDAG &DAG) {
8582   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8583   // we can convert that DUP into another extract_high (of a bigger DUP), which
8584   // helps the backend to decide that an sabdl2 would be useful, saving a real
8585   // extract_high operation.
8586   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8587       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8588     SDNode *ABDNode = N->getOperand(0).getNode();
8589     unsigned IID = getIntrinsicID(ABDNode);
8590     if (IID == Intrinsic::aarch64_neon_sabd ||
8591         IID == Intrinsic::aarch64_neon_uabd) {
8592       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8593       if (!NewABD.getNode())
8594         return SDValue();
8595 
8596       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8597                          NewABD);
8598     }
8599   }
8600 
8601   // This is effectively a custom type legalization for AArch64.
8602   //
8603   // Type legalization will split an extend of a small, legal, type to a larger
8604   // illegal type by first splitting the destination type, often creating
8605   // illegal source types, which then get legalized in isel-confusing ways,
8606   // leading to really terrible codegen. E.g.,
8607   //   %result = v8i32 sext v8i8 %value
8608   // becomes
8609   //   %losrc = extract_subreg %value, ...
8610   //   %hisrc = extract_subreg %value, ...
8611   //   %lo = v4i32 sext v4i8 %losrc
8612   //   %hi = v4i32 sext v4i8 %hisrc
8613   // Things go rapidly downhill from there.
8614   //
8615   // For AArch64, the [sz]ext vector instructions can only go up one element
8616   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8617   // take two instructions.
8618   //
8619   // This implies that the most efficient way to do the extend from v8i8
8620   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8621   // the normal splitting to happen for the v8i16->v8i32.
8622 
8623   // This is pre-legalization to catch some cases where the default
8624   // type legalization will create ill-tempered code.
8625   if (!DCI.isBeforeLegalizeOps())
8626     return SDValue();
8627 
8628   // We're only interested in cleaning things up for non-legal vector types
8629   // here. If both the source and destination are legal, things will just
8630   // work naturally without any fiddling.
8631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8632   EVT ResVT = N->getValueType(0);
8633   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8634     return SDValue();
8635   // If the vector type isn't a simple VT, it's beyond the scope of what
8636   // we're  worried about here. Let legalization do its thing and hope for
8637   // the best.
8638   SDValue Src = N->getOperand(0);
8639   EVT SrcVT = Src->getValueType(0);
8640   if (!ResVT.isSimple() || !SrcVT.isSimple())
8641     return SDValue();
8642 
8643   // If the source VT is a 64-bit vector, we can play games and get the
8644   // better results we want.
8645   if (SrcVT.getSizeInBits() != 64)
8646     return SDValue();
8647 
8648   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8649   unsigned ElementCount = SrcVT.getVectorNumElements();
8650   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8651   SDLoc DL(N);
8652   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8653 
8654   // Now split the rest of the operation into two halves, each with a 64
8655   // bit source.
8656   EVT LoVT, HiVT;
8657   SDValue Lo, Hi;
8658   unsigned NumElements = ResVT.getVectorNumElements();
8659   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8660   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8661                                  ResVT.getVectorElementType(), NumElements / 2);
8662 
8663   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8664                                LoVT.getVectorNumElements());
8665   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8666                    DAG.getConstant(0, DL, MVT::i64));
8667   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8668                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8669   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8670   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8671 
8672   // Now combine the parts back together so we still have a single result
8673   // like the combiner expects.
8674   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8675 }
8676 
8677 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8678 /// value. The load store optimizer pass will merge them to store pair stores.
8679 /// This has better performance than a splat of the scalar followed by a split
8680 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8681 /// followed by an ext.b and two stores.
8682 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8683   SDValue StVal = St->getValue();
8684   EVT VT = StVal.getValueType();
8685 
8686   // Don't replace floating point stores, they possibly won't be transformed to
8687   // stp because of the store pair suppress pass.
8688   if (VT.isFloatingPoint())
8689     return SDValue();
8690 
8691   // Check for insert vector elements.
8692   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8693     return SDValue();
8694 
8695   // We can express a splat as store pair(s) for 2 or 4 elements.
8696   unsigned NumVecElts = VT.getVectorNumElements();
8697   if (NumVecElts != 4 && NumVecElts != 2)
8698     return SDValue();
8699   SDValue SplatVal = StVal.getOperand(1);
8700   unsigned RemainInsertElts = NumVecElts - 1;
8701 
8702   // Check that this is a splat.
8703   while (--RemainInsertElts) {
8704     SDValue NextInsertElt = StVal.getOperand(0);
8705     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8706       return SDValue();
8707     if (NextInsertElt.getOperand(1) != SplatVal)
8708       return SDValue();
8709     StVal = NextInsertElt;
8710   }
8711   unsigned OrigAlignment = St->getAlignment();
8712   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8713   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8714 
8715   // Create scalar stores. This is at least as good as the code sequence for a
8716   // split unaligned store which is a dup.s, ext.b, and two stores.
8717   // Most of the time the three stores should be replaced by store pair
8718   // instructions (stp).
8719   SDLoc DL(St);
8720   SDValue BasePtr = St->getBasePtr();
8721   SDValue NewST1 =
8722       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8723                    St->getAlignment(), St->getMemOperand()->getFlags());
8724 
8725   unsigned Offset = EltOffset;
8726   while (--NumVecElts) {
8727     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8728                                     DAG.getConstant(Offset, DL, MVT::i64));
8729     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8730                           St->getPointerInfo(), Alignment,
8731                           St->getMemOperand()->getFlags());
8732     Offset += EltOffset;
8733   }
8734   return NewST1;
8735 }
8736 
8737 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8738                               SelectionDAG &DAG,
8739                               const AArch64Subtarget *Subtarget) {
8740   if (!DCI.isBeforeLegalize())
8741     return SDValue();
8742 
8743   StoreSDNode *S = cast<StoreSDNode>(N);
8744   if (S->isVolatile())
8745     return SDValue();
8746 
8747   // FIXME: The logic for deciding if an unaligned store should be split should
8748   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8749   // a call to that function here.
8750 
8751   if (!Subtarget->isMisaligned128StoreSlow())
8752     return SDValue();
8753 
8754   // Don't split at -Oz.
8755   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8756     return SDValue();
8757 
8758   SDValue StVal = S->getValue();
8759   EVT VT = StVal.getValueType();
8760 
8761   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8762   // those up regresses performance on micro-benchmarks and olden/bh.
8763   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8764     return SDValue();
8765 
8766   // Split unaligned 16B stores. They are terrible for performance.
8767   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8768   // extensions can use this to mark that it does not want splitting to happen
8769   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8770   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8771   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8772       S->getAlignment() <= 2)
8773     return SDValue();
8774 
8775   // If we get a splat of a scalar convert this vector store to a store of
8776   // scalars. They will be merged into store pairs thereby removing two
8777   // instructions.
8778   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8779     return ReplacedSplat;
8780 
8781   SDLoc DL(S);
8782   unsigned NumElts = VT.getVectorNumElements() / 2;
8783   // Split VT into two.
8784   EVT HalfVT =
8785       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8786   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8787                                    DAG.getConstant(0, DL, MVT::i64));
8788   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8789                                    DAG.getConstant(NumElts, DL, MVT::i64));
8790   SDValue BasePtr = S->getBasePtr();
8791   SDValue NewST1 =
8792       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8793                    S->getAlignment(), S->getMemOperand()->getFlags());
8794   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8795                                   DAG.getConstant(8, DL, MVT::i64));
8796   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8797                       S->getPointerInfo(), S->getAlignment(),
8798                       S->getMemOperand()->getFlags());
8799 }
8800 
8801 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8802 /// post-increment LD1R.
8803 static SDValue performPostLD1Combine(SDNode *N,
8804                                      TargetLowering::DAGCombinerInfo &DCI,
8805                                      bool IsLaneOp) {
8806   if (DCI.isBeforeLegalizeOps())
8807     return SDValue();
8808 
8809   SelectionDAG &DAG = DCI.DAG;
8810   EVT VT = N->getValueType(0);
8811 
8812   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8813   SDNode *LD = N->getOperand(LoadIdx).getNode();
8814   // If it is not LOAD, can not do such combine.
8815   if (LD->getOpcode() != ISD::LOAD)
8816     return SDValue();
8817 
8818   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8819   EVT MemVT = LoadSDN->getMemoryVT();
8820   // Check if memory operand is the same type as the vector element.
8821   if (MemVT != VT.getVectorElementType())
8822     return SDValue();
8823 
8824   // Check if there are other uses. If so, do not combine as it will introduce
8825   // an extra load.
8826   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8827        ++UI) {
8828     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8829       continue;
8830     if (*UI != N)
8831       return SDValue();
8832   }
8833 
8834   SDValue Addr = LD->getOperand(1);
8835   SDValue Vector = N->getOperand(0);
8836   // Search for a use of the address operand that is an increment.
8837   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8838        Addr.getNode()->use_end(); UI != UE; ++UI) {
8839     SDNode *User = *UI;
8840     if (User->getOpcode() != ISD::ADD
8841         || UI.getUse().getResNo() != Addr.getResNo())
8842       continue;
8843 
8844     // Check that the add is independent of the load.  Otherwise, folding it
8845     // would create a cycle.
8846     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8847       continue;
8848     // Also check that add is not used in the vector operand.  This would also
8849     // create a cycle.
8850     if (User->isPredecessorOf(Vector.getNode()))
8851       continue;
8852 
8853     // If the increment is a constant, it must match the memory ref size.
8854     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8855     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8856       uint32_t IncVal = CInc->getZExtValue();
8857       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8858       if (IncVal != NumBytes)
8859         continue;
8860       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8861     }
8862 
8863     // Finally, check that the vector doesn't depend on the load.
8864     // Again, this would create a cycle.
8865     // The load depending on the vector is fine, as that's the case for the
8866     // LD1*post we'll eventually generate anyway.
8867     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8868       continue;
8869 
8870     SmallVector<SDValue, 8> Ops;
8871     Ops.push_back(LD->getOperand(0));  // Chain
8872     if (IsLaneOp) {
8873       Ops.push_back(Vector);           // The vector to be inserted
8874       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8875     }
8876     Ops.push_back(Addr);
8877     Ops.push_back(Inc);
8878 
8879     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8880     SDVTList SDTys = DAG.getVTList(Tys);
8881     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8882     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8883                                            MemVT,
8884                                            LoadSDN->getMemOperand());
8885 
8886     // Update the uses.
8887     SDValue NewResults[] = {
8888         SDValue(LD, 0),            // The result of load
8889         SDValue(UpdN.getNode(), 2) // Chain
8890     };
8891     DCI.CombineTo(LD, NewResults);
8892     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8893     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8894 
8895     break;
8896   }
8897   return SDValue();
8898 }
8899 
8900 /// Simplify \Addr given that the top byte of it is ignored by HW during
8901 /// address translation.
8902 static bool performTBISimplification(SDValue Addr,
8903                                      TargetLowering::DAGCombinerInfo &DCI,
8904                                      SelectionDAG &DAG) {
8905   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8906   APInt KnownZero, KnownOne;
8907   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8908                                         DCI.isBeforeLegalizeOps());
8909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8910   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8911     DCI.CommitTargetLoweringOpt(TLO);
8912     return true;
8913   }
8914   return false;
8915 }
8916 
8917 static SDValue performSTORECombine(SDNode *N,
8918                                    TargetLowering::DAGCombinerInfo &DCI,
8919                                    SelectionDAG &DAG,
8920                                    const AArch64Subtarget *Subtarget) {
8921   if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
8922     return Split;
8923 
8924   if (Subtarget->supportsAddressTopByteIgnored() &&
8925       performTBISimplification(N->getOperand(2), DCI, DAG))
8926     return SDValue(N, 0);
8927 
8928   return SDValue();
8929 }
8930 
8931   /// This function handles the log2-shuffle pattern produced by the
8932 /// LoopVectorizer for the across vector reduction. It consists of
8933 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8934 /// are reduced, where s is an induction variable from 0 to
8935 /// log2(NumVectorElements).
8936 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8937                                                      unsigned Op,
8938                                                      SelectionDAG &DAG) {
8939   EVT VTy = OpV->getOperand(0).getValueType();
8940   if (!VTy.isVector())
8941     return SDValue();
8942 
8943   int NumVecElts = VTy.getVectorNumElements();
8944   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8945     if (NumVecElts != 4)
8946       return SDValue();
8947   } else {
8948     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8949       return SDValue();
8950   }
8951 
8952   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8953   SDValue PreOp = OpV;
8954   // Iterate over each step of the across vector reduction.
8955   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8956     SDValue CurOp = PreOp.getOperand(0);
8957     SDValue Shuffle = PreOp.getOperand(1);
8958     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8959       // Try to swap the 1st and 2nd operand as add and min/max instructions
8960       // are commutative.
8961       CurOp = PreOp.getOperand(1);
8962       Shuffle = PreOp.getOperand(0);
8963       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8964         return SDValue();
8965     }
8966 
8967     // Check if the input vector is fed by the operator we want to handle,
8968     // except the last step; the very first input vector is not necessarily
8969     // the same operator we are handling.
8970     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8971       return SDValue();
8972 
8973     // Check if it forms one step of the across vector reduction.
8974     // E.g.,
8975     //   %cur = add %1, %0
8976     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8977     //   %pre = add %cur, %shuffle
8978     if (Shuffle.getOperand(0) != CurOp)
8979       return SDValue();
8980 
8981     int NumMaskElts = 1 << CurStep;
8982     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8983     // Check mask values in each step.
8984     // We expect the shuffle mask in each step follows a specific pattern
8985     // denoted here by the <M, U> form, where M is a sequence of integers
8986     // starting from NumMaskElts, increasing by 1, and the number integers
8987     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8988     // of undef in U should be NumVecElts - NumMaskElts.
8989     // E.g., for <8 x i16>, mask values in each step should be :
8990     //   step 0 : <1,u,u,u,u,u,u,u>
8991     //   step 1 : <2,3,u,u,u,u,u,u>
8992     //   step 2 : <4,5,6,7,u,u,u,u>
8993     for (int i = 0; i < NumVecElts; ++i)
8994       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8995           (i >= NumMaskElts && !(Mask[i] < 0)))
8996         return SDValue();
8997 
8998     PreOp = CurOp;
8999   }
9000   unsigned Opcode;
9001   bool IsIntrinsic = false;
9002 
9003   switch (Op) {
9004   default:
9005     llvm_unreachable("Unexpected operator for across vector reduction");
9006   case ISD::ADD:
9007     Opcode = AArch64ISD::UADDV;
9008     break;
9009   case ISD::SMAX:
9010     Opcode = AArch64ISD::SMAXV;
9011     break;
9012   case ISD::UMAX:
9013     Opcode = AArch64ISD::UMAXV;
9014     break;
9015   case ISD::SMIN:
9016     Opcode = AArch64ISD::SMINV;
9017     break;
9018   case ISD::UMIN:
9019     Opcode = AArch64ISD::UMINV;
9020     break;
9021   case ISD::FMAXNUM:
9022     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9023     IsIntrinsic = true;
9024     break;
9025   case ISD::FMINNUM:
9026     Opcode = Intrinsic::aarch64_neon_fminnmv;
9027     IsIntrinsic = true;
9028     break;
9029   }
9030   SDLoc DL(N);
9031 
9032   return IsIntrinsic
9033              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9034                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9035              : DAG.getNode(
9036                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9037                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9038                    DAG.getConstant(0, DL, MVT::i64));
9039 }
9040 
9041 /// Target-specific DAG combine for the across vector min/max reductions.
9042 /// This function specifically handles the final clean-up step of the vector
9043 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9044 /// pattern, which narrows down and finds the final min/max value from all
9045 /// elements of the vector.
9046 /// For example, for a <16 x i8> vector :
9047 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9048 ///   %smax0 = smax %arr, svn0
9049 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9050 ///   %smax1 = smax %smax0, %svn1
9051 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9052 ///   %smax2 = smax %smax1, svn2
9053 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9054 ///   %sc = setcc %smax2, %svn3, gt
9055 ///   %n0 = extract_vector_elt %sc, #0
9056 ///   %n1 = extract_vector_elt %smax2, #0
9057 ///   %n2 = extract_vector_elt $smax2, #1
9058 ///   %result = select %n0, %n1, n2
9059 ///     becomes :
9060 ///   %1 = smaxv %0
9061 ///   %result = extract_vector_elt %1, 0
9062 static SDValue
9063 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9064                                         const AArch64Subtarget *Subtarget) {
9065   if (!Subtarget->hasNEON())
9066     return SDValue();
9067 
9068   SDValue N0 = N->getOperand(0);
9069   SDValue IfTrue = N->getOperand(1);
9070   SDValue IfFalse = N->getOperand(2);
9071 
9072   // Check if the SELECT merges up the final result of the min/max
9073   // from a vector.
9074   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9075       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9076       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9077     return SDValue();
9078 
9079   // Expect N0 is fed by SETCC.
9080   SDValue SetCC = N0.getOperand(0);
9081   EVT SetCCVT = SetCC.getValueType();
9082   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9083       SetCCVT.getVectorElementType() != MVT::i1)
9084     return SDValue();
9085 
9086   SDValue VectorOp = SetCC.getOperand(0);
9087   unsigned Op = VectorOp->getOpcode();
9088   // Check if the input vector is fed by the operator we want to handle.
9089   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9090       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9091     return SDValue();
9092 
9093   EVT VTy = VectorOp.getValueType();
9094   if (!VTy.isVector())
9095     return SDValue();
9096 
9097   if (VTy.getSizeInBits() < 64)
9098     return SDValue();
9099 
9100   EVT EltTy = VTy.getVectorElementType();
9101   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9102     if (EltTy != MVT::f32)
9103       return SDValue();
9104   } else {
9105     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9106       return SDValue();
9107   }
9108 
9109   // Check if extracting from the same vector.
9110   // For example,
9111   //   %sc = setcc %vector, %svn1, gt
9112   //   %n0 = extract_vector_elt %sc, #0
9113   //   %n1 = extract_vector_elt %vector, #0
9114   //   %n2 = extract_vector_elt $vector, #1
9115   if (!(VectorOp == IfTrue->getOperand(0) &&
9116         VectorOp == IfFalse->getOperand(0)))
9117     return SDValue();
9118 
9119   // Check if the condition code is matched with the operator type.
9120   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9121   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9122       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9123       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9124       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9125       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9126        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9127        CC != ISD::SETGE) ||
9128       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9129        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9130        CC != ISD::SETLE))
9131     return SDValue();
9132 
9133   // Expect to check only lane 0 from the vector SETCC.
9134   if (!isNullConstant(N0.getOperand(1)))
9135     return SDValue();
9136 
9137   // Expect to extract the true value from lane 0.
9138   if (!isNullConstant(IfTrue.getOperand(1)))
9139     return SDValue();
9140 
9141   // Expect to extract the false value from lane 1.
9142   if (!isOneConstant(IfFalse.getOperand(1)))
9143     return SDValue();
9144 
9145   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9146 }
9147 
9148 /// Target-specific DAG combine for the across vector add reduction.
9149 /// This function specifically handles the final clean-up step of the vector
9150 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9151 /// pattern, which adds all elements of a vector together.
9152 /// For example, for a <4 x i32> vector :
9153 ///   %1 = vector_shuffle %0, <2,3,u,u>
9154 ///   %2 = add %0, %1
9155 ///   %3 = vector_shuffle %2, <1,u,u,u>
9156 ///   %4 = add %2, %3
9157 ///   %result = extract_vector_elt %4, 0
9158 /// becomes :
9159 ///   %0 = uaddv %0
9160 ///   %result = extract_vector_elt %0, 0
9161 static SDValue
9162 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9163                                      const AArch64Subtarget *Subtarget) {
9164   if (!Subtarget->hasNEON())
9165     return SDValue();
9166   SDValue N0 = N->getOperand(0);
9167   SDValue N1 = N->getOperand(1);
9168 
9169   // Check if the input vector is fed by the ADD.
9170   if (N0->getOpcode() != ISD::ADD)
9171     return SDValue();
9172 
9173   // The vector extract idx must constant zero because we only expect the final
9174   // result of the reduction is placed in lane 0.
9175   if (!isNullConstant(N1))
9176     return SDValue();
9177 
9178   EVT VTy = N0.getValueType();
9179   if (!VTy.isVector())
9180     return SDValue();
9181 
9182   EVT EltTy = VTy.getVectorElementType();
9183   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9184     return SDValue();
9185 
9186   if (VTy.getSizeInBits() < 64)
9187     return SDValue();
9188 
9189   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9190 }
9191 
9192 /// Target-specific DAG combine function for NEON load/store intrinsics
9193 /// to merge base address updates.
9194 static SDValue performNEONPostLDSTCombine(SDNode *N,
9195                                           TargetLowering::DAGCombinerInfo &DCI,
9196                                           SelectionDAG &DAG) {
9197   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9198     return SDValue();
9199 
9200   unsigned AddrOpIdx = N->getNumOperands() - 1;
9201   SDValue Addr = N->getOperand(AddrOpIdx);
9202 
9203   // Search for a use of the address operand that is an increment.
9204   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9205        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9206     SDNode *User = *UI;
9207     if (User->getOpcode() != ISD::ADD ||
9208         UI.getUse().getResNo() != Addr.getResNo())
9209       continue;
9210 
9211     // Check that the add is independent of the load/store.  Otherwise, folding
9212     // it would create a cycle.
9213     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9214       continue;
9215 
9216     // Find the new opcode for the updating load/store.
9217     bool IsStore = false;
9218     bool IsLaneOp = false;
9219     bool IsDupOp = false;
9220     unsigned NewOpc = 0;
9221     unsigned NumVecs = 0;
9222     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9223     switch (IntNo) {
9224     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9225     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9226       NumVecs = 2; break;
9227     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9228       NumVecs = 3; break;
9229     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9230       NumVecs = 4; break;
9231     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9232       NumVecs = 2; IsStore = true; break;
9233     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9234       NumVecs = 3; IsStore = true; break;
9235     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9236       NumVecs = 4; IsStore = true; break;
9237     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9238       NumVecs = 2; break;
9239     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9240       NumVecs = 3; break;
9241     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9242       NumVecs = 4; break;
9243     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9244       NumVecs = 2; IsStore = true; break;
9245     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9246       NumVecs = 3; IsStore = true; break;
9247     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9248       NumVecs = 4; IsStore = true; break;
9249     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9250       NumVecs = 2; IsDupOp = true; break;
9251     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9252       NumVecs = 3; IsDupOp = true; break;
9253     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9254       NumVecs = 4; IsDupOp = true; break;
9255     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9256       NumVecs = 2; IsLaneOp = true; break;
9257     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9258       NumVecs = 3; IsLaneOp = true; break;
9259     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9260       NumVecs = 4; IsLaneOp = true; break;
9261     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9262       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9263     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9264       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9265     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9266       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9267     }
9268 
9269     EVT VecTy;
9270     if (IsStore)
9271       VecTy = N->getOperand(2).getValueType();
9272     else
9273       VecTy = N->getValueType(0);
9274 
9275     // If the increment is a constant, it must match the memory ref size.
9276     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9277     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9278       uint32_t IncVal = CInc->getZExtValue();
9279       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9280       if (IsLaneOp || IsDupOp)
9281         NumBytes /= VecTy.getVectorNumElements();
9282       if (IncVal != NumBytes)
9283         continue;
9284       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9285     }
9286     SmallVector<SDValue, 8> Ops;
9287     Ops.push_back(N->getOperand(0)); // Incoming chain
9288     // Load lane and store have vector list as input.
9289     if (IsLaneOp || IsStore)
9290       for (unsigned i = 2; i < AddrOpIdx; ++i)
9291         Ops.push_back(N->getOperand(i));
9292     Ops.push_back(Addr); // Base register
9293     Ops.push_back(Inc);
9294 
9295     // Return Types.
9296     EVT Tys[6];
9297     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9298     unsigned n;
9299     for (n = 0; n < NumResultVecs; ++n)
9300       Tys[n] = VecTy;
9301     Tys[n++] = MVT::i64;  // Type of write back register
9302     Tys[n] = MVT::Other;  // Type of the chain
9303     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9304 
9305     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9306     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9307                                            MemInt->getMemoryVT(),
9308                                            MemInt->getMemOperand());
9309 
9310     // Update the uses.
9311     std::vector<SDValue> NewResults;
9312     for (unsigned i = 0; i < NumResultVecs; ++i) {
9313       NewResults.push_back(SDValue(UpdN.getNode(), i));
9314     }
9315     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9316     DCI.CombineTo(N, NewResults);
9317     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9318 
9319     break;
9320   }
9321   return SDValue();
9322 }
9323 
9324 // Checks to see if the value is the prescribed width and returns information
9325 // about its extension mode.
9326 static
9327 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9328   ExtType = ISD::NON_EXTLOAD;
9329   switch(V.getNode()->getOpcode()) {
9330   default:
9331     return false;
9332   case ISD::LOAD: {
9333     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9334     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9335        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9336       ExtType = LoadNode->getExtensionType();
9337       return true;
9338     }
9339     return false;
9340   }
9341   case ISD::AssertSext: {
9342     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9343     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9344        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9345       ExtType = ISD::SEXTLOAD;
9346       return true;
9347     }
9348     return false;
9349   }
9350   case ISD::AssertZext: {
9351     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9352     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9353        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9354       ExtType = ISD::ZEXTLOAD;
9355       return true;
9356     }
9357     return false;
9358   }
9359   case ISD::Constant:
9360   case ISD::TargetConstant: {
9361     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9362            1LL << (width - 1);
9363   }
9364   }
9365 
9366   return true;
9367 }
9368 
9369 // This function does a whole lot of voodoo to determine if the tests are
9370 // equivalent without and with a mask. Essentially what happens is that given a
9371 // DAG resembling:
9372 //
9373 //  +-------------+ +-------------+ +-------------+ +-------------+
9374 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9375 //  +-------------+ +-------------+ +-------------+ +-------------+
9376 //           |           |           |               |
9377 //           V           V           |    +----------+
9378 //          +-------------+  +----+  |    |
9379 //          |     ADD     |  |0xff|  |    |
9380 //          +-------------+  +----+  |    |
9381 //                  |           |    |    |
9382 //                  V           V    |    |
9383 //                 +-------------+   |    |
9384 //                 |     AND     |   |    |
9385 //                 +-------------+   |    |
9386 //                      |            |    |
9387 //                      +-----+      |    |
9388 //                            |      |    |
9389 //                            V      V    V
9390 //                           +-------------+
9391 //                           |     CMP     |
9392 //                           +-------------+
9393 //
9394 // The AND node may be safely removed for some combinations of inputs. In
9395 // particular we need to take into account the extension type of the Input,
9396 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9397 // width of the input (this can work for any width inputs, the above graph is
9398 // specific to 8 bits.
9399 //
9400 // The specific equations were worked out by generating output tables for each
9401 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9402 // problem was simplified by working with 4 bit inputs, which means we only
9403 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9404 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9405 // patterns present in both extensions (0,7). For every distinct set of
9406 // AddConstant and CompConstants bit patterns we can consider the masked and
9407 // unmasked versions to be equivalent if the result of this function is true for
9408 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9409 //
9410 //   sub      w8, w0, w1
9411 //   and      w10, w8, #0x0f
9412 //   cmp      w8, w2
9413 //   cset     w9, AArch64CC
9414 //   cmp      w10, w2
9415 //   cset     w11, AArch64CC
9416 //   cmp      w9, w11
9417 //   cset     w0, eq
9418 //   ret
9419 //
9420 // Since the above function shows when the outputs are equivalent it defines
9421 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9422 // would be expensive to run during compiles. The equations below were written
9423 // in a test harness that confirmed they gave equivalent outputs to the above
9424 // for all inputs function, so they can be used determine if the removal is
9425 // legal instead.
9426 //
9427 // isEquivalentMaskless() is the code for testing if the AND can be removed
9428 // factored out of the DAG recognition as the DAG can take several forms.
9429 
9430 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9431                                  ISD::LoadExtType ExtType, int AddConstant,
9432                                  int CompConstant) {
9433   // By being careful about our equations and only writing the in term
9434   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9435   // make them generally applicable to all bit widths.
9436   int MaxUInt = (1 << width);
9437 
9438   // For the purposes of these comparisons sign extending the type is
9439   // equivalent to zero extending the add and displacing it by half the integer
9440   // width. Provided we are careful and make sure our equations are valid over
9441   // the whole range we can just adjust the input and avoid writing equations
9442   // for sign extended inputs.
9443   if (ExtType == ISD::SEXTLOAD)
9444     AddConstant -= (1 << (width-1));
9445 
9446   switch(CC) {
9447   case AArch64CC::LE:
9448   case AArch64CC::GT: {
9449     if ((AddConstant == 0) ||
9450         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9451         (AddConstant >= 0 && CompConstant < 0) ||
9452         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9453       return true;
9454   } break;
9455   case AArch64CC::LT:
9456   case AArch64CC::GE: {
9457     if ((AddConstant == 0) ||
9458         (AddConstant >= 0 && CompConstant <= 0) ||
9459         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9460       return true;
9461   } break;
9462   case AArch64CC::HI:
9463   case AArch64CC::LS: {
9464     if ((AddConstant >= 0 && CompConstant < 0) ||
9465        (AddConstant <= 0 && CompConstant >= -1 &&
9466         CompConstant < AddConstant + MaxUInt))
9467       return true;
9468   } break;
9469   case AArch64CC::PL:
9470   case AArch64CC::MI: {
9471     if ((AddConstant == 0) ||
9472         (AddConstant > 0 && CompConstant <= 0) ||
9473         (AddConstant < 0 && CompConstant <= AddConstant))
9474       return true;
9475   } break;
9476   case AArch64CC::LO:
9477   case AArch64CC::HS: {
9478     if ((AddConstant >= 0 && CompConstant <= 0) ||
9479         (AddConstant <= 0 && CompConstant >= 0 &&
9480          CompConstant <= AddConstant + MaxUInt))
9481       return true;
9482   } break;
9483   case AArch64CC::EQ:
9484   case AArch64CC::NE: {
9485     if ((AddConstant > 0 && CompConstant < 0) ||
9486         (AddConstant < 0 && CompConstant >= 0 &&
9487          CompConstant < AddConstant + MaxUInt) ||
9488         (AddConstant >= 0 && CompConstant >= 0 &&
9489          CompConstant >= AddConstant) ||
9490         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9491 
9492       return true;
9493   } break;
9494   case AArch64CC::VS:
9495   case AArch64CC::VC:
9496   case AArch64CC::AL:
9497   case AArch64CC::NV:
9498     return true;
9499   case AArch64CC::Invalid:
9500     break;
9501   }
9502 
9503   return false;
9504 }
9505 
9506 static
9507 SDValue performCONDCombine(SDNode *N,
9508                            TargetLowering::DAGCombinerInfo &DCI,
9509                            SelectionDAG &DAG, unsigned CCIndex,
9510                            unsigned CmpIndex) {
9511   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9512   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9513   unsigned CondOpcode = SubsNode->getOpcode();
9514 
9515   if (CondOpcode != AArch64ISD::SUBS)
9516     return SDValue();
9517 
9518   // There is a SUBS feeding this condition. Is it fed by a mask we can
9519   // use?
9520 
9521   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9522   unsigned MaskBits = 0;
9523 
9524   if (AndNode->getOpcode() != ISD::AND)
9525     return SDValue();
9526 
9527   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9528     uint32_t CNV = CN->getZExtValue();
9529     if (CNV == 255)
9530       MaskBits = 8;
9531     else if (CNV == 65535)
9532       MaskBits = 16;
9533   }
9534 
9535   if (!MaskBits)
9536     return SDValue();
9537 
9538   SDValue AddValue = AndNode->getOperand(0);
9539 
9540   if (AddValue.getOpcode() != ISD::ADD)
9541     return SDValue();
9542 
9543   // The basic dag structure is correct, grab the inputs and validate them.
9544 
9545   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9546   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9547   SDValue SubsInputValue = SubsNode->getOperand(1);
9548 
9549   // The mask is present and the provenance of all the values is a smaller type,
9550   // lets see if the mask is superfluous.
9551 
9552   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9553       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9554     return SDValue();
9555 
9556   ISD::LoadExtType ExtType;
9557 
9558   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9559       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9560       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9561     return SDValue();
9562 
9563   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9564                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9565                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9566     return SDValue();
9567 
9568   // The AND is not necessary, remove it.
9569 
9570   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9571                                SubsNode->getValueType(1));
9572   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9573 
9574   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9575   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9576 
9577   return SDValue(N, 0);
9578 }
9579 
9580 // Optimize compare with zero and branch.
9581 static SDValue performBRCONDCombine(SDNode *N,
9582                                     TargetLowering::DAGCombinerInfo &DCI,
9583                                     SelectionDAG &DAG) {
9584   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9585     N = NV.getNode();
9586   SDValue Chain = N->getOperand(0);
9587   SDValue Dest = N->getOperand(1);
9588   SDValue CCVal = N->getOperand(2);
9589   SDValue Cmp = N->getOperand(3);
9590 
9591   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9592   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9593   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9594     return SDValue();
9595 
9596   unsigned CmpOpc = Cmp.getOpcode();
9597   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9598     return SDValue();
9599 
9600   // Only attempt folding if there is only one use of the flag and no use of the
9601   // value.
9602   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9603     return SDValue();
9604 
9605   SDValue LHS = Cmp.getOperand(0);
9606   SDValue RHS = Cmp.getOperand(1);
9607 
9608   assert(LHS.getValueType() == RHS.getValueType() &&
9609          "Expected the value type to be the same for both operands!");
9610   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9611     return SDValue();
9612 
9613   if (isNullConstant(LHS))
9614     std::swap(LHS, RHS);
9615 
9616   if (!isNullConstant(RHS))
9617     return SDValue();
9618 
9619   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9620       LHS.getOpcode() == ISD::SRL)
9621     return SDValue();
9622 
9623   // Fold the compare into the branch instruction.
9624   SDValue BR;
9625   if (CC == AArch64CC::EQ)
9626     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9627   else
9628     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9629 
9630   // Do not add new nodes to DAG combiner worklist.
9631   DCI.CombineTo(N, BR, false);
9632 
9633   return SDValue();
9634 }
9635 
9636 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9637 // as well as whether the test should be inverted.  This code is required to
9638 // catch these cases (as opposed to standard dag combines) because
9639 // AArch64ISD::TBZ is matched during legalization.
9640 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9641                                  SelectionDAG &DAG) {
9642 
9643   if (!Op->hasOneUse())
9644     return Op;
9645 
9646   // We don't handle undef/constant-fold cases below, as they should have
9647   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9648   // etc.)
9649 
9650   // (tbz (trunc x), b) -> (tbz x, b)
9651   // This case is just here to enable more of the below cases to be caught.
9652   if (Op->getOpcode() == ISD::TRUNCATE &&
9653       Bit < Op->getValueType(0).getSizeInBits()) {
9654     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9655   }
9656 
9657   if (Op->getNumOperands() != 2)
9658     return Op;
9659 
9660   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9661   if (!C)
9662     return Op;
9663 
9664   switch (Op->getOpcode()) {
9665   default:
9666     return Op;
9667 
9668   // (tbz (and x, m), b) -> (tbz x, b)
9669   case ISD::AND:
9670     if ((C->getZExtValue() >> Bit) & 1)
9671       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9672     return Op;
9673 
9674   // (tbz (shl x, c), b) -> (tbz x, b-c)
9675   case ISD::SHL:
9676     if (C->getZExtValue() <= Bit &&
9677         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9678       Bit = Bit - C->getZExtValue();
9679       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9680     }
9681     return Op;
9682 
9683   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9684   case ISD::SRA:
9685     Bit = Bit + C->getZExtValue();
9686     if (Bit >= Op->getValueType(0).getSizeInBits())
9687       Bit = Op->getValueType(0).getSizeInBits() - 1;
9688     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9689 
9690   // (tbz (srl x, c), b) -> (tbz x, b+c)
9691   case ISD::SRL:
9692     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9693       Bit = Bit + C->getZExtValue();
9694       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9695     }
9696     return Op;
9697 
9698   // (tbz (xor x, -1), b) -> (tbnz x, b)
9699   case ISD::XOR:
9700     if ((C->getZExtValue() >> Bit) & 1)
9701       Invert = !Invert;
9702     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9703   }
9704 }
9705 
9706 // Optimize test single bit zero/non-zero and branch.
9707 static SDValue performTBZCombine(SDNode *N,
9708                                  TargetLowering::DAGCombinerInfo &DCI,
9709                                  SelectionDAG &DAG) {
9710   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9711   bool Invert = false;
9712   SDValue TestSrc = N->getOperand(1);
9713   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9714 
9715   if (TestSrc == NewTestSrc)
9716     return SDValue();
9717 
9718   unsigned NewOpc = N->getOpcode();
9719   if (Invert) {
9720     if (NewOpc == AArch64ISD::TBZ)
9721       NewOpc = AArch64ISD::TBNZ;
9722     else {
9723       assert(NewOpc == AArch64ISD::TBNZ);
9724       NewOpc = AArch64ISD::TBZ;
9725     }
9726   }
9727 
9728   SDLoc DL(N);
9729   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9730                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9731 }
9732 
9733 // vselect (v1i1 setcc) ->
9734 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9735 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9736 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9737 // such VSELECT.
9738 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9739   SDValue N0 = N->getOperand(0);
9740   EVT CCVT = N0.getValueType();
9741 
9742   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9743       CCVT.getVectorElementType() != MVT::i1)
9744     return SDValue();
9745 
9746   EVT ResVT = N->getValueType(0);
9747   EVT CmpVT = N0.getOperand(0).getValueType();
9748   // Only combine when the result type is of the same size as the compared
9749   // operands.
9750   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9751     return SDValue();
9752 
9753   SDValue IfTrue = N->getOperand(1);
9754   SDValue IfFalse = N->getOperand(2);
9755   SDValue SetCC =
9756       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9757                    N0.getOperand(0), N0.getOperand(1),
9758                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9759   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9760                      IfTrue, IfFalse);
9761 }
9762 
9763 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9764 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9765 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9766 /// with a vector one followed by a DUP shuffle on the result.
9767 static SDValue performSelectCombine(SDNode *N,
9768                                     TargetLowering::DAGCombinerInfo &DCI) {
9769   SelectionDAG &DAG = DCI.DAG;
9770   SDValue N0 = N->getOperand(0);
9771   EVT ResVT = N->getValueType(0);
9772 
9773   if (N0.getOpcode() != ISD::SETCC)
9774     return SDValue();
9775 
9776   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9777   // scalar SetCCResultType. We also don't expect vectors, because we assume
9778   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9779   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9780          "Scalar-SETCC feeding SELECT has unexpected result type!");
9781 
9782   // If NumMaskElts == 0, the comparison is larger than select result. The
9783   // largest real NEON comparison is 64-bits per lane, which means the result is
9784   // at most 32-bits and an illegal vector. Just bail out for now.
9785   EVT SrcVT = N0.getOperand(0).getValueType();
9786 
9787   // Don't try to do this optimization when the setcc itself has i1 operands.
9788   // There are no legal vectors of i1, so this would be pointless.
9789   if (SrcVT == MVT::i1)
9790     return SDValue();
9791 
9792   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9793   if (!ResVT.isVector() || NumMaskElts == 0)
9794     return SDValue();
9795 
9796   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9797   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9798 
9799   // Also bail out if the vector CCVT isn't the same size as ResVT.
9800   // This can happen if the SETCC operand size doesn't divide the ResVT size
9801   // (e.g., f64 vs v3f32).
9802   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9803     return SDValue();
9804 
9805   // Make sure we didn't create illegal types, if we're not supposed to.
9806   assert(DCI.isBeforeLegalize() ||
9807          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9808 
9809   // First perform a vector comparison, where lane 0 is the one we're interested
9810   // in.
9811   SDLoc DL(N0);
9812   SDValue LHS =
9813       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9814   SDValue RHS =
9815       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9816   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9817 
9818   // Now duplicate the comparison mask we want across all other lanes.
9819   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9820   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
9821   Mask = DAG.getNode(ISD::BITCAST, DL,
9822                      ResVT.changeVectorElementTypeToInteger(), Mask);
9823 
9824   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9825 }
9826 
9827 /// Get rid of unnecessary NVCASTs (that don't change the type).
9828 static SDValue performNVCASTCombine(SDNode *N) {
9829   if (N->getValueType(0) == N->getOperand(0).getValueType())
9830     return N->getOperand(0);
9831 
9832   return SDValue();
9833 }
9834 
9835 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9836                                                  DAGCombinerInfo &DCI) const {
9837   SelectionDAG &DAG = DCI.DAG;
9838   switch (N->getOpcode()) {
9839   default:
9840     break;
9841   case ISD::ADD:
9842   case ISD::SUB:
9843     return performAddSubLongCombine(N, DCI, DAG);
9844   case ISD::XOR:
9845     return performXorCombine(N, DAG, DCI, Subtarget);
9846   case ISD::MUL:
9847     return performMulCombine(N, DAG, DCI, Subtarget);
9848   case ISD::SINT_TO_FP:
9849   case ISD::UINT_TO_FP:
9850     return performIntToFpCombine(N, DAG, Subtarget);
9851   case ISD::FP_TO_SINT:
9852   case ISD::FP_TO_UINT:
9853     return performFpToIntCombine(N, DAG, DCI, Subtarget);
9854   case ISD::FDIV:
9855     return performFDivCombine(N, DAG, DCI, Subtarget);
9856   case ISD::OR:
9857     return performORCombine(N, DCI, Subtarget);
9858   case ISD::SRL:
9859     return performSRLCombine(N, DCI);
9860   case ISD::INTRINSIC_WO_CHAIN:
9861     return performIntrinsicCombine(N, DCI, Subtarget);
9862   case ISD::ANY_EXTEND:
9863   case ISD::ZERO_EXTEND:
9864   case ISD::SIGN_EXTEND:
9865     return performExtendCombine(N, DCI, DAG);
9866   case ISD::BITCAST:
9867     return performBitcastCombine(N, DCI, DAG);
9868   case ISD::CONCAT_VECTORS:
9869     return performConcatVectorsCombine(N, DCI, DAG);
9870   case ISD::SELECT: {
9871     SDValue RV = performSelectCombine(N, DCI);
9872     if (!RV.getNode())
9873       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9874     return RV;
9875   }
9876   case ISD::VSELECT:
9877     return performVSelectCombine(N, DCI.DAG);
9878   case ISD::LOAD:
9879     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9880       return SDValue(N, 0);
9881     break;
9882   case ISD::STORE:
9883     return performSTORECombine(N, DCI, DAG, Subtarget);
9884   case AArch64ISD::BRCOND:
9885     return performBRCONDCombine(N, DCI, DAG);
9886   case AArch64ISD::TBNZ:
9887   case AArch64ISD::TBZ:
9888     return performTBZCombine(N, DCI, DAG);
9889   case AArch64ISD::CSEL:
9890     return performCONDCombine(N, DCI, DAG, 2, 3);
9891   case AArch64ISD::DUP:
9892     return performPostLD1Combine(N, DCI, false);
9893   case AArch64ISD::NVCAST:
9894     return performNVCASTCombine(N);
9895   case ISD::INSERT_VECTOR_ELT:
9896     return performPostLD1Combine(N, DCI, true);
9897   case ISD::EXTRACT_VECTOR_ELT:
9898     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9899   case ISD::INTRINSIC_VOID:
9900   case ISD::INTRINSIC_W_CHAIN:
9901     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9902     case Intrinsic::aarch64_neon_ld2:
9903     case Intrinsic::aarch64_neon_ld3:
9904     case Intrinsic::aarch64_neon_ld4:
9905     case Intrinsic::aarch64_neon_ld1x2:
9906     case Intrinsic::aarch64_neon_ld1x3:
9907     case Intrinsic::aarch64_neon_ld1x4:
9908     case Intrinsic::aarch64_neon_ld2lane:
9909     case Intrinsic::aarch64_neon_ld3lane:
9910     case Intrinsic::aarch64_neon_ld4lane:
9911     case Intrinsic::aarch64_neon_ld2r:
9912     case Intrinsic::aarch64_neon_ld3r:
9913     case Intrinsic::aarch64_neon_ld4r:
9914     case Intrinsic::aarch64_neon_st2:
9915     case Intrinsic::aarch64_neon_st3:
9916     case Intrinsic::aarch64_neon_st4:
9917     case Intrinsic::aarch64_neon_st1x2:
9918     case Intrinsic::aarch64_neon_st1x3:
9919     case Intrinsic::aarch64_neon_st1x4:
9920     case Intrinsic::aarch64_neon_st2lane:
9921     case Intrinsic::aarch64_neon_st3lane:
9922     case Intrinsic::aarch64_neon_st4lane:
9923       return performNEONPostLDSTCombine(N, DCI, DAG);
9924     default:
9925       break;
9926     }
9927   }
9928   return SDValue();
9929 }
9930 
9931 // Check if the return value is used as only a return value, as otherwise
9932 // we can't perform a tail-call. In particular, we need to check for
9933 // target ISD nodes that are returns and any other "odd" constructs
9934 // that the generic analysis code won't necessarily catch.
9935 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9936                                                SDValue &Chain) const {
9937   if (N->getNumValues() != 1)
9938     return false;
9939   if (!N->hasNUsesOfValue(1, 0))
9940     return false;
9941 
9942   SDValue TCChain = Chain;
9943   SDNode *Copy = *N->use_begin();
9944   if (Copy->getOpcode() == ISD::CopyToReg) {
9945     // If the copy has a glue operand, we conservatively assume it isn't safe to
9946     // perform a tail call.
9947     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9948         MVT::Glue)
9949       return false;
9950     TCChain = Copy->getOperand(0);
9951   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9952     return false;
9953 
9954   bool HasRet = false;
9955   for (SDNode *Node : Copy->uses()) {
9956     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9957       return false;
9958     HasRet = true;
9959   }
9960 
9961   if (!HasRet)
9962     return false;
9963 
9964   Chain = TCChain;
9965   return true;
9966 }
9967 
9968 // Return whether the an instruction can potentially be optimized to a tail
9969 // call. This will cause the optimizers to attempt to move, or duplicate,
9970 // return instructions to help enable tail call optimizations for this
9971 // instruction.
9972 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9973   return CI->isTailCall();
9974 }
9975 
9976 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9977                                                    SDValue &Offset,
9978                                                    ISD::MemIndexedMode &AM,
9979                                                    bool &IsInc,
9980                                                    SelectionDAG &DAG) const {
9981   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9982     return false;
9983 
9984   Base = Op->getOperand(0);
9985   // All of the indexed addressing mode instructions take a signed
9986   // 9 bit immediate offset.
9987   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9988     int64_t RHSC = (int64_t)RHS->getZExtValue();
9989     if (RHSC >= 256 || RHSC <= -256)
9990       return false;
9991     IsInc = (Op->getOpcode() == ISD::ADD);
9992     Offset = Op->getOperand(1);
9993     return true;
9994   }
9995   return false;
9996 }
9997 
9998 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9999                                                       SDValue &Offset,
10000                                                       ISD::MemIndexedMode &AM,
10001                                                       SelectionDAG &DAG) const {
10002   EVT VT;
10003   SDValue Ptr;
10004   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10005     VT = LD->getMemoryVT();
10006     Ptr = LD->getBasePtr();
10007   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10008     VT = ST->getMemoryVT();
10009     Ptr = ST->getBasePtr();
10010   } else
10011     return false;
10012 
10013   bool IsInc;
10014   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10015     return false;
10016   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10017   return true;
10018 }
10019 
10020 bool AArch64TargetLowering::getPostIndexedAddressParts(
10021     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10022     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10023   EVT VT;
10024   SDValue Ptr;
10025   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10026     VT = LD->getMemoryVT();
10027     Ptr = LD->getBasePtr();
10028   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10029     VT = ST->getMemoryVT();
10030     Ptr = ST->getBasePtr();
10031   } else
10032     return false;
10033 
10034   bool IsInc;
10035   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10036     return false;
10037   // Post-indexing updates the base, so it's not a valid transform
10038   // if that's not the same as the load's pointer.
10039   if (Ptr != Base)
10040     return false;
10041   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10042   return true;
10043 }
10044 
10045 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10046                                   SelectionDAG &DAG) {
10047   SDLoc DL(N);
10048   SDValue Op = N->getOperand(0);
10049 
10050   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10051     return;
10052 
10053   Op = SDValue(
10054       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10055                          DAG.getUNDEF(MVT::i32), Op,
10056                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10057       0);
10058   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10059   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10060 }
10061 
10062 static void ReplaceReductionResults(SDNode *N,
10063                                     SmallVectorImpl<SDValue> &Results,
10064                                     SelectionDAG &DAG, unsigned InterOp,
10065                                     unsigned AcrossOp) {
10066   EVT LoVT, HiVT;
10067   SDValue Lo, Hi;
10068   SDLoc dl(N);
10069   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10070   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10071   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10072   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10073   Results.push_back(SplitVal);
10074 }
10075 
10076 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10077   SDLoc DL(N);
10078   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10079   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10080                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10081                                        DAG.getConstant(64, DL, MVT::i64)));
10082   return std::make_pair(Lo, Hi);
10083 }
10084 
10085 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10086                                        SmallVectorImpl<SDValue> & Results,
10087                                        SelectionDAG &DAG) {
10088   assert(N->getValueType(0) == MVT::i128 &&
10089          "AtomicCmpSwap on types less than 128 should be legal");
10090   auto Desired = splitInt128(N->getOperand(2), DAG);
10091   auto New = splitInt128(N->getOperand(3), DAG);
10092   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10093                    New.first,        New.second,    N->getOperand(0)};
10094   SDNode *CmpSwap = DAG.getMachineNode(
10095       AArch64::CMP_SWAP_128, SDLoc(N),
10096       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10097 
10098   MachineFunction &MF = DAG.getMachineFunction();
10099   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10100   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10101   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10102 
10103   Results.push_back(SDValue(CmpSwap, 0));
10104   Results.push_back(SDValue(CmpSwap, 1));
10105   Results.push_back(SDValue(CmpSwap, 3));
10106 }
10107 
10108 void AArch64TargetLowering::ReplaceNodeResults(
10109     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10110   switch (N->getOpcode()) {
10111   default:
10112     llvm_unreachable("Don't know how to custom expand this");
10113   case ISD::BITCAST:
10114     ReplaceBITCASTResults(N, Results, DAG);
10115     return;
10116   case AArch64ISD::SADDV:
10117     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10118     return;
10119   case AArch64ISD::UADDV:
10120     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10121     return;
10122   case AArch64ISD::SMINV:
10123     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10124     return;
10125   case AArch64ISD::UMINV:
10126     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10127     return;
10128   case AArch64ISD::SMAXV:
10129     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10130     return;
10131   case AArch64ISD::UMAXV:
10132     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10133     return;
10134   case ISD::FP_TO_UINT:
10135   case ISD::FP_TO_SINT:
10136     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10137     // Let normal code take care of it by not adding anything to Results.
10138     return;
10139   case ISD::ATOMIC_CMP_SWAP:
10140     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10141     return;
10142   }
10143 }
10144 
10145 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10146   if (!Subtarget->isTargetAndroid())
10147     return true;
10148   return TargetLowering::useLoadStackGuardNode();
10149 }
10150 
10151 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10152   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10153   // reciprocal if there are three or more FDIVs.
10154   return 3;
10155 }
10156 
10157 TargetLoweringBase::LegalizeTypeAction
10158 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10159   MVT SVT = VT.getSimpleVT();
10160   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10161   // v4i16, v2i32 instead of to promote.
10162   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10163       || SVT == MVT::v1f32)
10164     return TypeWidenVector;
10165 
10166   return TargetLoweringBase::getPreferredVectorAction(VT);
10167 }
10168 
10169 // Loads and stores less than 128-bits are already atomic; ones above that
10170 // are doomed anyway, so defer to the default libcall and blame the OS when
10171 // things go wrong.
10172 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10173   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10174   return Size == 128;
10175 }
10176 
10177 // Loads and stores less than 128-bits are already atomic; ones above that
10178 // are doomed anyway, so defer to the default libcall and blame the OS when
10179 // things go wrong.
10180 TargetLowering::AtomicExpansionKind
10181 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10182   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10183   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10184 }
10185 
10186 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10187 TargetLowering::AtomicExpansionKind
10188 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10189   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10190   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10191 }
10192 
10193 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10194     AtomicCmpXchgInst *AI) const {
10195   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10196   // implement cmpxchg without spilling. If the address being exchanged is also
10197   // on the stack and close enough to the spill slot, this can lead to a
10198   // situation where the monitor always gets cleared and the atomic operation
10199   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10200   return getTargetMachine().getOptLevel() != 0;
10201 }
10202 
10203 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10204                                              AtomicOrdering Ord) const {
10205   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10206   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10207   bool IsAcquire = isAcquireOrStronger(Ord);
10208 
10209   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10210   // intrinsic must return {i64, i64} and we have to recombine them into a
10211   // single i128 here.
10212   if (ValTy->getPrimitiveSizeInBits() == 128) {
10213     Intrinsic::ID Int =
10214         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10215     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10216 
10217     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10218     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10219 
10220     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10221     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10222     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10223     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10224     return Builder.CreateOr(
10225         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10226   }
10227 
10228   Type *Tys[] = { Addr->getType() };
10229   Intrinsic::ID Int =
10230       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10231   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10232 
10233   return Builder.CreateTruncOrBitCast(
10234       Builder.CreateCall(Ldxr, Addr),
10235       cast<PointerType>(Addr->getType())->getElementType());
10236 }
10237 
10238 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10239     IRBuilder<> &Builder) const {
10240   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10241   Builder.CreateCall(
10242       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10243 }
10244 
10245 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10246                                                    Value *Val, Value *Addr,
10247                                                    AtomicOrdering Ord) const {
10248   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10249   bool IsRelease = isReleaseOrStronger(Ord);
10250 
10251   // Since the intrinsics must have legal type, the i128 intrinsics take two
10252   // parameters: "i64, i64". We must marshal Val into the appropriate form
10253   // before the call.
10254   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10255     Intrinsic::ID Int =
10256         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10257     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10258     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10259 
10260     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10261     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10262     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10263     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10264   }
10265 
10266   Intrinsic::ID Int =
10267       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10268   Type *Tys[] = { Addr->getType() };
10269   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10270 
10271   return Builder.CreateCall(Stxr,
10272                             {Builder.CreateZExtOrBitCast(
10273                                  Val, Stxr->getFunctionType()->getParamType(0)),
10274                              Addr});
10275 }
10276 
10277 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10278     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10279   return Ty->isArrayTy();
10280 }
10281 
10282 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10283                                                             EVT) const {
10284   return false;
10285 }
10286 
10287 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10288   if (!Subtarget->isTargetAndroid())
10289     return TargetLowering::getIRStackGuard(IRB);
10290 
10291   // Android provides a fixed TLS slot for the stack cookie. See the definition
10292   // of TLS_SLOT_STACK_GUARD in
10293   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10294   const unsigned TlsOffset = 0x28;
10295   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10296   Function *ThreadPointerFunc =
10297       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10298   return IRB.CreatePointerCast(
10299       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10300       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10301 }
10302 
10303 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10304   if (!Subtarget->isTargetAndroid())
10305     return TargetLowering::getSafeStackPointerLocation(IRB);
10306 
10307   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10308   // definition of TLS_SLOT_SAFESTACK in
10309   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10310   const unsigned TlsOffset = 0x48;
10311   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10312   Function *ThreadPointerFunc =
10313       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10314   return IRB.CreatePointerCast(
10315       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10316       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10317 }
10318 
10319 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10320   // Update IsSplitCSR in AArch64unctionInfo.
10321   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10322   AFI->setIsSplitCSR(true);
10323 }
10324 
10325 void AArch64TargetLowering::insertCopiesSplitCSR(
10326     MachineBasicBlock *Entry,
10327     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10328   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10329   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10330   if (!IStart)
10331     return;
10332 
10333   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10334   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10335   MachineBasicBlock::iterator MBBI = Entry->begin();
10336   for (const MCPhysReg *I = IStart; *I; ++I) {
10337     const TargetRegisterClass *RC = nullptr;
10338     if (AArch64::GPR64RegClass.contains(*I))
10339       RC = &AArch64::GPR64RegClass;
10340     else if (AArch64::FPR64RegClass.contains(*I))
10341       RC = &AArch64::FPR64RegClass;
10342     else
10343       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10344 
10345     unsigned NewVR = MRI->createVirtualRegister(RC);
10346     // Create copy from CSR to a virtual register.
10347     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10348     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10349     // nounwind. If we want to generalize this later, we may need to emit
10350     // CFI pseudo-instructions.
10351     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10352                Attribute::NoUnwind) &&
10353            "Function should be nounwind in insertCopiesSplitCSR!");
10354     Entry->addLiveIn(*I);
10355     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10356         .addReg(*I);
10357 
10358     // Insert the copy-back instructions right before the terminator.
10359     for (auto *Exit : Exits)
10360       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10361               TII->get(TargetOpcode::COPY), *I)
10362           .addReg(NewVR);
10363   }
10364 }
10365 
10366 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10367   // Integer division on AArch64 is expensive. However, when aggressively
10368   // optimizing for code size, we prefer to use a div instruction, as it is
10369   // usually smaller than the alternative sequence.
10370   // The exception to this is vector division. Since AArch64 doesn't have vector
10371   // integer division, leaving the division as-is is a loss even in terms of
10372   // size, because it will have to be scalarized, while the alternative code
10373   // sequence can be performed in vector form.
10374   bool OptSize =
10375       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10376   return OptSize && !VT.isVector();
10377 }
10378