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   setHasExtractBitsInsn(true);
517 
518   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
519 
520   if (Subtarget->hasNEON()) {
521     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
522     // silliness like this:
523     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
524     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
525     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
526     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
527     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
528     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
529     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
530     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
531     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
532     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
533     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
534     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
535     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
536     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
537     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
538     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
540     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
541     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
542     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
543     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
544     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
545     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
546     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
547     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
548 
549     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
550     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
551     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
552     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
553     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
554 
555     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
556 
557     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
558     // elements smaller than i32, so promote the input to i32 first.
559     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
560     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
563     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
564     // -> v8f16 conversions.
565     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
566     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
567     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
569     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
570     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
571     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
572     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
574     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
575     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
576     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
577     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
578 
579     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
580     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
581 
582     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
583     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
584     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
585     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
586     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
587     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
588     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
589     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
590 
591     // AArch64 doesn't have MUL.2d:
592     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
593     // Custom handling for some quad-vector types to detect MULL.
594     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
595     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
596     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
597 
598     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
599     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
600     // Likewise, narrowing and extending vector loads/stores aren't handled
601     // directly.
602     for (MVT VT : MVT::vector_valuetypes()) {
603       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
604 
605       setOperationAction(ISD::MULHS, VT, Expand);
606       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
607       setOperationAction(ISD::MULHU, VT, Expand);
608       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
609 
610       setOperationAction(ISD::BSWAP, VT, Expand);
611 
612       for (MVT InnerVT : MVT::vector_valuetypes()) {
613         setTruncStoreAction(VT, InnerVT, Expand);
614         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
615         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
616         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
617       }
618     }
619 
620     // AArch64 has implementations of a lot of rounding-like FP operations.
621     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
622       setOperationAction(ISD::FFLOOR, Ty, Legal);
623       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
624       setOperationAction(ISD::FCEIL, Ty, Legal);
625       setOperationAction(ISD::FRINT, Ty, Legal);
626       setOperationAction(ISD::FTRUNC, Ty, Legal);
627       setOperationAction(ISD::FROUND, Ty, Legal);
628     }
629   }
630 
631   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
632 }
633 
634 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
635   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
636     setOperationAction(ISD::LOAD, VT, Promote);
637     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
638 
639     setOperationAction(ISD::STORE, VT, Promote);
640     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
641   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
642     setOperationAction(ISD::LOAD, VT, Promote);
643     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
644 
645     setOperationAction(ISD::STORE, VT, Promote);
646     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
647   }
648 
649   // Mark vector float intrinsics as expand.
650   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
651     setOperationAction(ISD::FSIN, VT, Expand);
652     setOperationAction(ISD::FCOS, VT, Expand);
653     setOperationAction(ISD::FPOWI, VT, Expand);
654     setOperationAction(ISD::FPOW, VT, Expand);
655     setOperationAction(ISD::FLOG, VT, Expand);
656     setOperationAction(ISD::FLOG2, VT, Expand);
657     setOperationAction(ISD::FLOG10, VT, Expand);
658     setOperationAction(ISD::FEXP, VT, Expand);
659     setOperationAction(ISD::FEXP2, VT, Expand);
660 
661     // But we do support custom-lowering for FCOPYSIGN.
662     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
663   }
664 
665   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
666   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
667   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
668   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
669   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
670   setOperationAction(ISD::SRA, VT, Custom);
671   setOperationAction(ISD::SRL, VT, Custom);
672   setOperationAction(ISD::SHL, VT, Custom);
673   setOperationAction(ISD::AND, VT, Custom);
674   setOperationAction(ISD::OR, VT, Custom);
675   setOperationAction(ISD::SETCC, VT, Custom);
676   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
677 
678   setOperationAction(ISD::SELECT, VT, Expand);
679   setOperationAction(ISD::SELECT_CC, VT, Expand);
680   setOperationAction(ISD::VSELECT, VT, Expand);
681   for (MVT InnerVT : MVT::all_valuetypes())
682     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
683 
684   // CNT supports only B element sizes.
685   if (VT != MVT::v8i8 && VT != MVT::v16i8)
686     setOperationAction(ISD::CTPOP, VT, Expand);
687 
688   setOperationAction(ISD::UDIV, VT, Expand);
689   setOperationAction(ISD::SDIV, VT, Expand);
690   setOperationAction(ISD::UREM, VT, Expand);
691   setOperationAction(ISD::SREM, VT, Expand);
692   setOperationAction(ISD::FREM, VT, Expand);
693 
694   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
695   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
696 
697   // [SU][MIN|MAX] are available for all NEON types apart from i64.
698   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
699     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
700       setOperationAction(Opcode, VT, Legal);
701 
702   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
703   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
704     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
705                             ISD::FMINNUM, ISD::FMAXNUM})
706       setOperationAction(Opcode, VT, Legal);
707 
708   if (Subtarget->isLittleEndian()) {
709     for (unsigned im = (unsigned)ISD::PRE_INC;
710          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
711       setIndexedLoadAction(im, VT, Legal);
712       setIndexedStoreAction(im, VT, Legal);
713     }
714   }
715 }
716 
717 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
718   addRegisterClass(VT, &AArch64::FPR64RegClass);
719   addTypeForNEON(VT, MVT::v2i32);
720 }
721 
722 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
723   addRegisterClass(VT, &AArch64::FPR128RegClass);
724   addTypeForNEON(VT, MVT::v4i32);
725 }
726 
727 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
728                                               EVT VT) const {
729   if (!VT.isVector())
730     return MVT::i32;
731   return VT.changeVectorElementTypeToInteger();
732 }
733 
734 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
735 /// Mask are known to be either zero or one and return them in the
736 /// KnownZero/KnownOne bitsets.
737 void AArch64TargetLowering::computeKnownBitsForTargetNode(
738     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
739     const SelectionDAG &DAG, unsigned Depth) const {
740   switch (Op.getOpcode()) {
741   default:
742     break;
743   case AArch64ISD::CSEL: {
744     APInt KnownZero2, KnownOne2;
745     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
746     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
747     KnownZero &= KnownZero2;
748     KnownOne &= KnownOne2;
749     break;
750   }
751   case ISD::INTRINSIC_W_CHAIN: {
752     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
753     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
754     switch (IntID) {
755     default: return;
756     case Intrinsic::aarch64_ldaxr:
757     case Intrinsic::aarch64_ldxr: {
758       unsigned BitWidth = KnownOne.getBitWidth();
759       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
760       unsigned MemBits = VT.getScalarType().getSizeInBits();
761       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
762       return;
763     }
764     }
765     break;
766   }
767   case ISD::INTRINSIC_WO_CHAIN:
768   case ISD::INTRINSIC_VOID: {
769     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
770     switch (IntNo) {
771     default:
772       break;
773     case Intrinsic::aarch64_neon_umaxv:
774     case Intrinsic::aarch64_neon_uminv: {
775       // Figure out the datatype of the vector operand. The UMINV instruction
776       // will zero extend the result, so we can mark as known zero all the
777       // bits larger than the element datatype. 32-bit or larget doesn't need
778       // this as those are legal types and will be handled by isel directly.
779       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
780       unsigned BitWidth = KnownZero.getBitWidth();
781       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
782         assert(BitWidth >= 8 && "Unexpected width!");
783         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
784         KnownZero |= Mask;
785       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
786         assert(BitWidth >= 16 && "Unexpected width!");
787         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
788         KnownZero |= Mask;
789       }
790       break;
791     } break;
792     }
793   }
794   }
795 }
796 
797 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
798                                                   EVT) const {
799   return MVT::i64;
800 }
801 
802 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
803                                                            unsigned AddrSpace,
804                                                            unsigned Align,
805                                                            bool *Fast) const {
806   if (Subtarget->requiresStrictAlign())
807     return false;
808 
809   if (Fast) {
810     // Some CPUs are fine with unaligned stores except for 128-bit ones.
811     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
812             // See comments in performSTORECombine() for more details about
813             // these conditions.
814 
815             // Code that uses clang vector extensions can mark that it
816             // wants unaligned accesses to be treated as fast by
817             // underspecifying alignment to be 1 or 2.
818             Align <= 2 ||
819 
820             // Disregard v2i64. Memcpy lowering produces those and splitting
821             // them regresses performance on micro-benchmarks and olden/bh.
822             VT == MVT::v2i64;
823   }
824   return true;
825 }
826 
827 FastISel *
828 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
829                                       const TargetLibraryInfo *libInfo) const {
830   return AArch64::createFastISel(funcInfo, libInfo);
831 }
832 
833 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
834   switch ((AArch64ISD::NodeType)Opcode) {
835   case AArch64ISD::FIRST_NUMBER:      break;
836   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
837   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
838   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
839   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
840   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
841   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
842   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
843   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
844   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
845   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
846   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
847   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
848   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
849   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
850   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
851   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
852   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
853   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
854   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
855   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
856   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
857   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
858   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
859   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
860   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
861   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
862   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
863   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
864   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
865   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
866   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
867   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
868   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
869   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
870   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
871   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
872   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
873   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
874   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
875   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
876   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
877   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
878   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
879   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
880   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
881   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
882   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
883   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
884   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
885   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
886   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
887   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
888   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
889   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
890   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
891   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
892   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
893   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
894   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
895   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
896   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
897   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
898   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
899   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
900   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
901   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
902   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
903   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
904   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
905   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
906   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
907   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
908   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
909   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
910   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
911   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
912   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
913   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
914   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
915   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
916   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
917   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
918   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
919   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
920   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
921   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
922   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
923   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
924   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
925   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
926   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
927   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
928   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
929   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
930   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
931   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
932   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
933   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
934   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
935   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
936   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
937   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
938   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
939   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
940   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
941   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
942   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
943   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
944   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
945   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
946   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
947   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
948   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
949   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
950   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
951   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
952   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
953   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
954   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
955   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
956   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
957   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
958   }
959   return nullptr;
960 }
961 
962 MachineBasicBlock *
963 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
964                                     MachineBasicBlock *MBB) const {
965   // We materialise the F128CSEL pseudo-instruction as some control flow and a
966   // phi node:
967 
968   // OrigBB:
969   //     [... previous instrs leading to comparison ...]
970   //     b.ne TrueBB
971   //     b EndBB
972   // TrueBB:
973   //     ; Fallthrough
974   // EndBB:
975   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
976 
977   MachineFunction *MF = MBB->getParent();
978   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
979   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
980   DebugLoc DL = MI.getDebugLoc();
981   MachineFunction::iterator It = ++MBB->getIterator();
982 
983   unsigned DestReg = MI.getOperand(0).getReg();
984   unsigned IfTrueReg = MI.getOperand(1).getReg();
985   unsigned IfFalseReg = MI.getOperand(2).getReg();
986   unsigned CondCode = MI.getOperand(3).getImm();
987   bool NZCVKilled = MI.getOperand(4).isKill();
988 
989   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
990   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
991   MF->insert(It, TrueBB);
992   MF->insert(It, EndBB);
993 
994   // Transfer rest of current basic-block to EndBB
995   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
996                 MBB->end());
997   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
998 
999   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1000   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1001   MBB->addSuccessor(TrueBB);
1002   MBB->addSuccessor(EndBB);
1003 
1004   // TrueBB falls through to the end.
1005   TrueBB->addSuccessor(EndBB);
1006 
1007   if (!NZCVKilled) {
1008     TrueBB->addLiveIn(AArch64::NZCV);
1009     EndBB->addLiveIn(AArch64::NZCV);
1010   }
1011 
1012   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1013       .addReg(IfTrueReg)
1014       .addMBB(TrueBB)
1015       .addReg(IfFalseReg)
1016       .addMBB(MBB);
1017 
1018   MI.eraseFromParent();
1019   return EndBB;
1020 }
1021 
1022 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1023     MachineInstr &MI, MachineBasicBlock *BB) const {
1024   switch (MI.getOpcode()) {
1025   default:
1026 #ifndef NDEBUG
1027     MI.dump();
1028 #endif
1029     llvm_unreachable("Unexpected instruction for custom inserter!");
1030 
1031   case AArch64::F128CSEL:
1032     return EmitF128CSEL(MI, BB);
1033 
1034   case TargetOpcode::STACKMAP:
1035   case TargetOpcode::PATCHPOINT:
1036     return emitPatchPoint(MI, BB);
1037   }
1038 }
1039 
1040 //===----------------------------------------------------------------------===//
1041 // AArch64 Lowering private implementation.
1042 //===----------------------------------------------------------------------===//
1043 
1044 //===----------------------------------------------------------------------===//
1045 // Lowering Code
1046 //===----------------------------------------------------------------------===//
1047 
1048 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1049 /// CC
1050 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1051   switch (CC) {
1052   default:
1053     llvm_unreachable("Unknown condition code!");
1054   case ISD::SETNE:
1055     return AArch64CC::NE;
1056   case ISD::SETEQ:
1057     return AArch64CC::EQ;
1058   case ISD::SETGT:
1059     return AArch64CC::GT;
1060   case ISD::SETGE:
1061     return AArch64CC::GE;
1062   case ISD::SETLT:
1063     return AArch64CC::LT;
1064   case ISD::SETLE:
1065     return AArch64CC::LE;
1066   case ISD::SETUGT:
1067     return AArch64CC::HI;
1068   case ISD::SETUGE:
1069     return AArch64CC::HS;
1070   case ISD::SETULT:
1071     return AArch64CC::LO;
1072   case ISD::SETULE:
1073     return AArch64CC::LS;
1074   }
1075 }
1076 
1077 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1078 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1079                                   AArch64CC::CondCode &CondCode,
1080                                   AArch64CC::CondCode &CondCode2) {
1081   CondCode2 = AArch64CC::AL;
1082   switch (CC) {
1083   default:
1084     llvm_unreachable("Unknown FP condition!");
1085   case ISD::SETEQ:
1086   case ISD::SETOEQ:
1087     CondCode = AArch64CC::EQ;
1088     break;
1089   case ISD::SETGT:
1090   case ISD::SETOGT:
1091     CondCode = AArch64CC::GT;
1092     break;
1093   case ISD::SETGE:
1094   case ISD::SETOGE:
1095     CondCode = AArch64CC::GE;
1096     break;
1097   case ISD::SETOLT:
1098     CondCode = AArch64CC::MI;
1099     break;
1100   case ISD::SETOLE:
1101     CondCode = AArch64CC::LS;
1102     break;
1103   case ISD::SETONE:
1104     CondCode = AArch64CC::MI;
1105     CondCode2 = AArch64CC::GT;
1106     break;
1107   case ISD::SETO:
1108     CondCode = AArch64CC::VC;
1109     break;
1110   case ISD::SETUO:
1111     CondCode = AArch64CC::VS;
1112     break;
1113   case ISD::SETUEQ:
1114     CondCode = AArch64CC::EQ;
1115     CondCode2 = AArch64CC::VS;
1116     break;
1117   case ISD::SETUGT:
1118     CondCode = AArch64CC::HI;
1119     break;
1120   case ISD::SETUGE:
1121     CondCode = AArch64CC::PL;
1122     break;
1123   case ISD::SETLT:
1124   case ISD::SETULT:
1125     CondCode = AArch64CC::LT;
1126     break;
1127   case ISD::SETLE:
1128   case ISD::SETULE:
1129     CondCode = AArch64CC::LE;
1130     break;
1131   case ISD::SETNE:
1132   case ISD::SETUNE:
1133     CondCode = AArch64CC::NE;
1134     break;
1135   }
1136 }
1137 
1138 /// Convert a DAG fp condition code to an AArch64 CC.
1139 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1140 /// should be AND'ed instead of OR'ed.
1141 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1142                                      AArch64CC::CondCode &CondCode,
1143                                      AArch64CC::CondCode &CondCode2) {
1144   CondCode2 = AArch64CC::AL;
1145   switch (CC) {
1146   default:
1147     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148     assert(CondCode2 == AArch64CC::AL);
1149     break;
1150   case ISD::SETONE:
1151     // (a one b)
1152     // == ((a olt b) || (a ogt b))
1153     // == ((a ord b) && (a une b))
1154     CondCode = AArch64CC::VC;
1155     CondCode2 = AArch64CC::NE;
1156     break;
1157   case ISD::SETUEQ:
1158     // (a ueq b)
1159     // == ((a uno b) || (a oeq b))
1160     // == ((a ule b) && (a uge b))
1161     CondCode = AArch64CC::PL;
1162     CondCode2 = AArch64CC::LE;
1163     break;
1164   }
1165 }
1166 
1167 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1168 /// CC usable with the vector instructions. Fewer operations are available
1169 /// without a real NZCV register, so we have to use less efficient combinations
1170 /// to get the same effect.
1171 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1172                                         AArch64CC::CondCode &CondCode,
1173                                         AArch64CC::CondCode &CondCode2,
1174                                         bool &Invert) {
1175   Invert = false;
1176   switch (CC) {
1177   default:
1178     // Mostly the scalar mappings work fine.
1179     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1180     break;
1181   case ISD::SETUO:
1182     Invert = true;
1183     LLVM_FALLTHROUGH;
1184   case ISD::SETO:
1185     CondCode = AArch64CC::MI;
1186     CondCode2 = AArch64CC::GE;
1187     break;
1188   case ISD::SETUEQ:
1189   case ISD::SETULT:
1190   case ISD::SETULE:
1191   case ISD::SETUGT:
1192   case ISD::SETUGE:
1193     // All of the compare-mask comparisons are ordered, but we can switch
1194     // between the two by a double inversion. E.g. ULE == !OGT.
1195     Invert = true;
1196     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1197     break;
1198   }
1199 }
1200 
1201 static bool isLegalArithImmed(uint64_t C) {
1202   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1203   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1204 }
1205 
1206 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1207                               const SDLoc &dl, SelectionDAG &DAG) {
1208   EVT VT = LHS.getValueType();
1209 
1210   if (VT.isFloatingPoint()) {
1211     assert(VT != MVT::f128);
1212     if (VT == MVT::f16) {
1213       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1214       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1215       VT = MVT::f32;
1216     }
1217     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1218   }
1219 
1220   // The CMP instruction is just an alias for SUBS, and representing it as
1221   // SUBS means that it's possible to get CSE with subtract operations.
1222   // A later phase can perform the optimization of setting the destination
1223   // register to WZR/XZR if it ends up being unused.
1224   unsigned Opcode = AArch64ISD::SUBS;
1225 
1226   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1227       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1228     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1229     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1230     // can be set differently by this operation. It comes down to whether
1231     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1232     // everything is fine. If not then the optimization is wrong. Thus general
1233     // comparisons are only valid if op2 != 0.
1234 
1235     // So, finally, the only LLVM-native comparisons that don't mention C and V
1236     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1237     // the absence of information about op2.
1238     Opcode = AArch64ISD::ADDS;
1239     RHS = RHS.getOperand(1);
1240   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1241              !isUnsignedIntSetCC(CC)) {
1242     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1243     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1244     // of the signed comparisons.
1245     Opcode = AArch64ISD::ANDS;
1246     RHS = LHS.getOperand(1);
1247     LHS = LHS.getOperand(0);
1248   }
1249 
1250   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1251       .getValue(1);
1252 }
1253 
1254 /// \defgroup AArch64CCMP CMP;CCMP matching
1255 ///
1256 /// These functions deal with the formation of CMP;CCMP;... sequences.
1257 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1258 /// a comparison. They set the NZCV flags to a predefined value if their
1259 /// predicate is false. This allows to express arbitrary conjunctions, for
1260 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1261 /// expressed as:
1262 ///   cmp A
1263 ///   ccmp B, inv(CB), CA
1264 ///   check for CB flags
1265 ///
1266 /// In general we can create code for arbitrary "... (and (and A B) C)"
1267 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1268 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1269 /// negation operations:
1270 /// We can negate the results of a single comparison by inverting the flags
1271 /// used when the predicate fails and inverting the flags tested in the next
1272 /// instruction; We can also negate the results of the whole previous
1273 /// conditional compare sequence by inverting the flags tested in the next
1274 /// instruction. However there is no way to negate the result of a partial
1275 /// sequence.
1276 ///
1277 /// Therefore on encountering an "or" expression we can negate the subtree on
1278 /// one side and have to be able to push the negate to the leafs of the subtree
1279 /// on the other side (see also the comments in code). As complete example:
1280 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1281 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1282 /// is transformed to
1283 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1284 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1285 /// and implemented as:
1286 ///   cmp C
1287 ///   ccmp D, inv(CD), CC
1288 ///   ccmp A, CA, inv(CD)
1289 ///   ccmp B, CB, inv(CA)
1290 ///   check for CB flags
1291 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1292 /// by conditional compare sequences.
1293 /// @{
1294 
1295 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1296 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1297                                          ISD::CondCode CC, SDValue CCOp,
1298                                          AArch64CC::CondCode Predicate,
1299                                          AArch64CC::CondCode OutCC,
1300                                          const SDLoc &DL, SelectionDAG &DAG) {
1301   unsigned Opcode = 0;
1302   if (LHS.getValueType().isFloatingPoint()) {
1303     assert(LHS.getValueType() != MVT::f128);
1304     if (LHS.getValueType() == MVT::f16) {
1305       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1306       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1307     }
1308     Opcode = AArch64ISD::FCCMP;
1309   } else if (RHS.getOpcode() == ISD::SUB) {
1310     SDValue SubOp0 = RHS.getOperand(0);
1311     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1312       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1313       Opcode = AArch64ISD::CCMN;
1314       RHS = RHS.getOperand(1);
1315     }
1316   }
1317   if (Opcode == 0)
1318     Opcode = AArch64ISD::CCMP;
1319 
1320   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1321   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1322   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1323   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1324   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1325 }
1326 
1327 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1328 /// CanPushNegate is set to true if we can push a negate operation through
1329 /// the tree in a was that we are left with AND operations and negate operations
1330 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1331 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1332 /// brought into such a form.
1333 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1334                                          unsigned Depth = 0) {
1335   if (!Val.hasOneUse())
1336     return false;
1337   unsigned Opcode = Val->getOpcode();
1338   if (Opcode == ISD::SETCC) {
1339     if (Val->getOperand(0).getValueType() == MVT::f128)
1340       return false;
1341     CanNegate = true;
1342     return true;
1343   }
1344   // Protect against exponential runtime and stack overflow.
1345   if (Depth > 6)
1346     return false;
1347   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1348     SDValue O0 = Val->getOperand(0);
1349     SDValue O1 = Val->getOperand(1);
1350     bool CanNegateL;
1351     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1352       return false;
1353     bool CanNegateR;
1354     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1355       return false;
1356 
1357     if (Opcode == ISD::OR) {
1358       // For an OR expression we need to be able to negate at least one side or
1359       // we cannot do the transformation at all.
1360       if (!CanNegateL && !CanNegateR)
1361         return false;
1362       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1363       // can negate the x and y subtrees.
1364       CanNegate = CanNegateL && CanNegateR;
1365     } else {
1366       // If the operands are OR expressions then we finally need to negate their
1367       // outputs, we can only do that for the operand with emitted last by
1368       // negating OutCC, not for both operands.
1369       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1370       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1371       if (NeedsNegOutL && NeedsNegOutR)
1372         return false;
1373       // We cannot negate an AND operation (it would become an OR),
1374       CanNegate = false;
1375     }
1376     return true;
1377   }
1378   return false;
1379 }
1380 
1381 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1382 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1383 /// Tries to transform the given i1 producing node @p Val to a series compare
1384 /// and conditional compare operations. @returns an NZCV flags producing node
1385 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1386 /// transformation was not possible.
1387 /// On recursive invocations @p PushNegate may be set to true to have negation
1388 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1389 /// for the comparisons in the current subtree; @p Depth limits the search
1390 /// depth to avoid stack overflow.
1391 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1392     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1393     AArch64CC::CondCode Predicate) {
1394   // We're at a tree leaf, produce a conditional comparison operation.
1395   unsigned Opcode = Val->getOpcode();
1396   if (Opcode == ISD::SETCC) {
1397     SDValue LHS = Val->getOperand(0);
1398     SDValue RHS = Val->getOperand(1);
1399     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1400     bool isInteger = LHS.getValueType().isInteger();
1401     if (Negate)
1402       CC = getSetCCInverse(CC, isInteger);
1403     SDLoc DL(Val);
1404     // Determine OutCC and handle FP special case.
1405     if (isInteger) {
1406       OutCC = changeIntCCToAArch64CC(CC);
1407     } else {
1408       assert(LHS.getValueType().isFloatingPoint());
1409       AArch64CC::CondCode ExtraCC;
1410       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1411       // Some floating point conditions can't be tested with a single condition
1412       // code. Construct an additional comparison in this case.
1413       if (ExtraCC != AArch64CC::AL) {
1414         SDValue ExtraCmp;
1415         if (!CCOp.getNode())
1416           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1417         else
1418           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1419                                                ExtraCC, DL, DAG);
1420         CCOp = ExtraCmp;
1421         Predicate = ExtraCC;
1422       }
1423     }
1424 
1425     // Produce a normal comparison if we are first in the chain
1426     if (!CCOp)
1427       return emitComparison(LHS, RHS, CC, DL, DAG);
1428     // Otherwise produce a ccmp.
1429     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1430                                      DAG);
1431   }
1432   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1433          "Valid conjunction/disjunction tree");
1434 
1435   // Check if both sides can be transformed.
1436   SDValue LHS = Val->getOperand(0);
1437   SDValue RHS = Val->getOperand(1);
1438 
1439   // In case of an OR we need to negate our operands and the result.
1440   // (A v B) <=> not(not(A) ^ not(B))
1441   bool NegateOpsAndResult = Opcode == ISD::OR;
1442   // We can negate the results of all previous operations by inverting the
1443   // predicate flags giving us a free negation for one side. The other side
1444   // must be negatable by itself.
1445   if (NegateOpsAndResult) {
1446     // See which side we can negate.
1447     bool CanNegateL;
1448     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1449     assert(isValidL && "Valid conjunction/disjunction tree");
1450     (void)isValidL;
1451 
1452 #ifndef NDEBUG
1453     bool CanNegateR;
1454     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1455     assert(isValidR && "Valid conjunction/disjunction tree");
1456     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1457 #endif
1458 
1459     // Order the side which we cannot negate to RHS so we can emit it first.
1460     if (!CanNegateL)
1461       std::swap(LHS, RHS);
1462   } else {
1463     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1464     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1465            "Valid conjunction/disjunction tree");
1466     // Order the side where we need to negate the output flags to RHS so it
1467     // gets emitted first.
1468     if (NeedsNegOutL)
1469       std::swap(LHS, RHS);
1470   }
1471 
1472   // Emit RHS. If we want to negate the tree we only need to push a negate
1473   // through if we are already in a PushNegate case, otherwise we can negate
1474   // the "flags to test" afterwards.
1475   AArch64CC::CondCode RHSCC;
1476   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1477                                                    CCOp, Predicate);
1478   if (NegateOpsAndResult && !Negate)
1479     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1480   // Emit LHS. We may need to negate it.
1481   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1482                                                    NegateOpsAndResult, CmpR,
1483                                                    RHSCC);
1484   // If we transformed an OR to and AND then we have to negate the result
1485   // (or absorb the Negate parameter).
1486   if (NegateOpsAndResult && !Negate)
1487     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1488   return CmpL;
1489 }
1490 
1491 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1492 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1493 /// \see emitConjunctionDisjunctionTreeRec().
1494 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1495                                               AArch64CC::CondCode &OutCC) {
1496   bool CanNegate;
1497   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1498     return SDValue();
1499 
1500   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1501                                            AArch64CC::AL);
1502 }
1503 
1504 /// @}
1505 
1506 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1507                              SDValue &AArch64cc, SelectionDAG &DAG,
1508                              const SDLoc &dl) {
1509   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1510     EVT VT = RHS.getValueType();
1511     uint64_t C = RHSC->getZExtValue();
1512     if (!isLegalArithImmed(C)) {
1513       // Constant does not fit, try adjusting it by one?
1514       switch (CC) {
1515       default:
1516         break;
1517       case ISD::SETLT:
1518       case ISD::SETGE:
1519         if ((VT == MVT::i32 && C != 0x80000000 &&
1520              isLegalArithImmed((uint32_t)(C - 1))) ||
1521             (VT == MVT::i64 && C != 0x80000000ULL &&
1522              isLegalArithImmed(C - 1ULL))) {
1523           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1524           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1525           RHS = DAG.getConstant(C, dl, VT);
1526         }
1527         break;
1528       case ISD::SETULT:
1529       case ISD::SETUGE:
1530         if ((VT == MVT::i32 && C != 0 &&
1531              isLegalArithImmed((uint32_t)(C - 1))) ||
1532             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1533           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1534           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1535           RHS = DAG.getConstant(C, dl, VT);
1536         }
1537         break;
1538       case ISD::SETLE:
1539       case ISD::SETGT:
1540         if ((VT == MVT::i32 && C != INT32_MAX &&
1541              isLegalArithImmed((uint32_t)(C + 1))) ||
1542             (VT == MVT::i64 && C != INT64_MAX &&
1543              isLegalArithImmed(C + 1ULL))) {
1544           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1545           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1546           RHS = DAG.getConstant(C, dl, VT);
1547         }
1548         break;
1549       case ISD::SETULE:
1550       case ISD::SETUGT:
1551         if ((VT == MVT::i32 && C != UINT32_MAX &&
1552              isLegalArithImmed((uint32_t)(C + 1))) ||
1553             (VT == MVT::i64 && C != UINT64_MAX &&
1554              isLegalArithImmed(C + 1ULL))) {
1555           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1556           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1557           RHS = DAG.getConstant(C, dl, VT);
1558         }
1559         break;
1560       }
1561     }
1562   }
1563   SDValue Cmp;
1564   AArch64CC::CondCode AArch64CC;
1565   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1566     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1567 
1568     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1569     // For the i8 operand, the largest immediate is 255, so this can be easily
1570     // encoded in the compare instruction. For the i16 operand, however, the
1571     // largest immediate cannot be encoded in the compare.
1572     // Therefore, use a sign extending load and cmn to avoid materializing the
1573     // -1 constant. For example,
1574     // movz w1, #65535
1575     // ldrh w0, [x0, #0]
1576     // cmp w0, w1
1577     // >
1578     // ldrsh w0, [x0, #0]
1579     // cmn w0, #1
1580     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1581     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1582     // ensure both the LHS and RHS are truly zero extended and to make sure the
1583     // transformation is profitable.
1584     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1585         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1586         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1587         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1588       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1589       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1590         SDValue SExt =
1591             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1592                         DAG.getValueType(MVT::i16));
1593         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1594                                                    RHS.getValueType()),
1595                              CC, dl, DAG);
1596         AArch64CC = changeIntCCToAArch64CC(CC);
1597       }
1598     }
1599 
1600     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1601       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1602         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1603           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1604       }
1605     }
1606   }
1607 
1608   if (!Cmp) {
1609     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1610     AArch64CC = changeIntCCToAArch64CC(CC);
1611   }
1612   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1613   return Cmp;
1614 }
1615 
1616 static std::pair<SDValue, SDValue>
1617 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1618   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1619          "Unsupported value type");
1620   SDValue Value, Overflow;
1621   SDLoc DL(Op);
1622   SDValue LHS = Op.getOperand(0);
1623   SDValue RHS = Op.getOperand(1);
1624   unsigned Opc = 0;
1625   switch (Op.getOpcode()) {
1626   default:
1627     llvm_unreachable("Unknown overflow instruction!");
1628   case ISD::SADDO:
1629     Opc = AArch64ISD::ADDS;
1630     CC = AArch64CC::VS;
1631     break;
1632   case ISD::UADDO:
1633     Opc = AArch64ISD::ADDS;
1634     CC = AArch64CC::HS;
1635     break;
1636   case ISD::SSUBO:
1637     Opc = AArch64ISD::SUBS;
1638     CC = AArch64CC::VS;
1639     break;
1640   case ISD::USUBO:
1641     Opc = AArch64ISD::SUBS;
1642     CC = AArch64CC::LO;
1643     break;
1644   // Multiply needs a little bit extra work.
1645   case ISD::SMULO:
1646   case ISD::UMULO: {
1647     CC = AArch64CC::NE;
1648     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1649     if (Op.getValueType() == MVT::i32) {
1650       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1651       // For a 32 bit multiply with overflow check we want the instruction
1652       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1653       // need to generate the following pattern:
1654       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1655       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1656       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1657       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1658       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1659                                 DAG.getConstant(0, DL, MVT::i64));
1660       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1661       // operation. We need to clear out the upper 32 bits, because we used a
1662       // widening multiply that wrote all 64 bits. In the end this should be a
1663       // noop.
1664       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1665       if (IsSigned) {
1666         // The signed overflow check requires more than just a simple check for
1667         // any bit set in the upper 32 bits of the result. These bits could be
1668         // just the sign bits of a negative number. To perform the overflow
1669         // check we have to arithmetic shift right the 32nd bit of the result by
1670         // 31 bits. Then we compare the result to the upper 32 bits.
1671         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1672                                         DAG.getConstant(32, DL, MVT::i64));
1673         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1674         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1675                                         DAG.getConstant(31, DL, MVT::i64));
1676         // It is important that LowerBits is last, otherwise the arithmetic
1677         // shift will not be folded into the compare (SUBS).
1678         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1679         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1680                        .getValue(1);
1681       } else {
1682         // The overflow check for unsigned multiply is easy. We only need to
1683         // check if any of the upper 32 bits are set. This can be done with a
1684         // CMP (shifted register). For that we need to generate the following
1685         // pattern:
1686         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1687         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1688                                         DAG.getConstant(32, DL, MVT::i64));
1689         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1690         Overflow =
1691             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1692                         DAG.getConstant(0, DL, MVT::i64),
1693                         UpperBits).getValue(1);
1694       }
1695       break;
1696     }
1697     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1698     // For the 64 bit multiply
1699     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1700     if (IsSigned) {
1701       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1702       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1703                                       DAG.getConstant(63, DL, MVT::i64));
1704       // It is important that LowerBits is last, otherwise the arithmetic
1705       // shift will not be folded into the compare (SUBS).
1706       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1707       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1708                      .getValue(1);
1709     } else {
1710       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1711       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1712       Overflow =
1713           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1714                       DAG.getConstant(0, DL, MVT::i64),
1715                       UpperBits).getValue(1);
1716     }
1717     break;
1718   }
1719   } // switch (...)
1720 
1721   if (Opc) {
1722     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1723 
1724     // Emit the AArch64 operation with overflow check.
1725     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1726     Overflow = Value.getValue(1);
1727   }
1728   return std::make_pair(Value, Overflow);
1729 }
1730 
1731 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1732                                              RTLIB::Libcall Call) const {
1733   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1734   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1735 }
1736 
1737 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1738   SDValue Sel = Op.getOperand(0);
1739   SDValue Other = Op.getOperand(1);
1740 
1741   // If neither operand is a SELECT_CC, give up.
1742   if (Sel.getOpcode() != ISD::SELECT_CC)
1743     std::swap(Sel, Other);
1744   if (Sel.getOpcode() != ISD::SELECT_CC)
1745     return Op;
1746 
1747   // The folding we want to perform is:
1748   // (xor x, (select_cc a, b, cc, 0, -1) )
1749   //   -->
1750   // (csel x, (xor x, -1), cc ...)
1751   //
1752   // The latter will get matched to a CSINV instruction.
1753 
1754   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1755   SDValue LHS = Sel.getOperand(0);
1756   SDValue RHS = Sel.getOperand(1);
1757   SDValue TVal = Sel.getOperand(2);
1758   SDValue FVal = Sel.getOperand(3);
1759   SDLoc dl(Sel);
1760 
1761   // FIXME: This could be generalized to non-integer comparisons.
1762   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1763     return Op;
1764 
1765   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1766   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1767 
1768   // The values aren't constants, this isn't the pattern we're looking for.
1769   if (!CFVal || !CTVal)
1770     return Op;
1771 
1772   // We can commute the SELECT_CC by inverting the condition.  This
1773   // might be needed to make this fit into a CSINV pattern.
1774   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1775     std::swap(TVal, FVal);
1776     std::swap(CTVal, CFVal);
1777     CC = ISD::getSetCCInverse(CC, true);
1778   }
1779 
1780   // If the constants line up, perform the transform!
1781   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1782     SDValue CCVal;
1783     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1784 
1785     FVal = Other;
1786     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1787                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1788 
1789     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1790                        CCVal, Cmp);
1791   }
1792 
1793   return Op;
1794 }
1795 
1796 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1797   EVT VT = Op.getValueType();
1798 
1799   // Let legalize expand this if it isn't a legal type yet.
1800   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1801     return SDValue();
1802 
1803   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1804 
1805   unsigned Opc;
1806   bool ExtraOp = false;
1807   switch (Op.getOpcode()) {
1808   default:
1809     llvm_unreachable("Invalid code");
1810   case ISD::ADDC:
1811     Opc = AArch64ISD::ADDS;
1812     break;
1813   case ISD::SUBC:
1814     Opc = AArch64ISD::SUBS;
1815     break;
1816   case ISD::ADDE:
1817     Opc = AArch64ISD::ADCS;
1818     ExtraOp = true;
1819     break;
1820   case ISD::SUBE:
1821     Opc = AArch64ISD::SBCS;
1822     ExtraOp = true;
1823     break;
1824   }
1825 
1826   if (!ExtraOp)
1827     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1828   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1829                      Op.getOperand(2));
1830 }
1831 
1832 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1833   // Let legalize expand this if it isn't a legal type yet.
1834   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1835     return SDValue();
1836 
1837   SDLoc dl(Op);
1838   AArch64CC::CondCode CC;
1839   // The actual operation that sets the overflow or carry flag.
1840   SDValue Value, Overflow;
1841   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1842 
1843   // We use 0 and 1 as false and true values.
1844   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1845   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1846 
1847   // We use an inverted condition, because the conditional select is inverted
1848   // too. This will allow it to be selected to a single instruction:
1849   // CSINC Wd, WZR, WZR, invert(cond).
1850   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1851   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1852                          CCVal, Overflow);
1853 
1854   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1855   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1856 }
1857 
1858 // Prefetch operands are:
1859 // 1: Address to prefetch
1860 // 2: bool isWrite
1861 // 3: int locality (0 = no locality ... 3 = extreme locality)
1862 // 4: bool isDataCache
1863 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1864   SDLoc DL(Op);
1865   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1866   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1867   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1868 
1869   bool IsStream = !Locality;
1870   // When the locality number is set
1871   if (Locality) {
1872     // The front-end should have filtered out the out-of-range values
1873     assert(Locality <= 3 && "Prefetch locality out-of-range");
1874     // The locality degree is the opposite of the cache speed.
1875     // Put the number the other way around.
1876     // The encoding starts at 0 for level 1
1877     Locality = 3 - Locality;
1878   }
1879 
1880   // built the mask value encoding the expected behavior.
1881   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1882                    (!IsData << 3) |     // IsDataCache bit
1883                    (Locality << 1) |    // Cache level bits
1884                    (unsigned)IsStream;  // Stream bit
1885   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1886                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1887 }
1888 
1889 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1890                                               SelectionDAG &DAG) const {
1891   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1892 
1893   RTLIB::Libcall LC;
1894   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1895 
1896   return LowerF128Call(Op, DAG, LC);
1897 }
1898 
1899 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1900                                              SelectionDAG &DAG) const {
1901   if (Op.getOperand(0).getValueType() != MVT::f128) {
1902     // It's legal except when f128 is involved
1903     return Op;
1904   }
1905 
1906   RTLIB::Libcall LC;
1907   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1908 
1909   // FP_ROUND node has a second operand indicating whether it is known to be
1910   // precise. That doesn't take part in the LibCall so we can't directly use
1911   // LowerF128Call.
1912   SDValue SrcVal = Op.getOperand(0);
1913   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1914                      SDLoc(Op)).first;
1915 }
1916 
1917 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1918   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1919   // Any additional optimization in this function should be recorded
1920   // in the cost tables.
1921   EVT InVT = Op.getOperand(0).getValueType();
1922   EVT VT = Op.getValueType();
1923   unsigned NumElts = InVT.getVectorNumElements();
1924 
1925   // f16 vectors are promoted to f32 before a conversion.
1926   if (InVT.getVectorElementType() == MVT::f16) {
1927     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1928     SDLoc dl(Op);
1929     return DAG.getNode(
1930         Op.getOpcode(), dl, Op.getValueType(),
1931         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1932   }
1933 
1934   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1935     SDLoc dl(Op);
1936     SDValue Cv =
1937         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1938                     Op.getOperand(0));
1939     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1940   }
1941 
1942   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1943     SDLoc dl(Op);
1944     MVT ExtVT =
1945         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1946                          VT.getVectorNumElements());
1947     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1948     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1949   }
1950 
1951   // Type changing conversions are illegal.
1952   return Op;
1953 }
1954 
1955 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1956                                               SelectionDAG &DAG) const {
1957   if (Op.getOperand(0).getValueType().isVector())
1958     return LowerVectorFP_TO_INT(Op, DAG);
1959 
1960   // f16 conversions are promoted to f32.
1961   if (Op.getOperand(0).getValueType() == MVT::f16) {
1962     SDLoc dl(Op);
1963     return DAG.getNode(
1964         Op.getOpcode(), dl, Op.getValueType(),
1965         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1966   }
1967 
1968   if (Op.getOperand(0).getValueType() != MVT::f128) {
1969     // It's legal except when f128 is involved
1970     return Op;
1971   }
1972 
1973   RTLIB::Libcall LC;
1974   if (Op.getOpcode() == ISD::FP_TO_SINT)
1975     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1976   else
1977     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1978 
1979   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1980   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1981 }
1982 
1983 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1984   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1985   // Any additional optimization in this function should be recorded
1986   // in the cost tables.
1987   EVT VT = Op.getValueType();
1988   SDLoc dl(Op);
1989   SDValue In = Op.getOperand(0);
1990   EVT InVT = In.getValueType();
1991 
1992   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1993     MVT CastVT =
1994         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1995                          InVT.getVectorNumElements());
1996     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1997     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1998   }
1999 
2000   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2001     unsigned CastOpc =
2002         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2003     EVT CastVT = VT.changeVectorElementTypeToInteger();
2004     In = DAG.getNode(CastOpc, dl, CastVT, In);
2005     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2006   }
2007 
2008   return Op;
2009 }
2010 
2011 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2012                                             SelectionDAG &DAG) const {
2013   if (Op.getValueType().isVector())
2014     return LowerVectorINT_TO_FP(Op, DAG);
2015 
2016   // f16 conversions are promoted to f32.
2017   if (Op.getValueType() == MVT::f16) {
2018     SDLoc dl(Op);
2019     return DAG.getNode(
2020         ISD::FP_ROUND, dl, MVT::f16,
2021         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2022         DAG.getIntPtrConstant(0, dl));
2023   }
2024 
2025   // i128 conversions are libcalls.
2026   if (Op.getOperand(0).getValueType() == MVT::i128)
2027     return SDValue();
2028 
2029   // Other conversions are legal, unless it's to the completely software-based
2030   // fp128.
2031   if (Op.getValueType() != MVT::f128)
2032     return Op;
2033 
2034   RTLIB::Libcall LC;
2035   if (Op.getOpcode() == ISD::SINT_TO_FP)
2036     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2037   else
2038     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2039 
2040   return LowerF128Call(Op, DAG, LC);
2041 }
2042 
2043 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2044                                             SelectionDAG &DAG) const {
2045   // For iOS, we want to call an alternative entry point: __sincos_stret,
2046   // which returns the values in two S / D registers.
2047   SDLoc dl(Op);
2048   SDValue Arg = Op.getOperand(0);
2049   EVT ArgVT = Arg.getValueType();
2050   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2051 
2052   ArgListTy Args;
2053   ArgListEntry Entry;
2054 
2055   Entry.Node = Arg;
2056   Entry.Ty = ArgTy;
2057   Entry.isSExt = false;
2058   Entry.isZExt = false;
2059   Args.push_back(Entry);
2060 
2061   const char *LibcallName =
2062       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2063   SDValue Callee =
2064       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2065 
2066   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2067   TargetLowering::CallLoweringInfo CLI(DAG);
2068   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2069     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2070 
2071   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2072   return CallResult.first;
2073 }
2074 
2075 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2076   if (Op.getValueType() != MVT::f16)
2077     return SDValue();
2078 
2079   assert(Op.getOperand(0).getValueType() == MVT::i16);
2080   SDLoc DL(Op);
2081 
2082   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2083   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2084   return SDValue(
2085       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2086                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2087       0);
2088 }
2089 
2090 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2091   if (OrigVT.getSizeInBits() >= 64)
2092     return OrigVT;
2093 
2094   assert(OrigVT.isSimple() && "Expecting a simple value type");
2095 
2096   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2097   switch (OrigSimpleTy) {
2098   default: llvm_unreachable("Unexpected Vector Type");
2099   case MVT::v2i8:
2100   case MVT::v2i16:
2101      return MVT::v2i32;
2102   case MVT::v4i8:
2103     return  MVT::v4i16;
2104   }
2105 }
2106 
2107 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2108                                                  const EVT &OrigTy,
2109                                                  const EVT &ExtTy,
2110                                                  unsigned ExtOpcode) {
2111   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2112   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2113   // 64-bits we need to insert a new extension so that it will be 64-bits.
2114   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2115   if (OrigTy.getSizeInBits() >= 64)
2116     return N;
2117 
2118   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2119   EVT NewVT = getExtensionTo64Bits(OrigTy);
2120 
2121   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2122 }
2123 
2124 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2125                                    bool isSigned) {
2126   EVT VT = N->getValueType(0);
2127 
2128   if (N->getOpcode() != ISD::BUILD_VECTOR)
2129     return false;
2130 
2131   for (const SDValue &Elt : N->op_values()) {
2132     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2133       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2134       unsigned HalfSize = EltSize / 2;
2135       if (isSigned) {
2136         if (!isIntN(HalfSize, C->getSExtValue()))
2137           return false;
2138       } else {
2139         if (!isUIntN(HalfSize, C->getZExtValue()))
2140           return false;
2141       }
2142       continue;
2143     }
2144     return false;
2145   }
2146 
2147   return true;
2148 }
2149 
2150 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2151   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2152     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2153                                              N->getOperand(0)->getValueType(0),
2154                                              N->getValueType(0),
2155                                              N->getOpcode());
2156 
2157   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2158   EVT VT = N->getValueType(0);
2159   SDLoc dl(N);
2160   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2161   unsigned NumElts = VT.getVectorNumElements();
2162   MVT TruncVT = MVT::getIntegerVT(EltSize);
2163   SmallVector<SDValue, 8> Ops;
2164   for (unsigned i = 0; i != NumElts; ++i) {
2165     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2166     const APInt &CInt = C->getAPIntValue();
2167     // Element types smaller than 32 bits are not legal, so use i32 elements.
2168     // The values are implicitly truncated so sext vs. zext doesn't matter.
2169     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2170   }
2171   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2172 }
2173 
2174 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2175   if (N->getOpcode() == ISD::SIGN_EXTEND)
2176     return true;
2177   if (isExtendedBUILD_VECTOR(N, DAG, true))
2178     return true;
2179   return false;
2180 }
2181 
2182 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2183   if (N->getOpcode() == ISD::ZERO_EXTEND)
2184     return true;
2185   if (isExtendedBUILD_VECTOR(N, DAG, false))
2186     return true;
2187   return false;
2188 }
2189 
2190 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2191   unsigned Opcode = N->getOpcode();
2192   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2193     SDNode *N0 = N->getOperand(0).getNode();
2194     SDNode *N1 = N->getOperand(1).getNode();
2195     return N0->hasOneUse() && N1->hasOneUse() &&
2196       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2197   }
2198   return false;
2199 }
2200 
2201 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2202   unsigned Opcode = N->getOpcode();
2203   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2204     SDNode *N0 = N->getOperand(0).getNode();
2205     SDNode *N1 = N->getOperand(1).getNode();
2206     return N0->hasOneUse() && N1->hasOneUse() &&
2207       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2208   }
2209   return false;
2210 }
2211 
2212 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2213   // Multiplications are only custom-lowered for 128-bit vectors so that
2214   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2215   EVT VT = Op.getValueType();
2216   assert(VT.is128BitVector() && VT.isInteger() &&
2217          "unexpected type for custom-lowering ISD::MUL");
2218   SDNode *N0 = Op.getOperand(0).getNode();
2219   SDNode *N1 = Op.getOperand(1).getNode();
2220   unsigned NewOpc = 0;
2221   bool isMLA = false;
2222   bool isN0SExt = isSignExtended(N0, DAG);
2223   bool isN1SExt = isSignExtended(N1, DAG);
2224   if (isN0SExt && isN1SExt)
2225     NewOpc = AArch64ISD::SMULL;
2226   else {
2227     bool isN0ZExt = isZeroExtended(N0, DAG);
2228     bool isN1ZExt = isZeroExtended(N1, DAG);
2229     if (isN0ZExt && isN1ZExt)
2230       NewOpc = AArch64ISD::UMULL;
2231     else if (isN1SExt || isN1ZExt) {
2232       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2233       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2234       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2235         NewOpc = AArch64ISD::SMULL;
2236         isMLA = true;
2237       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2238         NewOpc =  AArch64ISD::UMULL;
2239         isMLA = true;
2240       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2241         std::swap(N0, N1);
2242         NewOpc =  AArch64ISD::UMULL;
2243         isMLA = true;
2244       }
2245     }
2246 
2247     if (!NewOpc) {
2248       if (VT == MVT::v2i64)
2249         // Fall through to expand this.  It is not legal.
2250         return SDValue();
2251       else
2252         // Other vector multiplications are legal.
2253         return Op;
2254     }
2255   }
2256 
2257   // Legalize to a S/UMULL instruction
2258   SDLoc DL(Op);
2259   SDValue Op0;
2260   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2261   if (!isMLA) {
2262     Op0 = skipExtensionForVectorMULL(N0, DAG);
2263     assert(Op0.getValueType().is64BitVector() &&
2264            Op1.getValueType().is64BitVector() &&
2265            "unexpected types for extended operands to VMULL");
2266     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2267   }
2268   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2269   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2270   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2271   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2272   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2273   EVT Op1VT = Op1.getValueType();
2274   return DAG.getNode(N0->getOpcode(), DL, VT,
2275                      DAG.getNode(NewOpc, DL, VT,
2276                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2277                      DAG.getNode(NewOpc, DL, VT,
2278                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2279 }
2280 
2281 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2282                                                      SelectionDAG &DAG) const {
2283   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2284   SDLoc dl(Op);
2285   switch (IntNo) {
2286   default: return SDValue();    // Don't custom lower most intrinsics.
2287   case Intrinsic::thread_pointer: {
2288     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2289     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2290   }
2291   case Intrinsic::aarch64_neon_smax:
2292     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2293                        Op.getOperand(1), Op.getOperand(2));
2294   case Intrinsic::aarch64_neon_umax:
2295     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2296                        Op.getOperand(1), Op.getOperand(2));
2297   case Intrinsic::aarch64_neon_smin:
2298     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2299                        Op.getOperand(1), Op.getOperand(2));
2300   case Intrinsic::aarch64_neon_umin:
2301     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2302                        Op.getOperand(1), Op.getOperand(2));
2303   }
2304 }
2305 
2306 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2307                                               SelectionDAG &DAG) const {
2308   switch (Op.getOpcode()) {
2309   default:
2310     llvm_unreachable("unimplemented operand");
2311     return SDValue();
2312   case ISD::BITCAST:
2313     return LowerBITCAST(Op, DAG);
2314   case ISD::GlobalAddress:
2315     return LowerGlobalAddress(Op, DAG);
2316   case ISD::GlobalTLSAddress:
2317     return LowerGlobalTLSAddress(Op, DAG);
2318   case ISD::SETCC:
2319     return LowerSETCC(Op, DAG);
2320   case ISD::BR_CC:
2321     return LowerBR_CC(Op, DAG);
2322   case ISD::SELECT:
2323     return LowerSELECT(Op, DAG);
2324   case ISD::SELECT_CC:
2325     return LowerSELECT_CC(Op, DAG);
2326   case ISD::JumpTable:
2327     return LowerJumpTable(Op, DAG);
2328   case ISD::ConstantPool:
2329     return LowerConstantPool(Op, DAG);
2330   case ISD::BlockAddress:
2331     return LowerBlockAddress(Op, DAG);
2332   case ISD::VASTART:
2333     return LowerVASTART(Op, DAG);
2334   case ISD::VACOPY:
2335     return LowerVACOPY(Op, DAG);
2336   case ISD::VAARG:
2337     return LowerVAARG(Op, DAG);
2338   case ISD::ADDC:
2339   case ISD::ADDE:
2340   case ISD::SUBC:
2341   case ISD::SUBE:
2342     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2343   case ISD::SADDO:
2344   case ISD::UADDO:
2345   case ISD::SSUBO:
2346   case ISD::USUBO:
2347   case ISD::SMULO:
2348   case ISD::UMULO:
2349     return LowerXALUO(Op, DAG);
2350   case ISD::FADD:
2351     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2352   case ISD::FSUB:
2353     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2354   case ISD::FMUL:
2355     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2356   case ISD::FDIV:
2357     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2358   case ISD::FP_ROUND:
2359     return LowerFP_ROUND(Op, DAG);
2360   case ISD::FP_EXTEND:
2361     return LowerFP_EXTEND(Op, DAG);
2362   case ISD::FRAMEADDR:
2363     return LowerFRAMEADDR(Op, DAG);
2364   case ISD::RETURNADDR:
2365     return LowerRETURNADDR(Op, DAG);
2366   case ISD::INSERT_VECTOR_ELT:
2367     return LowerINSERT_VECTOR_ELT(Op, DAG);
2368   case ISD::EXTRACT_VECTOR_ELT:
2369     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2370   case ISD::BUILD_VECTOR:
2371     return LowerBUILD_VECTOR(Op, DAG);
2372   case ISD::VECTOR_SHUFFLE:
2373     return LowerVECTOR_SHUFFLE(Op, DAG);
2374   case ISD::EXTRACT_SUBVECTOR:
2375     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2376   case ISD::SRA:
2377   case ISD::SRL:
2378   case ISD::SHL:
2379     return LowerVectorSRA_SRL_SHL(Op, DAG);
2380   case ISD::SHL_PARTS:
2381     return LowerShiftLeftParts(Op, DAG);
2382   case ISD::SRL_PARTS:
2383   case ISD::SRA_PARTS:
2384     return LowerShiftRightParts(Op, DAG);
2385   case ISD::CTPOP:
2386     return LowerCTPOP(Op, DAG);
2387   case ISD::FCOPYSIGN:
2388     return LowerFCOPYSIGN(Op, DAG);
2389   case ISD::AND:
2390     return LowerVectorAND(Op, DAG);
2391   case ISD::OR:
2392     return LowerVectorOR(Op, DAG);
2393   case ISD::XOR:
2394     return LowerXOR(Op, DAG);
2395   case ISD::PREFETCH:
2396     return LowerPREFETCH(Op, DAG);
2397   case ISD::SINT_TO_FP:
2398   case ISD::UINT_TO_FP:
2399     return LowerINT_TO_FP(Op, DAG);
2400   case ISD::FP_TO_SINT:
2401   case ISD::FP_TO_UINT:
2402     return LowerFP_TO_INT(Op, DAG);
2403   case ISD::FSINCOS:
2404     return LowerFSINCOS(Op, DAG);
2405   case ISD::MUL:
2406     return LowerMUL(Op, DAG);
2407   case ISD::INTRINSIC_WO_CHAIN:
2408     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2409   }
2410 }
2411 
2412 //===----------------------------------------------------------------------===//
2413 //                      Calling Convention Implementation
2414 //===----------------------------------------------------------------------===//
2415 
2416 #include "AArch64GenCallingConv.inc"
2417 
2418 /// Selects the correct CCAssignFn for a given CallingConvention value.
2419 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2420                                                      bool IsVarArg) const {
2421   switch (CC) {
2422   default:
2423     llvm_unreachable("Unsupported calling convention.");
2424   case CallingConv::WebKit_JS:
2425     return CC_AArch64_WebKit_JS;
2426   case CallingConv::GHC:
2427     return CC_AArch64_GHC;
2428   case CallingConv::C:
2429   case CallingConv::Fast:
2430   case CallingConv::PreserveMost:
2431   case CallingConv::CXX_FAST_TLS:
2432   case CallingConv::Swift:
2433     if (!Subtarget->isTargetDarwin())
2434       return CC_AArch64_AAPCS;
2435     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2436   }
2437 }
2438 
2439 CCAssignFn *
2440 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2441   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2442                                       : RetCC_AArch64_AAPCS;
2443 }
2444 
2445 SDValue AArch64TargetLowering::LowerFormalArguments(
2446     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2447     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2448     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2449   MachineFunction &MF = DAG.getMachineFunction();
2450   MachineFrameInfo &MFI = MF.getFrameInfo();
2451 
2452   // Assign locations to all of the incoming arguments.
2453   SmallVector<CCValAssign, 16> ArgLocs;
2454   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2455                  *DAG.getContext());
2456 
2457   // At this point, Ins[].VT may already be promoted to i32. To correctly
2458   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2459   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2460   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2461   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2462   // LocVT.
2463   unsigned NumArgs = Ins.size();
2464   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2465   unsigned CurArgIdx = 0;
2466   for (unsigned i = 0; i != NumArgs; ++i) {
2467     MVT ValVT = Ins[i].VT;
2468     if (Ins[i].isOrigArg()) {
2469       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2470       CurArgIdx = Ins[i].getOrigArgIndex();
2471 
2472       // Get type of the original argument.
2473       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2474                                   /*AllowUnknown*/ true);
2475       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2476       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2477       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2478         ValVT = MVT::i8;
2479       else if (ActualMVT == MVT::i16)
2480         ValVT = MVT::i16;
2481     }
2482     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2483     bool Res =
2484         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2485     assert(!Res && "Call operand has unhandled type");
2486     (void)Res;
2487   }
2488   assert(ArgLocs.size() == Ins.size());
2489   SmallVector<SDValue, 16> ArgValues;
2490   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2491     CCValAssign &VA = ArgLocs[i];
2492 
2493     if (Ins[i].Flags.isByVal()) {
2494       // Byval is used for HFAs in the PCS, but the system should work in a
2495       // non-compliant manner for larger structs.
2496       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2497       int Size = Ins[i].Flags.getByValSize();
2498       unsigned NumRegs = (Size + 7) / 8;
2499 
2500       // FIXME: This works on big-endian for composite byvals, which are the common
2501       // case. It should also work for fundamental types too.
2502       unsigned FrameIdx =
2503         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2504       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2505       InVals.push_back(FrameIdxN);
2506 
2507       continue;
2508     }
2509 
2510     if (VA.isRegLoc()) {
2511       // Arguments stored in registers.
2512       EVT RegVT = VA.getLocVT();
2513 
2514       SDValue ArgValue;
2515       const TargetRegisterClass *RC;
2516 
2517       if (RegVT == MVT::i32)
2518         RC = &AArch64::GPR32RegClass;
2519       else if (RegVT == MVT::i64)
2520         RC = &AArch64::GPR64RegClass;
2521       else if (RegVT == MVT::f16)
2522         RC = &AArch64::FPR16RegClass;
2523       else if (RegVT == MVT::f32)
2524         RC = &AArch64::FPR32RegClass;
2525       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2526         RC = &AArch64::FPR64RegClass;
2527       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2528         RC = &AArch64::FPR128RegClass;
2529       else
2530         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2531 
2532       // Transform the arguments in physical registers into virtual ones.
2533       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2534       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2535 
2536       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2537       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2538       // truncate to the right size.
2539       switch (VA.getLocInfo()) {
2540       default:
2541         llvm_unreachable("Unknown loc info!");
2542       case CCValAssign::Full:
2543         break;
2544       case CCValAssign::BCvt:
2545         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2546         break;
2547       case CCValAssign::AExt:
2548       case CCValAssign::SExt:
2549       case CCValAssign::ZExt:
2550         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2551         // nodes after our lowering.
2552         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2553         break;
2554       }
2555 
2556       InVals.push_back(ArgValue);
2557 
2558     } else { // VA.isRegLoc()
2559       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2560       unsigned ArgOffset = VA.getLocMemOffset();
2561       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2562 
2563       uint32_t BEAlign = 0;
2564       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2565           !Ins[i].Flags.isInConsecutiveRegs())
2566         BEAlign = 8 - ArgSize;
2567 
2568       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2569 
2570       // Create load nodes to retrieve arguments from the stack.
2571       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2572       SDValue ArgValue;
2573 
2574       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2575       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2576       MVT MemVT = VA.getValVT();
2577 
2578       switch (VA.getLocInfo()) {
2579       default:
2580         break;
2581       case CCValAssign::BCvt:
2582         MemVT = VA.getLocVT();
2583         break;
2584       case CCValAssign::SExt:
2585         ExtType = ISD::SEXTLOAD;
2586         break;
2587       case CCValAssign::ZExt:
2588         ExtType = ISD::ZEXTLOAD;
2589         break;
2590       case CCValAssign::AExt:
2591         ExtType = ISD::EXTLOAD;
2592         break;
2593       }
2594 
2595       ArgValue = DAG.getExtLoad(
2596           ExtType, DL, VA.getLocVT(), Chain, FIN,
2597           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2598           MemVT);
2599 
2600       InVals.push_back(ArgValue);
2601     }
2602   }
2603 
2604   // varargs
2605   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2606   if (isVarArg) {
2607     if (!Subtarget->isTargetDarwin()) {
2608       // The AAPCS variadic function ABI is identical to the non-variadic
2609       // one. As a result there may be more arguments in registers and we should
2610       // save them for future reference.
2611       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2612     }
2613 
2614     // This will point to the next argument passed via stack.
2615     unsigned StackOffset = CCInfo.getNextStackOffset();
2616     // We currently pass all varargs at 8-byte alignment.
2617     StackOffset = ((StackOffset + 7) & ~7);
2618     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2619   }
2620 
2621   unsigned StackArgSize = CCInfo.getNextStackOffset();
2622   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2623   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2624     // This is a non-standard ABI so by fiat I say we're allowed to make full
2625     // use of the stack area to be popped, which must be aligned to 16 bytes in
2626     // any case:
2627     StackArgSize = alignTo(StackArgSize, 16);
2628 
2629     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2630     // a multiple of 16.
2631     FuncInfo->setArgumentStackToRestore(StackArgSize);
2632 
2633     // This realignment carries over to the available bytes below. Our own
2634     // callers will guarantee the space is free by giving an aligned value to
2635     // CALLSEQ_START.
2636   }
2637   // Even if we're not expected to free up the space, it's useful to know how
2638   // much is there while considering tail calls (because we can reuse it).
2639   FuncInfo->setBytesInStackArgArea(StackArgSize);
2640 
2641   return Chain;
2642 }
2643 
2644 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2645                                                 SelectionDAG &DAG,
2646                                                 const SDLoc &DL,
2647                                                 SDValue &Chain) const {
2648   MachineFunction &MF = DAG.getMachineFunction();
2649   MachineFrameInfo &MFI = MF.getFrameInfo();
2650   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2651   auto PtrVT = getPointerTy(DAG.getDataLayout());
2652 
2653   SmallVector<SDValue, 8> MemOps;
2654 
2655   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2656                                           AArch64::X3, AArch64::X4, AArch64::X5,
2657                                           AArch64::X6, AArch64::X7 };
2658   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2659   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2660 
2661   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2662   int GPRIdx = 0;
2663   if (GPRSaveSize != 0) {
2664     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2665 
2666     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2667 
2668     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2669       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2670       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2671       SDValue Store = DAG.getStore(
2672           Val.getValue(1), DL, Val, FIN,
2673           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2674       MemOps.push_back(Store);
2675       FIN =
2676           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2677     }
2678   }
2679   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2680   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2681 
2682   if (Subtarget->hasFPARMv8()) {
2683     static const MCPhysReg FPRArgRegs[] = {
2684         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2685         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2686     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2687     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2688 
2689     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2690     int FPRIdx = 0;
2691     if (FPRSaveSize != 0) {
2692       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2693 
2694       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2695 
2696       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2697         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2698         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2699 
2700         SDValue Store = DAG.getStore(
2701             Val.getValue(1), DL, Val, FIN,
2702             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2703         MemOps.push_back(Store);
2704         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2705                           DAG.getConstant(16, DL, PtrVT));
2706       }
2707     }
2708     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2709     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2710   }
2711 
2712   if (!MemOps.empty()) {
2713     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2714   }
2715 }
2716 
2717 /// LowerCallResult - Lower the result values of a call into the
2718 /// appropriate copies out of appropriate physical registers.
2719 SDValue AArch64TargetLowering::LowerCallResult(
2720     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2721     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2722     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2723     SDValue ThisVal) const {
2724   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2725                           ? RetCC_AArch64_WebKit_JS
2726                           : RetCC_AArch64_AAPCS;
2727   // Assign locations to each value returned by this call.
2728   SmallVector<CCValAssign, 16> RVLocs;
2729   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2730                  *DAG.getContext());
2731   CCInfo.AnalyzeCallResult(Ins, RetCC);
2732 
2733   // Copy all of the result registers out of their specified physreg.
2734   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2735     CCValAssign VA = RVLocs[i];
2736 
2737     // Pass 'this' value directly from the argument to return value, to avoid
2738     // reg unit interference
2739     if (i == 0 && isThisReturn) {
2740       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2741              "unexpected return calling convention register assignment");
2742       InVals.push_back(ThisVal);
2743       continue;
2744     }
2745 
2746     SDValue Val =
2747         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2748     Chain = Val.getValue(1);
2749     InFlag = Val.getValue(2);
2750 
2751     switch (VA.getLocInfo()) {
2752     default:
2753       llvm_unreachable("Unknown loc info!");
2754     case CCValAssign::Full:
2755       break;
2756     case CCValAssign::BCvt:
2757       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2758       break;
2759     }
2760 
2761     InVals.push_back(Val);
2762   }
2763 
2764   return Chain;
2765 }
2766 
2767 /// Return true if the calling convention is one that we can guarantee TCO for.
2768 static bool canGuaranteeTCO(CallingConv::ID CC) {
2769   return CC == CallingConv::Fast;
2770 }
2771 
2772 /// Return true if we might ever do TCO for calls with this calling convention.
2773 static bool mayTailCallThisCC(CallingConv::ID CC) {
2774   switch (CC) {
2775   case CallingConv::C:
2776   case CallingConv::PreserveMost:
2777   case CallingConv::Swift:
2778     return true;
2779   default:
2780     return canGuaranteeTCO(CC);
2781   }
2782 }
2783 
2784 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2785     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2786     const SmallVectorImpl<ISD::OutputArg> &Outs,
2787     const SmallVectorImpl<SDValue> &OutVals,
2788     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2789   if (!mayTailCallThisCC(CalleeCC))
2790     return false;
2791 
2792   MachineFunction &MF = DAG.getMachineFunction();
2793   const Function *CallerF = MF.getFunction();
2794   CallingConv::ID CallerCC = CallerF->getCallingConv();
2795   bool CCMatch = CallerCC == CalleeCC;
2796 
2797   // Byval parameters hand the function a pointer directly into the stack area
2798   // we want to reuse during a tail call. Working around this *is* possible (see
2799   // X86) but less efficient and uglier in LowerCall.
2800   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2801                                     e = CallerF->arg_end();
2802        i != e; ++i)
2803     if (i->hasByValAttr())
2804       return false;
2805 
2806   if (getTargetMachine().Options.GuaranteedTailCallOpt)
2807     return canGuaranteeTCO(CalleeCC) && CCMatch;
2808 
2809   // Externally-defined functions with weak linkage should not be
2810   // tail-called on AArch64 when the OS does not support dynamic
2811   // pre-emption of symbols, as the AAELF spec requires normal calls
2812   // to undefined weak functions to be replaced with a NOP or jump to the
2813   // next instruction. The behaviour of branch instructions in this
2814   // situation (as used for tail calls) is implementation-defined, so we
2815   // cannot rely on the linker replacing the tail call with a return.
2816   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2817     const GlobalValue *GV = G->getGlobal();
2818     const Triple &TT = getTargetMachine().getTargetTriple();
2819     if (GV->hasExternalWeakLinkage() &&
2820         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2821       return false;
2822   }
2823 
2824   // Now we search for cases where we can use a tail call without changing the
2825   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2826   // concept.
2827 
2828   // I want anyone implementing a new calling convention to think long and hard
2829   // about this assert.
2830   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2831          "Unexpected variadic calling convention");
2832 
2833   LLVMContext &C = *DAG.getContext();
2834   if (isVarArg && !Outs.empty()) {
2835     // At least two cases here: if caller is fastcc then we can't have any
2836     // memory arguments (we'd be expected to clean up the stack afterwards). If
2837     // caller is C then we could potentially use its argument area.
2838 
2839     // FIXME: for now we take the most conservative of these in both cases:
2840     // disallow all variadic memory operands.
2841     SmallVector<CCValAssign, 16> ArgLocs;
2842     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2843 
2844     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2845     for (const CCValAssign &ArgLoc : ArgLocs)
2846       if (!ArgLoc.isRegLoc())
2847         return false;
2848   }
2849 
2850   // Check that the call results are passed in the same way.
2851   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2852                                   CCAssignFnForCall(CalleeCC, isVarArg),
2853                                   CCAssignFnForCall(CallerCC, isVarArg)))
2854     return false;
2855   // The callee has to preserve all registers the caller needs to preserve.
2856   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2857   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2858   if (!CCMatch) {
2859     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2860     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2861       return false;
2862   }
2863 
2864   // Nothing more to check if the callee is taking no arguments
2865   if (Outs.empty())
2866     return true;
2867 
2868   SmallVector<CCValAssign, 16> ArgLocs;
2869   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2870 
2871   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2872 
2873   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2874 
2875   // If the stack arguments for this call do not fit into our own save area then
2876   // the call cannot be made tail.
2877   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2878     return false;
2879 
2880   const MachineRegisterInfo &MRI = MF.getRegInfo();
2881   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2882     return false;
2883 
2884   return true;
2885 }
2886 
2887 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2888                                                    SelectionDAG &DAG,
2889                                                    MachineFrameInfo &MFI,
2890                                                    int ClobberedFI) const {
2891   SmallVector<SDValue, 8> ArgChains;
2892   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2893   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2894 
2895   // Include the original chain at the beginning of the list. When this is
2896   // used by target LowerCall hooks, this helps legalize find the
2897   // CALLSEQ_BEGIN node.
2898   ArgChains.push_back(Chain);
2899 
2900   // Add a chain value for each stack argument corresponding
2901   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2902                             UE = DAG.getEntryNode().getNode()->use_end();
2903        U != UE; ++U)
2904     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2905       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2906         if (FI->getIndex() < 0) {
2907           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2908           int64_t InLastByte = InFirstByte;
2909           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2910 
2911           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2912               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2913             ArgChains.push_back(SDValue(L, 1));
2914         }
2915 
2916   // Build a tokenfactor for all the chains.
2917   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2918 }
2919 
2920 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2921                                                    bool TailCallOpt) const {
2922   return CallCC == CallingConv::Fast && TailCallOpt;
2923 }
2924 
2925 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2926 /// and add input and output parameter nodes.
2927 SDValue
2928 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2929                                  SmallVectorImpl<SDValue> &InVals) const {
2930   SelectionDAG &DAG = CLI.DAG;
2931   SDLoc &DL = CLI.DL;
2932   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2933   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2934   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2935   SDValue Chain = CLI.Chain;
2936   SDValue Callee = CLI.Callee;
2937   bool &IsTailCall = CLI.IsTailCall;
2938   CallingConv::ID CallConv = CLI.CallConv;
2939   bool IsVarArg = CLI.IsVarArg;
2940 
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   bool IsThisReturn = false;
2943 
2944   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2945   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2946   bool IsSibCall = false;
2947 
2948   if (IsTailCall) {
2949     // Check if it's really possible to do a tail call.
2950     IsTailCall = isEligibleForTailCallOptimization(
2951         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2952     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2953       report_fatal_error("failed to perform tail call elimination on a call "
2954                          "site marked musttail");
2955 
2956     // A sibling call is one where we're under the usual C ABI and not planning
2957     // to change that but can still do a tail call:
2958     if (!TailCallOpt && IsTailCall)
2959       IsSibCall = true;
2960 
2961     if (IsTailCall)
2962       ++NumTailCalls;
2963   }
2964 
2965   // Analyze operands of the call, assigning locations to each operand.
2966   SmallVector<CCValAssign, 16> ArgLocs;
2967   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2968                  *DAG.getContext());
2969 
2970   if (IsVarArg) {
2971     // Handle fixed and variable vector arguments differently.
2972     // Variable vector arguments always go into memory.
2973     unsigned NumArgs = Outs.size();
2974 
2975     for (unsigned i = 0; i != NumArgs; ++i) {
2976       MVT ArgVT = Outs[i].VT;
2977       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2978       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2979                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2980       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2981       assert(!Res && "Call operand has unhandled type");
2982       (void)Res;
2983     }
2984   } else {
2985     // At this point, Outs[].VT may already be promoted to i32. To correctly
2986     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2987     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2988     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2989     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2990     // LocVT.
2991     unsigned NumArgs = Outs.size();
2992     for (unsigned i = 0; i != NumArgs; ++i) {
2993       MVT ValVT = Outs[i].VT;
2994       // Get type of the original argument.
2995       EVT ActualVT = getValueType(DAG.getDataLayout(),
2996                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2997                                   /*AllowUnknown*/ true);
2998       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2999       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3000       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3001       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3002         ValVT = MVT::i8;
3003       else if (ActualMVT == MVT::i16)
3004         ValVT = MVT::i16;
3005 
3006       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3007       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3008       assert(!Res && "Call operand has unhandled type");
3009       (void)Res;
3010     }
3011   }
3012 
3013   // Get a count of how many bytes are to be pushed on the stack.
3014   unsigned NumBytes = CCInfo.getNextStackOffset();
3015 
3016   if (IsSibCall) {
3017     // Since we're not changing the ABI to make this a tail call, the memory
3018     // operands are already available in the caller's incoming argument space.
3019     NumBytes = 0;
3020   }
3021 
3022   // FPDiff is the byte offset of the call's argument area from the callee's.
3023   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3024   // by this amount for a tail call. In a sibling call it must be 0 because the
3025   // caller will deallocate the entire stack and the callee still expects its
3026   // arguments to begin at SP+0. Completely unused for non-tail calls.
3027   int FPDiff = 0;
3028 
3029   if (IsTailCall && !IsSibCall) {
3030     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3031 
3032     // Since callee will pop argument stack as a tail call, we must keep the
3033     // popped size 16-byte aligned.
3034     NumBytes = alignTo(NumBytes, 16);
3035 
3036     // FPDiff will be negative if this tail call requires more space than we
3037     // would automatically have in our incoming argument space. Positive if we
3038     // can actually shrink the stack.
3039     FPDiff = NumReusableBytes - NumBytes;
3040 
3041     // The stack pointer must be 16-byte aligned at all times it's used for a
3042     // memory operation, which in practice means at *all* times and in
3043     // particular across call boundaries. Therefore our own arguments started at
3044     // a 16-byte aligned SP and the delta applied for the tail call should
3045     // satisfy the same constraint.
3046     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3047   }
3048 
3049   // Adjust the stack pointer for the new arguments...
3050   // These operations are automatically eliminated by the prolog/epilog pass
3051   if (!IsSibCall)
3052     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3053                                                               true),
3054                                  DL);
3055 
3056   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3057                                         getPointerTy(DAG.getDataLayout()));
3058 
3059   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3060   SmallVector<SDValue, 8> MemOpChains;
3061   auto PtrVT = getPointerTy(DAG.getDataLayout());
3062 
3063   // Walk the register/memloc assignments, inserting copies/loads.
3064   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3065        ++i, ++realArgIdx) {
3066     CCValAssign &VA = ArgLocs[i];
3067     SDValue Arg = OutVals[realArgIdx];
3068     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3069 
3070     // Promote the value if needed.
3071     switch (VA.getLocInfo()) {
3072     default:
3073       llvm_unreachable("Unknown loc info!");
3074     case CCValAssign::Full:
3075       break;
3076     case CCValAssign::SExt:
3077       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3078       break;
3079     case CCValAssign::ZExt:
3080       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3081       break;
3082     case CCValAssign::AExt:
3083       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3084         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3085         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3086         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3087       }
3088       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3089       break;
3090     case CCValAssign::BCvt:
3091       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3092       break;
3093     case CCValAssign::FPExt:
3094       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3095       break;
3096     }
3097 
3098     if (VA.isRegLoc()) {
3099       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3100         assert(VA.getLocVT() == MVT::i64 &&
3101                "unexpected calling convention register assignment");
3102         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3103                "unexpected use of 'returned'");
3104         IsThisReturn = true;
3105       }
3106       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3107     } else {
3108       assert(VA.isMemLoc());
3109 
3110       SDValue DstAddr;
3111       MachinePointerInfo DstInfo;
3112 
3113       // FIXME: This works on big-endian for composite byvals, which are the
3114       // common case. It should also work for fundamental types too.
3115       uint32_t BEAlign = 0;
3116       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3117                                         : VA.getValVT().getSizeInBits();
3118       OpSize = (OpSize + 7) / 8;
3119       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3120           !Flags.isInConsecutiveRegs()) {
3121         if (OpSize < 8)
3122           BEAlign = 8 - OpSize;
3123       }
3124       unsigned LocMemOffset = VA.getLocMemOffset();
3125       int32_t Offset = LocMemOffset + BEAlign;
3126       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3127       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3128 
3129       if (IsTailCall) {
3130         Offset = Offset + FPDiff;
3131         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3132 
3133         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3134         DstInfo =
3135             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3136 
3137         // Make sure any stack arguments overlapping with where we're storing
3138         // are loaded before this eventual operation. Otherwise they'll be
3139         // clobbered.
3140         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3141       } else {
3142         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3143 
3144         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3145         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3146                                                LocMemOffset);
3147       }
3148 
3149       if (Outs[i].Flags.isByVal()) {
3150         SDValue SizeNode =
3151             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3152         SDValue Cpy = DAG.getMemcpy(
3153             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3154             /*isVol = */ false, /*AlwaysInline = */ false,
3155             /*isTailCall = */ false,
3156             DstInfo, MachinePointerInfo());
3157 
3158         MemOpChains.push_back(Cpy);
3159       } else {
3160         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3161         // promoted to a legal register type i32, we should truncate Arg back to
3162         // i1/i8/i16.
3163         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3164             VA.getValVT() == MVT::i16)
3165           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3166 
3167         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3168         MemOpChains.push_back(Store);
3169       }
3170     }
3171   }
3172 
3173   if (!MemOpChains.empty())
3174     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3175 
3176   // Build a sequence of copy-to-reg nodes chained together with token chain
3177   // and flag operands which copy the outgoing args into the appropriate regs.
3178   SDValue InFlag;
3179   for (auto &RegToPass : RegsToPass) {
3180     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3181                              RegToPass.second, InFlag);
3182     InFlag = Chain.getValue(1);
3183   }
3184 
3185   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3186   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3187   // node so that legalize doesn't hack it.
3188   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3189       Subtarget->isTargetMachO()) {
3190     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3191       const GlobalValue *GV = G->getGlobal();
3192       bool InternalLinkage = GV->hasInternalLinkage();
3193       if (InternalLinkage)
3194         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3195       else {
3196         Callee =
3197             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3198         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3199       }
3200     } else if (ExternalSymbolSDNode *S =
3201                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3202       const char *Sym = S->getSymbol();
3203       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3204       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3205     }
3206   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3207     const GlobalValue *GV = G->getGlobal();
3208     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3209   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3210     const char *Sym = S->getSymbol();
3211     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3212   }
3213 
3214   // We don't usually want to end the call-sequence here because we would tidy
3215   // the frame up *after* the call, however in the ABI-changing tail-call case
3216   // we've carefully laid out the parameters so that when sp is reset they'll be
3217   // in the correct location.
3218   if (IsTailCall && !IsSibCall) {
3219     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3220                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3221     InFlag = Chain.getValue(1);
3222   }
3223 
3224   std::vector<SDValue> Ops;
3225   Ops.push_back(Chain);
3226   Ops.push_back(Callee);
3227 
3228   if (IsTailCall) {
3229     // Each tail call may have to adjust the stack by a different amount, so
3230     // this information must travel along with the operation for eventual
3231     // consumption by emitEpilogue.
3232     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3233   }
3234 
3235   // Add argument registers to the end of the list so that they are known live
3236   // into the call.
3237   for (auto &RegToPass : RegsToPass)
3238     Ops.push_back(DAG.getRegister(RegToPass.first,
3239                                   RegToPass.second.getValueType()));
3240 
3241   // Add a register mask operand representing the call-preserved registers.
3242   const uint32_t *Mask;
3243   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3244   if (IsThisReturn) {
3245     // For 'this' returns, use the X0-preserving mask if applicable
3246     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3247     if (!Mask) {
3248       IsThisReturn = false;
3249       Mask = TRI->getCallPreservedMask(MF, CallConv);
3250     }
3251   } else
3252     Mask = TRI->getCallPreservedMask(MF, CallConv);
3253 
3254   assert(Mask && "Missing call preserved mask for calling convention");
3255   Ops.push_back(DAG.getRegisterMask(Mask));
3256 
3257   if (InFlag.getNode())
3258     Ops.push_back(InFlag);
3259 
3260   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3261 
3262   // If we're doing a tall call, use a TC_RETURN here rather than an
3263   // actual call instruction.
3264   if (IsTailCall) {
3265     MF.getFrameInfo().setHasTailCall();
3266     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3267   }
3268 
3269   // Returns a chain and a flag for retval copy to use.
3270   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3271   InFlag = Chain.getValue(1);
3272 
3273   uint64_t CalleePopBytes =
3274       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3275 
3276   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3277                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3278                              InFlag, DL);
3279   if (!Ins.empty())
3280     InFlag = Chain.getValue(1);
3281 
3282   // Handle result values, copying them out of physregs into vregs that we
3283   // return.
3284   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3285                          InVals, IsThisReturn,
3286                          IsThisReturn ? OutVals[0] : SDValue());
3287 }
3288 
3289 bool AArch64TargetLowering::CanLowerReturn(
3290     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3291     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3292   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3293                           ? RetCC_AArch64_WebKit_JS
3294                           : RetCC_AArch64_AAPCS;
3295   SmallVector<CCValAssign, 16> RVLocs;
3296   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3297   return CCInfo.CheckReturn(Outs, RetCC);
3298 }
3299 
3300 SDValue
3301 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3302                                    bool isVarArg,
3303                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3304                                    const SmallVectorImpl<SDValue> &OutVals,
3305                                    const SDLoc &DL, SelectionDAG &DAG) const {
3306   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3307                           ? RetCC_AArch64_WebKit_JS
3308                           : RetCC_AArch64_AAPCS;
3309   SmallVector<CCValAssign, 16> RVLocs;
3310   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3311                  *DAG.getContext());
3312   CCInfo.AnalyzeReturn(Outs, RetCC);
3313 
3314   // Copy the result values into the output registers.
3315   SDValue Flag;
3316   SmallVector<SDValue, 4> RetOps(1, Chain);
3317   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3318        ++i, ++realRVLocIdx) {
3319     CCValAssign &VA = RVLocs[i];
3320     assert(VA.isRegLoc() && "Can only return in registers!");
3321     SDValue Arg = OutVals[realRVLocIdx];
3322 
3323     switch (VA.getLocInfo()) {
3324     default:
3325       llvm_unreachable("Unknown loc info!");
3326     case CCValAssign::Full:
3327       if (Outs[i].ArgVT == MVT::i1) {
3328         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3329         // value. This is strictly redundant on Darwin (which uses "zeroext
3330         // i1"), but will be optimised out before ISel.
3331         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3332         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3333       }
3334       break;
3335     case CCValAssign::BCvt:
3336       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3337       break;
3338     }
3339 
3340     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3341     Flag = Chain.getValue(1);
3342     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3343   }
3344   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3345   const MCPhysReg *I =
3346       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3347   if (I) {
3348     for (; *I; ++I) {
3349       if (AArch64::GPR64RegClass.contains(*I))
3350         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3351       else if (AArch64::FPR64RegClass.contains(*I))
3352         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3353       else
3354         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3355     }
3356   }
3357 
3358   RetOps[0] = Chain; // Update chain.
3359 
3360   // Add the flag if we have it.
3361   if (Flag.getNode())
3362     RetOps.push_back(Flag);
3363 
3364   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3365 }
3366 
3367 //===----------------------------------------------------------------------===//
3368 //  Other Lowering Code
3369 //===----------------------------------------------------------------------===//
3370 
3371 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3372                                                   SelectionDAG &DAG) const {
3373   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3374   SDLoc DL(Op);
3375   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3376   const GlobalValue *GV = GN->getGlobal();
3377   unsigned char OpFlags =
3378       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3379 
3380   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3381          "unexpected offset in global node");
3382 
3383   // This also catched the large code model case for Darwin.
3384   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3385     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3386     // FIXME: Once remat is capable of dealing with instructions with register
3387     // operands, expand this into two nodes instead of using a wrapper node.
3388     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3389   }
3390 
3391   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3392     const unsigned char MO_NC = AArch64II::MO_NC;
3393     return DAG.getNode(
3394         AArch64ISD::WrapperLarge, DL, PtrVT,
3395         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3396         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3397         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3398         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3399   } else {
3400     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3401     // the only correct model on Darwin.
3402     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3403                                             OpFlags | AArch64II::MO_PAGE);
3404     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3405     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3406 
3407     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3408     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3409   }
3410 }
3411 
3412 /// \brief Convert a TLS address reference into the correct sequence of loads
3413 /// and calls to compute the variable's address (for Darwin, currently) and
3414 /// return an SDValue containing the final node.
3415 
3416 /// Darwin only has one TLS scheme which must be capable of dealing with the
3417 /// fully general situation, in the worst case. This means:
3418 ///     + "extern __thread" declaration.
3419 ///     + Defined in a possibly unknown dynamic library.
3420 ///
3421 /// The general system is that each __thread variable has a [3 x i64] descriptor
3422 /// which contains information used by the runtime to calculate the address. The
3423 /// only part of this the compiler needs to know about is the first xword, which
3424 /// contains a function pointer that must be called with the address of the
3425 /// entire descriptor in "x0".
3426 ///
3427 /// Since this descriptor may be in a different unit, in general even the
3428 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3429 /// is:
3430 ///     adrp x0, _var@TLVPPAGE
3431 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3432 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3433 ///                                      ; the function pointer
3434 ///     blr x1                           ; Uses descriptor address in x0
3435 ///     ; Address of _var is now in x0.
3436 ///
3437 /// If the address of _var's descriptor *is* known to the linker, then it can
3438 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3439 /// a slight efficiency gain.
3440 SDValue
3441 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3442                                                    SelectionDAG &DAG) const {
3443   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3444 
3445   SDLoc DL(Op);
3446   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3447   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3448 
3449   SDValue TLVPAddr =
3450       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3451   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3452 
3453   // The first entry in the descriptor is a function pointer that we must call
3454   // to obtain the address of the variable.
3455   SDValue Chain = DAG.getEntryNode();
3456   SDValue FuncTLVGet = DAG.getLoad(
3457       MVT::i64, DL, Chain, DescAddr,
3458       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3459       /* Alignment = */ 8,
3460       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3461           MachineMemOperand::MODereferenceable);
3462   Chain = FuncTLVGet.getValue(1);
3463 
3464   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3465   MFI.setAdjustsStack(true);
3466 
3467   // TLS calls preserve all registers except those that absolutely must be
3468   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3469   // silly).
3470   const uint32_t *Mask =
3471       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3472 
3473   // Finally, we can make the call. This is just a degenerate version of a
3474   // normal AArch64 call node: x0 takes the address of the descriptor, and
3475   // returns the address of the variable in this thread.
3476   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3477   Chain =
3478       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3479                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3480                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3481   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3482 }
3483 
3484 /// When accessing thread-local variables under either the general-dynamic or
3485 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3486 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3487 /// is a function pointer to carry out the resolution.
3488 ///
3489 /// The sequence is:
3490 ///    adrp  x0, :tlsdesc:var
3491 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3492 ///    add   x0, x0, #:tlsdesc_lo12:var
3493 ///    .tlsdesccall var
3494 ///    blr   x1
3495 ///    (TPIDR_EL0 offset now in x0)
3496 ///
3497 ///  The above sequence must be produced unscheduled, to enable the linker to
3498 ///  optimize/relax this sequence.
3499 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3500 ///  above sequence, and expanded really late in the compilation flow, to ensure
3501 ///  the sequence is produced as per above.
3502 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3503                                                       const SDLoc &DL,
3504                                                       SelectionDAG &DAG) const {
3505   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3506 
3507   SDValue Chain = DAG.getEntryNode();
3508   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3509 
3510   Chain =
3511       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3512   SDValue Glue = Chain.getValue(1);
3513 
3514   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3515 }
3516 
3517 SDValue
3518 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3519                                                 SelectionDAG &DAG) const {
3520   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3521   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3522          "ELF TLS only supported in small memory model");
3523   // Different choices can be made for the maximum size of the TLS area for a
3524   // module. For the small address model, the default TLS size is 16MiB and the
3525   // maximum TLS size is 4GiB.
3526   // FIXME: add -mtls-size command line option and make it control the 16MiB
3527   // vs. 4GiB code sequence generation.
3528   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3529 
3530   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3531 
3532   if (DAG.getTarget().Options.EmulatedTLS)
3533     return LowerToTLSEmulatedModel(GA, DAG);
3534 
3535   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3536     if (Model == TLSModel::LocalDynamic)
3537       Model = TLSModel::GeneralDynamic;
3538   }
3539 
3540   SDValue TPOff;
3541   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3542   SDLoc DL(Op);
3543   const GlobalValue *GV = GA->getGlobal();
3544 
3545   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3546 
3547   if (Model == TLSModel::LocalExec) {
3548     SDValue HiVar = DAG.getTargetGlobalAddress(
3549         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3550     SDValue LoVar = DAG.getTargetGlobalAddress(
3551         GV, DL, PtrVT, 0,
3552         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3553 
3554     SDValue TPWithOff_lo =
3555         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3556                                    HiVar,
3557                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3558                 0);
3559     SDValue TPWithOff =
3560         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3561                                    LoVar,
3562                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3563                 0);
3564     return TPWithOff;
3565   } else if (Model == TLSModel::InitialExec) {
3566     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3567     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3568   } else if (Model == TLSModel::LocalDynamic) {
3569     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3570     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3571     // the beginning of the module's TLS region, followed by a DTPREL offset
3572     // calculation.
3573 
3574     // These accesses will need deduplicating if there's more than one.
3575     AArch64FunctionInfo *MFI =
3576         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3577     MFI->incNumLocalDynamicTLSAccesses();
3578 
3579     // The call needs a relocation too for linker relaxation. It doesn't make
3580     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3581     // the address.
3582     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3583                                                   AArch64II::MO_TLS);
3584 
3585     // Now we can calculate the offset from TPIDR_EL0 to this module's
3586     // thread-local area.
3587     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3588 
3589     // Now use :dtprel_whatever: operations to calculate this variable's offset
3590     // in its thread-storage area.
3591     SDValue HiVar = DAG.getTargetGlobalAddress(
3592         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3593     SDValue LoVar = DAG.getTargetGlobalAddress(
3594         GV, DL, MVT::i64, 0,
3595         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3596 
3597     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3598                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3599                     0);
3600     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3601                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3602                     0);
3603   } else if (Model == TLSModel::GeneralDynamic) {
3604     // The call needs a relocation too for linker relaxation. It doesn't make
3605     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3606     // the address.
3607     SDValue SymAddr =
3608         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3609 
3610     // Finally we can make a call to calculate the offset from tpidr_el0.
3611     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3612   } else
3613     llvm_unreachable("Unsupported ELF TLS access model");
3614 
3615   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3616 }
3617 
3618 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3619                                                      SelectionDAG &DAG) const {
3620   if (Subtarget->isTargetDarwin())
3621     return LowerDarwinGlobalTLSAddress(Op, DAG);
3622   else if (Subtarget->isTargetELF())
3623     return LowerELFGlobalTLSAddress(Op, DAG);
3624 
3625   llvm_unreachable("Unexpected platform trying to use TLS");
3626 }
3627 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3628   SDValue Chain = Op.getOperand(0);
3629   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3630   SDValue LHS = Op.getOperand(2);
3631   SDValue RHS = Op.getOperand(3);
3632   SDValue Dest = Op.getOperand(4);
3633   SDLoc dl(Op);
3634 
3635   // Handle f128 first, since lowering it will result in comparing the return
3636   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3637   // is expecting to deal with.
3638   if (LHS.getValueType() == MVT::f128) {
3639     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3640 
3641     // If softenSetCCOperands returned a scalar, we need to compare the result
3642     // against zero to select between true and false values.
3643     if (!RHS.getNode()) {
3644       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3645       CC = ISD::SETNE;
3646     }
3647   }
3648 
3649   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3650   // instruction.
3651   unsigned Opc = LHS.getOpcode();
3652   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3653       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3654        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3655     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3656            "Unexpected condition code.");
3657     // Only lower legal XALUO ops.
3658     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3659       return SDValue();
3660 
3661     // The actual operation with overflow check.
3662     AArch64CC::CondCode OFCC;
3663     SDValue Value, Overflow;
3664     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3665 
3666     if (CC == ISD::SETNE)
3667       OFCC = getInvertedCondCode(OFCC);
3668     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3669 
3670     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3671                        Overflow);
3672   }
3673 
3674   if (LHS.getValueType().isInteger()) {
3675     assert((LHS.getValueType() == RHS.getValueType()) &&
3676            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3677 
3678     // If the RHS of the comparison is zero, we can potentially fold this
3679     // to a specialized branch.
3680     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3681     if (RHSC && RHSC->getZExtValue() == 0) {
3682       if (CC == ISD::SETEQ) {
3683         // See if we can use a TBZ to fold in an AND as well.
3684         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3685         // out of bounds, a late MI-layer pass rewrites branches.
3686         // 403.gcc is an example that hits this case.
3687         if (LHS.getOpcode() == ISD::AND &&
3688             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3689             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3690           SDValue Test = LHS.getOperand(0);
3691           uint64_t Mask = LHS.getConstantOperandVal(1);
3692           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3693                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3694                              Dest);
3695         }
3696 
3697         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3698       } else if (CC == ISD::SETNE) {
3699         // See if we can use a TBZ to fold in an AND as well.
3700         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3701         // out of bounds, a late MI-layer pass rewrites branches.
3702         // 403.gcc is an example that hits this case.
3703         if (LHS.getOpcode() == ISD::AND &&
3704             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3705             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3706           SDValue Test = LHS.getOperand(0);
3707           uint64_t Mask = LHS.getConstantOperandVal(1);
3708           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3709                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3710                              Dest);
3711         }
3712 
3713         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3714       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3715         // Don't combine AND since emitComparison converts the AND to an ANDS
3716         // (a.k.a. TST) and the test in the test bit and branch instruction
3717         // becomes redundant.  This would also increase register pressure.
3718         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3719         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3720                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3721       }
3722     }
3723     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3724         LHS.getOpcode() != ISD::AND) {
3725       // Don't combine AND since emitComparison converts the AND to an ANDS
3726       // (a.k.a. TST) and the test in the test bit and branch instruction
3727       // becomes redundant.  This would also increase register pressure.
3728       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3729       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3730                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3731     }
3732 
3733     SDValue CCVal;
3734     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3735     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3736                        Cmp);
3737   }
3738 
3739   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3740 
3741   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3742   // clean.  Some of them require two branches to implement.
3743   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3744   AArch64CC::CondCode CC1, CC2;
3745   changeFPCCToAArch64CC(CC, CC1, CC2);
3746   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3747   SDValue BR1 =
3748       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3749   if (CC2 != AArch64CC::AL) {
3750     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3751     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3752                        Cmp);
3753   }
3754 
3755   return BR1;
3756 }
3757 
3758 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3759                                               SelectionDAG &DAG) const {
3760   EVT VT = Op.getValueType();
3761   SDLoc DL(Op);
3762 
3763   SDValue In1 = Op.getOperand(0);
3764   SDValue In2 = Op.getOperand(1);
3765   EVT SrcVT = In2.getValueType();
3766 
3767   if (SrcVT.bitsLT(VT))
3768     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3769   else if (SrcVT.bitsGT(VT))
3770     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3771 
3772   EVT VecVT;
3773   EVT EltVT;
3774   uint64_t EltMask;
3775   SDValue VecVal1, VecVal2;
3776   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3777     EltVT = MVT::i32;
3778     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3779     EltMask = 0x80000000ULL;
3780 
3781     if (!VT.isVector()) {
3782       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3783                                           DAG.getUNDEF(VecVT), In1);
3784       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3785                                           DAG.getUNDEF(VecVT), In2);
3786     } else {
3787       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3788       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3789     }
3790   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3791     EltVT = MVT::i64;
3792     VecVT = MVT::v2i64;
3793 
3794     // We want to materialize a mask with the high bit set, but the AdvSIMD
3795     // immediate moves cannot materialize that in a single instruction for
3796     // 64-bit elements. Instead, materialize zero and then negate it.
3797     EltMask = 0;
3798 
3799     if (!VT.isVector()) {
3800       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3801                                           DAG.getUNDEF(VecVT), In1);
3802       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3803                                           DAG.getUNDEF(VecVT), In2);
3804     } else {
3805       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3806       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3807     }
3808   } else {
3809     llvm_unreachable("Invalid type for copysign!");
3810   }
3811 
3812   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3813 
3814   // If we couldn't materialize the mask above, then the mask vector will be
3815   // the zero vector, and we need to negate it here.
3816   if (VT == MVT::f64 || VT == MVT::v2f64) {
3817     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3818     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3819     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3820   }
3821 
3822   SDValue Sel =
3823       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3824 
3825   if (VT == MVT::f32)
3826     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3827   else if (VT == MVT::f64)
3828     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3829   else
3830     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3831 }
3832 
3833 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3834   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3835           Attribute::NoImplicitFloat))
3836     return SDValue();
3837 
3838   if (!Subtarget->hasNEON())
3839     return SDValue();
3840 
3841   // While there is no integer popcount instruction, it can
3842   // be more efficiently lowered to the following sequence that uses
3843   // AdvSIMD registers/instructions as long as the copies to/from
3844   // the AdvSIMD registers are cheap.
3845   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3846   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3847   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3848   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3849   SDValue Val = Op.getOperand(0);
3850   SDLoc DL(Op);
3851   EVT VT = Op.getValueType();
3852 
3853   if (VT == MVT::i32)
3854     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3855   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3856 
3857   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3858   SDValue UaddLV = DAG.getNode(
3859       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3860       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3861 
3862   if (VT == MVT::i64)
3863     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3864   return UaddLV;
3865 }
3866 
3867 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3868 
3869   if (Op.getValueType().isVector())
3870     return LowerVSETCC(Op, DAG);
3871 
3872   SDValue LHS = Op.getOperand(0);
3873   SDValue RHS = Op.getOperand(1);
3874   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3875   SDLoc dl(Op);
3876 
3877   // We chose ZeroOrOneBooleanContents, so use zero and one.
3878   EVT VT = Op.getValueType();
3879   SDValue TVal = DAG.getConstant(1, dl, VT);
3880   SDValue FVal = DAG.getConstant(0, dl, VT);
3881 
3882   // Handle f128 first, since one possible outcome is a normal integer
3883   // comparison which gets picked up by the next if statement.
3884   if (LHS.getValueType() == MVT::f128) {
3885     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3886 
3887     // If softenSetCCOperands returned a scalar, use it.
3888     if (!RHS.getNode()) {
3889       assert(LHS.getValueType() == Op.getValueType() &&
3890              "Unexpected setcc expansion!");
3891       return LHS;
3892     }
3893   }
3894 
3895   if (LHS.getValueType().isInteger()) {
3896     SDValue CCVal;
3897     SDValue Cmp =
3898         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3899 
3900     // Note that we inverted the condition above, so we reverse the order of
3901     // the true and false operands here.  This will allow the setcc to be
3902     // matched to a single CSINC instruction.
3903     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3904   }
3905 
3906   // Now we know we're dealing with FP values.
3907   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3908 
3909   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3910   // and do the comparison.
3911   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3912 
3913   AArch64CC::CondCode CC1, CC2;
3914   changeFPCCToAArch64CC(CC, CC1, CC2);
3915   if (CC2 == AArch64CC::AL) {
3916     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3917     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3918 
3919     // Note that we inverted the condition above, so we reverse the order of
3920     // the true and false operands here.  This will allow the setcc to be
3921     // matched to a single CSINC instruction.
3922     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3923   } else {
3924     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3925     // totally clean.  Some of them require two CSELs to implement.  As is in
3926     // this case, we emit the first CSEL and then emit a second using the output
3927     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3928 
3929     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3930     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3931     SDValue CS1 =
3932         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3933 
3934     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3935     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3936   }
3937 }
3938 
3939 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3940                                               SDValue RHS, SDValue TVal,
3941                                               SDValue FVal, const SDLoc &dl,
3942                                               SelectionDAG &DAG) const {
3943   // Handle f128 first, because it will result in a comparison of some RTLIB
3944   // call result against zero.
3945   if (LHS.getValueType() == MVT::f128) {
3946     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3947 
3948     // If softenSetCCOperands returned a scalar, we need to compare the result
3949     // against zero to select between true and false values.
3950     if (!RHS.getNode()) {
3951       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3952       CC = ISD::SETNE;
3953     }
3954   }
3955 
3956   // Also handle f16, for which we need to do a f32 comparison.
3957   if (LHS.getValueType() == MVT::f16) {
3958     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3959     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3960   }
3961 
3962   // Next, handle integers.
3963   if (LHS.getValueType().isInteger()) {
3964     assert((LHS.getValueType() == RHS.getValueType()) &&
3965            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3966 
3967     unsigned Opcode = AArch64ISD::CSEL;
3968 
3969     // If both the TVal and the FVal are constants, see if we can swap them in
3970     // order to for a CSINV or CSINC out of them.
3971     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3972     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3973 
3974     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3975       std::swap(TVal, FVal);
3976       std::swap(CTVal, CFVal);
3977       CC = ISD::getSetCCInverse(CC, true);
3978     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3979       std::swap(TVal, FVal);
3980       std::swap(CTVal, CFVal);
3981       CC = ISD::getSetCCInverse(CC, true);
3982     } else if (TVal.getOpcode() == ISD::XOR) {
3983       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3984       // with a CSINV rather than a CSEL.
3985       if (isAllOnesConstant(TVal.getOperand(1))) {
3986         std::swap(TVal, FVal);
3987         std::swap(CTVal, CFVal);
3988         CC = ISD::getSetCCInverse(CC, true);
3989       }
3990     } else if (TVal.getOpcode() == ISD::SUB) {
3991       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3992       // that we can match with a CSNEG rather than a CSEL.
3993       if (isNullConstant(TVal.getOperand(0))) {
3994         std::swap(TVal, FVal);
3995         std::swap(CTVal, CFVal);
3996         CC = ISD::getSetCCInverse(CC, true);
3997       }
3998     } else if (CTVal && CFVal) {
3999       const int64_t TrueVal = CTVal->getSExtValue();
4000       const int64_t FalseVal = CFVal->getSExtValue();
4001       bool Swap = false;
4002 
4003       // If both TVal and FVal are constants, see if FVal is the
4004       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4005       // instead of a CSEL in that case.
4006       if (TrueVal == ~FalseVal) {
4007         Opcode = AArch64ISD::CSINV;
4008       } else if (TrueVal == -FalseVal) {
4009         Opcode = AArch64ISD::CSNEG;
4010       } else if (TVal.getValueType() == MVT::i32) {
4011         // If our operands are only 32-bit wide, make sure we use 32-bit
4012         // arithmetic for the check whether we can use CSINC. This ensures that
4013         // the addition in the check will wrap around properly in case there is
4014         // an overflow (which would not be the case if we do the check with
4015         // 64-bit arithmetic).
4016         const uint32_t TrueVal32 = CTVal->getZExtValue();
4017         const uint32_t FalseVal32 = CFVal->getZExtValue();
4018 
4019         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4020           Opcode = AArch64ISD::CSINC;
4021 
4022           if (TrueVal32 > FalseVal32) {
4023             Swap = true;
4024           }
4025         }
4026         // 64-bit check whether we can use CSINC.
4027       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4028         Opcode = AArch64ISD::CSINC;
4029 
4030         if (TrueVal > FalseVal) {
4031           Swap = true;
4032         }
4033       }
4034 
4035       // Swap TVal and FVal if necessary.
4036       if (Swap) {
4037         std::swap(TVal, FVal);
4038         std::swap(CTVal, CFVal);
4039         CC = ISD::getSetCCInverse(CC, true);
4040       }
4041 
4042       if (Opcode != AArch64ISD::CSEL) {
4043         // Drop FVal since we can get its value by simply inverting/negating
4044         // TVal.
4045         FVal = TVal;
4046       }
4047     }
4048 
4049     // Avoid materializing a constant when possible by reusing a known value in
4050     // a register.  However, don't perform this optimization if the known value
4051     // is one, zero or negative one.  We can always materialize these values
4052     // using CSINC, CSEL and CSINV with wzr/xzr as the FVal, respectively.
4053     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4054     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4055         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4056       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4057       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4058       // "a != C ? x : a" to avoid materializing C.
4059       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4060         TVal = LHS;
4061       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4062         FVal = LHS;
4063     }
4064 
4065     SDValue CCVal;
4066     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4067 
4068     EVT VT = TVal.getValueType();
4069     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4070   }
4071 
4072   // Now we know we're dealing with FP values.
4073   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4074   assert(LHS.getValueType() == RHS.getValueType());
4075   EVT VT = TVal.getValueType();
4076   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4077 
4078   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4079   // clean.  Some of them require two CSELs to implement.
4080   AArch64CC::CondCode CC1, CC2;
4081   changeFPCCToAArch64CC(CC, CC1, CC2);
4082   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4083   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4084 
4085   // If we need a second CSEL, emit it, using the output of the first as the
4086   // RHS.  We're effectively OR'ing the two CC's together.
4087   if (CC2 != AArch64CC::AL) {
4088     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4089     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4090   }
4091 
4092   // Otherwise, return the output of the first CSEL.
4093   return CS1;
4094 }
4095 
4096 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4097                                               SelectionDAG &DAG) const {
4098   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4099   SDValue LHS = Op.getOperand(0);
4100   SDValue RHS = Op.getOperand(1);
4101   SDValue TVal = Op.getOperand(2);
4102   SDValue FVal = Op.getOperand(3);
4103   SDLoc DL(Op);
4104   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4105 }
4106 
4107 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4108                                            SelectionDAG &DAG) const {
4109   SDValue CCVal = Op->getOperand(0);
4110   SDValue TVal = Op->getOperand(1);
4111   SDValue FVal = Op->getOperand(2);
4112   SDLoc DL(Op);
4113 
4114   unsigned Opc = CCVal.getOpcode();
4115   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4116   // instruction.
4117   if (CCVal.getResNo() == 1 &&
4118       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4119        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4120     // Only lower legal XALUO ops.
4121     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4122       return SDValue();
4123 
4124     AArch64CC::CondCode OFCC;
4125     SDValue Value, Overflow;
4126     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4127     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4128 
4129     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4130                        CCVal, Overflow);
4131   }
4132 
4133   // Lower it the same way as we would lower a SELECT_CC node.
4134   ISD::CondCode CC;
4135   SDValue LHS, RHS;
4136   if (CCVal.getOpcode() == ISD::SETCC) {
4137     LHS = CCVal.getOperand(0);
4138     RHS = CCVal.getOperand(1);
4139     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4140   } else {
4141     LHS = CCVal;
4142     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4143     CC = ISD::SETNE;
4144   }
4145   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4146 }
4147 
4148 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4149                                               SelectionDAG &DAG) const {
4150   // Jump table entries as PC relative offsets. No additional tweaking
4151   // is necessary here. Just get the address of the jump table.
4152   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4153   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4154   SDLoc DL(Op);
4155 
4156   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4157       !Subtarget->isTargetMachO()) {
4158     const unsigned char MO_NC = AArch64II::MO_NC;
4159     return DAG.getNode(
4160         AArch64ISD::WrapperLarge, DL, PtrVT,
4161         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4162         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4163         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4164         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4165                                AArch64II::MO_G0 | MO_NC));
4166   }
4167 
4168   SDValue Hi =
4169       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4170   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4171                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4172   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4173   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4174 }
4175 
4176 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4177                                                  SelectionDAG &DAG) const {
4178   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4179   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4180   SDLoc DL(Op);
4181 
4182   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4183     // Use the GOT for the large code model on iOS.
4184     if (Subtarget->isTargetMachO()) {
4185       SDValue GotAddr = DAG.getTargetConstantPool(
4186           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4187           AArch64II::MO_GOT);
4188       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4189     }
4190 
4191     const unsigned char MO_NC = AArch64II::MO_NC;
4192     return DAG.getNode(
4193         AArch64ISD::WrapperLarge, DL, PtrVT,
4194         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4195                                   CP->getOffset(), AArch64II::MO_G3),
4196         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4197                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4198         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4199                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4200         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4201                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4202   } else {
4203     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4204     // ELF, the only valid one on Darwin.
4205     SDValue Hi =
4206         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4207                                   CP->getOffset(), AArch64II::MO_PAGE);
4208     SDValue Lo = DAG.getTargetConstantPool(
4209         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4210         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4211 
4212     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4213     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4214   }
4215 }
4216 
4217 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4218                                                SelectionDAG &DAG) const {
4219   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4220   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4221   SDLoc DL(Op);
4222   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4223       !Subtarget->isTargetMachO()) {
4224     const unsigned char MO_NC = AArch64II::MO_NC;
4225     return DAG.getNode(
4226         AArch64ISD::WrapperLarge, DL, PtrVT,
4227         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4228         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4229         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4230         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4231   } else {
4232     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4233     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4234                                                              AArch64II::MO_NC);
4235     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4236     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4237   }
4238 }
4239 
4240 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4241                                                  SelectionDAG &DAG) const {
4242   AArch64FunctionInfo *FuncInfo =
4243       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4244 
4245   SDLoc DL(Op);
4246   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4247                                  getPointerTy(DAG.getDataLayout()));
4248   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4249   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4250                       MachinePointerInfo(SV));
4251 }
4252 
4253 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4254                                                 SelectionDAG &DAG) const {
4255   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4256   // Standard, section B.3.
4257   MachineFunction &MF = DAG.getMachineFunction();
4258   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4259   auto PtrVT = getPointerTy(DAG.getDataLayout());
4260   SDLoc DL(Op);
4261 
4262   SDValue Chain = Op.getOperand(0);
4263   SDValue VAList = Op.getOperand(1);
4264   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4265   SmallVector<SDValue, 4> MemOps;
4266 
4267   // void *__stack at offset 0
4268   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4269   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4270                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4271 
4272   // void *__gr_top at offset 8
4273   int GPRSize = FuncInfo->getVarArgsGPRSize();
4274   if (GPRSize > 0) {
4275     SDValue GRTop, GRTopAddr;
4276 
4277     GRTopAddr =
4278         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4279 
4280     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4281     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4282                         DAG.getConstant(GPRSize, DL, PtrVT));
4283 
4284     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4285                                   MachinePointerInfo(SV, 8),
4286                                   /* Alignment = */ 8));
4287   }
4288 
4289   // void *__vr_top at offset 16
4290   int FPRSize = FuncInfo->getVarArgsFPRSize();
4291   if (FPRSize > 0) {
4292     SDValue VRTop, VRTopAddr;
4293     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4294                             DAG.getConstant(16, DL, PtrVT));
4295 
4296     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4297     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4298                         DAG.getConstant(FPRSize, DL, PtrVT));
4299 
4300     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4301                                   MachinePointerInfo(SV, 16),
4302                                   /* Alignment = */ 8));
4303   }
4304 
4305   // int __gr_offs at offset 24
4306   SDValue GROffsAddr =
4307       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4308   MemOps.push_back(DAG.getStore(
4309       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4310       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4311 
4312   // int __vr_offs at offset 28
4313   SDValue VROffsAddr =
4314       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4315   MemOps.push_back(DAG.getStore(
4316       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4317       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4318 
4319   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4320 }
4321 
4322 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4323                                             SelectionDAG &DAG) const {
4324   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4325                                      : LowerAAPCS_VASTART(Op, DAG);
4326 }
4327 
4328 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4329                                            SelectionDAG &DAG) const {
4330   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4331   // pointer.
4332   SDLoc DL(Op);
4333   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4334   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4335   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4336 
4337   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4338                        Op.getOperand(2),
4339                        DAG.getConstant(VaListSize, DL, MVT::i32),
4340                        8, false, false, false, MachinePointerInfo(DestSV),
4341                        MachinePointerInfo(SrcSV));
4342 }
4343 
4344 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4345   assert(Subtarget->isTargetDarwin() &&
4346          "automatic va_arg instruction only works on Darwin");
4347 
4348   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4349   EVT VT = Op.getValueType();
4350   SDLoc DL(Op);
4351   SDValue Chain = Op.getOperand(0);
4352   SDValue Addr = Op.getOperand(1);
4353   unsigned Align = Op.getConstantOperandVal(3);
4354   auto PtrVT = getPointerTy(DAG.getDataLayout());
4355 
4356   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4357   Chain = VAList.getValue(1);
4358 
4359   if (Align > 8) {
4360     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4361     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4362                          DAG.getConstant(Align - 1, DL, PtrVT));
4363     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4364                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4365   }
4366 
4367   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4368   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4369 
4370   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4371   // up to 64 bits.  At the very least, we have to increase the striding of the
4372   // vaargs list to match this, and for FP values we need to introduce
4373   // FP_ROUND nodes as well.
4374   if (VT.isInteger() && !VT.isVector())
4375     ArgSize = 8;
4376   bool NeedFPTrunc = false;
4377   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4378     ArgSize = 8;
4379     NeedFPTrunc = true;
4380   }
4381 
4382   // Increment the pointer, VAList, to the next vaarg
4383   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4384                                DAG.getConstant(ArgSize, DL, PtrVT));
4385   // Store the incremented VAList to the legalized pointer
4386   SDValue APStore =
4387       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4388 
4389   // Load the actual argument out of the pointer VAList
4390   if (NeedFPTrunc) {
4391     // Load the value as an f64.
4392     SDValue WideFP =
4393         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4394     // Round the value down to an f32.
4395     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4396                                    DAG.getIntPtrConstant(1, DL));
4397     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4398     // Merge the rounded value with the chain output of the load.
4399     return DAG.getMergeValues(Ops, DL);
4400   }
4401 
4402   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4403 }
4404 
4405 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4406                                               SelectionDAG &DAG) const {
4407   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4408   MFI.setFrameAddressIsTaken(true);
4409 
4410   EVT VT = Op.getValueType();
4411   SDLoc DL(Op);
4412   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4413   SDValue FrameAddr =
4414       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4415   while (Depth--)
4416     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4417                             MachinePointerInfo());
4418   return FrameAddr;
4419 }
4420 
4421 // FIXME? Maybe this could be a TableGen attribute on some registers and
4422 // this table could be generated automatically from RegInfo.
4423 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4424                                                   SelectionDAG &DAG) const {
4425   unsigned Reg = StringSwitch<unsigned>(RegName)
4426                        .Case("sp", AArch64::SP)
4427                        .Default(0);
4428   if (Reg)
4429     return Reg;
4430   report_fatal_error(Twine("Invalid register name \""
4431                               + StringRef(RegName)  + "\"."));
4432 }
4433 
4434 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4435                                                SelectionDAG &DAG) const {
4436   MachineFunction &MF = DAG.getMachineFunction();
4437   MachineFrameInfo &MFI = MF.getFrameInfo();
4438   MFI.setReturnAddressIsTaken(true);
4439 
4440   EVT VT = Op.getValueType();
4441   SDLoc DL(Op);
4442   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4443   if (Depth) {
4444     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4445     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4446     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4447                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4448                        MachinePointerInfo());
4449   }
4450 
4451   // Return LR, which contains the return address. Mark it an implicit live-in.
4452   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4453   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4454 }
4455 
4456 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4457 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4458 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4459                                                     SelectionDAG &DAG) const {
4460   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4461   EVT VT = Op.getValueType();
4462   unsigned VTBits = VT.getSizeInBits();
4463   SDLoc dl(Op);
4464   SDValue ShOpLo = Op.getOperand(0);
4465   SDValue ShOpHi = Op.getOperand(1);
4466   SDValue ShAmt = Op.getOperand(2);
4467   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4468 
4469   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4470 
4471   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4472                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4473   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4474 
4475   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4476   // is "undef". We wanted 0, so CSEL it directly.
4477   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4478                                ISD::SETEQ, dl, DAG);
4479   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4480   HiBitsForLo =
4481       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4482                   HiBitsForLo, CCVal, Cmp);
4483 
4484   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4485                                    DAG.getConstant(VTBits, dl, MVT::i64));
4486 
4487   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4488   SDValue LoForNormalShift =
4489       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4490 
4491   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4492                        dl, DAG);
4493   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4494   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4495   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4496                            LoForNormalShift, CCVal, Cmp);
4497 
4498   // AArch64 shifts larger than the register width are wrapped rather than
4499   // clamped, so we can't just emit "hi >> x".
4500   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4501   SDValue HiForBigShift =
4502       Opc == ISD::SRA
4503           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4504                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4505           : DAG.getConstant(0, dl, VT);
4506   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4507                            HiForNormalShift, CCVal, Cmp);
4508 
4509   SDValue Ops[2] = { Lo, Hi };
4510   return DAG.getMergeValues(Ops, dl);
4511 }
4512 
4513 
4514 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4515 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4516 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4517                                                    SelectionDAG &DAG) const {
4518   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4519   EVT VT = Op.getValueType();
4520   unsigned VTBits = VT.getSizeInBits();
4521   SDLoc dl(Op);
4522   SDValue ShOpLo = Op.getOperand(0);
4523   SDValue ShOpHi = Op.getOperand(1);
4524   SDValue ShAmt = Op.getOperand(2);
4525 
4526   assert(Op.getOpcode() == ISD::SHL_PARTS);
4527   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4528                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4529   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4530 
4531   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4532   // is "undef". We wanted 0, so CSEL it directly.
4533   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4534                                ISD::SETEQ, dl, DAG);
4535   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4536   LoBitsForHi =
4537       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4538                   LoBitsForHi, CCVal, Cmp);
4539 
4540   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4541                                    DAG.getConstant(VTBits, dl, MVT::i64));
4542   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4543   SDValue HiForNormalShift =
4544       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4545 
4546   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4547 
4548   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4549                        dl, DAG);
4550   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4551   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4552                            HiForNormalShift, CCVal, Cmp);
4553 
4554   // AArch64 shifts of larger than register sizes are wrapped rather than
4555   // clamped, so we can't just emit "lo << a" if a is too big.
4556   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4557   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4558   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4559                            LoForNormalShift, CCVal, Cmp);
4560 
4561   SDValue Ops[2] = { Lo, Hi };
4562   return DAG.getMergeValues(Ops, dl);
4563 }
4564 
4565 bool AArch64TargetLowering::isOffsetFoldingLegal(
4566     const GlobalAddressSDNode *GA) const {
4567   // The AArch64 target doesn't support folding offsets into global addresses.
4568   return false;
4569 }
4570 
4571 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4572   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4573   // FIXME: We should be able to handle f128 as well with a clever lowering.
4574   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4575     return true;
4576 
4577   if (VT == MVT::f64)
4578     return AArch64_AM::getFP64Imm(Imm) != -1;
4579   else if (VT == MVT::f32)
4580     return AArch64_AM::getFP32Imm(Imm) != -1;
4581   return false;
4582 }
4583 
4584 //===----------------------------------------------------------------------===//
4585 //                          AArch64 Optimization Hooks
4586 //===----------------------------------------------------------------------===//
4587 
4588 /// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4589 /// or the reciprocal square root.
4590 static SDValue getEstimate(const AArch64Subtarget &ST,
4591   const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4592   const SDValue &Operand, unsigned &ExtraSteps) {
4593   if (!ST.hasNEON())
4594     return SDValue();
4595 
4596   EVT VT = Operand.getValueType();
4597   if (VT != MVT::f64 && VT != MVT::v1f64 && VT != MVT::v2f64 &&
4598       VT != MVT::f32 && VT != MVT::v1f32 &&
4599       VT != MVT::v2f32 && VT != MVT::v4f32 &&
4600       (!ST.hasFullFP16() ||
4601        (VT != MVT::f16 && VT != MVT::v4f16 && VT != MVT::v8f16)))
4602     return SDValue();
4603 
4604   std::string RecipOp;
4605   RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4606   RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4607   RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4608 
4609   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4610   if (!Recips.isEnabled(RecipOp))
4611     return SDValue();
4612 
4613   ExtraSteps = Recips.getRefinementSteps(RecipOp);
4614   return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4615 }
4616 
4617 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4618   DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4619   return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4620 }
4621 
4622 SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4623   DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4624   UseOneConst = true;
4625   return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4626 }
4627 
4628 //===----------------------------------------------------------------------===//
4629 //                          AArch64 Inline Assembly Support
4630 //===----------------------------------------------------------------------===//
4631 
4632 // Table of Constraints
4633 // TODO: This is the current set of constraints supported by ARM for the
4634 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4635 //
4636 // r - A general register
4637 // w - An FP/SIMD register of some size in the range v0-v31
4638 // x - An FP/SIMD register of some size in the range v0-v15
4639 // I - Constant that can be used with an ADD instruction
4640 // J - Constant that can be used with a SUB instruction
4641 // K - Constant that can be used with a 32-bit logical instruction
4642 // L - Constant that can be used with a 64-bit logical instruction
4643 // M - Constant that can be used as a 32-bit MOV immediate
4644 // N - Constant that can be used as a 64-bit MOV immediate
4645 // Q - A memory reference with base register and no offset
4646 // S - A symbolic address
4647 // Y - Floating point constant zero
4648 // Z - Integer constant zero
4649 //
4650 //   Note that general register operands will be output using their 64-bit x
4651 // register name, whatever the size of the variable, unless the asm operand
4652 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4653 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4654 // %q modifier.
4655 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4656   // At this point, we have to lower this constraint to something else, so we
4657   // lower it to an "r" or "w". However, by doing this we will force the result
4658   // to be in register, while the X constraint is much more permissive.
4659   //
4660   // Although we are correct (we are free to emit anything, without
4661   // constraints), we might break use cases that would expect us to be more
4662   // efficient and emit something else.
4663   if (!Subtarget->hasFPARMv8())
4664     return "r";
4665 
4666   if (ConstraintVT.isFloatingPoint())
4667     return "w";
4668 
4669   if (ConstraintVT.isVector() &&
4670      (ConstraintVT.getSizeInBits() == 64 ||
4671       ConstraintVT.getSizeInBits() == 128))
4672     return "w";
4673 
4674   return "r";
4675 }
4676 
4677 /// getConstraintType - Given a constraint letter, return the type of
4678 /// constraint it is for this target.
4679 AArch64TargetLowering::ConstraintType
4680 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4681   if (Constraint.size() == 1) {
4682     switch (Constraint[0]) {
4683     default:
4684       break;
4685     case 'z':
4686       return C_Other;
4687     case 'x':
4688     case 'w':
4689       return C_RegisterClass;
4690     // An address with a single base register. Due to the way we
4691     // currently handle addresses it is the same as 'r'.
4692     case 'Q':
4693       return C_Memory;
4694     }
4695   }
4696   return TargetLowering::getConstraintType(Constraint);
4697 }
4698 
4699 /// Examine constraint type and operand type and determine a weight value.
4700 /// This object must already have been set up with the operand type
4701 /// and the current alternative constraint selected.
4702 TargetLowering::ConstraintWeight
4703 AArch64TargetLowering::getSingleConstraintMatchWeight(
4704     AsmOperandInfo &info, const char *constraint) const {
4705   ConstraintWeight weight = CW_Invalid;
4706   Value *CallOperandVal = info.CallOperandVal;
4707   // If we don't have a value, we can't do a match,
4708   // but allow it at the lowest weight.
4709   if (!CallOperandVal)
4710     return CW_Default;
4711   Type *type = CallOperandVal->getType();
4712   // Look at the constraint type.
4713   switch (*constraint) {
4714   default:
4715     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4716     break;
4717   case 'x':
4718   case 'w':
4719     if (type->isFloatingPointTy() || type->isVectorTy())
4720       weight = CW_Register;
4721     break;
4722   case 'z':
4723     weight = CW_Constant;
4724     break;
4725   }
4726   return weight;
4727 }
4728 
4729 std::pair<unsigned, const TargetRegisterClass *>
4730 AArch64TargetLowering::getRegForInlineAsmConstraint(
4731     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4732   if (Constraint.size() == 1) {
4733     switch (Constraint[0]) {
4734     case 'r':
4735       if (VT.getSizeInBits() == 64)
4736         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4737       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4738     case 'w':
4739       if (VT.getSizeInBits() == 32)
4740         return std::make_pair(0U, &AArch64::FPR32RegClass);
4741       if (VT.getSizeInBits() == 64)
4742         return std::make_pair(0U, &AArch64::FPR64RegClass);
4743       if (VT.getSizeInBits() == 128)
4744         return std::make_pair(0U, &AArch64::FPR128RegClass);
4745       break;
4746     // The instructions that this constraint is designed for can
4747     // only take 128-bit registers so just use that regclass.
4748     case 'x':
4749       if (VT.getSizeInBits() == 128)
4750         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4751       break;
4752     }
4753   }
4754   if (StringRef("{cc}").equals_lower(Constraint))
4755     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4756 
4757   // Use the default implementation in TargetLowering to convert the register
4758   // constraint into a member of a register class.
4759   std::pair<unsigned, const TargetRegisterClass *> Res;
4760   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4761 
4762   // Not found as a standard register?
4763   if (!Res.second) {
4764     unsigned Size = Constraint.size();
4765     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4766         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4767       int RegNo;
4768       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4769       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4770         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4771         // By default we'll emit v0-v31 for this unless there's a modifier where
4772         // we'll emit the correct register as well.
4773         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4774           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4775           Res.second = &AArch64::FPR64RegClass;
4776         } else {
4777           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4778           Res.second = &AArch64::FPR128RegClass;
4779         }
4780       }
4781     }
4782   }
4783 
4784   return Res;
4785 }
4786 
4787 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4788 /// vector.  If it is invalid, don't add anything to Ops.
4789 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4790     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4791     SelectionDAG &DAG) const {
4792   SDValue Result;
4793 
4794   // Currently only support length 1 constraints.
4795   if (Constraint.length() != 1)
4796     return;
4797 
4798   char ConstraintLetter = Constraint[0];
4799   switch (ConstraintLetter) {
4800   default:
4801     break;
4802 
4803   // This set of constraints deal with valid constants for various instructions.
4804   // Validate and return a target constant for them if we can.
4805   case 'z': {
4806     // 'z' maps to xzr or wzr so it needs an input of 0.
4807     if (!isNullConstant(Op))
4808       return;
4809 
4810     if (Op.getValueType() == MVT::i64)
4811       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4812     else
4813       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4814     break;
4815   }
4816 
4817   case 'I':
4818   case 'J':
4819   case 'K':
4820   case 'L':
4821   case 'M':
4822   case 'N':
4823     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4824     if (!C)
4825       return;
4826 
4827     // Grab the value and do some validation.
4828     uint64_t CVal = C->getZExtValue();
4829     switch (ConstraintLetter) {
4830     // The I constraint applies only to simple ADD or SUB immediate operands:
4831     // i.e. 0 to 4095 with optional shift by 12
4832     // The J constraint applies only to ADD or SUB immediates that would be
4833     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4834     // instruction [or vice versa], in other words -1 to -4095 with optional
4835     // left shift by 12.
4836     case 'I':
4837       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4838         break;
4839       return;
4840     case 'J': {
4841       uint64_t NVal = -C->getSExtValue();
4842       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4843         CVal = C->getSExtValue();
4844         break;
4845       }
4846       return;
4847     }
4848     // The K and L constraints apply *only* to logical immediates, including
4849     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4850     // been removed and MOV should be used). So these constraints have to
4851     // distinguish between bit patterns that are valid 32-bit or 64-bit
4852     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4853     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4854     // versa.
4855     case 'K':
4856       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4857         break;
4858       return;
4859     case 'L':
4860       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4861         break;
4862       return;
4863     // The M and N constraints are a superset of K and L respectively, for use
4864     // with the MOV (immediate) alias. As well as the logical immediates they
4865     // also match 32 or 64-bit immediates that can be loaded either using a
4866     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4867     // (M) or 64-bit 0x1234000000000000 (N) etc.
4868     // As a note some of this code is liberally stolen from the asm parser.
4869     case 'M': {
4870       if (!isUInt<32>(CVal))
4871         return;
4872       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4873         break;
4874       if ((CVal & 0xFFFF) == CVal)
4875         break;
4876       if ((CVal & 0xFFFF0000ULL) == CVal)
4877         break;
4878       uint64_t NCVal = ~(uint32_t)CVal;
4879       if ((NCVal & 0xFFFFULL) == NCVal)
4880         break;
4881       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4882         break;
4883       return;
4884     }
4885     case 'N': {
4886       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4887         break;
4888       if ((CVal & 0xFFFFULL) == CVal)
4889         break;
4890       if ((CVal & 0xFFFF0000ULL) == CVal)
4891         break;
4892       if ((CVal & 0xFFFF00000000ULL) == CVal)
4893         break;
4894       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4895         break;
4896       uint64_t NCVal = ~CVal;
4897       if ((NCVal & 0xFFFFULL) == NCVal)
4898         break;
4899       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4900         break;
4901       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4902         break;
4903       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4904         break;
4905       return;
4906     }
4907     default:
4908       return;
4909     }
4910 
4911     // All assembler immediates are 64-bit integers.
4912     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4913     break;
4914   }
4915 
4916   if (Result.getNode()) {
4917     Ops.push_back(Result);
4918     return;
4919   }
4920 
4921   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4922 }
4923 
4924 //===----------------------------------------------------------------------===//
4925 //                     AArch64 Advanced SIMD Support
4926 //===----------------------------------------------------------------------===//
4927 
4928 /// WidenVector - Given a value in the V64 register class, produce the
4929 /// equivalent value in the V128 register class.
4930 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4931   EVT VT = V64Reg.getValueType();
4932   unsigned NarrowSize = VT.getVectorNumElements();
4933   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4934   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4935   SDLoc DL(V64Reg);
4936 
4937   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4938                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4939 }
4940 
4941 /// getExtFactor - Determine the adjustment factor for the position when
4942 /// generating an "extract from vector registers" instruction.
4943 static unsigned getExtFactor(SDValue &V) {
4944   EVT EltType = V.getValueType().getVectorElementType();
4945   return EltType.getSizeInBits() / 8;
4946 }
4947 
4948 /// NarrowVector - Given a value in the V128 register class, produce the
4949 /// equivalent value in the V64 register class.
4950 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4951   EVT VT = V128Reg.getValueType();
4952   unsigned WideSize = VT.getVectorNumElements();
4953   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4954   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4955   SDLoc DL(V128Reg);
4956 
4957   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4958 }
4959 
4960 // Gather data to see if the operation can be modelled as a
4961 // shuffle in combination with VEXTs.
4962 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4963                                                   SelectionDAG &DAG) const {
4964   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4965   SDLoc dl(Op);
4966   EVT VT = Op.getValueType();
4967   unsigned NumElts = VT.getVectorNumElements();
4968 
4969   struct ShuffleSourceInfo {
4970     SDValue Vec;
4971     unsigned MinElt;
4972     unsigned MaxElt;
4973 
4974     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4975     // be compatible with the shuffle we intend to construct. As a result
4976     // ShuffleVec will be some sliding window into the original Vec.
4977     SDValue ShuffleVec;
4978 
4979     // Code should guarantee that element i in Vec starts at element "WindowBase
4980     // + i * WindowScale in ShuffleVec".
4981     int WindowBase;
4982     int WindowScale;
4983 
4984     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4985     ShuffleSourceInfo(SDValue Vec)
4986         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4987           WindowScale(1) {}
4988   };
4989 
4990   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4991   // node.
4992   SmallVector<ShuffleSourceInfo, 2> Sources;
4993   for (unsigned i = 0; i < NumElts; ++i) {
4994     SDValue V = Op.getOperand(i);
4995     if (V.isUndef())
4996       continue;
4997     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4998              !isa<ConstantSDNode>(V.getOperand(1))) {
4999       // A shuffle can only come from building a vector from various
5000       // elements of other vectors, provided their indices are constant.
5001       return SDValue();
5002     }
5003 
5004     // Add this element source to the list if it's not already there.
5005     SDValue SourceVec = V.getOperand(0);
5006     auto Source = find(Sources, SourceVec);
5007     if (Source == Sources.end())
5008       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5009 
5010     // Update the minimum and maximum lane number seen.
5011     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5012     Source->MinElt = std::min(Source->MinElt, EltNo);
5013     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5014   }
5015 
5016   // Currently only do something sane when at most two source vectors
5017   // are involved.
5018   if (Sources.size() > 2)
5019     return SDValue();
5020 
5021   // Find out the smallest element size among result and two sources, and use
5022   // it as element size to build the shuffle_vector.
5023   EVT SmallestEltTy = VT.getVectorElementType();
5024   for (auto &Source : Sources) {
5025     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5026     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5027       SmallestEltTy = SrcEltTy;
5028     }
5029   }
5030   unsigned ResMultiplier =
5031       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5032   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5033   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5034 
5035   // If the source vector is too wide or too narrow, we may nevertheless be able
5036   // to construct a compatible shuffle either by concatenating it with UNDEF or
5037   // extracting a suitable range of elements.
5038   for (auto &Src : Sources) {
5039     EVT SrcVT = Src.ShuffleVec.getValueType();
5040 
5041     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5042       continue;
5043 
5044     // This stage of the search produces a source with the same element type as
5045     // the original, but with a total width matching the BUILD_VECTOR output.
5046     EVT EltVT = SrcVT.getVectorElementType();
5047     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5048     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5049 
5050     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5051       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5052       // We can pad out the smaller vector for free, so if it's part of a
5053       // shuffle...
5054       Src.ShuffleVec =
5055           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5056                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5057       continue;
5058     }
5059 
5060     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5061 
5062     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5063       // Span too large for a VEXT to cope
5064       return SDValue();
5065     }
5066 
5067     if (Src.MinElt >= NumSrcElts) {
5068       // The extraction can just take the second half
5069       Src.ShuffleVec =
5070           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5071                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5072       Src.WindowBase = -NumSrcElts;
5073     } else if (Src.MaxElt < NumSrcElts) {
5074       // The extraction can just take the first half
5075       Src.ShuffleVec =
5076           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5077                       DAG.getConstant(0, dl, MVT::i64));
5078     } else {
5079       // An actual VEXT is needed
5080       SDValue VEXTSrc1 =
5081           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5082                       DAG.getConstant(0, dl, MVT::i64));
5083       SDValue VEXTSrc2 =
5084           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5085                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5086       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5087 
5088       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5089                                    VEXTSrc2,
5090                                    DAG.getConstant(Imm, dl, MVT::i32));
5091       Src.WindowBase = -Src.MinElt;
5092     }
5093   }
5094 
5095   // Another possible incompatibility occurs from the vector element types. We
5096   // can fix this by bitcasting the source vectors to the same type we intend
5097   // for the shuffle.
5098   for (auto &Src : Sources) {
5099     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5100     if (SrcEltTy == SmallestEltTy)
5101       continue;
5102     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5103     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5104     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5105     Src.WindowBase *= Src.WindowScale;
5106   }
5107 
5108   // Final sanity check before we try to actually produce a shuffle.
5109   DEBUG(
5110     for (auto Src : Sources)
5111       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5112   );
5113 
5114   // The stars all align, our next step is to produce the mask for the shuffle.
5115   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5116   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5117   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5118     SDValue Entry = Op.getOperand(i);
5119     if (Entry.isUndef())
5120       continue;
5121 
5122     auto Src = find(Sources, Entry.getOperand(0));
5123     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5124 
5125     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5126     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5127     // segment.
5128     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5129     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5130                                VT.getVectorElementType().getSizeInBits());
5131     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5132 
5133     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5134     // starting at the appropriate offset.
5135     int *LaneMask = &Mask[i * ResMultiplier];
5136 
5137     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5138     ExtractBase += NumElts * (Src - Sources.begin());
5139     for (int j = 0; j < LanesDefined; ++j)
5140       LaneMask[j] = ExtractBase + j;
5141   }
5142 
5143   // Final check before we try to produce nonsense...
5144   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5145     return SDValue();
5146 
5147   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5148   for (unsigned i = 0; i < Sources.size(); ++i)
5149     ShuffleOps[i] = Sources[i].ShuffleVec;
5150 
5151   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5152                                          ShuffleOps[1], Mask);
5153   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5154 }
5155 
5156 // check if an EXT instruction can handle the shuffle mask when the
5157 // vector sources of the shuffle are the same.
5158 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5159   unsigned NumElts = VT.getVectorNumElements();
5160 
5161   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5162   if (M[0] < 0)
5163     return false;
5164 
5165   Imm = M[0];
5166 
5167   // If this is a VEXT shuffle, the immediate value is the index of the first
5168   // element.  The other shuffle indices must be the successive elements after
5169   // the first one.
5170   unsigned ExpectedElt = Imm;
5171   for (unsigned i = 1; i < NumElts; ++i) {
5172     // Increment the expected index.  If it wraps around, just follow it
5173     // back to index zero and keep going.
5174     ++ExpectedElt;
5175     if (ExpectedElt == NumElts)
5176       ExpectedElt = 0;
5177 
5178     if (M[i] < 0)
5179       continue; // ignore UNDEF indices
5180     if (ExpectedElt != static_cast<unsigned>(M[i]))
5181       return false;
5182   }
5183 
5184   return true;
5185 }
5186 
5187 // check if an EXT instruction can handle the shuffle mask when the
5188 // vector sources of the shuffle are different.
5189 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5190                       unsigned &Imm) {
5191   // Look for the first non-undef element.
5192   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5193 
5194   // Benefit form APInt to handle overflow when calculating expected element.
5195   unsigned NumElts = VT.getVectorNumElements();
5196   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5197   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5198   // The following shuffle indices must be the successive elements after the
5199   // first real element.
5200   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5201       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5202   if (FirstWrongElt != M.end())
5203     return false;
5204 
5205   // The index of an EXT is the first element if it is not UNDEF.
5206   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5207   // value of the first element.  E.g.
5208   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5209   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5210   // ExpectedElt is the last mask index plus 1.
5211   Imm = ExpectedElt.getZExtValue();
5212 
5213   // There are two difference cases requiring to reverse input vectors.
5214   // For example, for vector <4 x i32> we have the following cases,
5215   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5216   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5217   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5218   // to reverse two input vectors.
5219   if (Imm < NumElts)
5220     ReverseEXT = true;
5221   else
5222     Imm -= NumElts;
5223 
5224   return true;
5225 }
5226 
5227 /// isREVMask - Check if a vector shuffle corresponds to a REV
5228 /// instruction with the specified blocksize.  (The order of the elements
5229 /// within each block of the vector is reversed.)
5230 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5231   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5232          "Only possible block sizes for REV are: 16, 32, 64");
5233 
5234   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5235   if (EltSz == 64)
5236     return false;
5237 
5238   unsigned NumElts = VT.getVectorNumElements();
5239   unsigned BlockElts = M[0] + 1;
5240   // If the first shuffle index is UNDEF, be optimistic.
5241   if (M[0] < 0)
5242     BlockElts = BlockSize / EltSz;
5243 
5244   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5245     return false;
5246 
5247   for (unsigned i = 0; i < NumElts; ++i) {
5248     if (M[i] < 0)
5249       continue; // ignore UNDEF indices
5250     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5251       return false;
5252   }
5253 
5254   return true;
5255 }
5256 
5257 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5258   unsigned NumElts = VT.getVectorNumElements();
5259   WhichResult = (M[0] == 0 ? 0 : 1);
5260   unsigned Idx = WhichResult * NumElts / 2;
5261   for (unsigned i = 0; i != NumElts; i += 2) {
5262     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5263         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5264       return false;
5265     Idx += 1;
5266   }
5267 
5268   return true;
5269 }
5270 
5271 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5272   unsigned NumElts = VT.getVectorNumElements();
5273   WhichResult = (M[0] == 0 ? 0 : 1);
5274   for (unsigned i = 0; i != NumElts; ++i) {
5275     if (M[i] < 0)
5276       continue; // ignore UNDEF indices
5277     if ((unsigned)M[i] != 2 * i + WhichResult)
5278       return false;
5279   }
5280 
5281   return true;
5282 }
5283 
5284 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5285   unsigned NumElts = VT.getVectorNumElements();
5286   WhichResult = (M[0] == 0 ? 0 : 1);
5287   for (unsigned i = 0; i < NumElts; i += 2) {
5288     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5289         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5290       return false;
5291   }
5292   return true;
5293 }
5294 
5295 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5296 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5297 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5298 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5299   unsigned NumElts = VT.getVectorNumElements();
5300   WhichResult = (M[0] == 0 ? 0 : 1);
5301   unsigned Idx = WhichResult * NumElts / 2;
5302   for (unsigned i = 0; i != NumElts; i += 2) {
5303     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5304         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5305       return false;
5306     Idx += 1;
5307   }
5308 
5309   return true;
5310 }
5311 
5312 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5313 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5314 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5315 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5316   unsigned Half = VT.getVectorNumElements() / 2;
5317   WhichResult = (M[0] == 0 ? 0 : 1);
5318   for (unsigned j = 0; j != 2; ++j) {
5319     unsigned Idx = WhichResult;
5320     for (unsigned i = 0; i != Half; ++i) {
5321       int MIdx = M[i + j * Half];
5322       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5323         return false;
5324       Idx += 2;
5325     }
5326   }
5327 
5328   return true;
5329 }
5330 
5331 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5332 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5333 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5334 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5335   unsigned NumElts = VT.getVectorNumElements();
5336   WhichResult = (M[0] == 0 ? 0 : 1);
5337   for (unsigned i = 0; i < NumElts; i += 2) {
5338     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5339         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5340       return false;
5341   }
5342   return true;
5343 }
5344 
5345 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5346                       bool &DstIsLeft, int &Anomaly) {
5347   if (M.size() != static_cast<size_t>(NumInputElements))
5348     return false;
5349 
5350   int NumLHSMatch = 0, NumRHSMatch = 0;
5351   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5352 
5353   for (int i = 0; i < NumInputElements; ++i) {
5354     if (M[i] == -1) {
5355       ++NumLHSMatch;
5356       ++NumRHSMatch;
5357       continue;
5358     }
5359 
5360     if (M[i] == i)
5361       ++NumLHSMatch;
5362     else
5363       LastLHSMismatch = i;
5364 
5365     if (M[i] == i + NumInputElements)
5366       ++NumRHSMatch;
5367     else
5368       LastRHSMismatch = i;
5369   }
5370 
5371   if (NumLHSMatch == NumInputElements - 1) {
5372     DstIsLeft = true;
5373     Anomaly = LastLHSMismatch;
5374     return true;
5375   } else if (NumRHSMatch == NumInputElements - 1) {
5376     DstIsLeft = false;
5377     Anomaly = LastRHSMismatch;
5378     return true;
5379   }
5380 
5381   return false;
5382 }
5383 
5384 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5385   if (VT.getSizeInBits() != 128)
5386     return false;
5387 
5388   unsigned NumElts = VT.getVectorNumElements();
5389 
5390   for (int I = 0, E = NumElts / 2; I != E; I++) {
5391     if (Mask[I] != I)
5392       return false;
5393   }
5394 
5395   int Offset = NumElts / 2;
5396   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5397     if (Mask[I] != I + SplitLHS * Offset)
5398       return false;
5399   }
5400 
5401   return true;
5402 }
5403 
5404 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5405   SDLoc DL(Op);
5406   EVT VT = Op.getValueType();
5407   SDValue V0 = Op.getOperand(0);
5408   SDValue V1 = Op.getOperand(1);
5409   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5410 
5411   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5412       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5413     return SDValue();
5414 
5415   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5416 
5417   if (!isConcatMask(Mask, VT, SplitV0))
5418     return SDValue();
5419 
5420   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5421                                 VT.getVectorNumElements() / 2);
5422   if (SplitV0) {
5423     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5424                      DAG.getConstant(0, DL, MVT::i64));
5425   }
5426   if (V1.getValueType().getSizeInBits() == 128) {
5427     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5428                      DAG.getConstant(0, DL, MVT::i64));
5429   }
5430   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5431 }
5432 
5433 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5434 /// the specified operations to build the shuffle.
5435 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5436                                       SDValue RHS, SelectionDAG &DAG,
5437                                       const SDLoc &dl) {
5438   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5439   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5440   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5441 
5442   enum {
5443     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5444     OP_VREV,
5445     OP_VDUP0,
5446     OP_VDUP1,
5447     OP_VDUP2,
5448     OP_VDUP3,
5449     OP_VEXT1,
5450     OP_VEXT2,
5451     OP_VEXT3,
5452     OP_VUZPL, // VUZP, left result
5453     OP_VUZPR, // VUZP, right result
5454     OP_VZIPL, // VZIP, left result
5455     OP_VZIPR, // VZIP, right result
5456     OP_VTRNL, // VTRN, left result
5457     OP_VTRNR  // VTRN, right result
5458   };
5459 
5460   if (OpNum == OP_COPY) {
5461     if (LHSID == (1 * 9 + 2) * 9 + 3)
5462       return LHS;
5463     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5464     return RHS;
5465   }
5466 
5467   SDValue OpLHS, OpRHS;
5468   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5469   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5470   EVT VT = OpLHS.getValueType();
5471 
5472   switch (OpNum) {
5473   default:
5474     llvm_unreachable("Unknown shuffle opcode!");
5475   case OP_VREV:
5476     // VREV divides the vector in half and swaps within the half.
5477     if (VT.getVectorElementType() == MVT::i32 ||
5478         VT.getVectorElementType() == MVT::f32)
5479       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5480     // vrev <4 x i16> -> REV32
5481     if (VT.getVectorElementType() == MVT::i16 ||
5482         VT.getVectorElementType() == MVT::f16)
5483       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5484     // vrev <4 x i8> -> REV16
5485     assert(VT.getVectorElementType() == MVT::i8);
5486     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5487   case OP_VDUP0:
5488   case OP_VDUP1:
5489   case OP_VDUP2:
5490   case OP_VDUP3: {
5491     EVT EltTy = VT.getVectorElementType();
5492     unsigned Opcode;
5493     if (EltTy == MVT::i8)
5494       Opcode = AArch64ISD::DUPLANE8;
5495     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5496       Opcode = AArch64ISD::DUPLANE16;
5497     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5498       Opcode = AArch64ISD::DUPLANE32;
5499     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5500       Opcode = AArch64ISD::DUPLANE64;
5501     else
5502       llvm_unreachable("Invalid vector element type?");
5503 
5504     if (VT.getSizeInBits() == 64)
5505       OpLHS = WidenVector(OpLHS, DAG);
5506     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5507     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5508   }
5509   case OP_VEXT1:
5510   case OP_VEXT2:
5511   case OP_VEXT3: {
5512     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5513     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5514                        DAG.getConstant(Imm, dl, MVT::i32));
5515   }
5516   case OP_VUZPL:
5517     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5518                        OpRHS);
5519   case OP_VUZPR:
5520     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5521                        OpRHS);
5522   case OP_VZIPL:
5523     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5524                        OpRHS);
5525   case OP_VZIPR:
5526     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5527                        OpRHS);
5528   case OP_VTRNL:
5529     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5530                        OpRHS);
5531   case OP_VTRNR:
5532     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5533                        OpRHS);
5534   }
5535 }
5536 
5537 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5538                            SelectionDAG &DAG) {
5539   // Check to see if we can use the TBL instruction.
5540   SDValue V1 = Op.getOperand(0);
5541   SDValue V2 = Op.getOperand(1);
5542   SDLoc DL(Op);
5543 
5544   EVT EltVT = Op.getValueType().getVectorElementType();
5545   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5546 
5547   SmallVector<SDValue, 8> TBLMask;
5548   for (int Val : ShuffleMask) {
5549     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5550       unsigned Offset = Byte + Val * BytesPerElt;
5551       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5552     }
5553   }
5554 
5555   MVT IndexVT = MVT::v8i8;
5556   unsigned IndexLen = 8;
5557   if (Op.getValueType().getSizeInBits() == 128) {
5558     IndexVT = MVT::v16i8;
5559     IndexLen = 16;
5560   }
5561 
5562   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5563   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5564 
5565   SDValue Shuffle;
5566   if (V2.getNode()->isUndef()) {
5567     if (IndexLen == 8)
5568       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5569     Shuffle = DAG.getNode(
5570         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5571         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5572         DAG.getBuildVector(IndexVT, DL,
5573                            makeArrayRef(TBLMask.data(), IndexLen)));
5574   } else {
5575     if (IndexLen == 8) {
5576       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5577       Shuffle = DAG.getNode(
5578           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5579           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5580           DAG.getBuildVector(IndexVT, DL,
5581                              makeArrayRef(TBLMask.data(), IndexLen)));
5582     } else {
5583       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5584       // cannot currently represent the register constraints on the input
5585       // table registers.
5586       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5587       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5588       //                   IndexLen));
5589       Shuffle = DAG.getNode(
5590           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5591           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5592           V2Cst, DAG.getBuildVector(IndexVT, DL,
5593                                     makeArrayRef(TBLMask.data(), IndexLen)));
5594     }
5595   }
5596   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5597 }
5598 
5599 static unsigned getDUPLANEOp(EVT EltType) {
5600   if (EltType == MVT::i8)
5601     return AArch64ISD::DUPLANE8;
5602   if (EltType == MVT::i16 || EltType == MVT::f16)
5603     return AArch64ISD::DUPLANE16;
5604   if (EltType == MVT::i32 || EltType == MVT::f32)
5605     return AArch64ISD::DUPLANE32;
5606   if (EltType == MVT::i64 || EltType == MVT::f64)
5607     return AArch64ISD::DUPLANE64;
5608 
5609   llvm_unreachable("Invalid vector element type?");
5610 }
5611 
5612 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5613                                                    SelectionDAG &DAG) const {
5614   SDLoc dl(Op);
5615   EVT VT = Op.getValueType();
5616 
5617   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5618 
5619   // Convert shuffles that are directly supported on NEON to target-specific
5620   // DAG nodes, instead of keeping them as shuffles and matching them again
5621   // during code selection.  This is more efficient and avoids the possibility
5622   // of inconsistencies between legalization and selection.
5623   ArrayRef<int> ShuffleMask = SVN->getMask();
5624 
5625   SDValue V1 = Op.getOperand(0);
5626   SDValue V2 = Op.getOperand(1);
5627 
5628   if (SVN->isSplat()) {
5629     int Lane = SVN->getSplatIndex();
5630     // If this is undef splat, generate it via "just" vdup, if possible.
5631     if (Lane == -1)
5632       Lane = 0;
5633 
5634     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5635       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5636                          V1.getOperand(0));
5637     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5638     // constant. If so, we can just reference the lane's definition directly.
5639     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5640         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5641       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5642 
5643     // Otherwise, duplicate from the lane of the input vector.
5644     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5645 
5646     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5647     // to make a vector of the same size as this SHUFFLE. We can ignore the
5648     // extract entirely, and canonicalise the concat using WidenVector.
5649     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5650       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5651       V1 = V1.getOperand(0);
5652     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5653       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5654       Lane -= Idx * VT.getVectorNumElements() / 2;
5655       V1 = WidenVector(V1.getOperand(Idx), DAG);
5656     } else if (VT.getSizeInBits() == 64)
5657       V1 = WidenVector(V1, DAG);
5658 
5659     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5660   }
5661 
5662   if (isREVMask(ShuffleMask, VT, 64))
5663     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5664   if (isREVMask(ShuffleMask, VT, 32))
5665     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5666   if (isREVMask(ShuffleMask, VT, 16))
5667     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5668 
5669   bool ReverseEXT = false;
5670   unsigned Imm;
5671   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5672     if (ReverseEXT)
5673       std::swap(V1, V2);
5674     Imm *= getExtFactor(V1);
5675     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5676                        DAG.getConstant(Imm, dl, MVT::i32));
5677   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5678     Imm *= getExtFactor(V1);
5679     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5680                        DAG.getConstant(Imm, dl, MVT::i32));
5681   }
5682 
5683   unsigned WhichResult;
5684   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5685     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5686     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5687   }
5688   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5689     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5690     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5691   }
5692   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5693     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5694     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5695   }
5696 
5697   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5698     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5699     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5700   }
5701   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5702     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5703     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5704   }
5705   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5706     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5707     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5708   }
5709 
5710   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5711     return Concat;
5712 
5713   bool DstIsLeft;
5714   int Anomaly;
5715   int NumInputElements = V1.getValueType().getVectorNumElements();
5716   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5717     SDValue DstVec = DstIsLeft ? V1 : V2;
5718     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5719 
5720     SDValue SrcVec = V1;
5721     int SrcLane = ShuffleMask[Anomaly];
5722     if (SrcLane >= NumInputElements) {
5723       SrcVec = V2;
5724       SrcLane -= VT.getVectorNumElements();
5725     }
5726     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5727 
5728     EVT ScalarVT = VT.getVectorElementType();
5729 
5730     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5731       ScalarVT = MVT::i32;
5732 
5733     return DAG.getNode(
5734         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5735         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5736         DstLaneV);
5737   }
5738 
5739   // If the shuffle is not directly supported and it has 4 elements, use
5740   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5741   unsigned NumElts = VT.getVectorNumElements();
5742   if (NumElts == 4) {
5743     unsigned PFIndexes[4];
5744     for (unsigned i = 0; i != 4; ++i) {
5745       if (ShuffleMask[i] < 0)
5746         PFIndexes[i] = 8;
5747       else
5748         PFIndexes[i] = ShuffleMask[i];
5749     }
5750 
5751     // Compute the index in the perfect shuffle table.
5752     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5753                             PFIndexes[2] * 9 + PFIndexes[3];
5754     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5755     unsigned Cost = (PFEntry >> 30);
5756 
5757     if (Cost <= 4)
5758       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5759   }
5760 
5761   return GenerateTBL(Op, ShuffleMask, DAG);
5762 }
5763 
5764 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5765                                APInt &UndefBits) {
5766   EVT VT = BVN->getValueType(0);
5767   APInt SplatBits, SplatUndef;
5768   unsigned SplatBitSize;
5769   bool HasAnyUndefs;
5770   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5771     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5772 
5773     for (unsigned i = 0; i < NumSplats; ++i) {
5774       CnstBits <<= SplatBitSize;
5775       UndefBits <<= SplatBitSize;
5776       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5777       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5778     }
5779 
5780     return true;
5781   }
5782 
5783   return false;
5784 }
5785 
5786 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5787                                               SelectionDAG &DAG) const {
5788   BuildVectorSDNode *BVN =
5789       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5790   SDValue LHS = Op.getOperand(0);
5791   SDLoc dl(Op);
5792   EVT VT = Op.getValueType();
5793 
5794   if (!BVN)
5795     return Op;
5796 
5797   APInt CnstBits(VT.getSizeInBits(), 0);
5798   APInt UndefBits(VT.getSizeInBits(), 0);
5799   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5800     // We only have BIC vector immediate instruction, which is and-not.
5801     CnstBits = ~CnstBits;
5802 
5803     // We make use of a little bit of goto ickiness in order to avoid having to
5804     // duplicate the immediate matching logic for the undef toggled case.
5805     bool SecondTry = false;
5806   AttemptModImm:
5807 
5808     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5809       CnstBits = CnstBits.zextOrTrunc(64);
5810       uint64_t CnstVal = CnstBits.getZExtValue();
5811 
5812       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5813         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5814         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType2(CnstVal)) {
5822         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5823         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5831         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5832         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5833         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5834                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5835                                   DAG.getConstant(16, dl, MVT::i32));
5836         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5837       }
5838 
5839       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5840         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5841         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5842         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5843                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5844                                   DAG.getConstant(24, dl, MVT::i32));
5845         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5846       }
5847 
5848       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5849         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5850         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5851         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5852                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5853                                   DAG.getConstant(0, dl, MVT::i32));
5854         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5855       }
5856 
5857       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5858         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5859         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5860         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5861                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5862                                   DAG.getConstant(8, dl, MVT::i32));
5863         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5864       }
5865     }
5866 
5867     if (SecondTry)
5868       goto FailedModImm;
5869     SecondTry = true;
5870     CnstBits = ~UndefBits;
5871     goto AttemptModImm;
5872   }
5873 
5874 // We can always fall back to a non-immediate AND.
5875 FailedModImm:
5876   return Op;
5877 }
5878 
5879 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5880 // consists of only the same constant int value, returned in reference arg
5881 // ConstVal
5882 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5883                                      uint64_t &ConstVal) {
5884   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5885   if (!Bvec)
5886     return false;
5887   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5888   if (!FirstElt)
5889     return false;
5890   EVT VT = Bvec->getValueType(0);
5891   unsigned NumElts = VT.getVectorNumElements();
5892   for (unsigned i = 1; i < NumElts; ++i)
5893     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5894       return false;
5895   ConstVal = FirstElt->getZExtValue();
5896   return true;
5897 }
5898 
5899 static unsigned getIntrinsicID(const SDNode *N) {
5900   unsigned Opcode = N->getOpcode();
5901   switch (Opcode) {
5902   default:
5903     return Intrinsic::not_intrinsic;
5904   case ISD::INTRINSIC_WO_CHAIN: {
5905     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5906     if (IID < Intrinsic::num_intrinsics)
5907       return IID;
5908     return Intrinsic::not_intrinsic;
5909   }
5910   }
5911 }
5912 
5913 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5914 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5915 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5916 // Also, logical shift right -> sri, with the same structure.
5917 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5918   EVT VT = N->getValueType(0);
5919 
5920   if (!VT.isVector())
5921     return SDValue();
5922 
5923   SDLoc DL(N);
5924 
5925   // Is the first op an AND?
5926   const SDValue And = N->getOperand(0);
5927   if (And.getOpcode() != ISD::AND)
5928     return SDValue();
5929 
5930   // Is the second op an shl or lshr?
5931   SDValue Shift = N->getOperand(1);
5932   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5933   // or AArch64ISD::VLSHR vector, #shift
5934   unsigned ShiftOpc = Shift.getOpcode();
5935   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5936     return SDValue();
5937   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5938 
5939   // Is the shift amount constant?
5940   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5941   if (!C2node)
5942     return SDValue();
5943 
5944   // Is the and mask vector all constant?
5945   uint64_t C1;
5946   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5947     return SDValue();
5948 
5949   // Is C1 == ~C2, taking into account how much one can shift elements of a
5950   // particular size?
5951   uint64_t C2 = C2node->getZExtValue();
5952   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5953   if (C2 > ElemSizeInBits)
5954     return SDValue();
5955   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5956   if ((C1 & ElemMask) != (~C2 & ElemMask))
5957     return SDValue();
5958 
5959   SDValue X = And.getOperand(0);
5960   SDValue Y = Shift.getOperand(0);
5961 
5962   unsigned Intrin =
5963       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5964   SDValue ResultSLI =
5965       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5966                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5967                   Shift.getOperand(1));
5968 
5969   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5970   DEBUG(N->dump(&DAG));
5971   DEBUG(dbgs() << "into: \n");
5972   DEBUG(ResultSLI->dump(&DAG));
5973 
5974   ++NumShiftInserts;
5975   return ResultSLI;
5976 }
5977 
5978 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5979                                              SelectionDAG &DAG) const {
5980   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5981   if (EnableAArch64SlrGeneration) {
5982     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
5983       return Res;
5984   }
5985 
5986   BuildVectorSDNode *BVN =
5987       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5988   SDValue LHS = Op.getOperand(1);
5989   SDLoc dl(Op);
5990   EVT VT = Op.getValueType();
5991 
5992   // OR commutes, so try swapping the operands.
5993   if (!BVN) {
5994     LHS = Op.getOperand(0);
5995     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5996   }
5997   if (!BVN)
5998     return Op;
5999 
6000   APInt CnstBits(VT.getSizeInBits(), 0);
6001   APInt UndefBits(VT.getSizeInBits(), 0);
6002   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6003     // We make use of a little bit of goto ickiness in order to avoid having to
6004     // duplicate the immediate matching logic for the undef toggled case.
6005     bool SecondTry = false;
6006   AttemptModImm:
6007 
6008     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6009       CnstBits = CnstBits.zextOrTrunc(64);
6010       uint64_t CnstVal = CnstBits.getZExtValue();
6011 
6012       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6013         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6014         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType2(CnstVal)) {
6022         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6023         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6031         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6032         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6033         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6034                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6035                                   DAG.getConstant(16, dl, MVT::i32));
6036         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6037       }
6038 
6039       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6040         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6041         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6042         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6043                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6044                                   DAG.getConstant(24, dl, MVT::i32));
6045         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6046       }
6047 
6048       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6049         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6050         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6051         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6052                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6053                                   DAG.getConstant(0, dl, MVT::i32));
6054         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6055       }
6056 
6057       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6058         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6059         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6060         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6061                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6062                                   DAG.getConstant(8, dl, MVT::i32));
6063         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6064       }
6065     }
6066 
6067     if (SecondTry)
6068       goto FailedModImm;
6069     SecondTry = true;
6070     CnstBits = UndefBits;
6071     goto AttemptModImm;
6072   }
6073 
6074 // We can always fall back to a non-immediate OR.
6075 FailedModImm:
6076   return Op;
6077 }
6078 
6079 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6080 // be truncated to fit element width.
6081 static SDValue NormalizeBuildVector(SDValue Op,
6082                                     SelectionDAG &DAG) {
6083   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6084   SDLoc dl(Op);
6085   EVT VT = Op.getValueType();
6086   EVT EltTy= VT.getVectorElementType();
6087 
6088   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6089     return Op;
6090 
6091   SmallVector<SDValue, 16> Ops;
6092   for (SDValue Lane : Op->ops()) {
6093     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6094       APInt LowBits(EltTy.getSizeInBits(),
6095                     CstLane->getZExtValue());
6096       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6097     }
6098     Ops.push_back(Lane);
6099   }
6100   return DAG.getBuildVector(VT, dl, Ops);
6101 }
6102 
6103 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6104                                                  SelectionDAG &DAG) const {
6105   SDLoc dl(Op);
6106   EVT VT = Op.getValueType();
6107   Op = NormalizeBuildVector(Op, DAG);
6108   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6109 
6110   APInt CnstBits(VT.getSizeInBits(), 0);
6111   APInt UndefBits(VT.getSizeInBits(), 0);
6112   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6113     // We make use of a little bit of goto ickiness in order to avoid having to
6114     // duplicate the immediate matching logic for the undef toggled case.
6115     bool SecondTry = false;
6116   AttemptModImm:
6117 
6118     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6119       CnstBits = CnstBits.zextOrTrunc(64);
6120       uint64_t CnstVal = CnstBits.getZExtValue();
6121 
6122       // Certain magic vector constants (used to express things like NOT
6123       // and NEG) are passed through unmodified.  This allows codegen patterns
6124       // for these operations to match.  Special-purpose patterns will lower
6125       // these immediates to MOVIs if it proves necessary.
6126       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6127         return Op;
6128 
6129       // The many faces of MOVI...
6130       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6131         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6132         if (VT.getSizeInBits() == 128) {
6133           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6134                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6135           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6136         }
6137 
6138         // Support the V64 version via subregister insertion.
6139         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6140                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6141         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6142       }
6143 
6144       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6145         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6146         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType2(CnstVal)) {
6154         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6155         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType3(CnstVal)) {
6163         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6164         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6165         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6166                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6167                                   DAG.getConstant(16, dl, MVT::i32));
6168         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6169       }
6170 
6171       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6172         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6173         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6174         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6175                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6176                                   DAG.getConstant(24, dl, MVT::i32));
6177         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6178       }
6179 
6180       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6181         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6182         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6183         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6184                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6185                                   DAG.getConstant(0, dl, MVT::i32));
6186         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6187       }
6188 
6189       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6190         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6191         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6192         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6193                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6194                                   DAG.getConstant(8, dl, MVT::i32));
6195         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6196       }
6197 
6198       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6199         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6200         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6201         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6202                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6203                                   DAG.getConstant(264, dl, MVT::i32));
6204         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6205       }
6206 
6207       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6208         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6209         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6210         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6211                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6212                                   DAG.getConstant(272, dl, MVT::i32));
6213         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6214       }
6215 
6216       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6217         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6218         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6219         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6220                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6221         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6222       }
6223 
6224       // The few faces of FMOV...
6225       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6226         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6227         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6228         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6229                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6230         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6231       }
6232 
6233       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6234           VT.getSizeInBits() == 128) {
6235         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6236         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6237                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6238         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6239       }
6240 
6241       // The many faces of MVNI...
6242       CnstVal = ~CnstVal;
6243       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6244         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6245         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType2(CnstVal)) {
6253         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6254         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
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::isAdvSIMDModImmType3(CnstVal)) {
6262         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6263         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6264         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6265                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6266                                   DAG.getConstant(16, dl, MVT::i32));
6267         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6268       }
6269 
6270       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6271         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6272         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6273         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6274                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6275                                   DAG.getConstant(24, dl, MVT::i32));
6276         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6277       }
6278 
6279       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6280         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6281         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6282         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6283                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6284                                   DAG.getConstant(0, dl, MVT::i32));
6285         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6286       }
6287 
6288       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6289         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6290         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6291         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6292                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6293                                   DAG.getConstant(8, dl, MVT::i32));
6294         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6295       }
6296 
6297       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6298         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6299         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6300         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6301                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6302                                   DAG.getConstant(264, dl, MVT::i32));
6303         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6304       }
6305 
6306       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6307         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6308         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6309         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6310                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6311                                   DAG.getConstant(272, dl, MVT::i32));
6312         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6313       }
6314     }
6315 
6316     if (SecondTry)
6317       goto FailedModImm;
6318     SecondTry = true;
6319     CnstBits = UndefBits;
6320     goto AttemptModImm;
6321   }
6322 FailedModImm:
6323 
6324   // Scan through the operands to find some interesting properties we can
6325   // exploit:
6326   //   1) If only one value is used, we can use a DUP, or
6327   //   2) if only the low element is not undef, we can just insert that, or
6328   //   3) if only one constant value is used (w/ some non-constant lanes),
6329   //      we can splat the constant value into the whole vector then fill
6330   //      in the non-constant lanes.
6331   //   4) FIXME: If different constant values are used, but we can intelligently
6332   //             select the values we'll be overwriting for the non-constant
6333   //             lanes such that we can directly materialize the vector
6334   //             some other way (MOVI, e.g.), we can be sneaky.
6335   unsigned NumElts = VT.getVectorNumElements();
6336   bool isOnlyLowElement = true;
6337   bool usesOnlyOneValue = true;
6338   bool usesOnlyOneConstantValue = true;
6339   bool isConstant = true;
6340   unsigned NumConstantLanes = 0;
6341   SDValue Value;
6342   SDValue ConstantValue;
6343   for (unsigned i = 0; i < NumElts; ++i) {
6344     SDValue V = Op.getOperand(i);
6345     if (V.isUndef())
6346       continue;
6347     if (i > 0)
6348       isOnlyLowElement = false;
6349     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6350       isConstant = false;
6351 
6352     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6353       ++NumConstantLanes;
6354       if (!ConstantValue.getNode())
6355         ConstantValue = V;
6356       else if (ConstantValue != V)
6357         usesOnlyOneConstantValue = false;
6358     }
6359 
6360     if (!Value.getNode())
6361       Value = V;
6362     else if (V != Value)
6363       usesOnlyOneValue = false;
6364   }
6365 
6366   if (!Value.getNode())
6367     return DAG.getUNDEF(VT);
6368 
6369   if (isOnlyLowElement)
6370     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6371 
6372   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6373   // i32 and try again.
6374   if (usesOnlyOneValue) {
6375     if (!isConstant) {
6376       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6377           Value.getValueType() != VT)
6378         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6379 
6380       // This is actually a DUPLANExx operation, which keeps everything vectory.
6381 
6382       // DUPLANE works on 128-bit vectors, widen it if necessary.
6383       SDValue Lane = Value.getOperand(1);
6384       Value = Value.getOperand(0);
6385       if (Value.getValueType().getSizeInBits() == 64)
6386         Value = WidenVector(Value, DAG);
6387 
6388       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6389       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6390     }
6391 
6392     if (VT.getVectorElementType().isFloatingPoint()) {
6393       SmallVector<SDValue, 8> Ops;
6394       EVT EltTy = VT.getVectorElementType();
6395       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6396               "Unsupported floating-point vector type");
6397       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6398       for (unsigned i = 0; i < NumElts; ++i)
6399         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6400       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6401       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6402       Val = LowerBUILD_VECTOR(Val, DAG);
6403       if (Val.getNode())
6404         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6405     }
6406   }
6407 
6408   // If there was only one constant value used and for more than one lane,
6409   // start by splatting that value, then replace the non-constant lanes. This
6410   // is better than the default, which will perform a separate initialization
6411   // for each lane.
6412   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6413     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6414     // Now insert the non-constant lanes.
6415     for (unsigned i = 0; i < NumElts; ++i) {
6416       SDValue V = Op.getOperand(i);
6417       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6418       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6419         // Note that type legalization likely mucked about with the VT of the
6420         // source operand, so we may have to convert it here before inserting.
6421         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6422       }
6423     }
6424     return Val;
6425   }
6426 
6427   // If all elements are constants and the case above didn't get hit, fall back
6428   // to the default expansion, which will generate a load from the constant
6429   // pool.
6430   if (isConstant)
6431     return SDValue();
6432 
6433   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6434   if (NumElts >= 4) {
6435     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6436       return shuffle;
6437   }
6438 
6439   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6440   // know the default expansion would otherwise fall back on something even
6441   // worse. For a vector with one or two non-undef values, that's
6442   // scalar_to_vector for the elements followed by a shuffle (provided the
6443   // shuffle is valid for the target) and materialization element by element
6444   // on the stack followed by a load for everything else.
6445   if (!isConstant && !usesOnlyOneValue) {
6446     SDValue Vec = DAG.getUNDEF(VT);
6447     SDValue Op0 = Op.getOperand(0);
6448     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6449     unsigned i = 0;
6450     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6451     // a) Avoid a RMW dependency on the full vector register, and
6452     // b) Allow the register coalescer to fold away the copy if the
6453     //    value is already in an S or D register.
6454     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6455     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6456     if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6457         (ElemSize == 32 || ElemSize == 64)) {
6458       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6459       MachineSDNode *N =
6460           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6461                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6462       Vec = SDValue(N, 0);
6463       ++i;
6464     }
6465     for (; i < NumElts; ++i) {
6466       SDValue V = Op.getOperand(i);
6467       if (V.isUndef())
6468         continue;
6469       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6470       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6471     }
6472     return Vec;
6473   }
6474 
6475   // Just use the default expansion. We failed to find a better alternative.
6476   return SDValue();
6477 }
6478 
6479 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6480                                                       SelectionDAG &DAG) const {
6481   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6482 
6483   // Check for non-constant or out of range lane.
6484   EVT VT = Op.getOperand(0).getValueType();
6485   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6486   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6487     return SDValue();
6488 
6489 
6490   // Insertion/extraction are legal for V128 types.
6491   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6492       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6493       VT == MVT::v8f16)
6494     return Op;
6495 
6496   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6497       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6498     return SDValue();
6499 
6500   // For V64 types, we perform insertion by expanding the value
6501   // to a V128 type and perform the insertion on that.
6502   SDLoc DL(Op);
6503   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6504   EVT WideTy = WideVec.getValueType();
6505 
6506   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6507                              Op.getOperand(1), Op.getOperand(2));
6508   // Re-narrow the resultant vector.
6509   return NarrowVector(Node, DAG);
6510 }
6511 
6512 SDValue
6513 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6514                                                SelectionDAG &DAG) const {
6515   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6516 
6517   // Check for non-constant or out of range lane.
6518   EVT VT = Op.getOperand(0).getValueType();
6519   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6520   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6521     return SDValue();
6522 
6523 
6524   // Insertion/extraction are legal for V128 types.
6525   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6526       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6527       VT == MVT::v8f16)
6528     return Op;
6529 
6530   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6531       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6532     return SDValue();
6533 
6534   // For V64 types, we perform extraction by expanding the value
6535   // to a V128 type and perform the extraction on that.
6536   SDLoc DL(Op);
6537   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6538   EVT WideTy = WideVec.getValueType();
6539 
6540   EVT ExtrTy = WideTy.getVectorElementType();
6541   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6542     ExtrTy = MVT::i32;
6543 
6544   // For extractions, we just return the result directly.
6545   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6546                      Op.getOperand(1));
6547 }
6548 
6549 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6550                                                       SelectionDAG &DAG) const {
6551   EVT VT = Op.getOperand(0).getValueType();
6552   SDLoc dl(Op);
6553   // Just in case...
6554   if (!VT.isVector())
6555     return SDValue();
6556 
6557   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6558   if (!Cst)
6559     return SDValue();
6560   unsigned Val = Cst->getZExtValue();
6561 
6562   unsigned Size = Op.getValueType().getSizeInBits();
6563 
6564   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6565   if (Val == 0)
6566     return Op;
6567 
6568   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6569   // that directly.
6570   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6571     return Op;
6572 
6573   return SDValue();
6574 }
6575 
6576 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6577                                                EVT VT) const {
6578   if (VT.getVectorNumElements() == 4 &&
6579       (VT.is128BitVector() || VT.is64BitVector())) {
6580     unsigned PFIndexes[4];
6581     for (unsigned i = 0; i != 4; ++i) {
6582       if (M[i] < 0)
6583         PFIndexes[i] = 8;
6584       else
6585         PFIndexes[i] = M[i];
6586     }
6587 
6588     // Compute the index in the perfect shuffle table.
6589     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6590                             PFIndexes[2] * 9 + PFIndexes[3];
6591     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6592     unsigned Cost = (PFEntry >> 30);
6593 
6594     if (Cost <= 4)
6595       return true;
6596   }
6597 
6598   bool DummyBool;
6599   int DummyInt;
6600   unsigned DummyUnsigned;
6601 
6602   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6603           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6604           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6605           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6606           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6607           isZIPMask(M, VT, DummyUnsigned) ||
6608           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6609           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6610           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6611           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6612           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6613 }
6614 
6615 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6616 /// operand of a vector shift operation, where all the elements of the
6617 /// build_vector must have the same constant integer value.
6618 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6619   // Ignore bit_converts.
6620   while (Op.getOpcode() == ISD::BITCAST)
6621     Op = Op.getOperand(0);
6622   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6623   APInt SplatBits, SplatUndef;
6624   unsigned SplatBitSize;
6625   bool HasAnyUndefs;
6626   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6627                                     HasAnyUndefs, ElementBits) ||
6628       SplatBitSize > ElementBits)
6629     return false;
6630   Cnt = SplatBits.getSExtValue();
6631   return true;
6632 }
6633 
6634 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6635 /// operand of a vector shift left operation.  That value must be in the range:
6636 ///   0 <= Value < ElementBits for a left shift; or
6637 ///   0 <= Value <= ElementBits for a long left shift.
6638 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6639   assert(VT.isVector() && "vector shift count is not a vector type");
6640   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6641   if (!getVShiftImm(Op, ElementBits, Cnt))
6642     return false;
6643   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6644 }
6645 
6646 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6647 /// operand of a vector shift right operation. The value must be in the range:
6648 ///   1 <= Value <= ElementBits for a right shift; or
6649 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6650   assert(VT.isVector() && "vector shift count is not a vector type");
6651   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6652   if (!getVShiftImm(Op, ElementBits, Cnt))
6653     return false;
6654   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6655 }
6656 
6657 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6658                                                       SelectionDAG &DAG) const {
6659   EVT VT = Op.getValueType();
6660   SDLoc DL(Op);
6661   int64_t Cnt;
6662 
6663   if (!Op.getOperand(1).getValueType().isVector())
6664     return Op;
6665   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6666 
6667   switch (Op.getOpcode()) {
6668   default:
6669     llvm_unreachable("unexpected shift opcode");
6670 
6671   case ISD::SHL:
6672     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6673       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6674                          DAG.getConstant(Cnt, DL, MVT::i32));
6675     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6676                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6677                                        MVT::i32),
6678                        Op.getOperand(0), Op.getOperand(1));
6679   case ISD::SRA:
6680   case ISD::SRL:
6681     // Right shift immediate
6682     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6683       unsigned Opc =
6684           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6685       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6686                          DAG.getConstant(Cnt, DL, MVT::i32));
6687     }
6688 
6689     // Right shift register.  Note, there is not a shift right register
6690     // instruction, but the shift left register instruction takes a signed
6691     // value, where negative numbers specify a right shift.
6692     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6693                                                 : Intrinsic::aarch64_neon_ushl;
6694     // negate the shift amount
6695     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6696     SDValue NegShiftLeft =
6697         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6698                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6699                     NegShift);
6700     return NegShiftLeft;
6701   }
6702 
6703   return SDValue();
6704 }
6705 
6706 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6707                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6708                                     const SDLoc &dl, SelectionDAG &DAG) {
6709   EVT SrcVT = LHS.getValueType();
6710   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6711          "function only supposed to emit natural comparisons");
6712 
6713   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6714   APInt CnstBits(VT.getSizeInBits(), 0);
6715   APInt UndefBits(VT.getSizeInBits(), 0);
6716   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6717   bool IsZero = IsCnst && (CnstBits == 0);
6718 
6719   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6720     switch (CC) {
6721     default:
6722       return SDValue();
6723     case AArch64CC::NE: {
6724       SDValue Fcmeq;
6725       if (IsZero)
6726         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6727       else
6728         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6729       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6730     }
6731     case AArch64CC::EQ:
6732       if (IsZero)
6733         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6734       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6735     case AArch64CC::GE:
6736       if (IsZero)
6737         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6738       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6739     case AArch64CC::GT:
6740       if (IsZero)
6741         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6742       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6743     case AArch64CC::LS:
6744       if (IsZero)
6745         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6746       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6747     case AArch64CC::LT:
6748       if (!NoNans)
6749         return SDValue();
6750       // If we ignore NaNs then we can use to the MI implementation.
6751       LLVM_FALLTHROUGH;
6752     case AArch64CC::MI:
6753       if (IsZero)
6754         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6755       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6756     }
6757   }
6758 
6759   switch (CC) {
6760   default:
6761     return SDValue();
6762   case AArch64CC::NE: {
6763     SDValue Cmeq;
6764     if (IsZero)
6765       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6766     else
6767       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6768     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6769   }
6770   case AArch64CC::EQ:
6771     if (IsZero)
6772       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6773     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6774   case AArch64CC::GE:
6775     if (IsZero)
6776       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6777     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6778   case AArch64CC::GT:
6779     if (IsZero)
6780       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6781     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6782   case AArch64CC::LE:
6783     if (IsZero)
6784       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6785     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6786   case AArch64CC::LS:
6787     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6788   case AArch64CC::LO:
6789     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6790   case AArch64CC::LT:
6791     if (IsZero)
6792       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6793     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6794   case AArch64CC::HI:
6795     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6796   case AArch64CC::HS:
6797     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6798   }
6799 }
6800 
6801 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6802                                            SelectionDAG &DAG) const {
6803   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6804   SDValue LHS = Op.getOperand(0);
6805   SDValue RHS = Op.getOperand(1);
6806   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6807   SDLoc dl(Op);
6808 
6809   if (LHS.getValueType().getVectorElementType().isInteger()) {
6810     assert(LHS.getValueType() == RHS.getValueType());
6811     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6812     SDValue Cmp =
6813         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6814     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6815   }
6816 
6817   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6818     return SDValue();
6819 
6820   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6821          LHS.getValueType().getVectorElementType() == MVT::f64);
6822 
6823   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6824   // clean.  Some of them require two branches to implement.
6825   AArch64CC::CondCode CC1, CC2;
6826   bool ShouldInvert;
6827   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6828 
6829   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6830   SDValue Cmp =
6831       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6832   if (!Cmp.getNode())
6833     return SDValue();
6834 
6835   if (CC2 != AArch64CC::AL) {
6836     SDValue Cmp2 =
6837         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6838     if (!Cmp2.getNode())
6839       return SDValue();
6840 
6841     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6842   }
6843 
6844   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6845 
6846   if (ShouldInvert)
6847     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6848 
6849   return Cmp;
6850 }
6851 
6852 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6853 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6854 /// specified in the intrinsic calls.
6855 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6856                                                const CallInst &I,
6857                                                unsigned Intrinsic) const {
6858   auto &DL = I.getModule()->getDataLayout();
6859   switch (Intrinsic) {
6860   case Intrinsic::aarch64_neon_ld2:
6861   case Intrinsic::aarch64_neon_ld3:
6862   case Intrinsic::aarch64_neon_ld4:
6863   case Intrinsic::aarch64_neon_ld1x2:
6864   case Intrinsic::aarch64_neon_ld1x3:
6865   case Intrinsic::aarch64_neon_ld1x4:
6866   case Intrinsic::aarch64_neon_ld2lane:
6867   case Intrinsic::aarch64_neon_ld3lane:
6868   case Intrinsic::aarch64_neon_ld4lane:
6869   case Intrinsic::aarch64_neon_ld2r:
6870   case Intrinsic::aarch64_neon_ld3r:
6871   case Intrinsic::aarch64_neon_ld4r: {
6872     Info.opc = ISD::INTRINSIC_W_CHAIN;
6873     // Conservatively set memVT to the entire set of vectors loaded.
6874     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6875     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6876     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6877     Info.offset = 0;
6878     Info.align = 0;
6879     Info.vol = false; // volatile loads with NEON intrinsics not supported
6880     Info.readMem = true;
6881     Info.writeMem = false;
6882     return true;
6883   }
6884   case Intrinsic::aarch64_neon_st2:
6885   case Intrinsic::aarch64_neon_st3:
6886   case Intrinsic::aarch64_neon_st4:
6887   case Intrinsic::aarch64_neon_st1x2:
6888   case Intrinsic::aarch64_neon_st1x3:
6889   case Intrinsic::aarch64_neon_st1x4:
6890   case Intrinsic::aarch64_neon_st2lane:
6891   case Intrinsic::aarch64_neon_st3lane:
6892   case Intrinsic::aarch64_neon_st4lane: {
6893     Info.opc = ISD::INTRINSIC_VOID;
6894     // Conservatively set memVT to the entire set of vectors stored.
6895     unsigned NumElts = 0;
6896     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6897       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6898       if (!ArgTy->isVectorTy())
6899         break;
6900       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6901     }
6902     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6903     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6904     Info.offset = 0;
6905     Info.align = 0;
6906     Info.vol = false; // volatile stores with NEON intrinsics not supported
6907     Info.readMem = false;
6908     Info.writeMem = true;
6909     return true;
6910   }
6911   case Intrinsic::aarch64_ldaxr:
6912   case Intrinsic::aarch64_ldxr: {
6913     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6914     Info.opc = ISD::INTRINSIC_W_CHAIN;
6915     Info.memVT = MVT::getVT(PtrTy->getElementType());
6916     Info.ptrVal = I.getArgOperand(0);
6917     Info.offset = 0;
6918     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6919     Info.vol = true;
6920     Info.readMem = true;
6921     Info.writeMem = false;
6922     return true;
6923   }
6924   case Intrinsic::aarch64_stlxr:
6925   case Intrinsic::aarch64_stxr: {
6926     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6927     Info.opc = ISD::INTRINSIC_W_CHAIN;
6928     Info.memVT = MVT::getVT(PtrTy->getElementType());
6929     Info.ptrVal = I.getArgOperand(1);
6930     Info.offset = 0;
6931     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6932     Info.vol = true;
6933     Info.readMem = false;
6934     Info.writeMem = true;
6935     return true;
6936   }
6937   case Intrinsic::aarch64_ldaxp:
6938   case Intrinsic::aarch64_ldxp: {
6939     Info.opc = ISD::INTRINSIC_W_CHAIN;
6940     Info.memVT = MVT::i128;
6941     Info.ptrVal = I.getArgOperand(0);
6942     Info.offset = 0;
6943     Info.align = 16;
6944     Info.vol = true;
6945     Info.readMem = true;
6946     Info.writeMem = false;
6947     return true;
6948   }
6949   case Intrinsic::aarch64_stlxp:
6950   case Intrinsic::aarch64_stxp: {
6951     Info.opc = ISD::INTRINSIC_W_CHAIN;
6952     Info.memVT = MVT::i128;
6953     Info.ptrVal = I.getArgOperand(2);
6954     Info.offset = 0;
6955     Info.align = 16;
6956     Info.vol = true;
6957     Info.readMem = false;
6958     Info.writeMem = true;
6959     return true;
6960   }
6961   default:
6962     break;
6963   }
6964 
6965   return false;
6966 }
6967 
6968 // Truncations from 64-bit GPR to 32-bit GPR is free.
6969 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6970   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6971     return false;
6972   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6973   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6974   return NumBits1 > NumBits2;
6975 }
6976 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6977   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6978     return false;
6979   unsigned NumBits1 = VT1.getSizeInBits();
6980   unsigned NumBits2 = VT2.getSizeInBits();
6981   return NumBits1 > NumBits2;
6982 }
6983 
6984 /// Check if it is profitable to hoist instruction in then/else to if.
6985 /// Not profitable if I and it's user can form a FMA instruction
6986 /// because we prefer FMSUB/FMADD.
6987 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6988   if (I->getOpcode() != Instruction::FMul)
6989     return true;
6990 
6991   if (I->getNumUses() != 1)
6992     return true;
6993 
6994   Instruction *User = I->user_back();
6995 
6996   if (User &&
6997       !(User->getOpcode() == Instruction::FSub ||
6998         User->getOpcode() == Instruction::FAdd))
6999     return true;
7000 
7001   const TargetOptions &Options = getTargetMachine().Options;
7002   const DataLayout &DL = I->getModule()->getDataLayout();
7003   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7004 
7005   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7006            isOperationLegalOrCustom(ISD::FMA, VT) &&
7007            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7008             Options.UnsafeFPMath));
7009 }
7010 
7011 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7012 // 64-bit GPR.
7013 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7014   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7015     return false;
7016   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7017   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7018   return NumBits1 == 32 && NumBits2 == 64;
7019 }
7020 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7021   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7022     return false;
7023   unsigned NumBits1 = VT1.getSizeInBits();
7024   unsigned NumBits2 = VT2.getSizeInBits();
7025   return NumBits1 == 32 && NumBits2 == 64;
7026 }
7027 
7028 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7029   EVT VT1 = Val.getValueType();
7030   if (isZExtFree(VT1, VT2)) {
7031     return true;
7032   }
7033 
7034   if (Val.getOpcode() != ISD::LOAD)
7035     return false;
7036 
7037   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7038   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7039           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7040           VT1.getSizeInBits() <= 32);
7041 }
7042 
7043 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7044   if (isa<FPExtInst>(Ext))
7045     return false;
7046 
7047   // Vector types are next free.
7048   if (Ext->getType()->isVectorTy())
7049     return false;
7050 
7051   for (const Use &U : Ext->uses()) {
7052     // The extension is free if we can fold it with a left shift in an
7053     // addressing mode or an arithmetic operation: add, sub, and cmp.
7054 
7055     // Is there a shift?
7056     const Instruction *Instr = cast<Instruction>(U.getUser());
7057 
7058     // Is this a constant shift?
7059     switch (Instr->getOpcode()) {
7060     case Instruction::Shl:
7061       if (!isa<ConstantInt>(Instr->getOperand(1)))
7062         return false;
7063       break;
7064     case Instruction::GetElementPtr: {
7065       gep_type_iterator GTI = gep_type_begin(Instr);
7066       auto &DL = Ext->getModule()->getDataLayout();
7067       std::advance(GTI, U.getOperandNo());
7068       Type *IdxTy = *GTI;
7069       // This extension will end up with a shift because of the scaling factor.
7070       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7071       // Get the shift amount based on the scaling factor:
7072       // log2(sizeof(IdxTy)) - log2(8).
7073       uint64_t ShiftAmt =
7074           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7075       // Is the constant foldable in the shift of the addressing mode?
7076       // I.e., shift amount is between 1 and 4 inclusive.
7077       if (ShiftAmt == 0 || ShiftAmt > 4)
7078         return false;
7079       break;
7080     }
7081     case Instruction::Trunc:
7082       // Check if this is a noop.
7083       // trunc(sext ty1 to ty2) to ty1.
7084       if (Instr->getType() == Ext->getOperand(0)->getType())
7085         continue;
7086       LLVM_FALLTHROUGH;
7087     default:
7088       return false;
7089     }
7090 
7091     // At this point we can use the bfm family, so this extension is free
7092     // for that use.
7093   }
7094   return true;
7095 }
7096 
7097 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7098                                           unsigned &RequiredAligment) const {
7099   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7100     return false;
7101   // Cyclone supports unaligned accesses.
7102   RequiredAligment = 0;
7103   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7104   return NumBits == 32 || NumBits == 64;
7105 }
7106 
7107 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7108                                           unsigned &RequiredAligment) const {
7109   if (!LoadedType.isSimple() ||
7110       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7111     return false;
7112   // Cyclone supports unaligned accesses.
7113   RequiredAligment = 0;
7114   unsigned NumBits = LoadedType.getSizeInBits();
7115   return NumBits == 32 || NumBits == 64;
7116 }
7117 
7118 /// \brief Lower an interleaved load into a ldN intrinsic.
7119 ///
7120 /// E.g. Lower an interleaved load (Factor = 2):
7121 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7122 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7123 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7124 ///
7125 ///      Into:
7126 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7127 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7128 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7129 bool AArch64TargetLowering::lowerInterleavedLoad(
7130     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7131     ArrayRef<unsigned> Indices, unsigned Factor) const {
7132   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7133          "Invalid interleave factor");
7134   assert(!Shuffles.empty() && "Empty shufflevector input");
7135   assert(Shuffles.size() == Indices.size() &&
7136          "Unmatched number of shufflevectors and indices");
7137 
7138   const DataLayout &DL = LI->getModule()->getDataLayout();
7139 
7140   VectorType *VecTy = Shuffles[0]->getType();
7141   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7142 
7143   // Skip if we do not have NEON and skip illegal vector types.
7144   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7145     return false;
7146 
7147   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7148   // load integer vectors first and then convert to pointer vectors.
7149   Type *EltTy = VecTy->getVectorElementType();
7150   if (EltTy->isPointerTy())
7151     VecTy =
7152         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7153 
7154   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7155   Type *Tys[2] = {VecTy, PtrTy};
7156   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7157                                             Intrinsic::aarch64_neon_ld3,
7158                                             Intrinsic::aarch64_neon_ld4};
7159   Function *LdNFunc =
7160       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7161 
7162   IRBuilder<> Builder(LI);
7163   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7164 
7165   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7166 
7167   // Replace uses of each shufflevector with the corresponding vector loaded
7168   // by ldN.
7169   for (unsigned i = 0; i < Shuffles.size(); i++) {
7170     ShuffleVectorInst *SVI = Shuffles[i];
7171     unsigned Index = Indices[i];
7172 
7173     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7174 
7175     // Convert the integer vector to pointer vector if the element is pointer.
7176     if (EltTy->isPointerTy())
7177       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7178 
7179     SVI->replaceAllUsesWith(SubVec);
7180   }
7181 
7182   return true;
7183 }
7184 
7185 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7186 ///
7187 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7188 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7189                                    unsigned NumElts) {
7190   SmallVector<Constant *, 16> Mask;
7191   for (unsigned i = 0; i < NumElts; i++)
7192     Mask.push_back(Builder.getInt32(Start + i));
7193 
7194   return ConstantVector::get(Mask);
7195 }
7196 
7197 /// \brief Lower an interleaved store into a stN intrinsic.
7198 ///
7199 /// E.g. Lower an interleaved store (Factor = 3):
7200 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7201 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7202 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7203 ///
7204 ///      Into:
7205 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7206 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7207 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7208 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7209 ///
7210 /// Note that the new shufflevectors will be removed and we'll only generate one
7211 /// st3 instruction in CodeGen.
7212 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7213                                                   ShuffleVectorInst *SVI,
7214                                                   unsigned Factor) const {
7215   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7216          "Invalid interleave factor");
7217 
7218   VectorType *VecTy = SVI->getType();
7219   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7220          "Invalid interleaved store");
7221 
7222   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7223   Type *EltTy = VecTy->getVectorElementType();
7224   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7225 
7226   const DataLayout &DL = SI->getModule()->getDataLayout();
7227   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7228 
7229   // Skip if we do not have NEON and skip illegal vector types.
7230   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7231     return false;
7232 
7233   Value *Op0 = SVI->getOperand(0);
7234   Value *Op1 = SVI->getOperand(1);
7235   IRBuilder<> Builder(SI);
7236 
7237   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7238   // vectors to integer vectors.
7239   if (EltTy->isPointerTy()) {
7240     Type *IntTy = DL.getIntPtrType(EltTy);
7241     unsigned NumOpElts =
7242         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7243 
7244     // Convert to the corresponding integer vector.
7245     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7246     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7247     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7248 
7249     SubVecTy = VectorType::get(IntTy, NumSubElts);
7250   }
7251 
7252   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7253   Type *Tys[2] = {SubVecTy, PtrTy};
7254   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7255                                              Intrinsic::aarch64_neon_st3,
7256                                              Intrinsic::aarch64_neon_st4};
7257   Function *StNFunc =
7258       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7259 
7260   SmallVector<Value *, 5> Ops;
7261 
7262   // Split the shufflevector operands into sub vectors for the new stN call.
7263   for (unsigned i = 0; i < Factor; i++)
7264     Ops.push_back(Builder.CreateShuffleVector(
7265         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7266 
7267   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7268   Builder.CreateCall(StNFunc, Ops);
7269   return true;
7270 }
7271 
7272 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7273                        unsigned AlignCheck) {
7274   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7275           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7276 }
7277 
7278 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7279                                                unsigned SrcAlign, bool IsMemset,
7280                                                bool ZeroMemset,
7281                                                bool MemcpyStrSrc,
7282                                                MachineFunction &MF) const {
7283   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7284   // instruction to materialize the v2i64 zero and one store (with restrictive
7285   // addressing mode). Just do two i64 store of zero-registers.
7286   bool Fast;
7287   const Function *F = MF.getFunction();
7288   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7289       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7290       (memOpAlign(SrcAlign, DstAlign, 16) ||
7291        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7292     return MVT::f128;
7293 
7294   if (Size >= 8 &&
7295       (memOpAlign(SrcAlign, DstAlign, 8) ||
7296        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7297     return MVT::i64;
7298 
7299   if (Size >= 4 &&
7300       (memOpAlign(SrcAlign, DstAlign, 4) ||
7301        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7302     return MVT::i32;
7303 
7304   return MVT::Other;
7305 }
7306 
7307 // 12-bit optionally shifted immediates are legal for adds.
7308 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7309   // Avoid UB for INT64_MIN.
7310   if (Immed == std::numeric_limits<int64_t>::min())
7311     return false;
7312   // Same encoding for add/sub, just flip the sign.
7313   Immed = std::abs(Immed);
7314   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7315 }
7316 
7317 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7318 // immediates is the same as for an add or a sub.
7319 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7320   return isLegalAddImmediate(Immed);
7321 }
7322 
7323 /// isLegalAddressingMode - Return true if the addressing mode represented
7324 /// by AM is legal for this target, for a load/store of the specified type.
7325 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7326                                                   const AddrMode &AM, Type *Ty,
7327                                                   unsigned AS) const {
7328   // AArch64 has five basic addressing modes:
7329   //  reg
7330   //  reg + 9-bit signed offset
7331   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7332   //  reg1 + reg2
7333   //  reg + SIZE_IN_BYTES * reg
7334 
7335   // No global is ever allowed as a base.
7336   if (AM.BaseGV)
7337     return false;
7338 
7339   // No reg+reg+imm addressing.
7340   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7341     return false;
7342 
7343   // check reg + imm case:
7344   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7345   uint64_t NumBytes = 0;
7346   if (Ty->isSized()) {
7347     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7348     NumBytes = NumBits / 8;
7349     if (!isPowerOf2_64(NumBits))
7350       NumBytes = 0;
7351   }
7352 
7353   if (!AM.Scale) {
7354     int64_t Offset = AM.BaseOffs;
7355 
7356     // 9-bit signed offset
7357     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7358       return true;
7359 
7360     // 12-bit unsigned offset
7361     unsigned shift = Log2_64(NumBytes);
7362     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7363         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7364         (Offset >> shift) << shift == Offset)
7365       return true;
7366     return false;
7367   }
7368 
7369   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7370 
7371   return !AM.Scale || AM.Scale == 1 ||
7372          (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7373 }
7374 
7375 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7376                                                 const AddrMode &AM, Type *Ty,
7377                                                 unsigned AS) const {
7378   // Scaling factors are not free at all.
7379   // Operands                     | Rt Latency
7380   // -------------------------------------------
7381   // Rt, [Xn, Xm]                 | 4
7382   // -------------------------------------------
7383   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7384   // Rt, [Xn, Wm, <extend> #imm]  |
7385   if (isLegalAddressingMode(DL, AM, Ty, AS))
7386     // Scale represents reg2 * scale, thus account for 1 if
7387     // it is not equal to 0 or 1.
7388     return AM.Scale != 0 && AM.Scale != 1;
7389   return -1;
7390 }
7391 
7392 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7393   VT = VT.getScalarType();
7394 
7395   if (!VT.isSimple())
7396     return false;
7397 
7398   switch (VT.getSimpleVT().SimpleTy) {
7399   case MVT::f32:
7400   case MVT::f64:
7401     return true;
7402   default:
7403     break;
7404   }
7405 
7406   return false;
7407 }
7408 
7409 const MCPhysReg *
7410 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7411   // LR is a callee-save register, but we must treat it as clobbered by any call
7412   // site. Hence we include LR in the scratch registers, which are in turn added
7413   // as implicit-defs for stackmaps and patchpoints.
7414   static const MCPhysReg ScratchRegs[] = {
7415     AArch64::X16, AArch64::X17, AArch64::LR, 0
7416   };
7417   return ScratchRegs;
7418 }
7419 
7420 bool
7421 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7422   EVT VT = N->getValueType(0);
7423     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7424     // it with shift to let it be lowered to UBFX.
7425   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7426       isa<ConstantSDNode>(N->getOperand(1))) {
7427     uint64_t TruncMask = N->getConstantOperandVal(1);
7428     if (isMask_64(TruncMask) &&
7429       N->getOperand(0).getOpcode() == ISD::SRL &&
7430       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7431       return false;
7432   }
7433   return true;
7434 }
7435 
7436 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7437                                                               Type *Ty) const {
7438   assert(Ty->isIntegerTy());
7439 
7440   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7441   if (BitSize == 0)
7442     return false;
7443 
7444   int64_t Val = Imm.getSExtValue();
7445   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7446     return true;
7447 
7448   if ((int64_t)Val < 0)
7449     Val = ~Val;
7450   if (BitSize == 32)
7451     Val &= (1LL << 32) - 1;
7452 
7453   unsigned LZ = countLeadingZeros((uint64_t)Val);
7454   unsigned Shift = (63 - LZ) / 16;
7455   // MOVZ is free so return true for one or fewer MOVK.
7456   return Shift < 3;
7457 }
7458 
7459 /// Turn vector tests of the signbit in the form of:
7460 ///   xor (sra X, elt_size(X)-1), -1
7461 /// into:
7462 ///   cmge X, X, #0
7463 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7464                                          const AArch64Subtarget *Subtarget) {
7465   EVT VT = N->getValueType(0);
7466   if (!Subtarget->hasNEON() || !VT.isVector())
7467     return SDValue();
7468 
7469   // There must be a shift right algebraic before the xor, and the xor must be a
7470   // 'not' operation.
7471   SDValue Shift = N->getOperand(0);
7472   SDValue Ones = N->getOperand(1);
7473   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7474       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7475     return SDValue();
7476 
7477   // The shift should be smearing the sign bit across each vector element.
7478   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7479   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7480   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7481     return SDValue();
7482 
7483   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7484 }
7485 
7486 // Generate SUBS and CSEL for integer abs.
7487 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7488   EVT VT = N->getValueType(0);
7489 
7490   SDValue N0 = N->getOperand(0);
7491   SDValue N1 = N->getOperand(1);
7492   SDLoc DL(N);
7493 
7494   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7495   // and change it to SUB and CSEL.
7496   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7497       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7498       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7499     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7500       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7501         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7502                                   N0.getOperand(0));
7503         // Generate SUBS & CSEL.
7504         SDValue Cmp =
7505             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7506                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7507         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7508                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7509                            SDValue(Cmp.getNode(), 1));
7510       }
7511   return SDValue();
7512 }
7513 
7514 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7515                                  TargetLowering::DAGCombinerInfo &DCI,
7516                                  const AArch64Subtarget *Subtarget) {
7517   if (DCI.isBeforeLegalizeOps())
7518     return SDValue();
7519 
7520   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7521     return Cmp;
7522 
7523   return performIntegerAbsCombine(N, DAG);
7524 }
7525 
7526 SDValue
7527 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7528                                      SelectionDAG &DAG,
7529                                      std::vector<SDNode *> *Created) const {
7530   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7531   if (isIntDivCheap(N->getValueType(0), Attr))
7532     return SDValue(N,0); // Lower SDIV as SDIV
7533 
7534   // fold (sdiv X, pow2)
7535   EVT VT = N->getValueType(0);
7536   if ((VT != MVT::i32 && VT != MVT::i64) ||
7537       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7538     return SDValue();
7539 
7540   SDLoc DL(N);
7541   SDValue N0 = N->getOperand(0);
7542   unsigned Lg2 = Divisor.countTrailingZeros();
7543   SDValue Zero = DAG.getConstant(0, DL, VT);
7544   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7545 
7546   // Add (N0 < 0) ? Pow2 - 1 : 0;
7547   SDValue CCVal;
7548   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7549   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7550   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7551 
7552   if (Created) {
7553     Created->push_back(Cmp.getNode());
7554     Created->push_back(Add.getNode());
7555     Created->push_back(CSel.getNode());
7556   }
7557 
7558   // Divide by pow2.
7559   SDValue SRA =
7560       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7561 
7562   // If we're dividing by a positive value, we're done.  Otherwise, we must
7563   // negate the result.
7564   if (Divisor.isNonNegative())
7565     return SRA;
7566 
7567   if (Created)
7568     Created->push_back(SRA.getNode());
7569   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7570 }
7571 
7572 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7573                                  TargetLowering::DAGCombinerInfo &DCI,
7574                                  const AArch64Subtarget *Subtarget) {
7575   if (DCI.isBeforeLegalizeOps())
7576     return SDValue();
7577 
7578   // Multiplication of a power of two plus/minus one can be done more
7579   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7580   // future CPUs have a cheaper MADD instruction, this may need to be
7581   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7582   // 64-bit is 5 cycles, so this is always a win.
7583   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7584     const APInt &Value = C->getAPIntValue();
7585     EVT VT = N->getValueType(0);
7586     SDLoc DL(N);
7587     if (Value.isNonNegative()) {
7588       // (mul x, 2^N + 1) => (add (shl x, N), x)
7589       APInt VM1 = Value - 1;
7590       if (VM1.isPowerOf2()) {
7591         SDValue ShiftedVal =
7592             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7593                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7594         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7595                            N->getOperand(0));
7596       }
7597       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7598       APInt VP1 = Value + 1;
7599       if (VP1.isPowerOf2()) {
7600         SDValue ShiftedVal =
7601             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7602                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7603         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7604                            N->getOperand(0));
7605       }
7606     } else {
7607       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7608       APInt VNP1 = -Value + 1;
7609       if (VNP1.isPowerOf2()) {
7610         SDValue ShiftedVal =
7611             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7612                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7613         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7614                            ShiftedVal);
7615       }
7616       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7617       APInt VNM1 = -Value - 1;
7618       if (VNM1.isPowerOf2()) {
7619         SDValue ShiftedVal =
7620             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7621                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7622         SDValue Add =
7623             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7624         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7625       }
7626     }
7627   }
7628   return SDValue();
7629 }
7630 
7631 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7632                                                          SelectionDAG &DAG) {
7633   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7634   // optimize away operation when it's from a constant.
7635   //
7636   // The general transformation is:
7637   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7638   //       AND(VECTOR_CMP(x,y), constant2)
7639   //    constant2 = UNARYOP(constant)
7640 
7641   // Early exit if this isn't a vector operation, the operand of the
7642   // unary operation isn't a bitwise AND, or if the sizes of the operations
7643   // aren't the same.
7644   EVT VT = N->getValueType(0);
7645   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7646       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7647       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7648     return SDValue();
7649 
7650   // Now check that the other operand of the AND is a constant. We could
7651   // make the transformation for non-constant splats as well, but it's unclear
7652   // that would be a benefit as it would not eliminate any operations, just
7653   // perform one more step in scalar code before moving to the vector unit.
7654   if (BuildVectorSDNode *BV =
7655           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7656     // Bail out if the vector isn't a constant.
7657     if (!BV->isConstant())
7658       return SDValue();
7659 
7660     // Everything checks out. Build up the new and improved node.
7661     SDLoc DL(N);
7662     EVT IntVT = BV->getValueType(0);
7663     // Create a new constant of the appropriate type for the transformed
7664     // DAG.
7665     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7666     // The AND node needs bitcasts to/from an integer vector type around it.
7667     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7668     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7669                                  N->getOperand(0)->getOperand(0), MaskConst);
7670     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7671     return Res;
7672   }
7673 
7674   return SDValue();
7675 }
7676 
7677 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7678                                      const AArch64Subtarget *Subtarget) {
7679   // First try to optimize away the conversion when it's conditionally from
7680   // a constant. Vectors only.
7681   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7682     return Res;
7683 
7684   EVT VT = N->getValueType(0);
7685   if (VT != MVT::f32 && VT != MVT::f64)
7686     return SDValue();
7687 
7688   // Only optimize when the source and destination types have the same width.
7689   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7690     return SDValue();
7691 
7692   // If the result of an integer load is only used by an integer-to-float
7693   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7694   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7695   SDValue N0 = N->getOperand(0);
7696   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7697       // Do not change the width of a volatile load.
7698       !cast<LoadSDNode>(N0)->isVolatile()) {
7699     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7700     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7701                                LN0->getPointerInfo(), LN0->getAlignment(),
7702                                LN0->getMemOperand()->getFlags());
7703 
7704     // Make sure successors of the original load stay after it by updating them
7705     // to use the new Chain.
7706     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7707 
7708     unsigned Opcode =
7709         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7710     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7711   }
7712 
7713   return SDValue();
7714 }
7715 
7716 /// Fold a floating-point multiply by power of two into floating-point to
7717 /// fixed-point conversion.
7718 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7719                                      TargetLowering::DAGCombinerInfo &DCI,
7720                                      const AArch64Subtarget *Subtarget) {
7721   if (!Subtarget->hasNEON())
7722     return SDValue();
7723 
7724   SDValue Op = N->getOperand(0);
7725   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7726       Op.getOpcode() != ISD::FMUL)
7727     return SDValue();
7728 
7729   SDValue ConstVec = Op->getOperand(1);
7730   if (!isa<BuildVectorSDNode>(ConstVec))
7731     return SDValue();
7732 
7733   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7734   uint32_t FloatBits = FloatTy.getSizeInBits();
7735   if (FloatBits != 32 && FloatBits != 64)
7736     return SDValue();
7737 
7738   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7739   uint32_t IntBits = IntTy.getSizeInBits();
7740   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7741     return SDValue();
7742 
7743   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7744   if (IntBits > FloatBits)
7745     return SDValue();
7746 
7747   BitVector UndefElements;
7748   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7749   int32_t Bits = IntBits == 64 ? 64 : 32;
7750   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7751   if (C == -1 || C == 0 || C > Bits)
7752     return SDValue();
7753 
7754   MVT ResTy;
7755   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7756   switch (NumLanes) {
7757   default:
7758     return SDValue();
7759   case 2:
7760     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7761     break;
7762   case 4:
7763     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7764     break;
7765   }
7766 
7767   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7768     return SDValue();
7769 
7770   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7771          "Illegal vector type after legalization");
7772 
7773   SDLoc DL(N);
7774   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7775   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7776                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7777   SDValue FixConv =
7778       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7779                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7780                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7781   // We can handle smaller integers by generating an extra trunc.
7782   if (IntBits < FloatBits)
7783     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7784 
7785   return FixConv;
7786 }
7787 
7788 /// Fold a floating-point divide by power of two into fixed-point to
7789 /// floating-point conversion.
7790 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7791                                   TargetLowering::DAGCombinerInfo &DCI,
7792                                   const AArch64Subtarget *Subtarget) {
7793   if (!Subtarget->hasNEON())
7794     return SDValue();
7795 
7796   SDValue Op = N->getOperand(0);
7797   unsigned Opc = Op->getOpcode();
7798   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7799       !Op.getOperand(0).getValueType().isSimple() ||
7800       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7801     return SDValue();
7802 
7803   SDValue ConstVec = N->getOperand(1);
7804   if (!isa<BuildVectorSDNode>(ConstVec))
7805     return SDValue();
7806 
7807   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7808   int32_t IntBits = IntTy.getSizeInBits();
7809   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7810     return SDValue();
7811 
7812   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7813   int32_t FloatBits = FloatTy.getSizeInBits();
7814   if (FloatBits != 32 && FloatBits != 64)
7815     return SDValue();
7816 
7817   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7818   if (IntBits > FloatBits)
7819     return SDValue();
7820 
7821   BitVector UndefElements;
7822   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7823   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7824   if (C == -1 || C == 0 || C > FloatBits)
7825     return SDValue();
7826 
7827   MVT ResTy;
7828   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7829   switch (NumLanes) {
7830   default:
7831     return SDValue();
7832   case 2:
7833     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7834     break;
7835   case 4:
7836     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7837     break;
7838   }
7839 
7840   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7841     return SDValue();
7842 
7843   SDLoc DL(N);
7844   SDValue ConvInput = Op.getOperand(0);
7845   bool IsSigned = Opc == ISD::SINT_TO_FP;
7846   if (IntBits < FloatBits)
7847     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7848                             ResTy, ConvInput);
7849 
7850   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7851                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7852   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7853                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7854                      DAG.getConstant(C, DL, MVT::i32));
7855 }
7856 
7857 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7858 /// searches for and classifies those shifts.
7859 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7860                          bool &FromHi) {
7861   if (N.getOpcode() == ISD::SHL)
7862     FromHi = false;
7863   else if (N.getOpcode() == ISD::SRL)
7864     FromHi = true;
7865   else
7866     return false;
7867 
7868   if (!isa<ConstantSDNode>(N.getOperand(1)))
7869     return false;
7870 
7871   ShiftAmount = N->getConstantOperandVal(1);
7872   Src = N->getOperand(0);
7873   return true;
7874 }
7875 
7876 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7877 /// registers viewed as a high/low pair. This function looks for the pattern:
7878 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7879 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7880 /// independent.
7881 static SDValue tryCombineToEXTR(SDNode *N,
7882                                 TargetLowering::DAGCombinerInfo &DCI) {
7883   SelectionDAG &DAG = DCI.DAG;
7884   SDLoc DL(N);
7885   EVT VT = N->getValueType(0);
7886 
7887   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7888 
7889   if (VT != MVT::i32 && VT != MVT::i64)
7890     return SDValue();
7891 
7892   SDValue LHS;
7893   uint32_t ShiftLHS = 0;
7894   bool LHSFromHi = 0;
7895   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7896     return SDValue();
7897 
7898   SDValue RHS;
7899   uint32_t ShiftRHS = 0;
7900   bool RHSFromHi = 0;
7901   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7902     return SDValue();
7903 
7904   // If they're both trying to come from the high part of the register, they're
7905   // not really an EXTR.
7906   if (LHSFromHi == RHSFromHi)
7907     return SDValue();
7908 
7909   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7910     return SDValue();
7911 
7912   if (LHSFromHi) {
7913     std::swap(LHS, RHS);
7914     std::swap(ShiftLHS, ShiftRHS);
7915   }
7916 
7917   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7918                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7919 }
7920 
7921 static SDValue tryCombineToBSL(SDNode *N,
7922                                 TargetLowering::DAGCombinerInfo &DCI) {
7923   EVT VT = N->getValueType(0);
7924   SelectionDAG &DAG = DCI.DAG;
7925   SDLoc DL(N);
7926 
7927   if (!VT.isVector())
7928     return SDValue();
7929 
7930   SDValue N0 = N->getOperand(0);
7931   if (N0.getOpcode() != ISD::AND)
7932     return SDValue();
7933 
7934   SDValue N1 = N->getOperand(1);
7935   if (N1.getOpcode() != ISD::AND)
7936     return SDValue();
7937 
7938   // We only have to look for constant vectors here since the general, variable
7939   // case can be handled in TableGen.
7940   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7941   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7942   for (int i = 1; i >= 0; --i)
7943     for (int j = 1; j >= 0; --j) {
7944       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7945       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7946       if (!BVN0 || !BVN1)
7947         continue;
7948 
7949       bool FoundMatch = true;
7950       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7951         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7952         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7953         if (!CN0 || !CN1 ||
7954             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7955           FoundMatch = false;
7956           break;
7957         }
7958       }
7959 
7960       if (FoundMatch)
7961         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7962                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7963     }
7964 
7965   return SDValue();
7966 }
7967 
7968 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7969                                 const AArch64Subtarget *Subtarget) {
7970   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7971   SelectionDAG &DAG = DCI.DAG;
7972   EVT VT = N->getValueType(0);
7973 
7974   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7975     return SDValue();
7976 
7977   if (SDValue Res = tryCombineToEXTR(N, DCI))
7978     return Res;
7979 
7980   if (SDValue Res = tryCombineToBSL(N, DCI))
7981     return Res;
7982 
7983   return SDValue();
7984 }
7985 
7986 static SDValue performSRLCombine(SDNode *N,
7987                                  TargetLowering::DAGCombinerInfo &DCI) {
7988   SelectionDAG &DAG = DCI.DAG;
7989   EVT VT = N->getValueType(0);
7990   if (VT != MVT::i32 && VT != MVT::i64)
7991     return SDValue();
7992 
7993   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7994   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7995   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7996   SDValue N0 = N->getOperand(0);
7997   if (N0.getOpcode() == ISD::BSWAP) {
7998     SDLoc DL(N);
7999     SDValue N1 = N->getOperand(1);
8000     SDValue N00 = N0.getOperand(0);
8001     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8002       uint64_t ShiftAmt = C->getZExtValue();
8003       if (VT == MVT::i32 && ShiftAmt == 16 &&
8004           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8005         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8006       if (VT == MVT::i64 && ShiftAmt == 32 &&
8007           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8008         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8009     }
8010   }
8011   return SDValue();
8012 }
8013 
8014 static SDValue performBitcastCombine(SDNode *N,
8015                                      TargetLowering::DAGCombinerInfo &DCI,
8016                                      SelectionDAG &DAG) {
8017   // Wait 'til after everything is legalized to try this. That way we have
8018   // legal vector types and such.
8019   if (DCI.isBeforeLegalizeOps())
8020     return SDValue();
8021 
8022   // Remove extraneous bitcasts around an extract_subvector.
8023   // For example,
8024   //    (v4i16 (bitconvert
8025   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8026   //  becomes
8027   //    (extract_subvector ((v8i16 ...), (i64 4)))
8028 
8029   // Only interested in 64-bit vectors as the ultimate result.
8030   EVT VT = N->getValueType(0);
8031   if (!VT.isVector())
8032     return SDValue();
8033   if (VT.getSimpleVT().getSizeInBits() != 64)
8034     return SDValue();
8035   // Is the operand an extract_subvector starting at the beginning or halfway
8036   // point of the vector? A low half may also come through as an
8037   // EXTRACT_SUBREG, so look for that, too.
8038   SDValue Op0 = N->getOperand(0);
8039   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8040       !(Op0->isMachineOpcode() &&
8041         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8042     return SDValue();
8043   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8044   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8045     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8046       return SDValue();
8047   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8048     if (idx != AArch64::dsub)
8049       return SDValue();
8050     // The dsub reference is equivalent to a lane zero subvector reference.
8051     idx = 0;
8052   }
8053   // Look through the bitcast of the input to the extract.
8054   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8055     return SDValue();
8056   SDValue Source = Op0->getOperand(0)->getOperand(0);
8057   // If the source type has twice the number of elements as our destination
8058   // type, we know this is an extract of the high or low half of the vector.
8059   EVT SVT = Source->getValueType(0);
8060   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8061     return SDValue();
8062 
8063   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8064 
8065   // Create the simplified form to just extract the low or high half of the
8066   // vector directly rather than bothering with the bitcasts.
8067   SDLoc dl(N);
8068   unsigned NumElements = VT.getVectorNumElements();
8069   if (idx) {
8070     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8071     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8072   } else {
8073     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8074     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8075                                       Source, SubReg),
8076                    0);
8077   }
8078 }
8079 
8080 static SDValue performConcatVectorsCombine(SDNode *N,
8081                                            TargetLowering::DAGCombinerInfo &DCI,
8082                                            SelectionDAG &DAG) {
8083   SDLoc dl(N);
8084   EVT VT = N->getValueType(0);
8085   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8086 
8087   // Optimize concat_vectors of truncated vectors, where the intermediate
8088   // type is illegal, to avoid said illegality,  e.g.,
8089   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8090   //                          (v2i16 (truncate (v2i64)))))
8091   // ->
8092   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8093   //                                    (v4i32 (bitcast (v2i64))),
8094   //                                    <0, 2, 4, 6>)))
8095   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8096   // on both input and result type, so we might generate worse code.
8097   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8098   if (N->getNumOperands() == 2 &&
8099       N0->getOpcode() == ISD::TRUNCATE &&
8100       N1->getOpcode() == ISD::TRUNCATE) {
8101     SDValue N00 = N0->getOperand(0);
8102     SDValue N10 = N1->getOperand(0);
8103     EVT N00VT = N00.getValueType();
8104 
8105     if (N00VT == N10.getValueType() &&
8106         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8107         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8108       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8109       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8110       for (size_t i = 0; i < Mask.size(); ++i)
8111         Mask[i] = i * 2;
8112       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8113                          DAG.getVectorShuffle(
8114                              MidVT, dl,
8115                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8116                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8117     }
8118   }
8119 
8120   // Wait 'til after everything is legalized to try this. That way we have
8121   // legal vector types and such.
8122   if (DCI.isBeforeLegalizeOps())
8123     return SDValue();
8124 
8125   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8126   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8127   // canonicalise to that.
8128   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8129     assert(VT.getVectorElementType().getSizeInBits() == 64);
8130     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8131                        DAG.getConstant(0, dl, MVT::i64));
8132   }
8133 
8134   // Canonicalise concat_vectors so that the right-hand vector has as few
8135   // bit-casts as possible before its real operation. The primary matching
8136   // destination for these operations will be the narrowing "2" instructions,
8137   // which depend on the operation being performed on this right-hand vector.
8138   // For example,
8139   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8140   // becomes
8141   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8142 
8143   if (N1->getOpcode() != ISD::BITCAST)
8144     return SDValue();
8145   SDValue RHS = N1->getOperand(0);
8146   MVT RHSTy = RHS.getValueType().getSimpleVT();
8147   // If the RHS is not a vector, this is not the pattern we're looking for.
8148   if (!RHSTy.isVector())
8149     return SDValue();
8150 
8151   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8152 
8153   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8154                                   RHSTy.getVectorNumElements() * 2);
8155   return DAG.getNode(ISD::BITCAST, dl, VT,
8156                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8157                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8158                                  RHS));
8159 }
8160 
8161 static SDValue tryCombineFixedPointConvert(SDNode *N,
8162                                            TargetLowering::DAGCombinerInfo &DCI,
8163                                            SelectionDAG &DAG) {
8164   // Wait 'til after everything is legalized to try this. That way we have
8165   // legal vector types and such.
8166   if (DCI.isBeforeLegalizeOps())
8167     return SDValue();
8168   // Transform a scalar conversion of a value from a lane extract into a
8169   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8170   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8171   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8172   //
8173   // The second form interacts better with instruction selection and the
8174   // register allocator to avoid cross-class register copies that aren't
8175   // coalescable due to a lane reference.
8176 
8177   // Check the operand and see if it originates from a lane extract.
8178   SDValue Op1 = N->getOperand(1);
8179   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8180     // Yep, no additional predication needed. Perform the transform.
8181     SDValue IID = N->getOperand(0);
8182     SDValue Shift = N->getOperand(2);
8183     SDValue Vec = Op1.getOperand(0);
8184     SDValue Lane = Op1.getOperand(1);
8185     EVT ResTy = N->getValueType(0);
8186     EVT VecResTy;
8187     SDLoc DL(N);
8188 
8189     // The vector width should be 128 bits by the time we get here, even
8190     // if it started as 64 bits (the extract_vector handling will have
8191     // done so).
8192     assert(Vec.getValueType().getSizeInBits() == 128 &&
8193            "unexpected vector size on extract_vector_elt!");
8194     if (Vec.getValueType() == MVT::v4i32)
8195       VecResTy = MVT::v4f32;
8196     else if (Vec.getValueType() == MVT::v2i64)
8197       VecResTy = MVT::v2f64;
8198     else
8199       llvm_unreachable("unexpected vector type!");
8200 
8201     SDValue Convert =
8202         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8203     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8204   }
8205   return SDValue();
8206 }
8207 
8208 // AArch64 high-vector "long" operations are formed by performing the non-high
8209 // version on an extract_subvector of each operand which gets the high half:
8210 //
8211 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8212 //
8213 // However, there are cases which don't have an extract_high explicitly, but
8214 // have another operation that can be made compatible with one for free. For
8215 // example:
8216 //
8217 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8218 //
8219 // This routine does the actual conversion of such DUPs, once outer routines
8220 // have determined that everything else is in order.
8221 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8222 // similarly here.
8223 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8224   switch (N.getOpcode()) {
8225   case AArch64ISD::DUP:
8226   case AArch64ISD::DUPLANE8:
8227   case AArch64ISD::DUPLANE16:
8228   case AArch64ISD::DUPLANE32:
8229   case AArch64ISD::DUPLANE64:
8230   case AArch64ISD::MOVI:
8231   case AArch64ISD::MOVIshift:
8232   case AArch64ISD::MOVIedit:
8233   case AArch64ISD::MOVImsl:
8234   case AArch64ISD::MVNIshift:
8235   case AArch64ISD::MVNImsl:
8236     break;
8237   default:
8238     // FMOV could be supported, but isn't very useful, as it would only occur
8239     // if you passed a bitcast' floating point immediate to an eligible long
8240     // integer op (addl, smull, ...).
8241     return SDValue();
8242   }
8243 
8244   MVT NarrowTy = N.getSimpleValueType();
8245   if (!NarrowTy.is64BitVector())
8246     return SDValue();
8247 
8248   MVT ElementTy = NarrowTy.getVectorElementType();
8249   unsigned NumElems = NarrowTy.getVectorNumElements();
8250   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8251 
8252   SDLoc dl(N);
8253   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8254                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8255                      DAG.getConstant(NumElems, dl, MVT::i64));
8256 }
8257 
8258 static bool isEssentiallyExtractSubvector(SDValue N) {
8259   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8260     return true;
8261 
8262   return N.getOpcode() == ISD::BITCAST &&
8263          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8264 }
8265 
8266 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8267 struct GenericSetCCInfo {
8268   const SDValue *Opnd0;
8269   const SDValue *Opnd1;
8270   ISD::CondCode CC;
8271 };
8272 
8273 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8274 struct AArch64SetCCInfo {
8275   const SDValue *Cmp;
8276   AArch64CC::CondCode CC;
8277 };
8278 
8279 /// \brief Helper structure to keep track of SetCC information.
8280 union SetCCInfo {
8281   GenericSetCCInfo Generic;
8282   AArch64SetCCInfo AArch64;
8283 };
8284 
8285 /// \brief Helper structure to be able to read SetCC information.  If set to
8286 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8287 /// GenericSetCCInfo.
8288 struct SetCCInfoAndKind {
8289   SetCCInfo Info;
8290   bool IsAArch64;
8291 };
8292 
8293 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8294 /// an
8295 /// AArch64 lowered one.
8296 /// \p SetCCInfo is filled accordingly.
8297 /// \post SetCCInfo is meanginfull only when this function returns true.
8298 /// \return True when Op is a kind of SET_CC operation.
8299 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8300   // If this is a setcc, this is straight forward.
8301   if (Op.getOpcode() == ISD::SETCC) {
8302     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8303     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8304     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8305     SetCCInfo.IsAArch64 = false;
8306     return true;
8307   }
8308   // Otherwise, check if this is a matching csel instruction.
8309   // In other words:
8310   // - csel 1, 0, cc
8311   // - csel 0, 1, !cc
8312   if (Op.getOpcode() != AArch64ISD::CSEL)
8313     return false;
8314   // Set the information about the operands.
8315   // TODO: we want the operands of the Cmp not the csel
8316   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8317   SetCCInfo.IsAArch64 = true;
8318   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8319       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8320 
8321   // Check that the operands matches the constraints:
8322   // (1) Both operands must be constants.
8323   // (2) One must be 1 and the other must be 0.
8324   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8325   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8326 
8327   // Check (1).
8328   if (!TValue || !FValue)
8329     return false;
8330 
8331   // Check (2).
8332   if (!TValue->isOne()) {
8333     // Update the comparison when we are interested in !cc.
8334     std::swap(TValue, FValue);
8335     SetCCInfo.Info.AArch64.CC =
8336         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8337   }
8338   return TValue->isOne() && FValue->isNullValue();
8339 }
8340 
8341 // Returns true if Op is setcc or zext of setcc.
8342 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8343   if (isSetCC(Op, Info))
8344     return true;
8345   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8346     isSetCC(Op->getOperand(0), Info));
8347 }
8348 
8349 // The folding we want to perform is:
8350 // (add x, [zext] (setcc cc ...) )
8351 //   -->
8352 // (csel x, (add x, 1), !cc ...)
8353 //
8354 // The latter will get matched to a CSINC instruction.
8355 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8356   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8357   SDValue LHS = Op->getOperand(0);
8358   SDValue RHS = Op->getOperand(1);
8359   SetCCInfoAndKind InfoAndKind;
8360 
8361   // If neither operand is a SET_CC, give up.
8362   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8363     std::swap(LHS, RHS);
8364     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8365       return SDValue();
8366   }
8367 
8368   // FIXME: This could be generatized to work for FP comparisons.
8369   EVT CmpVT = InfoAndKind.IsAArch64
8370                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8371                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8372   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8373     return SDValue();
8374 
8375   SDValue CCVal;
8376   SDValue Cmp;
8377   SDLoc dl(Op);
8378   if (InfoAndKind.IsAArch64) {
8379     CCVal = DAG.getConstant(
8380         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8381         MVT::i32);
8382     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8383   } else
8384     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8385                       *InfoAndKind.Info.Generic.Opnd1,
8386                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8387                       CCVal, DAG, dl);
8388 
8389   EVT VT = Op->getValueType(0);
8390   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8391   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8392 }
8393 
8394 // The basic add/sub long vector instructions have variants with "2" on the end
8395 // which act on the high-half of their inputs. They are normally matched by
8396 // patterns like:
8397 //
8398 // (add (zeroext (extract_high LHS)),
8399 //      (zeroext (extract_high RHS)))
8400 // -> uaddl2 vD, vN, vM
8401 //
8402 // However, if one of the extracts is something like a duplicate, this
8403 // instruction can still be used profitably. This function puts the DAG into a
8404 // more appropriate form for those patterns to trigger.
8405 static SDValue performAddSubLongCombine(SDNode *N,
8406                                         TargetLowering::DAGCombinerInfo &DCI,
8407                                         SelectionDAG &DAG) {
8408   if (DCI.isBeforeLegalizeOps())
8409     return SDValue();
8410 
8411   MVT VT = N->getSimpleValueType(0);
8412   if (!VT.is128BitVector()) {
8413     if (N->getOpcode() == ISD::ADD)
8414       return performSetccAddFolding(N, DAG);
8415     return SDValue();
8416   }
8417 
8418   // Make sure both branches are extended in the same way.
8419   SDValue LHS = N->getOperand(0);
8420   SDValue RHS = N->getOperand(1);
8421   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8422        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8423       LHS.getOpcode() != RHS.getOpcode())
8424     return SDValue();
8425 
8426   unsigned ExtType = LHS.getOpcode();
8427 
8428   // It's not worth doing if at least one of the inputs isn't already an
8429   // extract, but we don't know which it'll be so we have to try both.
8430   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8431     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8432     if (!RHS.getNode())
8433       return SDValue();
8434 
8435     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8436   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8437     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8438     if (!LHS.getNode())
8439       return SDValue();
8440 
8441     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8442   }
8443 
8444   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8445 }
8446 
8447 // Massage DAGs which we can use the high-half "long" operations on into
8448 // something isel will recognize better. E.g.
8449 //
8450 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8451 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8452 //                     (extract_high (v2i64 (dup128 scalar)))))
8453 //
8454 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8455                                        TargetLowering::DAGCombinerInfo &DCI,
8456                                        SelectionDAG &DAG) {
8457   if (DCI.isBeforeLegalizeOps())
8458     return SDValue();
8459 
8460   SDValue LHS = N->getOperand(1);
8461   SDValue RHS = N->getOperand(2);
8462   assert(LHS.getValueType().is64BitVector() &&
8463          RHS.getValueType().is64BitVector() &&
8464          "unexpected shape for long operation");
8465 
8466   // Either node could be a DUP, but it's not worth doing both of them (you'd
8467   // just as well use the non-high version) so look for a corresponding extract
8468   // operation on the other "wing".
8469   if (isEssentiallyExtractSubvector(LHS)) {
8470     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8471     if (!RHS.getNode())
8472       return SDValue();
8473   } else if (isEssentiallyExtractSubvector(RHS)) {
8474     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8475     if (!LHS.getNode())
8476       return SDValue();
8477   }
8478 
8479   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8480                      N->getOperand(0), LHS, RHS);
8481 }
8482 
8483 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8484   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8485   unsigned ElemBits = ElemTy.getSizeInBits();
8486 
8487   int64_t ShiftAmount;
8488   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8489     APInt SplatValue, SplatUndef;
8490     unsigned SplatBitSize;
8491     bool HasAnyUndefs;
8492     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8493                               HasAnyUndefs, ElemBits) ||
8494         SplatBitSize != ElemBits)
8495       return SDValue();
8496 
8497     ShiftAmount = SplatValue.getSExtValue();
8498   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8499     ShiftAmount = CVN->getSExtValue();
8500   } else
8501     return SDValue();
8502 
8503   unsigned Opcode;
8504   bool IsRightShift;
8505   switch (IID) {
8506   default:
8507     llvm_unreachable("Unknown shift intrinsic");
8508   case Intrinsic::aarch64_neon_sqshl:
8509     Opcode = AArch64ISD::SQSHL_I;
8510     IsRightShift = false;
8511     break;
8512   case Intrinsic::aarch64_neon_uqshl:
8513     Opcode = AArch64ISD::UQSHL_I;
8514     IsRightShift = false;
8515     break;
8516   case Intrinsic::aarch64_neon_srshl:
8517     Opcode = AArch64ISD::SRSHR_I;
8518     IsRightShift = true;
8519     break;
8520   case Intrinsic::aarch64_neon_urshl:
8521     Opcode = AArch64ISD::URSHR_I;
8522     IsRightShift = true;
8523     break;
8524   case Intrinsic::aarch64_neon_sqshlu:
8525     Opcode = AArch64ISD::SQSHLU_I;
8526     IsRightShift = false;
8527     break;
8528   }
8529 
8530   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8531     SDLoc dl(N);
8532     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8533                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8534   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8535     SDLoc dl(N);
8536     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8537                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8538   }
8539 
8540   return SDValue();
8541 }
8542 
8543 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8544 // the intrinsics must be legal and take an i32, this means there's almost
8545 // certainly going to be a zext in the DAG which we can eliminate.
8546 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8547   SDValue AndN = N->getOperand(2);
8548   if (AndN.getOpcode() != ISD::AND)
8549     return SDValue();
8550 
8551   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8552   if (!CMask || CMask->getZExtValue() != Mask)
8553     return SDValue();
8554 
8555   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8556                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8557 }
8558 
8559 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8560                                            SelectionDAG &DAG) {
8561   SDLoc dl(N);
8562   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8563                      DAG.getNode(Opc, dl,
8564                                  N->getOperand(1).getSimpleValueType(),
8565                                  N->getOperand(1)),
8566                      DAG.getConstant(0, dl, MVT::i64));
8567 }
8568 
8569 static SDValue performIntrinsicCombine(SDNode *N,
8570                                        TargetLowering::DAGCombinerInfo &DCI,
8571                                        const AArch64Subtarget *Subtarget) {
8572   SelectionDAG &DAG = DCI.DAG;
8573   unsigned IID = getIntrinsicID(N);
8574   switch (IID) {
8575   default:
8576     break;
8577   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8578   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8579     return tryCombineFixedPointConvert(N, DCI, DAG);
8580   case Intrinsic::aarch64_neon_saddv:
8581     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8582   case Intrinsic::aarch64_neon_uaddv:
8583     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8584   case Intrinsic::aarch64_neon_sminv:
8585     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8586   case Intrinsic::aarch64_neon_uminv:
8587     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8588   case Intrinsic::aarch64_neon_smaxv:
8589     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8590   case Intrinsic::aarch64_neon_umaxv:
8591     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8592   case Intrinsic::aarch64_neon_fmax:
8593     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8594                        N->getOperand(1), N->getOperand(2));
8595   case Intrinsic::aarch64_neon_fmin:
8596     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8597                        N->getOperand(1), N->getOperand(2));
8598   case Intrinsic::aarch64_neon_fmaxnm:
8599     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8600                        N->getOperand(1), N->getOperand(2));
8601   case Intrinsic::aarch64_neon_fminnm:
8602     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8603                        N->getOperand(1), N->getOperand(2));
8604   case Intrinsic::aarch64_neon_smull:
8605   case Intrinsic::aarch64_neon_umull:
8606   case Intrinsic::aarch64_neon_pmull:
8607   case Intrinsic::aarch64_neon_sqdmull:
8608     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8609   case Intrinsic::aarch64_neon_sqshl:
8610   case Intrinsic::aarch64_neon_uqshl:
8611   case Intrinsic::aarch64_neon_sqshlu:
8612   case Intrinsic::aarch64_neon_srshl:
8613   case Intrinsic::aarch64_neon_urshl:
8614     return tryCombineShiftImm(IID, N, DAG);
8615   case Intrinsic::aarch64_crc32b:
8616   case Intrinsic::aarch64_crc32cb:
8617     return tryCombineCRC32(0xff, N, DAG);
8618   case Intrinsic::aarch64_crc32h:
8619   case Intrinsic::aarch64_crc32ch:
8620     return tryCombineCRC32(0xffff, N, DAG);
8621   }
8622   return SDValue();
8623 }
8624 
8625 static SDValue performExtendCombine(SDNode *N,
8626                                     TargetLowering::DAGCombinerInfo &DCI,
8627                                     SelectionDAG &DAG) {
8628   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8629   // we can convert that DUP into another extract_high (of a bigger DUP), which
8630   // helps the backend to decide that an sabdl2 would be useful, saving a real
8631   // extract_high operation.
8632   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8633       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8634     SDNode *ABDNode = N->getOperand(0).getNode();
8635     unsigned IID = getIntrinsicID(ABDNode);
8636     if (IID == Intrinsic::aarch64_neon_sabd ||
8637         IID == Intrinsic::aarch64_neon_uabd) {
8638       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8639       if (!NewABD.getNode())
8640         return SDValue();
8641 
8642       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8643                          NewABD);
8644     }
8645   }
8646 
8647   // This is effectively a custom type legalization for AArch64.
8648   //
8649   // Type legalization will split an extend of a small, legal, type to a larger
8650   // illegal type by first splitting the destination type, often creating
8651   // illegal source types, which then get legalized in isel-confusing ways,
8652   // leading to really terrible codegen. E.g.,
8653   //   %result = v8i32 sext v8i8 %value
8654   // becomes
8655   //   %losrc = extract_subreg %value, ...
8656   //   %hisrc = extract_subreg %value, ...
8657   //   %lo = v4i32 sext v4i8 %losrc
8658   //   %hi = v4i32 sext v4i8 %hisrc
8659   // Things go rapidly downhill from there.
8660   //
8661   // For AArch64, the [sz]ext vector instructions can only go up one element
8662   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8663   // take two instructions.
8664   //
8665   // This implies that the most efficient way to do the extend from v8i8
8666   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8667   // the normal splitting to happen for the v8i16->v8i32.
8668 
8669   // This is pre-legalization to catch some cases where the default
8670   // type legalization will create ill-tempered code.
8671   if (!DCI.isBeforeLegalizeOps())
8672     return SDValue();
8673 
8674   // We're only interested in cleaning things up for non-legal vector types
8675   // here. If both the source and destination are legal, things will just
8676   // work naturally without any fiddling.
8677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8678   EVT ResVT = N->getValueType(0);
8679   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8680     return SDValue();
8681   // If the vector type isn't a simple VT, it's beyond the scope of what
8682   // we're  worried about here. Let legalization do its thing and hope for
8683   // the best.
8684   SDValue Src = N->getOperand(0);
8685   EVT SrcVT = Src->getValueType(0);
8686   if (!ResVT.isSimple() || !SrcVT.isSimple())
8687     return SDValue();
8688 
8689   // If the source VT is a 64-bit vector, we can play games and get the
8690   // better results we want.
8691   if (SrcVT.getSizeInBits() != 64)
8692     return SDValue();
8693 
8694   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8695   unsigned ElementCount = SrcVT.getVectorNumElements();
8696   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8697   SDLoc DL(N);
8698   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8699 
8700   // Now split the rest of the operation into two halves, each with a 64
8701   // bit source.
8702   EVT LoVT, HiVT;
8703   SDValue Lo, Hi;
8704   unsigned NumElements = ResVT.getVectorNumElements();
8705   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8706   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8707                                  ResVT.getVectorElementType(), NumElements / 2);
8708 
8709   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8710                                LoVT.getVectorNumElements());
8711   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8712                    DAG.getConstant(0, DL, MVT::i64));
8713   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8714                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8715   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8716   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8717 
8718   // Now combine the parts back together so we still have a single result
8719   // like the combiner expects.
8720   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8721 }
8722 
8723 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8724 /// value. The load store optimizer pass will merge them to store pair stores.
8725 /// This has better performance than a splat of the scalar followed by a split
8726 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8727 /// followed by an ext.b and two stores.
8728 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8729   SDValue StVal = St->getValue();
8730   EVT VT = StVal.getValueType();
8731 
8732   // Don't replace floating point stores, they possibly won't be transformed to
8733   // stp because of the store pair suppress pass.
8734   if (VT.isFloatingPoint())
8735     return SDValue();
8736 
8737   // Check for insert vector elements.
8738   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8739     return SDValue();
8740 
8741   // We can express a splat as store pair(s) for 2 or 4 elements.
8742   unsigned NumVecElts = VT.getVectorNumElements();
8743   if (NumVecElts != 4 && NumVecElts != 2)
8744     return SDValue();
8745   SDValue SplatVal = StVal.getOperand(1);
8746   unsigned RemainInsertElts = NumVecElts - 1;
8747 
8748   // Check that this is a splat.
8749   while (--RemainInsertElts) {
8750     SDValue NextInsertElt = StVal.getOperand(0);
8751     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8752       return SDValue();
8753     if (NextInsertElt.getOperand(1) != SplatVal)
8754       return SDValue();
8755     StVal = NextInsertElt;
8756   }
8757   unsigned OrigAlignment = St->getAlignment();
8758   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8759   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8760 
8761   // Create scalar stores. This is at least as good as the code sequence for a
8762   // split unaligned store which is a dup.s, ext.b, and two stores.
8763   // Most of the time the three stores should be replaced by store pair
8764   // instructions (stp).
8765   SDLoc DL(St);
8766   SDValue BasePtr = St->getBasePtr();
8767   SDValue NewST1 =
8768       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8769                    St->getAlignment(), St->getMemOperand()->getFlags());
8770 
8771   unsigned Offset = EltOffset;
8772   while (--NumVecElts) {
8773     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8774                                     DAG.getConstant(Offset, DL, MVT::i64));
8775     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8776                           St->getPointerInfo(), Alignment,
8777                           St->getMemOperand()->getFlags());
8778     Offset += EltOffset;
8779   }
8780   return NewST1;
8781 }
8782 
8783 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8784                               SelectionDAG &DAG,
8785                               const AArch64Subtarget *Subtarget) {
8786   if (!DCI.isBeforeLegalize())
8787     return SDValue();
8788 
8789   StoreSDNode *S = cast<StoreSDNode>(N);
8790   if (S->isVolatile())
8791     return SDValue();
8792 
8793   // FIXME: The logic for deciding if an unaligned store should be split should
8794   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8795   // a call to that function here.
8796 
8797   if (!Subtarget->isMisaligned128StoreSlow())
8798     return SDValue();
8799 
8800   // Don't split at -Oz.
8801   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8802     return SDValue();
8803 
8804   SDValue StVal = S->getValue();
8805   EVT VT = StVal.getValueType();
8806 
8807   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8808   // those up regresses performance on micro-benchmarks and olden/bh.
8809   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8810     return SDValue();
8811 
8812   // Split unaligned 16B stores. They are terrible for performance.
8813   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8814   // extensions can use this to mark that it does not want splitting to happen
8815   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8816   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8817   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8818       S->getAlignment() <= 2)
8819     return SDValue();
8820 
8821   // If we get a splat of a scalar convert this vector store to a store of
8822   // scalars. They will be merged into store pairs thereby removing two
8823   // instructions.
8824   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8825     return ReplacedSplat;
8826 
8827   SDLoc DL(S);
8828   unsigned NumElts = VT.getVectorNumElements() / 2;
8829   // Split VT into two.
8830   EVT HalfVT =
8831       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8832   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8833                                    DAG.getConstant(0, DL, MVT::i64));
8834   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8835                                    DAG.getConstant(NumElts, DL, MVT::i64));
8836   SDValue BasePtr = S->getBasePtr();
8837   SDValue NewST1 =
8838       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8839                    S->getAlignment(), S->getMemOperand()->getFlags());
8840   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8841                                   DAG.getConstant(8, DL, MVT::i64));
8842   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8843                       S->getPointerInfo(), S->getAlignment(),
8844                       S->getMemOperand()->getFlags());
8845 }
8846 
8847 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8848 /// post-increment LD1R.
8849 static SDValue performPostLD1Combine(SDNode *N,
8850                                      TargetLowering::DAGCombinerInfo &DCI,
8851                                      bool IsLaneOp) {
8852   if (DCI.isBeforeLegalizeOps())
8853     return SDValue();
8854 
8855   SelectionDAG &DAG = DCI.DAG;
8856   EVT VT = N->getValueType(0);
8857 
8858   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8859   SDNode *LD = N->getOperand(LoadIdx).getNode();
8860   // If it is not LOAD, can not do such combine.
8861   if (LD->getOpcode() != ISD::LOAD)
8862     return SDValue();
8863 
8864   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8865   EVT MemVT = LoadSDN->getMemoryVT();
8866   // Check if memory operand is the same type as the vector element.
8867   if (MemVT != VT.getVectorElementType())
8868     return SDValue();
8869 
8870   // Check if there are other uses. If so, do not combine as it will introduce
8871   // an extra load.
8872   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8873        ++UI) {
8874     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8875       continue;
8876     if (*UI != N)
8877       return SDValue();
8878   }
8879 
8880   SDValue Addr = LD->getOperand(1);
8881   SDValue Vector = N->getOperand(0);
8882   // Search for a use of the address operand that is an increment.
8883   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8884        Addr.getNode()->use_end(); UI != UE; ++UI) {
8885     SDNode *User = *UI;
8886     if (User->getOpcode() != ISD::ADD
8887         || UI.getUse().getResNo() != Addr.getResNo())
8888       continue;
8889 
8890     // Check that the add is independent of the load.  Otherwise, folding it
8891     // would create a cycle.
8892     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8893       continue;
8894     // Also check that add is not used in the vector operand.  This would also
8895     // create a cycle.
8896     if (User->isPredecessorOf(Vector.getNode()))
8897       continue;
8898 
8899     // If the increment is a constant, it must match the memory ref size.
8900     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8901     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8902       uint32_t IncVal = CInc->getZExtValue();
8903       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8904       if (IncVal != NumBytes)
8905         continue;
8906       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8907     }
8908 
8909     // Finally, check that the vector doesn't depend on the load.
8910     // Again, this would create a cycle.
8911     // The load depending on the vector is fine, as that's the case for the
8912     // LD1*post we'll eventually generate anyway.
8913     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8914       continue;
8915 
8916     SmallVector<SDValue, 8> Ops;
8917     Ops.push_back(LD->getOperand(0));  // Chain
8918     if (IsLaneOp) {
8919       Ops.push_back(Vector);           // The vector to be inserted
8920       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8921     }
8922     Ops.push_back(Addr);
8923     Ops.push_back(Inc);
8924 
8925     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8926     SDVTList SDTys = DAG.getVTList(Tys);
8927     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8928     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8929                                            MemVT,
8930                                            LoadSDN->getMemOperand());
8931 
8932     // Update the uses.
8933     SDValue NewResults[] = {
8934         SDValue(LD, 0),            // The result of load
8935         SDValue(UpdN.getNode(), 2) // Chain
8936     };
8937     DCI.CombineTo(LD, NewResults);
8938     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8939     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8940 
8941     break;
8942   }
8943   return SDValue();
8944 }
8945 
8946 /// Simplify \Addr given that the top byte of it is ignored by HW during
8947 /// address translation.
8948 static bool performTBISimplification(SDValue Addr,
8949                                      TargetLowering::DAGCombinerInfo &DCI,
8950                                      SelectionDAG &DAG) {
8951   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8952   APInt KnownZero, KnownOne;
8953   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8954                                         DCI.isBeforeLegalizeOps());
8955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8956   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8957     DCI.CommitTargetLoweringOpt(TLO);
8958     return true;
8959   }
8960   return false;
8961 }
8962 
8963 static SDValue performSTORECombine(SDNode *N,
8964                                    TargetLowering::DAGCombinerInfo &DCI,
8965                                    SelectionDAG &DAG,
8966                                    const AArch64Subtarget *Subtarget) {
8967   if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
8968     return Split;
8969 
8970   if (Subtarget->supportsAddressTopByteIgnored() &&
8971       performTBISimplification(N->getOperand(2), DCI, DAG))
8972     return SDValue(N, 0);
8973 
8974   return SDValue();
8975 }
8976 
8977   /// This function handles the log2-shuffle pattern produced by the
8978 /// LoopVectorizer for the across vector reduction. It consists of
8979 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8980 /// are reduced, where s is an induction variable from 0 to
8981 /// log2(NumVectorElements).
8982 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8983                                                      unsigned Op,
8984                                                      SelectionDAG &DAG) {
8985   EVT VTy = OpV->getOperand(0).getValueType();
8986   if (!VTy.isVector())
8987     return SDValue();
8988 
8989   int NumVecElts = VTy.getVectorNumElements();
8990   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8991     if (NumVecElts != 4)
8992       return SDValue();
8993   } else {
8994     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8995       return SDValue();
8996   }
8997 
8998   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8999   SDValue PreOp = OpV;
9000   // Iterate over each step of the across vector reduction.
9001   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9002     SDValue CurOp = PreOp.getOperand(0);
9003     SDValue Shuffle = PreOp.getOperand(1);
9004     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9005       // Try to swap the 1st and 2nd operand as add and min/max instructions
9006       // are commutative.
9007       CurOp = PreOp.getOperand(1);
9008       Shuffle = PreOp.getOperand(0);
9009       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9010         return SDValue();
9011     }
9012 
9013     // Check if the input vector is fed by the operator we want to handle,
9014     // except the last step; the very first input vector is not necessarily
9015     // the same operator we are handling.
9016     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9017       return SDValue();
9018 
9019     // Check if it forms one step of the across vector reduction.
9020     // E.g.,
9021     //   %cur = add %1, %0
9022     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
9023     //   %pre = add %cur, %shuffle
9024     if (Shuffle.getOperand(0) != CurOp)
9025       return SDValue();
9026 
9027     int NumMaskElts = 1 << CurStep;
9028     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9029     // Check mask values in each step.
9030     // We expect the shuffle mask in each step follows a specific pattern
9031     // denoted here by the <M, U> form, where M is a sequence of integers
9032     // starting from NumMaskElts, increasing by 1, and the number integers
9033     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9034     // of undef in U should be NumVecElts - NumMaskElts.
9035     // E.g., for <8 x i16>, mask values in each step should be :
9036     //   step 0 : <1,u,u,u,u,u,u,u>
9037     //   step 1 : <2,3,u,u,u,u,u,u>
9038     //   step 2 : <4,5,6,7,u,u,u,u>
9039     for (int i = 0; i < NumVecElts; ++i)
9040       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9041           (i >= NumMaskElts && !(Mask[i] < 0)))
9042         return SDValue();
9043 
9044     PreOp = CurOp;
9045   }
9046   unsigned Opcode;
9047   bool IsIntrinsic = false;
9048 
9049   switch (Op) {
9050   default:
9051     llvm_unreachable("Unexpected operator for across vector reduction");
9052   case ISD::ADD:
9053     Opcode = AArch64ISD::UADDV;
9054     break;
9055   case ISD::SMAX:
9056     Opcode = AArch64ISD::SMAXV;
9057     break;
9058   case ISD::UMAX:
9059     Opcode = AArch64ISD::UMAXV;
9060     break;
9061   case ISD::SMIN:
9062     Opcode = AArch64ISD::SMINV;
9063     break;
9064   case ISD::UMIN:
9065     Opcode = AArch64ISD::UMINV;
9066     break;
9067   case ISD::FMAXNUM:
9068     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9069     IsIntrinsic = true;
9070     break;
9071   case ISD::FMINNUM:
9072     Opcode = Intrinsic::aarch64_neon_fminnmv;
9073     IsIntrinsic = true;
9074     break;
9075   }
9076   SDLoc DL(N);
9077 
9078   return IsIntrinsic
9079              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9080                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9081              : DAG.getNode(
9082                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9083                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9084                    DAG.getConstant(0, DL, MVT::i64));
9085 }
9086 
9087 /// Target-specific DAG combine for the across vector min/max reductions.
9088 /// This function specifically handles the final clean-up step of the vector
9089 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9090 /// pattern, which narrows down and finds the final min/max value from all
9091 /// elements of the vector.
9092 /// For example, for a <16 x i8> vector :
9093 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9094 ///   %smax0 = smax %arr, svn0
9095 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9096 ///   %smax1 = smax %smax0, %svn1
9097 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9098 ///   %smax2 = smax %smax1, svn2
9099 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9100 ///   %sc = setcc %smax2, %svn3, gt
9101 ///   %n0 = extract_vector_elt %sc, #0
9102 ///   %n1 = extract_vector_elt %smax2, #0
9103 ///   %n2 = extract_vector_elt $smax2, #1
9104 ///   %result = select %n0, %n1, n2
9105 ///     becomes :
9106 ///   %1 = smaxv %0
9107 ///   %result = extract_vector_elt %1, 0
9108 static SDValue
9109 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9110                                         const AArch64Subtarget *Subtarget) {
9111   if (!Subtarget->hasNEON())
9112     return SDValue();
9113 
9114   SDValue N0 = N->getOperand(0);
9115   SDValue IfTrue = N->getOperand(1);
9116   SDValue IfFalse = N->getOperand(2);
9117 
9118   // Check if the SELECT merges up the final result of the min/max
9119   // from a vector.
9120   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9121       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9122       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9123     return SDValue();
9124 
9125   // Expect N0 is fed by SETCC.
9126   SDValue SetCC = N0.getOperand(0);
9127   EVT SetCCVT = SetCC.getValueType();
9128   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9129       SetCCVT.getVectorElementType() != MVT::i1)
9130     return SDValue();
9131 
9132   SDValue VectorOp = SetCC.getOperand(0);
9133   unsigned Op = VectorOp->getOpcode();
9134   // Check if the input vector is fed by the operator we want to handle.
9135   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9136       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9137     return SDValue();
9138 
9139   EVT VTy = VectorOp.getValueType();
9140   if (!VTy.isVector())
9141     return SDValue();
9142 
9143   if (VTy.getSizeInBits() < 64)
9144     return SDValue();
9145 
9146   EVT EltTy = VTy.getVectorElementType();
9147   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9148     if (EltTy != MVT::f32)
9149       return SDValue();
9150   } else {
9151     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9152       return SDValue();
9153   }
9154 
9155   // Check if extracting from the same vector.
9156   // For example,
9157   //   %sc = setcc %vector, %svn1, gt
9158   //   %n0 = extract_vector_elt %sc, #0
9159   //   %n1 = extract_vector_elt %vector, #0
9160   //   %n2 = extract_vector_elt $vector, #1
9161   if (!(VectorOp == IfTrue->getOperand(0) &&
9162         VectorOp == IfFalse->getOperand(0)))
9163     return SDValue();
9164 
9165   // Check if the condition code is matched with the operator type.
9166   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9167   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9168       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9169       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9170       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9171       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9172        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9173        CC != ISD::SETGE) ||
9174       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9175        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9176        CC != ISD::SETLE))
9177     return SDValue();
9178 
9179   // Expect to check only lane 0 from the vector SETCC.
9180   if (!isNullConstant(N0.getOperand(1)))
9181     return SDValue();
9182 
9183   // Expect to extract the true value from lane 0.
9184   if (!isNullConstant(IfTrue.getOperand(1)))
9185     return SDValue();
9186 
9187   // Expect to extract the false value from lane 1.
9188   if (!isOneConstant(IfFalse.getOperand(1)))
9189     return SDValue();
9190 
9191   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9192 }
9193 
9194 /// Target-specific DAG combine for the across vector add reduction.
9195 /// This function specifically handles the final clean-up step of the vector
9196 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9197 /// pattern, which adds all elements of a vector together.
9198 /// For example, for a <4 x i32> vector :
9199 ///   %1 = vector_shuffle %0, <2,3,u,u>
9200 ///   %2 = add %0, %1
9201 ///   %3 = vector_shuffle %2, <1,u,u,u>
9202 ///   %4 = add %2, %3
9203 ///   %result = extract_vector_elt %4, 0
9204 /// becomes :
9205 ///   %0 = uaddv %0
9206 ///   %result = extract_vector_elt %0, 0
9207 static SDValue
9208 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9209                                      const AArch64Subtarget *Subtarget) {
9210   if (!Subtarget->hasNEON())
9211     return SDValue();
9212   SDValue N0 = N->getOperand(0);
9213   SDValue N1 = N->getOperand(1);
9214 
9215   // Check if the input vector is fed by the ADD.
9216   if (N0->getOpcode() != ISD::ADD)
9217     return SDValue();
9218 
9219   // The vector extract idx must constant zero because we only expect the final
9220   // result of the reduction is placed in lane 0.
9221   if (!isNullConstant(N1))
9222     return SDValue();
9223 
9224   EVT VTy = N0.getValueType();
9225   if (!VTy.isVector())
9226     return SDValue();
9227 
9228   EVT EltTy = VTy.getVectorElementType();
9229   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9230     return SDValue();
9231 
9232   if (VTy.getSizeInBits() < 64)
9233     return SDValue();
9234 
9235   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9236 }
9237 
9238 /// Target-specific DAG combine function for NEON load/store intrinsics
9239 /// to merge base address updates.
9240 static SDValue performNEONPostLDSTCombine(SDNode *N,
9241                                           TargetLowering::DAGCombinerInfo &DCI,
9242                                           SelectionDAG &DAG) {
9243   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9244     return SDValue();
9245 
9246   unsigned AddrOpIdx = N->getNumOperands() - 1;
9247   SDValue Addr = N->getOperand(AddrOpIdx);
9248 
9249   // Search for a use of the address operand that is an increment.
9250   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9251        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9252     SDNode *User = *UI;
9253     if (User->getOpcode() != ISD::ADD ||
9254         UI.getUse().getResNo() != Addr.getResNo())
9255       continue;
9256 
9257     // Check that the add is independent of the load/store.  Otherwise, folding
9258     // it would create a cycle.
9259     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9260       continue;
9261 
9262     // Find the new opcode for the updating load/store.
9263     bool IsStore = false;
9264     bool IsLaneOp = false;
9265     bool IsDupOp = false;
9266     unsigned NewOpc = 0;
9267     unsigned NumVecs = 0;
9268     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9269     switch (IntNo) {
9270     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9271     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9272       NumVecs = 2; break;
9273     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9274       NumVecs = 3; break;
9275     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9276       NumVecs = 4; break;
9277     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9278       NumVecs = 2; IsStore = true; break;
9279     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9280       NumVecs = 3; IsStore = true; break;
9281     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9282       NumVecs = 4; IsStore = true; break;
9283     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9284       NumVecs = 2; break;
9285     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9286       NumVecs = 3; break;
9287     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9288       NumVecs = 4; break;
9289     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9290       NumVecs = 2; IsStore = true; break;
9291     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9292       NumVecs = 3; IsStore = true; break;
9293     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9294       NumVecs = 4; IsStore = true; break;
9295     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9296       NumVecs = 2; IsDupOp = true; break;
9297     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9298       NumVecs = 3; IsDupOp = true; break;
9299     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9300       NumVecs = 4; IsDupOp = true; break;
9301     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9302       NumVecs = 2; IsLaneOp = true; break;
9303     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9304       NumVecs = 3; IsLaneOp = true; break;
9305     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9306       NumVecs = 4; IsLaneOp = true; break;
9307     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9308       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9309     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9310       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9311     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9312       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9313     }
9314 
9315     EVT VecTy;
9316     if (IsStore)
9317       VecTy = N->getOperand(2).getValueType();
9318     else
9319       VecTy = N->getValueType(0);
9320 
9321     // If the increment is a constant, it must match the memory ref size.
9322     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9323     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9324       uint32_t IncVal = CInc->getZExtValue();
9325       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9326       if (IsLaneOp || IsDupOp)
9327         NumBytes /= VecTy.getVectorNumElements();
9328       if (IncVal != NumBytes)
9329         continue;
9330       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9331     }
9332     SmallVector<SDValue, 8> Ops;
9333     Ops.push_back(N->getOperand(0)); // Incoming chain
9334     // Load lane and store have vector list as input.
9335     if (IsLaneOp || IsStore)
9336       for (unsigned i = 2; i < AddrOpIdx; ++i)
9337         Ops.push_back(N->getOperand(i));
9338     Ops.push_back(Addr); // Base register
9339     Ops.push_back(Inc);
9340 
9341     // Return Types.
9342     EVT Tys[6];
9343     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9344     unsigned n;
9345     for (n = 0; n < NumResultVecs; ++n)
9346       Tys[n] = VecTy;
9347     Tys[n++] = MVT::i64;  // Type of write back register
9348     Tys[n] = MVT::Other;  // Type of the chain
9349     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9350 
9351     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9352     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9353                                            MemInt->getMemoryVT(),
9354                                            MemInt->getMemOperand());
9355 
9356     // Update the uses.
9357     std::vector<SDValue> NewResults;
9358     for (unsigned i = 0; i < NumResultVecs; ++i) {
9359       NewResults.push_back(SDValue(UpdN.getNode(), i));
9360     }
9361     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9362     DCI.CombineTo(N, NewResults);
9363     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9364 
9365     break;
9366   }
9367   return SDValue();
9368 }
9369 
9370 // Checks to see if the value is the prescribed width and returns information
9371 // about its extension mode.
9372 static
9373 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9374   ExtType = ISD::NON_EXTLOAD;
9375   switch(V.getNode()->getOpcode()) {
9376   default:
9377     return false;
9378   case ISD::LOAD: {
9379     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9380     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9381        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9382       ExtType = LoadNode->getExtensionType();
9383       return true;
9384     }
9385     return false;
9386   }
9387   case ISD::AssertSext: {
9388     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9389     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9390        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9391       ExtType = ISD::SEXTLOAD;
9392       return true;
9393     }
9394     return false;
9395   }
9396   case ISD::AssertZext: {
9397     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9398     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9399        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9400       ExtType = ISD::ZEXTLOAD;
9401       return true;
9402     }
9403     return false;
9404   }
9405   case ISD::Constant:
9406   case ISD::TargetConstant: {
9407     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9408            1LL << (width - 1);
9409   }
9410   }
9411 
9412   return true;
9413 }
9414 
9415 // This function does a whole lot of voodoo to determine if the tests are
9416 // equivalent without and with a mask. Essentially what happens is that given a
9417 // DAG resembling:
9418 //
9419 //  +-------------+ +-------------+ +-------------+ +-------------+
9420 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9421 //  +-------------+ +-------------+ +-------------+ +-------------+
9422 //           |           |           |               |
9423 //           V           V           |    +----------+
9424 //          +-------------+  +----+  |    |
9425 //          |     ADD     |  |0xff|  |    |
9426 //          +-------------+  +----+  |    |
9427 //                  |           |    |    |
9428 //                  V           V    |    |
9429 //                 +-------------+   |    |
9430 //                 |     AND     |   |    |
9431 //                 +-------------+   |    |
9432 //                      |            |    |
9433 //                      +-----+      |    |
9434 //                            |      |    |
9435 //                            V      V    V
9436 //                           +-------------+
9437 //                           |     CMP     |
9438 //                           +-------------+
9439 //
9440 // The AND node may be safely removed for some combinations of inputs. In
9441 // particular we need to take into account the extension type of the Input,
9442 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9443 // width of the input (this can work for any width inputs, the above graph is
9444 // specific to 8 bits.
9445 //
9446 // The specific equations were worked out by generating output tables for each
9447 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9448 // problem was simplified by working with 4 bit inputs, which means we only
9449 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9450 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9451 // patterns present in both extensions (0,7). For every distinct set of
9452 // AddConstant and CompConstants bit patterns we can consider the masked and
9453 // unmasked versions to be equivalent if the result of this function is true for
9454 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9455 //
9456 //   sub      w8, w0, w1
9457 //   and      w10, w8, #0x0f
9458 //   cmp      w8, w2
9459 //   cset     w9, AArch64CC
9460 //   cmp      w10, w2
9461 //   cset     w11, AArch64CC
9462 //   cmp      w9, w11
9463 //   cset     w0, eq
9464 //   ret
9465 //
9466 // Since the above function shows when the outputs are equivalent it defines
9467 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9468 // would be expensive to run during compiles. The equations below were written
9469 // in a test harness that confirmed they gave equivalent outputs to the above
9470 // for all inputs function, so they can be used determine if the removal is
9471 // legal instead.
9472 //
9473 // isEquivalentMaskless() is the code for testing if the AND can be removed
9474 // factored out of the DAG recognition as the DAG can take several forms.
9475 
9476 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9477                                  ISD::LoadExtType ExtType, int AddConstant,
9478                                  int CompConstant) {
9479   // By being careful about our equations and only writing the in term
9480   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9481   // make them generally applicable to all bit widths.
9482   int MaxUInt = (1 << width);
9483 
9484   // For the purposes of these comparisons sign extending the type is
9485   // equivalent to zero extending the add and displacing it by half the integer
9486   // width. Provided we are careful and make sure our equations are valid over
9487   // the whole range we can just adjust the input and avoid writing equations
9488   // for sign extended inputs.
9489   if (ExtType == ISD::SEXTLOAD)
9490     AddConstant -= (1 << (width-1));
9491 
9492   switch(CC) {
9493   case AArch64CC::LE:
9494   case AArch64CC::GT: {
9495     if ((AddConstant == 0) ||
9496         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9497         (AddConstant >= 0 && CompConstant < 0) ||
9498         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9499       return true;
9500   } break;
9501   case AArch64CC::LT:
9502   case AArch64CC::GE: {
9503     if ((AddConstant == 0) ||
9504         (AddConstant >= 0 && CompConstant <= 0) ||
9505         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9506       return true;
9507   } break;
9508   case AArch64CC::HI:
9509   case AArch64CC::LS: {
9510     if ((AddConstant >= 0 && CompConstant < 0) ||
9511        (AddConstant <= 0 && CompConstant >= -1 &&
9512         CompConstant < AddConstant + MaxUInt))
9513       return true;
9514   } break;
9515   case AArch64CC::PL:
9516   case AArch64CC::MI: {
9517     if ((AddConstant == 0) ||
9518         (AddConstant > 0 && CompConstant <= 0) ||
9519         (AddConstant < 0 && CompConstant <= AddConstant))
9520       return true;
9521   } break;
9522   case AArch64CC::LO:
9523   case AArch64CC::HS: {
9524     if ((AddConstant >= 0 && CompConstant <= 0) ||
9525         (AddConstant <= 0 && CompConstant >= 0 &&
9526          CompConstant <= AddConstant + MaxUInt))
9527       return true;
9528   } break;
9529   case AArch64CC::EQ:
9530   case AArch64CC::NE: {
9531     if ((AddConstant > 0 && CompConstant < 0) ||
9532         (AddConstant < 0 && CompConstant >= 0 &&
9533          CompConstant < AddConstant + MaxUInt) ||
9534         (AddConstant >= 0 && CompConstant >= 0 &&
9535          CompConstant >= AddConstant) ||
9536         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9537 
9538       return true;
9539   } break;
9540   case AArch64CC::VS:
9541   case AArch64CC::VC:
9542   case AArch64CC::AL:
9543   case AArch64CC::NV:
9544     return true;
9545   case AArch64CC::Invalid:
9546     break;
9547   }
9548 
9549   return false;
9550 }
9551 
9552 static
9553 SDValue performCONDCombine(SDNode *N,
9554                            TargetLowering::DAGCombinerInfo &DCI,
9555                            SelectionDAG &DAG, unsigned CCIndex,
9556                            unsigned CmpIndex) {
9557   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9558   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9559   unsigned CondOpcode = SubsNode->getOpcode();
9560 
9561   if (CondOpcode != AArch64ISD::SUBS)
9562     return SDValue();
9563 
9564   // There is a SUBS feeding this condition. Is it fed by a mask we can
9565   // use?
9566 
9567   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9568   unsigned MaskBits = 0;
9569 
9570   if (AndNode->getOpcode() != ISD::AND)
9571     return SDValue();
9572 
9573   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9574     uint32_t CNV = CN->getZExtValue();
9575     if (CNV == 255)
9576       MaskBits = 8;
9577     else if (CNV == 65535)
9578       MaskBits = 16;
9579   }
9580 
9581   if (!MaskBits)
9582     return SDValue();
9583 
9584   SDValue AddValue = AndNode->getOperand(0);
9585 
9586   if (AddValue.getOpcode() != ISD::ADD)
9587     return SDValue();
9588 
9589   // The basic dag structure is correct, grab the inputs and validate them.
9590 
9591   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9592   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9593   SDValue SubsInputValue = SubsNode->getOperand(1);
9594 
9595   // The mask is present and the provenance of all the values is a smaller type,
9596   // lets see if the mask is superfluous.
9597 
9598   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9599       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9600     return SDValue();
9601 
9602   ISD::LoadExtType ExtType;
9603 
9604   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9605       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9606       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9607     return SDValue();
9608 
9609   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9610                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9611                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9612     return SDValue();
9613 
9614   // The AND is not necessary, remove it.
9615 
9616   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9617                                SubsNode->getValueType(1));
9618   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9619 
9620   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9621   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9622 
9623   return SDValue(N, 0);
9624 }
9625 
9626 // Optimize compare with zero and branch.
9627 static SDValue performBRCONDCombine(SDNode *N,
9628                                     TargetLowering::DAGCombinerInfo &DCI,
9629                                     SelectionDAG &DAG) {
9630   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9631     N = NV.getNode();
9632   SDValue Chain = N->getOperand(0);
9633   SDValue Dest = N->getOperand(1);
9634   SDValue CCVal = N->getOperand(2);
9635   SDValue Cmp = N->getOperand(3);
9636 
9637   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9638   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9639   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9640     return SDValue();
9641 
9642   unsigned CmpOpc = Cmp.getOpcode();
9643   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9644     return SDValue();
9645 
9646   // Only attempt folding if there is only one use of the flag and no use of the
9647   // value.
9648   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9649     return SDValue();
9650 
9651   SDValue LHS = Cmp.getOperand(0);
9652   SDValue RHS = Cmp.getOperand(1);
9653 
9654   assert(LHS.getValueType() == RHS.getValueType() &&
9655          "Expected the value type to be the same for both operands!");
9656   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9657     return SDValue();
9658 
9659   if (isNullConstant(LHS))
9660     std::swap(LHS, RHS);
9661 
9662   if (!isNullConstant(RHS))
9663     return SDValue();
9664 
9665   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9666       LHS.getOpcode() == ISD::SRL)
9667     return SDValue();
9668 
9669   // Fold the compare into the branch instruction.
9670   SDValue BR;
9671   if (CC == AArch64CC::EQ)
9672     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9673   else
9674     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9675 
9676   // Do not add new nodes to DAG combiner worklist.
9677   DCI.CombineTo(N, BR, false);
9678 
9679   return SDValue();
9680 }
9681 
9682 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9683 // as well as whether the test should be inverted.  This code is required to
9684 // catch these cases (as opposed to standard dag combines) because
9685 // AArch64ISD::TBZ is matched during legalization.
9686 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9687                                  SelectionDAG &DAG) {
9688 
9689   if (!Op->hasOneUse())
9690     return Op;
9691 
9692   // We don't handle undef/constant-fold cases below, as they should have
9693   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9694   // etc.)
9695 
9696   // (tbz (trunc x), b) -> (tbz x, b)
9697   // This case is just here to enable more of the below cases to be caught.
9698   if (Op->getOpcode() == ISD::TRUNCATE &&
9699       Bit < Op->getValueType(0).getSizeInBits()) {
9700     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9701   }
9702 
9703   if (Op->getNumOperands() != 2)
9704     return Op;
9705 
9706   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9707   if (!C)
9708     return Op;
9709 
9710   switch (Op->getOpcode()) {
9711   default:
9712     return Op;
9713 
9714   // (tbz (and x, m), b) -> (tbz x, b)
9715   case ISD::AND:
9716     if ((C->getZExtValue() >> Bit) & 1)
9717       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9718     return Op;
9719 
9720   // (tbz (shl x, c), b) -> (tbz x, b-c)
9721   case ISD::SHL:
9722     if (C->getZExtValue() <= Bit &&
9723         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9724       Bit = Bit - C->getZExtValue();
9725       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9726     }
9727     return Op;
9728 
9729   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9730   case ISD::SRA:
9731     Bit = Bit + C->getZExtValue();
9732     if (Bit >= Op->getValueType(0).getSizeInBits())
9733       Bit = Op->getValueType(0).getSizeInBits() - 1;
9734     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9735 
9736   // (tbz (srl x, c), b) -> (tbz x, b+c)
9737   case ISD::SRL:
9738     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9739       Bit = Bit + C->getZExtValue();
9740       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9741     }
9742     return Op;
9743 
9744   // (tbz (xor x, -1), b) -> (tbnz x, b)
9745   case ISD::XOR:
9746     if ((C->getZExtValue() >> Bit) & 1)
9747       Invert = !Invert;
9748     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9749   }
9750 }
9751 
9752 // Optimize test single bit zero/non-zero and branch.
9753 static SDValue performTBZCombine(SDNode *N,
9754                                  TargetLowering::DAGCombinerInfo &DCI,
9755                                  SelectionDAG &DAG) {
9756   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9757   bool Invert = false;
9758   SDValue TestSrc = N->getOperand(1);
9759   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9760 
9761   if (TestSrc == NewTestSrc)
9762     return SDValue();
9763 
9764   unsigned NewOpc = N->getOpcode();
9765   if (Invert) {
9766     if (NewOpc == AArch64ISD::TBZ)
9767       NewOpc = AArch64ISD::TBNZ;
9768     else {
9769       assert(NewOpc == AArch64ISD::TBNZ);
9770       NewOpc = AArch64ISD::TBZ;
9771     }
9772   }
9773 
9774   SDLoc DL(N);
9775   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9776                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9777 }
9778 
9779 // vselect (v1i1 setcc) ->
9780 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9781 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9782 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9783 // such VSELECT.
9784 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9785   SDValue N0 = N->getOperand(0);
9786   EVT CCVT = N0.getValueType();
9787 
9788   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9789       CCVT.getVectorElementType() != MVT::i1)
9790     return SDValue();
9791 
9792   EVT ResVT = N->getValueType(0);
9793   EVT CmpVT = N0.getOperand(0).getValueType();
9794   // Only combine when the result type is of the same size as the compared
9795   // operands.
9796   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9797     return SDValue();
9798 
9799   SDValue IfTrue = N->getOperand(1);
9800   SDValue IfFalse = N->getOperand(2);
9801   SDValue SetCC =
9802       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9803                    N0.getOperand(0), N0.getOperand(1),
9804                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9805   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9806                      IfTrue, IfFalse);
9807 }
9808 
9809 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9810 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9811 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9812 /// with a vector one followed by a DUP shuffle on the result.
9813 static SDValue performSelectCombine(SDNode *N,
9814                                     TargetLowering::DAGCombinerInfo &DCI) {
9815   SelectionDAG &DAG = DCI.DAG;
9816   SDValue N0 = N->getOperand(0);
9817   EVT ResVT = N->getValueType(0);
9818 
9819   if (N0.getOpcode() != ISD::SETCC)
9820     return SDValue();
9821 
9822   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9823   // scalar SetCCResultType. We also don't expect vectors, because we assume
9824   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9825   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9826          "Scalar-SETCC feeding SELECT has unexpected result type!");
9827 
9828   // If NumMaskElts == 0, the comparison is larger than select result. The
9829   // largest real NEON comparison is 64-bits per lane, which means the result is
9830   // at most 32-bits and an illegal vector. Just bail out for now.
9831   EVT SrcVT = N0.getOperand(0).getValueType();
9832 
9833   // Don't try to do this optimization when the setcc itself has i1 operands.
9834   // There are no legal vectors of i1, so this would be pointless.
9835   if (SrcVT == MVT::i1)
9836     return SDValue();
9837 
9838   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9839   if (!ResVT.isVector() || NumMaskElts == 0)
9840     return SDValue();
9841 
9842   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9843   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9844 
9845   // Also bail out if the vector CCVT isn't the same size as ResVT.
9846   // This can happen if the SETCC operand size doesn't divide the ResVT size
9847   // (e.g., f64 vs v3f32).
9848   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9849     return SDValue();
9850 
9851   // Make sure we didn't create illegal types, if we're not supposed to.
9852   assert(DCI.isBeforeLegalize() ||
9853          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9854 
9855   // First perform a vector comparison, where lane 0 is the one we're interested
9856   // in.
9857   SDLoc DL(N0);
9858   SDValue LHS =
9859       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9860   SDValue RHS =
9861       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9862   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9863 
9864   // Now duplicate the comparison mask we want across all other lanes.
9865   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9866   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
9867   Mask = DAG.getNode(ISD::BITCAST, DL,
9868                      ResVT.changeVectorElementTypeToInteger(), Mask);
9869 
9870   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9871 }
9872 
9873 /// Get rid of unnecessary NVCASTs (that don't change the type).
9874 static SDValue performNVCASTCombine(SDNode *N) {
9875   if (N->getValueType(0) == N->getOperand(0).getValueType())
9876     return N->getOperand(0);
9877 
9878   return SDValue();
9879 }
9880 
9881 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9882                                                  DAGCombinerInfo &DCI) const {
9883   SelectionDAG &DAG = DCI.DAG;
9884   switch (N->getOpcode()) {
9885   default:
9886     break;
9887   case ISD::ADD:
9888   case ISD::SUB:
9889     return performAddSubLongCombine(N, DCI, DAG);
9890   case ISD::XOR:
9891     return performXorCombine(N, DAG, DCI, Subtarget);
9892   case ISD::MUL:
9893     return performMulCombine(N, DAG, DCI, Subtarget);
9894   case ISD::SINT_TO_FP:
9895   case ISD::UINT_TO_FP:
9896     return performIntToFpCombine(N, DAG, Subtarget);
9897   case ISD::FP_TO_SINT:
9898   case ISD::FP_TO_UINT:
9899     return performFpToIntCombine(N, DAG, DCI, Subtarget);
9900   case ISD::FDIV:
9901     return performFDivCombine(N, DAG, DCI, Subtarget);
9902   case ISD::OR:
9903     return performORCombine(N, DCI, Subtarget);
9904   case ISD::SRL:
9905     return performSRLCombine(N, DCI);
9906   case ISD::INTRINSIC_WO_CHAIN:
9907     return performIntrinsicCombine(N, DCI, Subtarget);
9908   case ISD::ANY_EXTEND:
9909   case ISD::ZERO_EXTEND:
9910   case ISD::SIGN_EXTEND:
9911     return performExtendCombine(N, DCI, DAG);
9912   case ISD::BITCAST:
9913     return performBitcastCombine(N, DCI, DAG);
9914   case ISD::CONCAT_VECTORS:
9915     return performConcatVectorsCombine(N, DCI, DAG);
9916   case ISD::SELECT: {
9917     SDValue RV = performSelectCombine(N, DCI);
9918     if (!RV.getNode())
9919       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9920     return RV;
9921   }
9922   case ISD::VSELECT:
9923     return performVSelectCombine(N, DCI.DAG);
9924   case ISD::LOAD:
9925     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9926       return SDValue(N, 0);
9927     break;
9928   case ISD::STORE:
9929     return performSTORECombine(N, DCI, DAG, Subtarget);
9930   case AArch64ISD::BRCOND:
9931     return performBRCONDCombine(N, DCI, DAG);
9932   case AArch64ISD::TBNZ:
9933   case AArch64ISD::TBZ:
9934     return performTBZCombine(N, DCI, DAG);
9935   case AArch64ISD::CSEL:
9936     return performCONDCombine(N, DCI, DAG, 2, 3);
9937   case AArch64ISD::DUP:
9938     return performPostLD1Combine(N, DCI, false);
9939   case AArch64ISD::NVCAST:
9940     return performNVCASTCombine(N);
9941   case ISD::INSERT_VECTOR_ELT:
9942     return performPostLD1Combine(N, DCI, true);
9943   case ISD::EXTRACT_VECTOR_ELT:
9944     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9945   case ISD::INTRINSIC_VOID:
9946   case ISD::INTRINSIC_W_CHAIN:
9947     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9948     case Intrinsic::aarch64_neon_ld2:
9949     case Intrinsic::aarch64_neon_ld3:
9950     case Intrinsic::aarch64_neon_ld4:
9951     case Intrinsic::aarch64_neon_ld1x2:
9952     case Intrinsic::aarch64_neon_ld1x3:
9953     case Intrinsic::aarch64_neon_ld1x4:
9954     case Intrinsic::aarch64_neon_ld2lane:
9955     case Intrinsic::aarch64_neon_ld3lane:
9956     case Intrinsic::aarch64_neon_ld4lane:
9957     case Intrinsic::aarch64_neon_ld2r:
9958     case Intrinsic::aarch64_neon_ld3r:
9959     case Intrinsic::aarch64_neon_ld4r:
9960     case Intrinsic::aarch64_neon_st2:
9961     case Intrinsic::aarch64_neon_st3:
9962     case Intrinsic::aarch64_neon_st4:
9963     case Intrinsic::aarch64_neon_st1x2:
9964     case Intrinsic::aarch64_neon_st1x3:
9965     case Intrinsic::aarch64_neon_st1x4:
9966     case Intrinsic::aarch64_neon_st2lane:
9967     case Intrinsic::aarch64_neon_st3lane:
9968     case Intrinsic::aarch64_neon_st4lane:
9969       return performNEONPostLDSTCombine(N, DCI, DAG);
9970     default:
9971       break;
9972     }
9973   }
9974   return SDValue();
9975 }
9976 
9977 // Check if the return value is used as only a return value, as otherwise
9978 // we can't perform a tail-call. In particular, we need to check for
9979 // target ISD nodes that are returns and any other "odd" constructs
9980 // that the generic analysis code won't necessarily catch.
9981 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9982                                                SDValue &Chain) const {
9983   if (N->getNumValues() != 1)
9984     return false;
9985   if (!N->hasNUsesOfValue(1, 0))
9986     return false;
9987 
9988   SDValue TCChain = Chain;
9989   SDNode *Copy = *N->use_begin();
9990   if (Copy->getOpcode() == ISD::CopyToReg) {
9991     // If the copy has a glue operand, we conservatively assume it isn't safe to
9992     // perform a tail call.
9993     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9994         MVT::Glue)
9995       return false;
9996     TCChain = Copy->getOperand(0);
9997   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9998     return false;
9999 
10000   bool HasRet = false;
10001   for (SDNode *Node : Copy->uses()) {
10002     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10003       return false;
10004     HasRet = true;
10005   }
10006 
10007   if (!HasRet)
10008     return false;
10009 
10010   Chain = TCChain;
10011   return true;
10012 }
10013 
10014 // Return whether the an instruction can potentially be optimized to a tail
10015 // call. This will cause the optimizers to attempt to move, or duplicate,
10016 // return instructions to help enable tail call optimizations for this
10017 // instruction.
10018 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
10019   return CI->isTailCall();
10020 }
10021 
10022 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10023                                                    SDValue &Offset,
10024                                                    ISD::MemIndexedMode &AM,
10025                                                    bool &IsInc,
10026                                                    SelectionDAG &DAG) const {
10027   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10028     return false;
10029 
10030   Base = Op->getOperand(0);
10031   // All of the indexed addressing mode instructions take a signed
10032   // 9 bit immediate offset.
10033   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10034     int64_t RHSC = (int64_t)RHS->getZExtValue();
10035     if (RHSC >= 256 || RHSC <= -256)
10036       return false;
10037     IsInc = (Op->getOpcode() == ISD::ADD);
10038     Offset = Op->getOperand(1);
10039     return true;
10040   }
10041   return false;
10042 }
10043 
10044 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10045                                                       SDValue &Offset,
10046                                                       ISD::MemIndexedMode &AM,
10047                                                       SelectionDAG &DAG) const {
10048   EVT VT;
10049   SDValue Ptr;
10050   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10051     VT = LD->getMemoryVT();
10052     Ptr = LD->getBasePtr();
10053   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10054     VT = ST->getMemoryVT();
10055     Ptr = ST->getBasePtr();
10056   } else
10057     return false;
10058 
10059   bool IsInc;
10060   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10061     return false;
10062   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10063   return true;
10064 }
10065 
10066 bool AArch64TargetLowering::getPostIndexedAddressParts(
10067     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10068     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10069   EVT VT;
10070   SDValue Ptr;
10071   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10072     VT = LD->getMemoryVT();
10073     Ptr = LD->getBasePtr();
10074   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10075     VT = ST->getMemoryVT();
10076     Ptr = ST->getBasePtr();
10077   } else
10078     return false;
10079 
10080   bool IsInc;
10081   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10082     return false;
10083   // Post-indexing updates the base, so it's not a valid transform
10084   // if that's not the same as the load's pointer.
10085   if (Ptr != Base)
10086     return false;
10087   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10088   return true;
10089 }
10090 
10091 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10092                                   SelectionDAG &DAG) {
10093   SDLoc DL(N);
10094   SDValue Op = N->getOperand(0);
10095 
10096   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10097     return;
10098 
10099   Op = SDValue(
10100       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10101                          DAG.getUNDEF(MVT::i32), Op,
10102                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10103       0);
10104   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10105   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10106 }
10107 
10108 static void ReplaceReductionResults(SDNode *N,
10109                                     SmallVectorImpl<SDValue> &Results,
10110                                     SelectionDAG &DAG, unsigned InterOp,
10111                                     unsigned AcrossOp) {
10112   EVT LoVT, HiVT;
10113   SDValue Lo, Hi;
10114   SDLoc dl(N);
10115   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10116   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10117   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10118   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10119   Results.push_back(SplitVal);
10120 }
10121 
10122 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10123   SDLoc DL(N);
10124   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10125   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10126                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10127                                        DAG.getConstant(64, DL, MVT::i64)));
10128   return std::make_pair(Lo, Hi);
10129 }
10130 
10131 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10132                                        SmallVectorImpl<SDValue> & Results,
10133                                        SelectionDAG &DAG) {
10134   assert(N->getValueType(0) == MVT::i128 &&
10135          "AtomicCmpSwap on types less than 128 should be legal");
10136   auto Desired = splitInt128(N->getOperand(2), DAG);
10137   auto New = splitInt128(N->getOperand(3), DAG);
10138   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10139                    New.first,        New.second,    N->getOperand(0)};
10140   SDNode *CmpSwap = DAG.getMachineNode(
10141       AArch64::CMP_SWAP_128, SDLoc(N),
10142       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10143 
10144   MachineFunction &MF = DAG.getMachineFunction();
10145   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10146   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10147   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10148 
10149   Results.push_back(SDValue(CmpSwap, 0));
10150   Results.push_back(SDValue(CmpSwap, 1));
10151   Results.push_back(SDValue(CmpSwap, 3));
10152 }
10153 
10154 void AArch64TargetLowering::ReplaceNodeResults(
10155     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10156   switch (N->getOpcode()) {
10157   default:
10158     llvm_unreachable("Don't know how to custom expand this");
10159   case ISD::BITCAST:
10160     ReplaceBITCASTResults(N, Results, DAG);
10161     return;
10162   case AArch64ISD::SADDV:
10163     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10164     return;
10165   case AArch64ISD::UADDV:
10166     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10167     return;
10168   case AArch64ISD::SMINV:
10169     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10170     return;
10171   case AArch64ISD::UMINV:
10172     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10173     return;
10174   case AArch64ISD::SMAXV:
10175     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10176     return;
10177   case AArch64ISD::UMAXV:
10178     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10179     return;
10180   case ISD::FP_TO_UINT:
10181   case ISD::FP_TO_SINT:
10182     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10183     // Let normal code take care of it by not adding anything to Results.
10184     return;
10185   case ISD::ATOMIC_CMP_SWAP:
10186     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10187     return;
10188   }
10189 }
10190 
10191 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10192   if (!Subtarget->isTargetAndroid())
10193     return true;
10194   return TargetLowering::useLoadStackGuardNode();
10195 }
10196 
10197 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10198   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10199   // reciprocal if there are three or more FDIVs.
10200   return 3;
10201 }
10202 
10203 TargetLoweringBase::LegalizeTypeAction
10204 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10205   MVT SVT = VT.getSimpleVT();
10206   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10207   // v4i16, v2i32 instead of to promote.
10208   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10209       || SVT == MVT::v1f32)
10210     return TypeWidenVector;
10211 
10212   return TargetLoweringBase::getPreferredVectorAction(VT);
10213 }
10214 
10215 // Loads and stores less than 128-bits are already atomic; ones above that
10216 // are doomed anyway, so defer to the default libcall and blame the OS when
10217 // things go wrong.
10218 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10219   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10220   return Size == 128;
10221 }
10222 
10223 // Loads and stores less than 128-bits are already atomic; ones above that
10224 // are doomed anyway, so defer to the default libcall and blame the OS when
10225 // things go wrong.
10226 TargetLowering::AtomicExpansionKind
10227 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10228   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10229   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10230 }
10231 
10232 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10233 TargetLowering::AtomicExpansionKind
10234 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10235   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10236   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10237 }
10238 
10239 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10240     AtomicCmpXchgInst *AI) const {
10241   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10242   // implement cmpxchg without spilling. If the address being exchanged is also
10243   // on the stack and close enough to the spill slot, this can lead to a
10244   // situation where the monitor always gets cleared and the atomic operation
10245   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10246   return getTargetMachine().getOptLevel() != 0;
10247 }
10248 
10249 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10250                                              AtomicOrdering Ord) const {
10251   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10252   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10253   bool IsAcquire = isAcquireOrStronger(Ord);
10254 
10255   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10256   // intrinsic must return {i64, i64} and we have to recombine them into a
10257   // single i128 here.
10258   if (ValTy->getPrimitiveSizeInBits() == 128) {
10259     Intrinsic::ID Int =
10260         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10261     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10262 
10263     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10264     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10265 
10266     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10267     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10268     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10269     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10270     return Builder.CreateOr(
10271         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10272   }
10273 
10274   Type *Tys[] = { Addr->getType() };
10275   Intrinsic::ID Int =
10276       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10277   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10278 
10279   return Builder.CreateTruncOrBitCast(
10280       Builder.CreateCall(Ldxr, Addr),
10281       cast<PointerType>(Addr->getType())->getElementType());
10282 }
10283 
10284 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10285     IRBuilder<> &Builder) const {
10286   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10287   Builder.CreateCall(
10288       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10289 }
10290 
10291 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10292                                                    Value *Val, Value *Addr,
10293                                                    AtomicOrdering Ord) const {
10294   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10295   bool IsRelease = isReleaseOrStronger(Ord);
10296 
10297   // Since the intrinsics must have legal type, the i128 intrinsics take two
10298   // parameters: "i64, i64". We must marshal Val into the appropriate form
10299   // before the call.
10300   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10301     Intrinsic::ID Int =
10302         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10303     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10304     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10305 
10306     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10307     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10308     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10309     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10310   }
10311 
10312   Intrinsic::ID Int =
10313       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10314   Type *Tys[] = { Addr->getType() };
10315   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10316 
10317   return Builder.CreateCall(Stxr,
10318                             {Builder.CreateZExtOrBitCast(
10319                                  Val, Stxr->getFunctionType()->getParamType(0)),
10320                              Addr});
10321 }
10322 
10323 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10324     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10325   return Ty->isArrayTy();
10326 }
10327 
10328 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10329                                                             EVT) const {
10330   return false;
10331 }
10332 
10333 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10334   if (!Subtarget->isTargetAndroid())
10335     return TargetLowering::getIRStackGuard(IRB);
10336 
10337   // Android provides a fixed TLS slot for the stack cookie. See the definition
10338   // of TLS_SLOT_STACK_GUARD in
10339   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10340   const unsigned TlsOffset = 0x28;
10341   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10342   Function *ThreadPointerFunc =
10343       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10344   return IRB.CreatePointerCast(
10345       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10346       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10347 }
10348 
10349 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10350   if (!Subtarget->isTargetAndroid())
10351     return TargetLowering::getSafeStackPointerLocation(IRB);
10352 
10353   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10354   // definition of TLS_SLOT_SAFESTACK in
10355   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10356   const unsigned TlsOffset = 0x48;
10357   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10358   Function *ThreadPointerFunc =
10359       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10360   return IRB.CreatePointerCast(
10361       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10362       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10363 }
10364 
10365 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10366   // Update IsSplitCSR in AArch64unctionInfo.
10367   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10368   AFI->setIsSplitCSR(true);
10369 }
10370 
10371 void AArch64TargetLowering::insertCopiesSplitCSR(
10372     MachineBasicBlock *Entry,
10373     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10374   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10375   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10376   if (!IStart)
10377     return;
10378 
10379   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10380   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10381   MachineBasicBlock::iterator MBBI = Entry->begin();
10382   for (const MCPhysReg *I = IStart; *I; ++I) {
10383     const TargetRegisterClass *RC = nullptr;
10384     if (AArch64::GPR64RegClass.contains(*I))
10385       RC = &AArch64::GPR64RegClass;
10386     else if (AArch64::FPR64RegClass.contains(*I))
10387       RC = &AArch64::FPR64RegClass;
10388     else
10389       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10390 
10391     unsigned NewVR = MRI->createVirtualRegister(RC);
10392     // Create copy from CSR to a virtual register.
10393     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10394     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10395     // nounwind. If we want to generalize this later, we may need to emit
10396     // CFI pseudo-instructions.
10397     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10398                Attribute::NoUnwind) &&
10399            "Function should be nounwind in insertCopiesSplitCSR!");
10400     Entry->addLiveIn(*I);
10401     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10402         .addReg(*I);
10403 
10404     // Insert the copy-back instructions right before the terminator.
10405     for (auto *Exit : Exits)
10406       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10407               TII->get(TargetOpcode::COPY), *I)
10408           .addReg(NewVR);
10409   }
10410 }
10411 
10412 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10413   // Integer division on AArch64 is expensive. However, when aggressively
10414   // optimizing for code size, we prefer to use a div instruction, as it is
10415   // usually smaller than the alternative sequence.
10416   // The exception to this is vector division. Since AArch64 doesn't have vector
10417   // integer division, leaving the division as-is is a loss even in terms of
10418   // size, because it will have to be scalarized, while the alternative code
10419   // sequence can be performed in vector form.
10420   bool OptSize =
10421       Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10422   return OptSize && !VT.isVector();
10423 }
10424