1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "aarch64-lower"
39 
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42 
43 // Place holder until extr generation is tested fully.
44 static cl::opt<bool>
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47                           cl::init(true));
48 
49 static cl::opt<bool>
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51                            cl::desc("Allow AArch64 SLI/SRI formation"),
52                            cl::init(false));
53 
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58     "aarch64-elf-ldtls-generation", cl::Hidden,
59     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60     cl::init(false));
61 
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
64 
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66                                              const AArch64Subtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68 
69   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70   // we have to make something up. Arbitrarily, choose ZeroOrOne.
71   setBooleanContents(ZeroOrOneBooleanContent);
72   // When comparing vectors the result sets the different elements in the
73   // vector to all-one or all-zero.
74   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75 
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79 
80   if (Subtarget->hasFPARMv8()) {
81     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85   }
86 
87   if (Subtarget->hasNEON()) {
88     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90     // Someone set us up the NEON.
91     addDRTypeForNEON(MVT::v2f32);
92     addDRTypeForNEON(MVT::v8i8);
93     addDRTypeForNEON(MVT::v4i16);
94     addDRTypeForNEON(MVT::v2i32);
95     addDRTypeForNEON(MVT::v1i64);
96     addDRTypeForNEON(MVT::v1f64);
97     addDRTypeForNEON(MVT::v4f16);
98 
99     addQRTypeForNEON(MVT::v4f32);
100     addQRTypeForNEON(MVT::v2f64);
101     addQRTypeForNEON(MVT::v16i8);
102     addQRTypeForNEON(MVT::v8i16);
103     addQRTypeForNEON(MVT::v4i32);
104     addQRTypeForNEON(MVT::v2i64);
105     addQRTypeForNEON(MVT::v8f16);
106   }
107 
108   // Compute derived properties from the register classes
109   computeRegisterProperties(Subtarget->getRegisterInfo());
110 
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133 
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137 
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141 
142   // Custom lowering hooks are needed for XOR
143   // to fold it into CSINC/CSINV.
144   setOperationAction(ISD::XOR, MVT::i32, Custom);
145   setOperationAction(ISD::XOR, MVT::i64, Custom);
146 
147   // Custom lowering hooks are needed for OR
148   // to fold it into CCMP.
149   setOperationAction(ISD::OR, MVT::i32, Custom);
150   setOperationAction(ISD::OR, MVT::i64, Custom);
151 
152   // Custom lowering hooks are needed for AND
153   // to fold it into CCMP.
154   setOperationAction(ISD::AND, MVT::i32, Custom);
155   setOperationAction(ISD::AND, MVT::i64, Custom);
156 
157   // Virtually no operation on f128 is legal, but LLVM can't expand them when
158   // there's a valid register class, so we need custom operations in most cases.
159   setOperationAction(ISD::FABS, MVT::f128, Expand);
160   setOperationAction(ISD::FADD, MVT::f128, Custom);
161   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
162   setOperationAction(ISD::FCOS, MVT::f128, Expand);
163   setOperationAction(ISD::FDIV, MVT::f128, Custom);
164   setOperationAction(ISD::FMA, MVT::f128, Expand);
165   setOperationAction(ISD::FMUL, MVT::f128, Custom);
166   setOperationAction(ISD::FNEG, MVT::f128, Expand);
167   setOperationAction(ISD::FPOW, MVT::f128, Expand);
168   setOperationAction(ISD::FREM, MVT::f128, Expand);
169   setOperationAction(ISD::FRINT, MVT::f128, Expand);
170   setOperationAction(ISD::FSIN, MVT::f128, Expand);
171   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
172   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
173   setOperationAction(ISD::FSUB, MVT::f128, Custom);
174   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
175   setOperationAction(ISD::SETCC, MVT::f128, Custom);
176   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
177   setOperationAction(ISD::SELECT, MVT::f128, Custom);
178   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
179   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
180 
181   // Lowering for many of the conversions is actually specified by the non-f128
182   // type. The LowerXXX function will be trivial when f128 isn't involved.
183   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
184   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
185   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
186   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
187   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
188   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
189   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
190   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
191   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
192   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
193   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
194   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
195   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
196   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
197 
198   // Variable arguments.
199   setOperationAction(ISD::VASTART, MVT::Other, Custom);
200   setOperationAction(ISD::VAARG, MVT::Other, Custom);
201   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
202   setOperationAction(ISD::VAEND, MVT::Other, Expand);
203 
204   // Variable-sized objects.
205   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
208 
209   // Constant pool entries
210   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
211 
212   // BlockAddress
213   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
214 
215   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
216   setOperationAction(ISD::ADDC, MVT::i32, Custom);
217   setOperationAction(ISD::ADDE, MVT::i32, Custom);
218   setOperationAction(ISD::SUBC, MVT::i32, Custom);
219   setOperationAction(ISD::SUBE, MVT::i32, Custom);
220   setOperationAction(ISD::ADDC, MVT::i64, Custom);
221   setOperationAction(ISD::ADDE, MVT::i64, Custom);
222   setOperationAction(ISD::SUBC, MVT::i64, Custom);
223   setOperationAction(ISD::SUBE, MVT::i64, Custom);
224 
225   // AArch64 lacks both left-rotate and popcount instructions.
226   setOperationAction(ISD::ROTL, MVT::i32, Expand);
227   setOperationAction(ISD::ROTL, MVT::i64, Expand);
228   for (MVT VT : MVT::vector_valuetypes()) {
229     setOperationAction(ISD::ROTL, VT, Expand);
230     setOperationAction(ISD::ROTR, VT, Expand);
231   }
232 
233   // AArch64 doesn't have {U|S}MUL_LOHI.
234   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
235   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
236 
237 
238   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
239   // counterparts, which AArch64 supports directly.
240   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
241   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
242   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
243   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
244 
245   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
246   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
247 
248   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
249   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
250   for (MVT VT : MVT::vector_valuetypes()) {
251     setOperationAction(ISD::SDIVREM, VT, Expand);
252     setOperationAction(ISD::UDIVREM, VT, Expand);
253   }
254   setOperationAction(ISD::SREM, MVT::i32, Expand);
255   setOperationAction(ISD::SREM, MVT::i64, Expand);
256   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
257   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
258   setOperationAction(ISD::UREM, MVT::i32, Expand);
259   setOperationAction(ISD::UREM, MVT::i64, Expand);
260 
261   // Custom lower Add/Sub/Mul with overflow.
262   setOperationAction(ISD::SADDO, MVT::i32, Custom);
263   setOperationAction(ISD::SADDO, MVT::i64, Custom);
264   setOperationAction(ISD::UADDO, MVT::i32, Custom);
265   setOperationAction(ISD::UADDO, MVT::i64, Custom);
266   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
267   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
268   setOperationAction(ISD::USUBO, MVT::i32, Custom);
269   setOperationAction(ISD::USUBO, MVT::i64, Custom);
270   setOperationAction(ISD::SMULO, MVT::i32, Custom);
271   setOperationAction(ISD::SMULO, MVT::i64, Custom);
272   setOperationAction(ISD::UMULO, MVT::i32, Custom);
273   setOperationAction(ISD::UMULO, MVT::i64, Custom);
274 
275   setOperationAction(ISD::FSIN, MVT::f32, Expand);
276   setOperationAction(ISD::FSIN, MVT::f64, Expand);
277   setOperationAction(ISD::FCOS, MVT::f32, Expand);
278   setOperationAction(ISD::FCOS, MVT::f64, Expand);
279   setOperationAction(ISD::FPOW, MVT::f32, Expand);
280   setOperationAction(ISD::FPOW, MVT::f64, Expand);
281   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
282   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
283 
284   // f16 is a storage-only type, always promote it to f32.
285   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
286   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
287   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
288   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
289   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
290   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
291   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
292   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
293   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
294   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
295   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
296   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
297   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
298   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
299   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
300   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
301   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
302   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
303   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
304   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
305   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
306   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
307   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
308   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
309   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
310   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
311   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
312   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
313   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
314   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
315   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
316   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
317   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
318   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
319 
320   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
321   // known to be safe.
322   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
323   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
324   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
325   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
326   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
327   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
328   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
329   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
330   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
331   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
332   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
333   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
334 
335   // Expand all other v4f16 operations.
336   // FIXME: We could generate better code by promoting some operations to
337   // a pair of v4f32s
338   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
339   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
340   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
341   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
342   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
343   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
344   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
345   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
346   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
347   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
348   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
349   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
350   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
351   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
353   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
354   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
355   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
356   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
357   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
358   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
359   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
360   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
362   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
363   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
364 
365 
366   // v8f16 is also a storage-only type, so expand it.
367   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
368   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
369   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
370   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
371   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
372   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
373   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
374   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
375   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
376   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
377   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
378   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
379   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
380   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
381   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
382   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
383   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
384   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
385   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
386   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
387   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
388   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
389   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
390   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
391   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
392   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
393   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
394   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
395   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
396   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
397   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
398 
399   // AArch64 has implementations of a lot of rounding-like FP operations.
400   for (MVT Ty : {MVT::f32, MVT::f64}) {
401     setOperationAction(ISD::FFLOOR, Ty, Legal);
402     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
403     setOperationAction(ISD::FCEIL, Ty, Legal);
404     setOperationAction(ISD::FRINT, Ty, Legal);
405     setOperationAction(ISD::FTRUNC, Ty, Legal);
406     setOperationAction(ISD::FROUND, Ty, Legal);
407     setOperationAction(ISD::FMINNUM, Ty, Legal);
408     setOperationAction(ISD::FMAXNUM, Ty, Legal);
409     setOperationAction(ISD::FMINNAN, Ty, Legal);
410     setOperationAction(ISD::FMAXNAN, Ty, Legal);
411   }
412 
413   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
414 
415   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
416   // This requires the Performance Monitors extension.
417   if (Subtarget->hasPerfMon())
418     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
419 
420   if (Subtarget->isTargetMachO()) {
421     // For iOS, we don't want to the normal expansion of a libcall to
422     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
423     // traffic.
424     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
425     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
426   } else {
427     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
428     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
429   }
430 
431   // Make floating-point constants legal for the large code model, so they don't
432   // become loads from the constant pool.
433   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
434     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
435     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
436   }
437 
438   // AArch64 does not have floating-point extending loads, i1 sign-extending
439   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
440   for (MVT VT : MVT::fp_valuetypes()) {
441     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
442     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
443     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
444     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
445   }
446   for (MVT VT : MVT::integer_valuetypes())
447     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
448 
449   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
450   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
451   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
453   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
454   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
455   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
456 
457   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
458   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
459 
460   // Indexed loads and stores are supported.
461   for (unsigned im = (unsigned)ISD::PRE_INC;
462        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
463     setIndexedLoadAction(im, MVT::i8, Legal);
464     setIndexedLoadAction(im, MVT::i16, Legal);
465     setIndexedLoadAction(im, MVT::i32, Legal);
466     setIndexedLoadAction(im, MVT::i64, Legal);
467     setIndexedLoadAction(im, MVT::f64, Legal);
468     setIndexedLoadAction(im, MVT::f32, Legal);
469     setIndexedLoadAction(im, MVT::f16, Legal);
470     setIndexedStoreAction(im, MVT::i8, Legal);
471     setIndexedStoreAction(im, MVT::i16, Legal);
472     setIndexedStoreAction(im, MVT::i32, Legal);
473     setIndexedStoreAction(im, MVT::i64, Legal);
474     setIndexedStoreAction(im, MVT::f64, Legal);
475     setIndexedStoreAction(im, MVT::f32, Legal);
476     setIndexedStoreAction(im, MVT::f16, Legal);
477   }
478 
479   // Trap.
480   setOperationAction(ISD::TRAP, MVT::Other, Legal);
481 
482   // We combine OR nodes for bitfield operations.
483   setTargetDAGCombine(ISD::OR);
484 
485   // Vector add and sub nodes may conceal a high-half opportunity.
486   // Also, try to fold ADD into CSINC/CSINV..
487   setTargetDAGCombine(ISD::ADD);
488   setTargetDAGCombine(ISD::SUB);
489 
490   setTargetDAGCombine(ISD::XOR);
491   setTargetDAGCombine(ISD::SINT_TO_FP);
492   setTargetDAGCombine(ISD::UINT_TO_FP);
493 
494   setTargetDAGCombine(ISD::FP_TO_SINT);
495   setTargetDAGCombine(ISD::FP_TO_UINT);
496   setTargetDAGCombine(ISD::FDIV);
497 
498   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
499 
500   setTargetDAGCombine(ISD::ANY_EXTEND);
501   setTargetDAGCombine(ISD::ZERO_EXTEND);
502   setTargetDAGCombine(ISD::SIGN_EXTEND);
503   setTargetDAGCombine(ISD::BITCAST);
504   setTargetDAGCombine(ISD::CONCAT_VECTORS);
505   setTargetDAGCombine(ISD::STORE);
506   if (Subtarget->supportsAddressTopByteIgnored())
507     setTargetDAGCombine(ISD::LOAD);
508 
509   setTargetDAGCombine(ISD::MUL);
510 
511   setTargetDAGCombine(ISD::SELECT);
512   setTargetDAGCombine(ISD::VSELECT);
513 
514   setTargetDAGCombine(ISD::INTRINSIC_VOID);
515   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
516   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
517   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
518 
519   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
520   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
521   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
522 
523   setStackPointerRegisterToSaveRestore(AArch64::SP);
524 
525   setSchedulingPreference(Sched::Hybrid);
526 
527   // Enable TBZ/TBNZ
528   MaskAndBranchFoldingIsLegal = true;
529   EnableExtLdPromotion = true;
530 
531   setMinFunctionAlignment(2);
532 
533   setHasExtractBitsInsn(true);
534 
535   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
536 
537   if (Subtarget->hasNEON()) {
538     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
539     // silliness like this:
540     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
541     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
542     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
543     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
544     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
545     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
546     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
547     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
548     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
549     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
550     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
551     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
552     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
553     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
554     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
555     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
556     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
557     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
558     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
559     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
560     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
561     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
562     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
563     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
564     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
565 
566     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
567     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
568     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
569     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
570     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
571 
572     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
573 
574     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
575     // elements smaller than i32, so promote the input to i32 first.
576     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
577     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
578     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
579     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
580     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
581     // -> v8f16 conversions.
582     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
583     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
584     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
585     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
586     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
587     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
588     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
589     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
590     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
591     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
592     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
593     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
594     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
595 
596     // AArch64 doesn't have MUL.2d:
597     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
598     // Custom handling for some quad-vector types to detect MULL.
599     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
600     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
601     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
602 
603     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
604     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
605     // Likewise, narrowing and extending vector loads/stores aren't handled
606     // directly.
607     for (MVT VT : MVT::vector_valuetypes()) {
608       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
609 
610       setOperationAction(ISD::MULHS, VT, Expand);
611       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
612       setOperationAction(ISD::MULHU, VT, Expand);
613       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
614 
615       setOperationAction(ISD::BSWAP, VT, Expand);
616 
617       for (MVT InnerVT : MVT::vector_valuetypes()) {
618         setTruncStoreAction(VT, InnerVT, Expand);
619         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
620         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
621         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
622       }
623     }
624 
625     // AArch64 has implementations of a lot of rounding-like FP operations.
626     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
627       setOperationAction(ISD::FFLOOR, Ty, Legal);
628       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
629       setOperationAction(ISD::FCEIL, Ty, Legal);
630       setOperationAction(ISD::FRINT, Ty, Legal);
631       setOperationAction(ISD::FTRUNC, Ty, Legal);
632       setOperationAction(ISD::FROUND, Ty, Legal);
633     }
634   }
635 
636   // Prefer likely predicted branches to selects on out-of-order cores.
637   if (Subtarget->isCortexA57() || Subtarget->isKryo())
638     PredictableSelectIsExpensive = true;
639 }
640 
641 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
642   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
643     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
644     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
645 
646     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
647     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
648   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
649     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
650     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
651 
652     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
653     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
654   }
655 
656   // Mark vector float intrinsics as expand.
657   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
658     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
659     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
660     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
661     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
662     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
663     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
664     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
665     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
666     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
667 
668     // But we do support custom-lowering for FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
670   }
671 
672   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
673   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
674   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
675   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
676   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
677   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
678   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
679   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
680   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
681   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
682   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
683   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
684 
685   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
686   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
687   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
688   for (MVT InnerVT : MVT::all_valuetypes())
689     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
690 
691   // CNT supports only B element sizes.
692   if (VT != MVT::v8i8 && VT != MVT::v16i8)
693     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
694 
695   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
696   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
697   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
698   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
699   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
700 
701   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
702   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
703 
704   // [SU][MIN|MAX] are available for all NEON types apart from i64.
705   if (!VT.isFloatingPoint() &&
706       VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
707     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
708       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
709 
710   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
711   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
712     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
713                             ISD::FMINNUM, ISD::FMAXNUM})
714       setOperationAction(Opcode, VT.getSimpleVT(), Legal);
715 
716   if (Subtarget->isLittleEndian()) {
717     for (unsigned im = (unsigned)ISD::PRE_INC;
718          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
719       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
720       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
721     }
722   }
723 }
724 
725 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
726   addRegisterClass(VT, &AArch64::FPR64RegClass);
727   addTypeForNEON(VT, MVT::v2i32);
728 }
729 
730 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
731   addRegisterClass(VT, &AArch64::FPR128RegClass);
732   addTypeForNEON(VT, MVT::v4i32);
733 }
734 
735 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
736                                               EVT VT) const {
737   if (!VT.isVector())
738     return MVT::i32;
739   return VT.changeVectorElementTypeToInteger();
740 }
741 
742 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
743 /// Mask are known to be either zero or one and return them in the
744 /// KnownZero/KnownOne bitsets.
745 void AArch64TargetLowering::computeKnownBitsForTargetNode(
746     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
747     const SelectionDAG &DAG, unsigned Depth) const {
748   switch (Op.getOpcode()) {
749   default:
750     break;
751   case AArch64ISD::CSEL: {
752     APInt KnownZero2, KnownOne2;
753     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
754     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
755     KnownZero &= KnownZero2;
756     KnownOne &= KnownOne2;
757     break;
758   }
759   case ISD::INTRINSIC_W_CHAIN: {
760     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
761     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
762     switch (IntID) {
763     default: return;
764     case Intrinsic::aarch64_ldaxr:
765     case Intrinsic::aarch64_ldxr: {
766       unsigned BitWidth = KnownOne.getBitWidth();
767       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
768       unsigned MemBits = VT.getScalarType().getSizeInBits();
769       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
770       return;
771     }
772     }
773     break;
774   }
775   case ISD::INTRINSIC_WO_CHAIN:
776   case ISD::INTRINSIC_VOID: {
777     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
778     switch (IntNo) {
779     default:
780       break;
781     case Intrinsic::aarch64_neon_umaxv:
782     case Intrinsic::aarch64_neon_uminv: {
783       // Figure out the datatype of the vector operand. The UMINV instruction
784       // will zero extend the result, so we can mark as known zero all the
785       // bits larger than the element datatype. 32-bit or larget doesn't need
786       // this as those are legal types and will be handled by isel directly.
787       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
788       unsigned BitWidth = KnownZero.getBitWidth();
789       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
790         assert(BitWidth >= 8 && "Unexpected width!");
791         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
792         KnownZero |= Mask;
793       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
794         assert(BitWidth >= 16 && "Unexpected width!");
795         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
796         KnownZero |= Mask;
797       }
798       break;
799     } break;
800     }
801   }
802   }
803 }
804 
805 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
806                                                   EVT) const {
807   return MVT::i64;
808 }
809 
810 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
811                                                            unsigned AddrSpace,
812                                                            unsigned Align,
813                                                            bool *Fast) const {
814   if (Subtarget->requiresStrictAlign())
815     return false;
816 
817   // FIXME: This is mostly true for Cyclone, but not necessarily others.
818   if (Fast) {
819     // FIXME: Define an attribute for slow unaligned accesses instead of
820     // relying on the CPU type as a proxy.
821     // On Cyclone, unaligned 128-bit stores are slow.
822     *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
823             // See comments in performSTORECombine() for more details about
824             // these conditions.
825 
826             // Code that uses clang vector extensions can mark that it
827             // wants unaligned accesses to be treated as fast by
828             // underspecifying alignment to be 1 or 2.
829             Align <= 2 ||
830 
831             // Disregard v2i64. Memcpy lowering produces those and splitting
832             // them regresses performance on micro-benchmarks and olden/bh.
833             VT == MVT::v2i64;
834   }
835   return true;
836 }
837 
838 FastISel *
839 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
840                                       const TargetLibraryInfo *libInfo) const {
841   return AArch64::createFastISel(funcInfo, libInfo);
842 }
843 
844 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
845   switch ((AArch64ISD::NodeType)Opcode) {
846   case AArch64ISD::FIRST_NUMBER:      break;
847   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
848   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
849   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
850   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
851   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
852   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
853   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
854   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
855   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
856   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
857   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
858   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
859   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
860   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
861   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
862   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
863   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
864   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
865   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
866   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
867   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
868   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
869   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
870   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
871   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
872   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
873   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
874   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
875   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
876   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
877   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
878   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
879   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
880   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
881   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
882   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
883   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
884   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
885   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
886   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
887   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
888   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
889   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
890   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
891   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
892   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
893   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
894   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
895   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
896   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
897   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
898   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
899   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
900   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
901   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
902   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
903   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
904   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
905   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
906   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
907   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
908   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
909   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
910   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
911   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
912   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
913   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
914   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
915   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
916   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
917   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
918   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
919   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
920   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
921   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
922   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
923   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
924   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
925   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
926   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
927   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
928   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
929   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
930   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
931   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
932   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
933   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
934   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
935   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
936   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
937   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
938   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
939   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
940   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
941   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
942   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
943   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
944   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
945   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
946   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
947   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
948   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
949   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
950   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
951   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
952   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
953   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
954   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
955   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
956   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
957   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
958   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
959   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
960   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
961   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
962   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
963   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
964   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
965   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
966   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
967   }
968   return nullptr;
969 }
970 
971 MachineBasicBlock *
972 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
973                                     MachineBasicBlock *MBB) const {
974   // We materialise the F128CSEL pseudo-instruction as some control flow and a
975   // phi node:
976 
977   // OrigBB:
978   //     [... previous instrs leading to comparison ...]
979   //     b.ne TrueBB
980   //     b EndBB
981   // TrueBB:
982   //     ; Fallthrough
983   // EndBB:
984   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
985 
986   MachineFunction *MF = MBB->getParent();
987   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
988   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
989   DebugLoc DL = MI->getDebugLoc();
990   MachineFunction::iterator It = ++MBB->getIterator();
991 
992   unsigned DestReg = MI->getOperand(0).getReg();
993   unsigned IfTrueReg = MI->getOperand(1).getReg();
994   unsigned IfFalseReg = MI->getOperand(2).getReg();
995   unsigned CondCode = MI->getOperand(3).getImm();
996   bool NZCVKilled = MI->getOperand(4).isKill();
997 
998   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
999   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000   MF->insert(It, TrueBB);
1001   MF->insert(It, EndBB);
1002 
1003   // Transfer rest of current basic-block to EndBB
1004   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1005                 MBB->end());
1006   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1007 
1008   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1009   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1010   MBB->addSuccessor(TrueBB);
1011   MBB->addSuccessor(EndBB);
1012 
1013   // TrueBB falls through to the end.
1014   TrueBB->addSuccessor(EndBB);
1015 
1016   if (!NZCVKilled) {
1017     TrueBB->addLiveIn(AArch64::NZCV);
1018     EndBB->addLiveIn(AArch64::NZCV);
1019   }
1020 
1021   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1022       .addReg(IfTrueReg)
1023       .addMBB(TrueBB)
1024       .addReg(IfFalseReg)
1025       .addMBB(MBB);
1026 
1027   MI->eraseFromParent();
1028   return EndBB;
1029 }
1030 
1031 MachineBasicBlock *
1032 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1033                                                  MachineBasicBlock *BB) const {
1034   switch (MI->getOpcode()) {
1035   default:
1036 #ifndef NDEBUG
1037     MI->dump();
1038 #endif
1039     llvm_unreachable("Unexpected instruction for custom inserter!");
1040 
1041   case AArch64::F128CSEL:
1042     return EmitF128CSEL(MI, BB);
1043 
1044   case TargetOpcode::STACKMAP:
1045   case TargetOpcode::PATCHPOINT:
1046     return emitPatchPoint(MI, BB);
1047   }
1048 }
1049 
1050 //===----------------------------------------------------------------------===//
1051 // AArch64 Lowering private implementation.
1052 //===----------------------------------------------------------------------===//
1053 
1054 //===----------------------------------------------------------------------===//
1055 // Lowering Code
1056 //===----------------------------------------------------------------------===//
1057 
1058 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1059 /// CC
1060 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1061   switch (CC) {
1062   default:
1063     llvm_unreachable("Unknown condition code!");
1064   case ISD::SETNE:
1065     return AArch64CC::NE;
1066   case ISD::SETEQ:
1067     return AArch64CC::EQ;
1068   case ISD::SETGT:
1069     return AArch64CC::GT;
1070   case ISD::SETGE:
1071     return AArch64CC::GE;
1072   case ISD::SETLT:
1073     return AArch64CC::LT;
1074   case ISD::SETLE:
1075     return AArch64CC::LE;
1076   case ISD::SETUGT:
1077     return AArch64CC::HI;
1078   case ISD::SETUGE:
1079     return AArch64CC::HS;
1080   case ISD::SETULT:
1081     return AArch64CC::LO;
1082   case ISD::SETULE:
1083     return AArch64CC::LS;
1084   }
1085 }
1086 
1087 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1088 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1089                                   AArch64CC::CondCode &CondCode,
1090                                   AArch64CC::CondCode &CondCode2) {
1091   CondCode2 = AArch64CC::AL;
1092   switch (CC) {
1093   default:
1094     llvm_unreachable("Unknown FP condition!");
1095   case ISD::SETEQ:
1096   case ISD::SETOEQ:
1097     CondCode = AArch64CC::EQ;
1098     break;
1099   case ISD::SETGT:
1100   case ISD::SETOGT:
1101     CondCode = AArch64CC::GT;
1102     break;
1103   case ISD::SETGE:
1104   case ISD::SETOGE:
1105     CondCode = AArch64CC::GE;
1106     break;
1107   case ISD::SETOLT:
1108     CondCode = AArch64CC::MI;
1109     break;
1110   case ISD::SETOLE:
1111     CondCode = AArch64CC::LS;
1112     break;
1113   case ISD::SETONE:
1114     CondCode = AArch64CC::MI;
1115     CondCode2 = AArch64CC::GT;
1116     break;
1117   case ISD::SETO:
1118     CondCode = AArch64CC::VC;
1119     break;
1120   case ISD::SETUO:
1121     CondCode = AArch64CC::VS;
1122     break;
1123   case ISD::SETUEQ:
1124     CondCode = AArch64CC::EQ;
1125     CondCode2 = AArch64CC::VS;
1126     break;
1127   case ISD::SETUGT:
1128     CondCode = AArch64CC::HI;
1129     break;
1130   case ISD::SETUGE:
1131     CondCode = AArch64CC::PL;
1132     break;
1133   case ISD::SETLT:
1134   case ISD::SETULT:
1135     CondCode = AArch64CC::LT;
1136     break;
1137   case ISD::SETLE:
1138   case ISD::SETULE:
1139     CondCode = AArch64CC::LE;
1140     break;
1141   case ISD::SETNE:
1142   case ISD::SETUNE:
1143     CondCode = AArch64CC::NE;
1144     break;
1145   }
1146 }
1147 
1148 /// Convert a DAG fp condition code to an AArch64 CC.
1149 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1150 /// should be AND'ed instead of OR'ed.
1151 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1152                                      AArch64CC::CondCode &CondCode,
1153                                      AArch64CC::CondCode &CondCode2) {
1154   CondCode2 = AArch64CC::AL;
1155   switch (CC) {
1156   default:
1157     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1158     assert(CondCode2 == AArch64CC::AL);
1159     break;
1160   case ISD::SETONE:
1161     // (a one b)
1162     // == ((a olt b) || (a ogt b))
1163     // == ((a ord b) && (a une b))
1164     CondCode = AArch64CC::VC;
1165     CondCode2 = AArch64CC::NE;
1166     break;
1167   case ISD::SETUEQ:
1168     // (a ueq b)
1169     // == ((a uno b) || (a oeq b))
1170     // == ((a ule b) && (a uge b))
1171     CondCode = AArch64CC::PL;
1172     CondCode2 = AArch64CC::LE;
1173     break;
1174   }
1175 }
1176 
1177 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1178 /// CC usable with the vector instructions. Fewer operations are available
1179 /// without a real NZCV register, so we have to use less efficient combinations
1180 /// to get the same effect.
1181 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1182                                         AArch64CC::CondCode &CondCode,
1183                                         AArch64CC::CondCode &CondCode2,
1184                                         bool &Invert) {
1185   Invert = false;
1186   switch (CC) {
1187   default:
1188     // Mostly the scalar mappings work fine.
1189     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1190     break;
1191   case ISD::SETUO:
1192     Invert = true; // Fallthrough
1193   case ISD::SETO:
1194     CondCode = AArch64CC::MI;
1195     CondCode2 = AArch64CC::GE;
1196     break;
1197   case ISD::SETUEQ:
1198   case ISD::SETULT:
1199   case ISD::SETULE:
1200   case ISD::SETUGT:
1201   case ISD::SETUGE:
1202     // All of the compare-mask comparisons are ordered, but we can switch
1203     // between the two by a double inversion. E.g. ULE == !OGT.
1204     Invert = true;
1205     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1206     break;
1207   }
1208 }
1209 
1210 static bool isLegalArithImmed(uint64_t C) {
1211   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1212   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1213 }
1214 
1215 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1216                               SDLoc dl, SelectionDAG &DAG) {
1217   EVT VT = LHS.getValueType();
1218 
1219   if (VT.isFloatingPoint())
1220     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1221 
1222   // The CMP instruction is just an alias for SUBS, and representing it as
1223   // SUBS means that it's possible to get CSE with subtract operations.
1224   // A later phase can perform the optimization of setting the destination
1225   // register to WZR/XZR if it ends up being unused.
1226   unsigned Opcode = AArch64ISD::SUBS;
1227 
1228   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1229       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1230     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1231     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1232     // can be set differently by this operation. It comes down to whether
1233     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1234     // everything is fine. If not then the optimization is wrong. Thus general
1235     // comparisons are only valid if op2 != 0.
1236 
1237     // So, finally, the only LLVM-native comparisons that don't mention C and V
1238     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1239     // the absence of information about op2.
1240     Opcode = AArch64ISD::ADDS;
1241     RHS = RHS.getOperand(1);
1242   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1243              !isUnsignedIntSetCC(CC)) {
1244     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1245     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1246     // of the signed comparisons.
1247     Opcode = AArch64ISD::ANDS;
1248     RHS = LHS.getOperand(1);
1249     LHS = LHS.getOperand(0);
1250   }
1251 
1252   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1253       .getValue(1);
1254 }
1255 
1256 /// \defgroup AArch64CCMP CMP;CCMP matching
1257 ///
1258 /// These functions deal with the formation of CMP;CCMP;... sequences.
1259 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1260 /// a comparison. They set the NZCV flags to a predefined value if their
1261 /// predicate is false. This allows to express arbitrary conjunctions, for
1262 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1263 /// expressed as:
1264 ///   cmp A
1265 ///   ccmp B, inv(CB), CA
1266 ///   check for CB flags
1267 ///
1268 /// In general we can create code for arbitrary "... (and (and A B) C)"
1269 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1270 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1271 /// negation operations:
1272 /// We can negate the results of a single comparison by inverting the flags
1273 /// used when the predicate fails and inverting the flags tested in the next
1274 /// instruction; We can also negate the results of the whole previous
1275 /// conditional compare sequence by inverting the flags tested in the next
1276 /// instruction. However there is no way to negate the result of a partial
1277 /// sequence.
1278 ///
1279 /// Therefore on encountering an "or" expression we can negate the subtree on
1280 /// one side and have to be able to push the negate to the leafs of the subtree
1281 /// on the other side (see also the comments in code). As complete example:
1282 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1283 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1284 /// is transformed to
1285 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1286 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1287 /// and implemented as:
1288 ///   cmp C
1289 ///   ccmp D, inv(CD), CC
1290 ///   ccmp A, CA, inv(CD)
1291 ///   ccmp B, CB, inv(CA)
1292 ///   check for CB flags
1293 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1294 /// by conditional compare sequences.
1295 /// @{
1296 
1297 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1298 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1299                                          ISD::CondCode CC, SDValue CCOp,
1300                                          AArch64CC::CondCode Predicate,
1301                                          AArch64CC::CondCode OutCC,
1302                                          SDLoc DL, SelectionDAG &DAG) {
1303   unsigned Opcode = 0;
1304   if (LHS.getValueType().isFloatingPoint())
1305     Opcode = AArch64ISD::FCCMP;
1306   else if (RHS.getOpcode() == ISD::SUB) {
1307     SDValue SubOp0 = RHS.getOperand(0);
1308     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1309       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1310       Opcode = AArch64ISD::CCMN;
1311       RHS = RHS.getOperand(1);
1312     }
1313   }
1314   if (Opcode == 0)
1315     Opcode = AArch64ISD::CCMP;
1316 
1317   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1318   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1319   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1320   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1321   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1322 }
1323 
1324 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1325 /// CanPushNegate is set to true if we can push a negate operation through
1326 /// the tree in a was that we are left with AND operations and negate operations
1327 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1328 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1329 /// brought into such a form.
1330 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1331                                          unsigned Depth = 0) {
1332   if (!Val.hasOneUse())
1333     return false;
1334   unsigned Opcode = Val->getOpcode();
1335   if (Opcode == ISD::SETCC) {
1336     CanNegate = true;
1337     return true;
1338   }
1339   // Protect against exponential runtime and stack overflow.
1340   if (Depth > 6)
1341     return false;
1342   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1343     SDValue O0 = Val->getOperand(0);
1344     SDValue O1 = Val->getOperand(1);
1345     bool CanNegateL;
1346     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1347       return false;
1348     bool CanNegateR;
1349     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1350       return false;
1351 
1352     if (Opcode == ISD::OR) {
1353       // For an OR expression we need to be able to negate at least one side or
1354       // we cannot do the transformation at all.
1355       if (!CanNegateL && !CanNegateR)
1356         return false;
1357       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1358       // can negate the x and y subtrees.
1359       CanNegate = CanNegateL && CanNegateR;
1360     } else {
1361       // If the operands are OR expressions then we finally need to negate their
1362       // outputs, we can only do that for the operand with emitted last by
1363       // negating OutCC, not for both operands.
1364       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1365       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1366       if (NeedsNegOutL && NeedsNegOutR)
1367         return false;
1368       // We cannot negate an AND operation (it would become an OR),
1369       CanNegate = false;
1370     }
1371     return true;
1372   }
1373   return false;
1374 }
1375 
1376 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1377 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1378 /// Tries to transform the given i1 producing node @p Val to a series compare
1379 /// and conditional compare operations. @returns an NZCV flags producing node
1380 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1381 /// transformation was not possible.
1382 /// On recursive invocations @p PushNegate may be set to true to have negation
1383 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1384 /// for the comparisons in the current subtree; @p Depth limits the search
1385 /// depth to avoid stack overflow.
1386 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1387     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1388     AArch64CC::CondCode Predicate) {
1389   // We're at a tree leaf, produce a conditional comparison operation.
1390   unsigned Opcode = Val->getOpcode();
1391   if (Opcode == ISD::SETCC) {
1392     SDValue LHS = Val->getOperand(0);
1393     SDValue RHS = Val->getOperand(1);
1394     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1395     bool isInteger = LHS.getValueType().isInteger();
1396     if (Negate)
1397       CC = getSetCCInverse(CC, isInteger);
1398     SDLoc DL(Val);
1399     // Determine OutCC and handle FP special case.
1400     if (isInteger) {
1401       OutCC = changeIntCCToAArch64CC(CC);
1402     } else {
1403       assert(LHS.getValueType().isFloatingPoint());
1404       AArch64CC::CondCode ExtraCC;
1405       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1406       // Some floating point conditions can't be tested with a single condition
1407       // code. Construct an additional comparison in this case.
1408       if (ExtraCC != AArch64CC::AL) {
1409         SDValue ExtraCmp;
1410         if (!CCOp.getNode())
1411           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1412         else
1413           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1414                                                ExtraCC, DL, DAG);
1415         CCOp = ExtraCmp;
1416         Predicate = ExtraCC;
1417       }
1418     }
1419 
1420     // Produce a normal comparison if we are first in the chain
1421     if (!CCOp)
1422       return emitComparison(LHS, RHS, CC, DL, DAG);
1423     // Otherwise produce a ccmp.
1424     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1425                                      DAG);
1426   }
1427   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1428          "Valid conjunction/disjunction tree");
1429 
1430   // Check if both sides can be transformed.
1431   SDValue LHS = Val->getOperand(0);
1432   SDValue RHS = Val->getOperand(1);
1433 
1434   // In case of an OR we need to negate our operands and the result.
1435   // (A v B) <=> not(not(A) ^ not(B))
1436   bool NegateOpsAndResult = Opcode == ISD::OR;
1437   // We can negate the results of all previous operations by inverting the
1438   // predicate flags giving us a free negation for one side. The other side
1439   // must be negatable by itself.
1440   if (NegateOpsAndResult) {
1441     // See which side we can negate.
1442     bool CanNegateL;
1443     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1444     assert(isValidL && "Valid conjunction/disjunction tree");
1445     (void)isValidL;
1446 
1447 #ifndef NDEBUG
1448     bool CanNegateR;
1449     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1450     assert(isValidR && "Valid conjunction/disjunction tree");
1451     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1452 #endif
1453 
1454     // Order the side which we cannot negate to RHS so we can emit it first.
1455     if (!CanNegateL)
1456       std::swap(LHS, RHS);
1457   } else {
1458     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1459     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1460            "Valid conjunction/disjunction tree");
1461     // Order the side where we need to negate the output flags to RHS so it
1462     // gets emitted first.
1463     if (NeedsNegOutL)
1464       std::swap(LHS, RHS);
1465   }
1466 
1467   // Emit RHS. If we want to negate the tree we only need to push a negate
1468   // through if we are already in a PushNegate case, otherwise we can negate
1469   // the "flags to test" afterwards.
1470   AArch64CC::CondCode RHSCC;
1471   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1472                                                    CCOp, Predicate);
1473   if (NegateOpsAndResult && !Negate)
1474     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1475   // Emit LHS. We may need to negate it.
1476   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1477                                                    NegateOpsAndResult, CmpR,
1478                                                    RHSCC);
1479   // If we transformed an OR to and AND then we have to negate the result
1480   // (or absorb the Negate parameter).
1481   if (NegateOpsAndResult && !Negate)
1482     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1483   return CmpL;
1484 }
1485 
1486 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1487 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1488 /// \see emitConjunctionDisjunctionTreeRec().
1489 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1490                                               AArch64CC::CondCode &OutCC) {
1491   bool CanNegate;
1492   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1493     return SDValue();
1494 
1495   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1496                                            AArch64CC::AL);
1497 }
1498 
1499 /// @}
1500 
1501 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1502                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1503   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1504     EVT VT = RHS.getValueType();
1505     uint64_t C = RHSC->getZExtValue();
1506     if (!isLegalArithImmed(C)) {
1507       // Constant does not fit, try adjusting it by one?
1508       switch (CC) {
1509       default:
1510         break;
1511       case ISD::SETLT:
1512       case ISD::SETGE:
1513         if ((VT == MVT::i32 && C != 0x80000000 &&
1514              isLegalArithImmed((uint32_t)(C - 1))) ||
1515             (VT == MVT::i64 && C != 0x80000000ULL &&
1516              isLegalArithImmed(C - 1ULL))) {
1517           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1518           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1519           RHS = DAG.getConstant(C, dl, VT);
1520         }
1521         break;
1522       case ISD::SETULT:
1523       case ISD::SETUGE:
1524         if ((VT == MVT::i32 && C != 0 &&
1525              isLegalArithImmed((uint32_t)(C - 1))) ||
1526             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1527           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1528           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1529           RHS = DAG.getConstant(C, dl, VT);
1530         }
1531         break;
1532       case ISD::SETLE:
1533       case ISD::SETGT:
1534         if ((VT == MVT::i32 && C != INT32_MAX &&
1535              isLegalArithImmed((uint32_t)(C + 1))) ||
1536             (VT == MVT::i64 && C != INT64_MAX &&
1537              isLegalArithImmed(C + 1ULL))) {
1538           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1539           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1540           RHS = DAG.getConstant(C, dl, VT);
1541         }
1542         break;
1543       case ISD::SETULE:
1544       case ISD::SETUGT:
1545         if ((VT == MVT::i32 && C != UINT32_MAX &&
1546              isLegalArithImmed((uint32_t)(C + 1))) ||
1547             (VT == MVT::i64 && C != UINT64_MAX &&
1548              isLegalArithImmed(C + 1ULL))) {
1549           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1550           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1551           RHS = DAG.getConstant(C, dl, VT);
1552         }
1553         break;
1554       }
1555     }
1556   }
1557   SDValue Cmp;
1558   AArch64CC::CondCode AArch64CC;
1559   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1560     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1561 
1562     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1563     // For the i8 operand, the largest immediate is 255, so this can be easily
1564     // encoded in the compare instruction. For the i16 operand, however, the
1565     // largest immediate cannot be encoded in the compare.
1566     // Therefore, use a sign extending load and cmn to avoid materializing the
1567     // -1 constant. For example,
1568     // movz w1, #65535
1569     // ldrh w0, [x0, #0]
1570     // cmp w0, w1
1571     // >
1572     // ldrsh w0, [x0, #0]
1573     // cmn w0, #1
1574     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1575     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1576     // ensure both the LHS and RHS are truly zero extended and to make sure the
1577     // transformation is profitable.
1578     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1579         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1580         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1581         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1582       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1583       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1584         SDValue SExt =
1585             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1586                         DAG.getValueType(MVT::i16));
1587         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1588                                                    RHS.getValueType()),
1589                              CC, dl, DAG);
1590         AArch64CC = changeIntCCToAArch64CC(CC);
1591       }
1592     }
1593 
1594     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1595       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1596         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1597           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1598       }
1599     }
1600   }
1601 
1602   if (!Cmp) {
1603     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1604     AArch64CC = changeIntCCToAArch64CC(CC);
1605   }
1606   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1607   return Cmp;
1608 }
1609 
1610 // Attempt to form conditional compare sequences for and/or trees
1611 // with setcc leafs.
1612 static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) {
1613   SDValue LHS = Op.getOperand(0);
1614   SDValue RHS = Op.getOperand(1);
1615   if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC))
1616     return Op;
1617 
1618   bool CanNegate;
1619   if (!isConjunctionDisjunctionTree(Op, CanNegate))
1620     return SDValue();
1621 
1622   EVT VT = Op.getValueType();
1623   SDLoc DL(Op);
1624   SDValue TVal = DAG.getConstant(1, DL, VT);
1625   SDValue FVal = DAG.getConstant(0, DL, VT);
1626   SDValue CCVal;
1627   SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL);
1628   return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp);
1629 }
1630 
1631 static std::pair<SDValue, SDValue>
1632 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1633   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1634          "Unsupported value type");
1635   SDValue Value, Overflow;
1636   SDLoc DL(Op);
1637   SDValue LHS = Op.getOperand(0);
1638   SDValue RHS = Op.getOperand(1);
1639   unsigned Opc = 0;
1640   switch (Op.getOpcode()) {
1641   default:
1642     llvm_unreachable("Unknown overflow instruction!");
1643   case ISD::SADDO:
1644     Opc = AArch64ISD::ADDS;
1645     CC = AArch64CC::VS;
1646     break;
1647   case ISD::UADDO:
1648     Opc = AArch64ISD::ADDS;
1649     CC = AArch64CC::HS;
1650     break;
1651   case ISD::SSUBO:
1652     Opc = AArch64ISD::SUBS;
1653     CC = AArch64CC::VS;
1654     break;
1655   case ISD::USUBO:
1656     Opc = AArch64ISD::SUBS;
1657     CC = AArch64CC::LO;
1658     break;
1659   // Multiply needs a little bit extra work.
1660   case ISD::SMULO:
1661   case ISD::UMULO: {
1662     CC = AArch64CC::NE;
1663     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1664     if (Op.getValueType() == MVT::i32) {
1665       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1666       // For a 32 bit multiply with overflow check we want the instruction
1667       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1668       // need to generate the following pattern:
1669       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1670       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1671       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1672       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1673       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1674                                 DAG.getConstant(0, DL, MVT::i64));
1675       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1676       // operation. We need to clear out the upper 32 bits, because we used a
1677       // widening multiply that wrote all 64 bits. In the end this should be a
1678       // noop.
1679       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1680       if (IsSigned) {
1681         // The signed overflow check requires more than just a simple check for
1682         // any bit set in the upper 32 bits of the result. These bits could be
1683         // just the sign bits of a negative number. To perform the overflow
1684         // check we have to arithmetic shift right the 32nd bit of the result by
1685         // 31 bits. Then we compare the result to the upper 32 bits.
1686         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1687                                         DAG.getConstant(32, DL, MVT::i64));
1688         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1689         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1690                                         DAG.getConstant(31, DL, MVT::i64));
1691         // It is important that LowerBits is last, otherwise the arithmetic
1692         // shift will not be folded into the compare (SUBS).
1693         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1694         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1695                        .getValue(1);
1696       } else {
1697         // The overflow check for unsigned multiply is easy. We only need to
1698         // check if any of the upper 32 bits are set. This can be done with a
1699         // CMP (shifted register). For that we need to generate the following
1700         // pattern:
1701         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1702         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1703                                         DAG.getConstant(32, DL, MVT::i64));
1704         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1705         Overflow =
1706             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1707                         DAG.getConstant(0, DL, MVT::i64),
1708                         UpperBits).getValue(1);
1709       }
1710       break;
1711     }
1712     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1713     // For the 64 bit multiply
1714     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1715     if (IsSigned) {
1716       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1717       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1718                                       DAG.getConstant(63, DL, MVT::i64));
1719       // It is important that LowerBits is last, otherwise the arithmetic
1720       // shift will not be folded into the compare (SUBS).
1721       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1722       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1723                      .getValue(1);
1724     } else {
1725       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1726       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1727       Overflow =
1728           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1729                       DAG.getConstant(0, DL, MVT::i64),
1730                       UpperBits).getValue(1);
1731     }
1732     break;
1733   }
1734   } // switch (...)
1735 
1736   if (Opc) {
1737     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1738 
1739     // Emit the AArch64 operation with overflow check.
1740     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1741     Overflow = Value.getValue(1);
1742   }
1743   return std::make_pair(Value, Overflow);
1744 }
1745 
1746 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1747                                              RTLIB::Libcall Call) const {
1748   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1749   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1750 }
1751 
1752 SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const {
1753   if (Op.getValueType().isVector())
1754     return LowerVectorAND(Op, DAG);
1755   return tryLowerToAArch64Cmp(Op, DAG);
1756 }
1757 
1758 SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const {
1759   if (Op.getValueType().isVector())
1760     return LowerVectorOR(Op, DAG);
1761   return tryLowerToAArch64Cmp(Op, DAG);
1762 }
1763 
1764 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1765   SDValue Sel = Op.getOperand(0);
1766   SDValue Other = Op.getOperand(1);
1767 
1768   // If neither operand is a SELECT_CC, give up.
1769   if (Sel.getOpcode() != ISD::SELECT_CC)
1770     std::swap(Sel, Other);
1771   if (Sel.getOpcode() != ISD::SELECT_CC)
1772     return Op;
1773 
1774   // The folding we want to perform is:
1775   // (xor x, (select_cc a, b, cc, 0, -1) )
1776   //   -->
1777   // (csel x, (xor x, -1), cc ...)
1778   //
1779   // The latter will get matched to a CSINV instruction.
1780 
1781   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1782   SDValue LHS = Sel.getOperand(0);
1783   SDValue RHS = Sel.getOperand(1);
1784   SDValue TVal = Sel.getOperand(2);
1785   SDValue FVal = Sel.getOperand(3);
1786   SDLoc dl(Sel);
1787 
1788   // FIXME: This could be generalized to non-integer comparisons.
1789   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1790     return Op;
1791 
1792   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1793   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1794 
1795   // The values aren't constants, this isn't the pattern we're looking for.
1796   if (!CFVal || !CTVal)
1797     return Op;
1798 
1799   // We can commute the SELECT_CC by inverting the condition.  This
1800   // might be needed to make this fit into a CSINV pattern.
1801   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1802     std::swap(TVal, FVal);
1803     std::swap(CTVal, CFVal);
1804     CC = ISD::getSetCCInverse(CC, true);
1805   }
1806 
1807   // If the constants line up, perform the transform!
1808   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1809     SDValue CCVal;
1810     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1811 
1812     FVal = Other;
1813     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1814                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1815 
1816     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1817                        CCVal, Cmp);
1818   }
1819 
1820   return Op;
1821 }
1822 
1823 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1824   EVT VT = Op.getValueType();
1825 
1826   // Let legalize expand this if it isn't a legal type yet.
1827   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1828     return SDValue();
1829 
1830   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1831 
1832   unsigned Opc;
1833   bool ExtraOp = false;
1834   switch (Op.getOpcode()) {
1835   default:
1836     llvm_unreachable("Invalid code");
1837   case ISD::ADDC:
1838     Opc = AArch64ISD::ADDS;
1839     break;
1840   case ISD::SUBC:
1841     Opc = AArch64ISD::SUBS;
1842     break;
1843   case ISD::ADDE:
1844     Opc = AArch64ISD::ADCS;
1845     ExtraOp = true;
1846     break;
1847   case ISD::SUBE:
1848     Opc = AArch64ISD::SBCS;
1849     ExtraOp = true;
1850     break;
1851   }
1852 
1853   if (!ExtraOp)
1854     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1855   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1856                      Op.getOperand(2));
1857 }
1858 
1859 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1860   // Let legalize expand this if it isn't a legal type yet.
1861   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1862     return SDValue();
1863 
1864   SDLoc dl(Op);
1865   AArch64CC::CondCode CC;
1866   // The actual operation that sets the overflow or carry flag.
1867   SDValue Value, Overflow;
1868   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1869 
1870   // We use 0 and 1 as false and true values.
1871   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1872   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1873 
1874   // We use an inverted condition, because the conditional select is inverted
1875   // too. This will allow it to be selected to a single instruction:
1876   // CSINC Wd, WZR, WZR, invert(cond).
1877   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1878   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1879                          CCVal, Overflow);
1880 
1881   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1882   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1883 }
1884 
1885 // Prefetch operands are:
1886 // 1: Address to prefetch
1887 // 2: bool isWrite
1888 // 3: int locality (0 = no locality ... 3 = extreme locality)
1889 // 4: bool isDataCache
1890 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1891   SDLoc DL(Op);
1892   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1893   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1894   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1895 
1896   bool IsStream = !Locality;
1897   // When the locality number is set
1898   if (Locality) {
1899     // The front-end should have filtered out the out-of-range values
1900     assert(Locality <= 3 && "Prefetch locality out-of-range");
1901     // The locality degree is the opposite of the cache speed.
1902     // Put the number the other way around.
1903     // The encoding starts at 0 for level 1
1904     Locality = 3 - Locality;
1905   }
1906 
1907   // built the mask value encoding the expected behavior.
1908   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1909                    (!IsData << 3) |     // IsDataCache bit
1910                    (Locality << 1) |    // Cache level bits
1911                    (unsigned)IsStream;  // Stream bit
1912   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1913                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1914 }
1915 
1916 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1917                                               SelectionDAG &DAG) const {
1918   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1919 
1920   RTLIB::Libcall LC;
1921   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1922 
1923   return LowerF128Call(Op, DAG, LC);
1924 }
1925 
1926 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1927                                              SelectionDAG &DAG) const {
1928   if (Op.getOperand(0).getValueType() != MVT::f128) {
1929     // It's legal except when f128 is involved
1930     return Op;
1931   }
1932 
1933   RTLIB::Libcall LC;
1934   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1935 
1936   // FP_ROUND node has a second operand indicating whether it is known to be
1937   // precise. That doesn't take part in the LibCall so we can't directly use
1938   // LowerF128Call.
1939   SDValue SrcVal = Op.getOperand(0);
1940   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1941                      SDLoc(Op)).first;
1942 }
1943 
1944 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1945   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1946   // Any additional optimization in this function should be recorded
1947   // in the cost tables.
1948   EVT InVT = Op.getOperand(0).getValueType();
1949   EVT VT = Op.getValueType();
1950   unsigned NumElts = InVT.getVectorNumElements();
1951 
1952   // f16 vectors are promoted to f32 before a conversion.
1953   if (InVT.getVectorElementType() == MVT::f16) {
1954     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1955     SDLoc dl(Op);
1956     return DAG.getNode(
1957         Op.getOpcode(), dl, Op.getValueType(),
1958         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1959   }
1960 
1961   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1962     SDLoc dl(Op);
1963     SDValue Cv =
1964         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1965                     Op.getOperand(0));
1966     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1967   }
1968 
1969   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1970     SDLoc dl(Op);
1971     MVT ExtVT =
1972         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1973                          VT.getVectorNumElements());
1974     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1975     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1976   }
1977 
1978   // Type changing conversions are illegal.
1979   return Op;
1980 }
1981 
1982 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1983                                               SelectionDAG &DAG) const {
1984   if (Op.getOperand(0).getValueType().isVector())
1985     return LowerVectorFP_TO_INT(Op, DAG);
1986 
1987   // f16 conversions are promoted to f32.
1988   if (Op.getOperand(0).getValueType() == MVT::f16) {
1989     SDLoc dl(Op);
1990     return DAG.getNode(
1991         Op.getOpcode(), dl, Op.getValueType(),
1992         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1993   }
1994 
1995   if (Op.getOperand(0).getValueType() != MVT::f128) {
1996     // It's legal except when f128 is involved
1997     return Op;
1998   }
1999 
2000   RTLIB::Libcall LC;
2001   if (Op.getOpcode() == ISD::FP_TO_SINT)
2002     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2003   else
2004     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2005 
2006   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2007   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2008 }
2009 
2010 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2011   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2012   // Any additional optimization in this function should be recorded
2013   // in the cost tables.
2014   EVT VT = Op.getValueType();
2015   SDLoc dl(Op);
2016   SDValue In = Op.getOperand(0);
2017   EVT InVT = In.getValueType();
2018 
2019   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2020     MVT CastVT =
2021         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2022                          InVT.getVectorNumElements());
2023     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2024     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2025   }
2026 
2027   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2028     unsigned CastOpc =
2029         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2030     EVT CastVT = VT.changeVectorElementTypeToInteger();
2031     In = DAG.getNode(CastOpc, dl, CastVT, In);
2032     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2033   }
2034 
2035   return Op;
2036 }
2037 
2038 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2039                                             SelectionDAG &DAG) const {
2040   if (Op.getValueType().isVector())
2041     return LowerVectorINT_TO_FP(Op, DAG);
2042 
2043   // f16 conversions are promoted to f32.
2044   if (Op.getValueType() == MVT::f16) {
2045     SDLoc dl(Op);
2046     return DAG.getNode(
2047         ISD::FP_ROUND, dl, MVT::f16,
2048         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2049         DAG.getIntPtrConstant(0, dl));
2050   }
2051 
2052   // i128 conversions are libcalls.
2053   if (Op.getOperand(0).getValueType() == MVT::i128)
2054     return SDValue();
2055 
2056   // Other conversions are legal, unless it's to the completely software-based
2057   // fp128.
2058   if (Op.getValueType() != MVT::f128)
2059     return Op;
2060 
2061   RTLIB::Libcall LC;
2062   if (Op.getOpcode() == ISD::SINT_TO_FP)
2063     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2064   else
2065     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2066 
2067   return LowerF128Call(Op, DAG, LC);
2068 }
2069 
2070 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2071                                             SelectionDAG &DAG) const {
2072   // For iOS, we want to call an alternative entry point: __sincos_stret,
2073   // which returns the values in two S / D registers.
2074   SDLoc dl(Op);
2075   SDValue Arg = Op.getOperand(0);
2076   EVT ArgVT = Arg.getValueType();
2077   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2078 
2079   ArgListTy Args;
2080   ArgListEntry Entry;
2081 
2082   Entry.Node = Arg;
2083   Entry.Ty = ArgTy;
2084   Entry.isSExt = false;
2085   Entry.isZExt = false;
2086   Args.push_back(Entry);
2087 
2088   const char *LibcallName =
2089       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2090   SDValue Callee =
2091       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2092 
2093   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2094   TargetLowering::CallLoweringInfo CLI(DAG);
2095   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2096     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
2097 
2098   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2099   return CallResult.first;
2100 }
2101 
2102 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2103   if (Op.getValueType() != MVT::f16)
2104     return SDValue();
2105 
2106   assert(Op.getOperand(0).getValueType() == MVT::i16);
2107   SDLoc DL(Op);
2108 
2109   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2110   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2111   return SDValue(
2112       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2113                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2114       0);
2115 }
2116 
2117 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2118   if (OrigVT.getSizeInBits() >= 64)
2119     return OrigVT;
2120 
2121   assert(OrigVT.isSimple() && "Expecting a simple value type");
2122 
2123   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2124   switch (OrigSimpleTy) {
2125   default: llvm_unreachable("Unexpected Vector Type");
2126   case MVT::v2i8:
2127   case MVT::v2i16:
2128      return MVT::v2i32;
2129   case MVT::v4i8:
2130     return  MVT::v4i16;
2131   }
2132 }
2133 
2134 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2135                                                  const EVT &OrigTy,
2136                                                  const EVT &ExtTy,
2137                                                  unsigned ExtOpcode) {
2138   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2139   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2140   // 64-bits we need to insert a new extension so that it will be 64-bits.
2141   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2142   if (OrigTy.getSizeInBits() >= 64)
2143     return N;
2144 
2145   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2146   EVT NewVT = getExtensionTo64Bits(OrigTy);
2147 
2148   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2149 }
2150 
2151 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2152                                    bool isSigned) {
2153   EVT VT = N->getValueType(0);
2154 
2155   if (N->getOpcode() != ISD::BUILD_VECTOR)
2156     return false;
2157 
2158   for (const SDValue &Elt : N->op_values()) {
2159     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2160       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2161       unsigned HalfSize = EltSize / 2;
2162       if (isSigned) {
2163         if (!isIntN(HalfSize, C->getSExtValue()))
2164           return false;
2165       } else {
2166         if (!isUIntN(HalfSize, C->getZExtValue()))
2167           return false;
2168       }
2169       continue;
2170     }
2171     return false;
2172   }
2173 
2174   return true;
2175 }
2176 
2177 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2178   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2179     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2180                                              N->getOperand(0)->getValueType(0),
2181                                              N->getValueType(0),
2182                                              N->getOpcode());
2183 
2184   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2185   EVT VT = N->getValueType(0);
2186   SDLoc dl(N);
2187   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2188   unsigned NumElts = VT.getVectorNumElements();
2189   MVT TruncVT = MVT::getIntegerVT(EltSize);
2190   SmallVector<SDValue, 8> Ops;
2191   for (unsigned i = 0; i != NumElts; ++i) {
2192     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2193     const APInt &CInt = C->getAPIntValue();
2194     // Element types smaller than 32 bits are not legal, so use i32 elements.
2195     // The values are implicitly truncated so sext vs. zext doesn't matter.
2196     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2197   }
2198   return DAG.getNode(ISD::BUILD_VECTOR, dl,
2199                      MVT::getVectorVT(TruncVT, NumElts), Ops);
2200 }
2201 
2202 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2203   if (N->getOpcode() == ISD::SIGN_EXTEND)
2204     return true;
2205   if (isExtendedBUILD_VECTOR(N, DAG, true))
2206     return true;
2207   return false;
2208 }
2209 
2210 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2211   if (N->getOpcode() == ISD::ZERO_EXTEND)
2212     return true;
2213   if (isExtendedBUILD_VECTOR(N, DAG, false))
2214     return true;
2215   return false;
2216 }
2217 
2218 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2219   unsigned Opcode = N->getOpcode();
2220   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2221     SDNode *N0 = N->getOperand(0).getNode();
2222     SDNode *N1 = N->getOperand(1).getNode();
2223     return N0->hasOneUse() && N1->hasOneUse() &&
2224       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2225   }
2226   return false;
2227 }
2228 
2229 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2230   unsigned Opcode = N->getOpcode();
2231   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2232     SDNode *N0 = N->getOperand(0).getNode();
2233     SDNode *N1 = N->getOperand(1).getNode();
2234     return N0->hasOneUse() && N1->hasOneUse() &&
2235       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2236   }
2237   return false;
2238 }
2239 
2240 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2241   // Multiplications are only custom-lowered for 128-bit vectors so that
2242   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2243   EVT VT = Op.getValueType();
2244   assert(VT.is128BitVector() && VT.isInteger() &&
2245          "unexpected type for custom-lowering ISD::MUL");
2246   SDNode *N0 = Op.getOperand(0).getNode();
2247   SDNode *N1 = Op.getOperand(1).getNode();
2248   unsigned NewOpc = 0;
2249   bool isMLA = false;
2250   bool isN0SExt = isSignExtended(N0, DAG);
2251   bool isN1SExt = isSignExtended(N1, DAG);
2252   if (isN0SExt && isN1SExt)
2253     NewOpc = AArch64ISD::SMULL;
2254   else {
2255     bool isN0ZExt = isZeroExtended(N0, DAG);
2256     bool isN1ZExt = isZeroExtended(N1, DAG);
2257     if (isN0ZExt && isN1ZExt)
2258       NewOpc = AArch64ISD::UMULL;
2259     else if (isN1SExt || isN1ZExt) {
2260       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2261       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2262       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2263         NewOpc = AArch64ISD::SMULL;
2264         isMLA = true;
2265       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2266         NewOpc =  AArch64ISD::UMULL;
2267         isMLA = true;
2268       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2269         std::swap(N0, N1);
2270         NewOpc =  AArch64ISD::UMULL;
2271         isMLA = true;
2272       }
2273     }
2274 
2275     if (!NewOpc) {
2276       if (VT == MVT::v2i64)
2277         // Fall through to expand this.  It is not legal.
2278         return SDValue();
2279       else
2280         // Other vector multiplications are legal.
2281         return Op;
2282     }
2283   }
2284 
2285   // Legalize to a S/UMULL instruction
2286   SDLoc DL(Op);
2287   SDValue Op0;
2288   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2289   if (!isMLA) {
2290     Op0 = skipExtensionForVectorMULL(N0, DAG);
2291     assert(Op0.getValueType().is64BitVector() &&
2292            Op1.getValueType().is64BitVector() &&
2293            "unexpected types for extended operands to VMULL");
2294     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2295   }
2296   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2297   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2298   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2299   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2300   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2301   EVT Op1VT = Op1.getValueType();
2302   return DAG.getNode(N0->getOpcode(), DL, VT,
2303                      DAG.getNode(NewOpc, DL, VT,
2304                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2305                      DAG.getNode(NewOpc, DL, VT,
2306                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2307 }
2308 
2309 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2310                                                      SelectionDAG &DAG) const {
2311   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2312   SDLoc dl(Op);
2313   switch (IntNo) {
2314   default: return SDValue();    // Don't custom lower most intrinsics.
2315   case Intrinsic::aarch64_thread_pointer: {
2316     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2317     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2318   }
2319   case Intrinsic::aarch64_neon_smax:
2320     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2321                        Op.getOperand(1), Op.getOperand(2));
2322   case Intrinsic::aarch64_neon_umax:
2323     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2324                        Op.getOperand(1), Op.getOperand(2));
2325   case Intrinsic::aarch64_neon_smin:
2326     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2327                        Op.getOperand(1), Op.getOperand(2));
2328   case Intrinsic::aarch64_neon_umin:
2329     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2330                        Op.getOperand(1), Op.getOperand(2));
2331   }
2332 }
2333 
2334 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2335                                               SelectionDAG &DAG) const {
2336   switch (Op.getOpcode()) {
2337   default:
2338     llvm_unreachable("unimplemented operand");
2339     return SDValue();
2340   case ISD::BITCAST:
2341     return LowerBITCAST(Op, DAG);
2342   case ISD::GlobalAddress:
2343     return LowerGlobalAddress(Op, DAG);
2344   case ISD::GlobalTLSAddress:
2345     return LowerGlobalTLSAddress(Op, DAG);
2346   case ISD::SETCC:
2347     return LowerSETCC(Op, DAG);
2348   case ISD::BR_CC:
2349     return LowerBR_CC(Op, DAG);
2350   case ISD::SELECT:
2351     return LowerSELECT(Op, DAG);
2352   case ISD::SELECT_CC:
2353     return LowerSELECT_CC(Op, DAG);
2354   case ISD::JumpTable:
2355     return LowerJumpTable(Op, DAG);
2356   case ISD::ConstantPool:
2357     return LowerConstantPool(Op, DAG);
2358   case ISD::BlockAddress:
2359     return LowerBlockAddress(Op, DAG);
2360   case ISD::VASTART:
2361     return LowerVASTART(Op, DAG);
2362   case ISD::VACOPY:
2363     return LowerVACOPY(Op, DAG);
2364   case ISD::VAARG:
2365     return LowerVAARG(Op, DAG);
2366   case ISD::ADDC:
2367   case ISD::ADDE:
2368   case ISD::SUBC:
2369   case ISD::SUBE:
2370     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2371   case ISD::SADDO:
2372   case ISD::UADDO:
2373   case ISD::SSUBO:
2374   case ISD::USUBO:
2375   case ISD::SMULO:
2376   case ISD::UMULO:
2377     return LowerXALUO(Op, DAG);
2378   case ISD::FADD:
2379     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2380   case ISD::FSUB:
2381     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2382   case ISD::FMUL:
2383     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2384   case ISD::FDIV:
2385     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2386   case ISD::FP_ROUND:
2387     return LowerFP_ROUND(Op, DAG);
2388   case ISD::FP_EXTEND:
2389     return LowerFP_EXTEND(Op, DAG);
2390   case ISD::FRAMEADDR:
2391     return LowerFRAMEADDR(Op, DAG);
2392   case ISD::RETURNADDR:
2393     return LowerRETURNADDR(Op, DAG);
2394   case ISD::INSERT_VECTOR_ELT:
2395     return LowerINSERT_VECTOR_ELT(Op, DAG);
2396   case ISD::EXTRACT_VECTOR_ELT:
2397     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2398   case ISD::BUILD_VECTOR:
2399     return LowerBUILD_VECTOR(Op, DAG);
2400   case ISD::VECTOR_SHUFFLE:
2401     return LowerVECTOR_SHUFFLE(Op, DAG);
2402   case ISD::EXTRACT_SUBVECTOR:
2403     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2404   case ISD::SRA:
2405   case ISD::SRL:
2406   case ISD::SHL:
2407     return LowerVectorSRA_SRL_SHL(Op, DAG);
2408   case ISD::SHL_PARTS:
2409     return LowerShiftLeftParts(Op, DAG);
2410   case ISD::SRL_PARTS:
2411   case ISD::SRA_PARTS:
2412     return LowerShiftRightParts(Op, DAG);
2413   case ISD::CTPOP:
2414     return LowerCTPOP(Op, DAG);
2415   case ISD::FCOPYSIGN:
2416     return LowerFCOPYSIGN(Op, DAG);
2417   case ISD::AND:
2418     return LowerAND(Op, DAG);
2419   case ISD::OR:
2420     return LowerOR(Op, DAG);
2421   case ISD::XOR:
2422     return LowerXOR(Op, DAG);
2423   case ISD::PREFETCH:
2424     return LowerPREFETCH(Op, DAG);
2425   case ISD::SINT_TO_FP:
2426   case ISD::UINT_TO_FP:
2427     return LowerINT_TO_FP(Op, DAG);
2428   case ISD::FP_TO_SINT:
2429   case ISD::FP_TO_UINT:
2430     return LowerFP_TO_INT(Op, DAG);
2431   case ISD::FSINCOS:
2432     return LowerFSINCOS(Op, DAG);
2433   case ISD::MUL:
2434     return LowerMUL(Op, DAG);
2435   case ISD::INTRINSIC_WO_CHAIN:
2436     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2437   }
2438 }
2439 
2440 //===----------------------------------------------------------------------===//
2441 //                      Calling Convention Implementation
2442 //===----------------------------------------------------------------------===//
2443 
2444 #include "AArch64GenCallingConv.inc"
2445 
2446 /// Selects the correct CCAssignFn for a given CallingConvention value.
2447 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2448                                                      bool IsVarArg) const {
2449   switch (CC) {
2450   default:
2451     llvm_unreachable("Unsupported calling convention.");
2452   case CallingConv::WebKit_JS:
2453     return CC_AArch64_WebKit_JS;
2454   case CallingConv::GHC:
2455     return CC_AArch64_GHC;
2456   case CallingConv::C:
2457   case CallingConv::Fast:
2458     if (!Subtarget->isTargetDarwin())
2459       return CC_AArch64_AAPCS;
2460     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2461   }
2462 }
2463 
2464 SDValue AArch64TargetLowering::LowerFormalArguments(
2465     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2466     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2467     SmallVectorImpl<SDValue> &InVals) const {
2468   MachineFunction &MF = DAG.getMachineFunction();
2469   MachineFrameInfo *MFI = MF.getFrameInfo();
2470 
2471   // Assign locations to all of the incoming arguments.
2472   SmallVector<CCValAssign, 16> ArgLocs;
2473   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2474                  *DAG.getContext());
2475 
2476   // At this point, Ins[].VT may already be promoted to i32. To correctly
2477   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2478   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2479   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2480   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2481   // LocVT.
2482   unsigned NumArgs = Ins.size();
2483   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2484   unsigned CurArgIdx = 0;
2485   for (unsigned i = 0; i != NumArgs; ++i) {
2486     MVT ValVT = Ins[i].VT;
2487     if (Ins[i].isOrigArg()) {
2488       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2489       CurArgIdx = Ins[i].getOrigArgIndex();
2490 
2491       // Get type of the original argument.
2492       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2493                                   /*AllowUnknown*/ true);
2494       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2495       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2496       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2497         ValVT = MVT::i8;
2498       else if (ActualMVT == MVT::i16)
2499         ValVT = MVT::i16;
2500     }
2501     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2502     bool Res =
2503         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2504     assert(!Res && "Call operand has unhandled type");
2505     (void)Res;
2506   }
2507   assert(ArgLocs.size() == Ins.size());
2508   SmallVector<SDValue, 16> ArgValues;
2509   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2510     CCValAssign &VA = ArgLocs[i];
2511 
2512     if (Ins[i].Flags.isByVal()) {
2513       // Byval is used for HFAs in the PCS, but the system should work in a
2514       // non-compliant manner for larger structs.
2515       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2516       int Size = Ins[i].Flags.getByValSize();
2517       unsigned NumRegs = (Size + 7) / 8;
2518 
2519       // FIXME: This works on big-endian for composite byvals, which are the common
2520       // case. It should also work for fundamental types too.
2521       unsigned FrameIdx =
2522         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2523       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2524       InVals.push_back(FrameIdxN);
2525 
2526       continue;
2527     }
2528 
2529     if (VA.isRegLoc()) {
2530       // Arguments stored in registers.
2531       EVT RegVT = VA.getLocVT();
2532 
2533       SDValue ArgValue;
2534       const TargetRegisterClass *RC;
2535 
2536       if (RegVT == MVT::i32)
2537         RC = &AArch64::GPR32RegClass;
2538       else if (RegVT == MVT::i64)
2539         RC = &AArch64::GPR64RegClass;
2540       else if (RegVT == MVT::f16)
2541         RC = &AArch64::FPR16RegClass;
2542       else if (RegVT == MVT::f32)
2543         RC = &AArch64::FPR32RegClass;
2544       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2545         RC = &AArch64::FPR64RegClass;
2546       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2547         RC = &AArch64::FPR128RegClass;
2548       else
2549         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2550 
2551       // Transform the arguments in physical registers into virtual ones.
2552       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2553       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2554 
2555       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2556       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2557       // truncate to the right size.
2558       switch (VA.getLocInfo()) {
2559       default:
2560         llvm_unreachable("Unknown loc info!");
2561       case CCValAssign::Full:
2562         break;
2563       case CCValAssign::BCvt:
2564         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2565         break;
2566       case CCValAssign::AExt:
2567       case CCValAssign::SExt:
2568       case CCValAssign::ZExt:
2569         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2570         // nodes after our lowering.
2571         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2572         break;
2573       }
2574 
2575       InVals.push_back(ArgValue);
2576 
2577     } else { // VA.isRegLoc()
2578       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2579       unsigned ArgOffset = VA.getLocMemOffset();
2580       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2581 
2582       uint32_t BEAlign = 0;
2583       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2584           !Ins[i].Flags.isInConsecutiveRegs())
2585         BEAlign = 8 - ArgSize;
2586 
2587       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2588 
2589       // Create load nodes to retrieve arguments from the stack.
2590       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2591       SDValue ArgValue;
2592 
2593       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2594       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2595       MVT MemVT = VA.getValVT();
2596 
2597       switch (VA.getLocInfo()) {
2598       default:
2599         break;
2600       case CCValAssign::BCvt:
2601         MemVT = VA.getLocVT();
2602         break;
2603       case CCValAssign::SExt:
2604         ExtType = ISD::SEXTLOAD;
2605         break;
2606       case CCValAssign::ZExt:
2607         ExtType = ISD::ZEXTLOAD;
2608         break;
2609       case CCValAssign::AExt:
2610         ExtType = ISD::EXTLOAD;
2611         break;
2612       }
2613 
2614       ArgValue = DAG.getExtLoad(
2615           ExtType, DL, VA.getLocVT(), Chain, FIN,
2616           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2617           MemVT, false, false, false, 0);
2618 
2619       InVals.push_back(ArgValue);
2620     }
2621   }
2622 
2623   // varargs
2624   if (isVarArg) {
2625     if (!Subtarget->isTargetDarwin()) {
2626       // The AAPCS variadic function ABI is identical to the non-variadic
2627       // one. As a result there may be more arguments in registers and we should
2628       // save them for future reference.
2629       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2630     }
2631 
2632     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2633     // This will point to the next argument passed via stack.
2634     unsigned StackOffset = CCInfo.getNextStackOffset();
2635     // We currently pass all varargs at 8-byte alignment.
2636     StackOffset = ((StackOffset + 7) & ~7);
2637     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2638   }
2639 
2640   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2641   unsigned StackArgSize = CCInfo.getNextStackOffset();
2642   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2643   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2644     // This is a non-standard ABI so by fiat I say we're allowed to make full
2645     // use of the stack area to be popped, which must be aligned to 16 bytes in
2646     // any case:
2647     StackArgSize = alignTo(StackArgSize, 16);
2648 
2649     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2650     // a multiple of 16.
2651     FuncInfo->setArgumentStackToRestore(StackArgSize);
2652 
2653     // This realignment carries over to the available bytes below. Our own
2654     // callers will guarantee the space is free by giving an aligned value to
2655     // CALLSEQ_START.
2656   }
2657   // Even if we're not expected to free up the space, it's useful to know how
2658   // much is there while considering tail calls (because we can reuse it).
2659   FuncInfo->setBytesInStackArgArea(StackArgSize);
2660 
2661   return Chain;
2662 }
2663 
2664 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2665                                                 SelectionDAG &DAG, SDLoc DL,
2666                                                 SDValue &Chain) const {
2667   MachineFunction &MF = DAG.getMachineFunction();
2668   MachineFrameInfo *MFI = MF.getFrameInfo();
2669   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2670   auto PtrVT = getPointerTy(DAG.getDataLayout());
2671 
2672   SmallVector<SDValue, 8> MemOps;
2673 
2674   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2675                                           AArch64::X3, AArch64::X4, AArch64::X5,
2676                                           AArch64::X6, AArch64::X7 };
2677   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2678   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2679 
2680   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2681   int GPRIdx = 0;
2682   if (GPRSaveSize != 0) {
2683     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2684 
2685     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2686 
2687     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2688       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2689       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2690       SDValue Store = DAG.getStore(
2691           Val.getValue(1), DL, Val, FIN,
2692           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2693           false, 0);
2694       MemOps.push_back(Store);
2695       FIN =
2696           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2697     }
2698   }
2699   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2700   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2701 
2702   if (Subtarget->hasFPARMv8()) {
2703     static const MCPhysReg FPRArgRegs[] = {
2704         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2705         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2706     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2707     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2708 
2709     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2710     int FPRIdx = 0;
2711     if (FPRSaveSize != 0) {
2712       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2713 
2714       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2715 
2716       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2717         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2718         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2719 
2720         SDValue Store = DAG.getStore(
2721             Val.getValue(1), DL, Val, FIN,
2722             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2723             false, false, 0);
2724         MemOps.push_back(Store);
2725         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2726                           DAG.getConstant(16, DL, PtrVT));
2727       }
2728     }
2729     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2730     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2731   }
2732 
2733   if (!MemOps.empty()) {
2734     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2735   }
2736 }
2737 
2738 /// LowerCallResult - Lower the result values of a call into the
2739 /// appropriate copies out of appropriate physical registers.
2740 SDValue AArch64TargetLowering::LowerCallResult(
2741     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2742     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2743     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2744     SDValue ThisVal) const {
2745   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2746                           ? RetCC_AArch64_WebKit_JS
2747                           : RetCC_AArch64_AAPCS;
2748   // Assign locations to each value returned by this call.
2749   SmallVector<CCValAssign, 16> RVLocs;
2750   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2751                  *DAG.getContext());
2752   CCInfo.AnalyzeCallResult(Ins, RetCC);
2753 
2754   // Copy all of the result registers out of their specified physreg.
2755   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2756     CCValAssign VA = RVLocs[i];
2757 
2758     // Pass 'this' value directly from the argument to return value, to avoid
2759     // reg unit interference
2760     if (i == 0 && isThisReturn) {
2761       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2762              "unexpected return calling convention register assignment");
2763       InVals.push_back(ThisVal);
2764       continue;
2765     }
2766 
2767     SDValue Val =
2768         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2769     Chain = Val.getValue(1);
2770     InFlag = Val.getValue(2);
2771 
2772     switch (VA.getLocInfo()) {
2773     default:
2774       llvm_unreachable("Unknown loc info!");
2775     case CCValAssign::Full:
2776       break;
2777     case CCValAssign::BCvt:
2778       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2779       break;
2780     }
2781 
2782     InVals.push_back(Val);
2783   }
2784 
2785   return Chain;
2786 }
2787 
2788 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2789     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2790     bool isCalleeStructRet, bool isCallerStructRet,
2791     const SmallVectorImpl<ISD::OutputArg> &Outs,
2792     const SmallVectorImpl<SDValue> &OutVals,
2793     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2794   // For CallingConv::C this function knows whether the ABI needs
2795   // changing. That's not true for other conventions so they will have to opt in
2796   // manually.
2797   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2798     return false;
2799 
2800   const MachineFunction &MF = DAG.getMachineFunction();
2801   const Function *CallerF = MF.getFunction();
2802   CallingConv::ID CallerCC = CallerF->getCallingConv();
2803   bool CCMatch = CallerCC == CalleeCC;
2804 
2805   // Byval parameters hand the function a pointer directly into the stack area
2806   // we want to reuse during a tail call. Working around this *is* possible (see
2807   // X86) but less efficient and uglier in LowerCall.
2808   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809                                     e = CallerF->arg_end();
2810        i != e; ++i)
2811     if (i->hasByValAttr())
2812       return false;
2813 
2814   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2815     if (IsTailCallConvention(CalleeCC) && CCMatch)
2816       return true;
2817     return false;
2818   }
2819 
2820   // Externally-defined functions with weak linkage should not be
2821   // tail-called on AArch64 when the OS does not support dynamic
2822   // pre-emption of symbols, as the AAELF spec requires normal calls
2823   // to undefined weak functions to be replaced with a NOP or jump to the
2824   // next instruction. The behaviour of branch instructions in this
2825   // situation (as used for tail calls) is implementation-defined, so we
2826   // cannot rely on the linker replacing the tail call with a return.
2827   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2828     const GlobalValue *GV = G->getGlobal();
2829     const Triple &TT = getTargetMachine().getTargetTriple();
2830     if (GV->hasExternalWeakLinkage() &&
2831         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2832       return false;
2833   }
2834 
2835   // Now we search for cases where we can use a tail call without changing the
2836   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2837   // concept.
2838 
2839   // I want anyone implementing a new calling convention to think long and hard
2840   // about this assert.
2841   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2842          "Unexpected variadic calling convention");
2843 
2844   if (isVarArg && !Outs.empty()) {
2845     // At least two cases here: if caller is fastcc then we can't have any
2846     // memory arguments (we'd be expected to clean up the stack afterwards). If
2847     // caller is C then we could potentially use its argument area.
2848 
2849     // FIXME: for now we take the most conservative of these in both cases:
2850     // disallow all variadic memory operands.
2851     SmallVector<CCValAssign, 16> ArgLocs;
2852     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2853                    *DAG.getContext());
2854 
2855     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2856     for (const CCValAssign &ArgLoc : ArgLocs)
2857       if (!ArgLoc.isRegLoc())
2858         return false;
2859   }
2860 
2861   // If the calling conventions do not match, then we'd better make sure the
2862   // results are returned in the same way as what the caller expects.
2863   if (!CCMatch) {
2864     SmallVector<CCValAssign, 16> RVLocs1;
2865     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2866                     *DAG.getContext());
2867     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2868 
2869     SmallVector<CCValAssign, 16> RVLocs2;
2870     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2871                     *DAG.getContext());
2872     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2873 
2874     if (RVLocs1.size() != RVLocs2.size())
2875       return false;
2876     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2877       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2878         return false;
2879       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2880         return false;
2881       if (RVLocs1[i].isRegLoc()) {
2882         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2883           return false;
2884       } else {
2885         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2886           return false;
2887       }
2888     }
2889   }
2890 
2891   // Nothing more to check if the callee is taking no arguments
2892   if (Outs.empty())
2893     return true;
2894 
2895   SmallVector<CCValAssign, 16> ArgLocs;
2896   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2897                  *DAG.getContext());
2898 
2899   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2900 
2901   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2902 
2903   // If the stack arguments for this call would fit into our own save area then
2904   // the call can be made tail.
2905   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2906 }
2907 
2908 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2909                                                    SelectionDAG &DAG,
2910                                                    MachineFrameInfo *MFI,
2911                                                    int ClobberedFI) const {
2912   SmallVector<SDValue, 8> ArgChains;
2913   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2914   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2915 
2916   // Include the original chain at the beginning of the list. When this is
2917   // used by target LowerCall hooks, this helps legalize find the
2918   // CALLSEQ_BEGIN node.
2919   ArgChains.push_back(Chain);
2920 
2921   // Add a chain value for each stack argument corresponding
2922   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2923                             UE = DAG.getEntryNode().getNode()->use_end();
2924        U != UE; ++U)
2925     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2926       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2927         if (FI->getIndex() < 0) {
2928           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2929           int64_t InLastByte = InFirstByte;
2930           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2931 
2932           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2933               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2934             ArgChains.push_back(SDValue(L, 1));
2935         }
2936 
2937   // Build a tokenfactor for all the chains.
2938   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2939 }
2940 
2941 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2942                                                    bool TailCallOpt) const {
2943   return CallCC == CallingConv::Fast && TailCallOpt;
2944 }
2945 
2946 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2947   return CallCC == CallingConv::Fast;
2948 }
2949 
2950 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2951 /// and add input and output parameter nodes.
2952 SDValue
2953 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2954                                  SmallVectorImpl<SDValue> &InVals) const {
2955   SelectionDAG &DAG = CLI.DAG;
2956   SDLoc &DL = CLI.DL;
2957   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2958   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2959   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2960   SDValue Chain = CLI.Chain;
2961   SDValue Callee = CLI.Callee;
2962   bool &IsTailCall = CLI.IsTailCall;
2963   CallingConv::ID CallConv = CLI.CallConv;
2964   bool IsVarArg = CLI.IsVarArg;
2965 
2966   MachineFunction &MF = DAG.getMachineFunction();
2967   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2968   bool IsThisReturn = false;
2969 
2970   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2971   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2972   bool IsSibCall = false;
2973 
2974   if (IsTailCall) {
2975     // Check if it's really possible to do a tail call.
2976     IsTailCall = isEligibleForTailCallOptimization(
2977         Callee, CallConv, IsVarArg, IsStructRet,
2978         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2979     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2980       report_fatal_error("failed to perform tail call elimination on a call "
2981                          "site marked musttail");
2982 
2983     // A sibling call is one where we're under the usual C ABI and not planning
2984     // to change that but can still do a tail call:
2985     if (!TailCallOpt && IsTailCall)
2986       IsSibCall = true;
2987 
2988     if (IsTailCall)
2989       ++NumTailCalls;
2990   }
2991 
2992   // Analyze operands of the call, assigning locations to each operand.
2993   SmallVector<CCValAssign, 16> ArgLocs;
2994   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2995                  *DAG.getContext());
2996 
2997   if (IsVarArg) {
2998     // Handle fixed and variable vector arguments differently.
2999     // Variable vector arguments always go into memory.
3000     unsigned NumArgs = Outs.size();
3001 
3002     for (unsigned i = 0; i != NumArgs; ++i) {
3003       MVT ArgVT = Outs[i].VT;
3004       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3005       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3006                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3007       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3008       assert(!Res && "Call operand has unhandled type");
3009       (void)Res;
3010     }
3011   } else {
3012     // At this point, Outs[].VT may already be promoted to i32. To correctly
3013     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3014     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3015     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3016     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3017     // LocVT.
3018     unsigned NumArgs = Outs.size();
3019     for (unsigned i = 0; i != NumArgs; ++i) {
3020       MVT ValVT = Outs[i].VT;
3021       // Get type of the original argument.
3022       EVT ActualVT = getValueType(DAG.getDataLayout(),
3023                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3024                                   /*AllowUnknown*/ true);
3025       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3026       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3027       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3028       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3029         ValVT = MVT::i8;
3030       else if (ActualMVT == MVT::i16)
3031         ValVT = MVT::i16;
3032 
3033       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3034       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3035       assert(!Res && "Call operand has unhandled type");
3036       (void)Res;
3037     }
3038   }
3039 
3040   // Get a count of how many bytes are to be pushed on the stack.
3041   unsigned NumBytes = CCInfo.getNextStackOffset();
3042 
3043   if (IsSibCall) {
3044     // Since we're not changing the ABI to make this a tail call, the memory
3045     // operands are already available in the caller's incoming argument space.
3046     NumBytes = 0;
3047   }
3048 
3049   // FPDiff is the byte offset of the call's argument area from the callee's.
3050   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3051   // by this amount for a tail call. In a sibling call it must be 0 because the
3052   // caller will deallocate the entire stack and the callee still expects its
3053   // arguments to begin at SP+0. Completely unused for non-tail calls.
3054   int FPDiff = 0;
3055 
3056   if (IsTailCall && !IsSibCall) {
3057     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3058 
3059     // Since callee will pop argument stack as a tail call, we must keep the
3060     // popped size 16-byte aligned.
3061     NumBytes = alignTo(NumBytes, 16);
3062 
3063     // FPDiff will be negative if this tail call requires more space than we
3064     // would automatically have in our incoming argument space. Positive if we
3065     // can actually shrink the stack.
3066     FPDiff = NumReusableBytes - NumBytes;
3067 
3068     // The stack pointer must be 16-byte aligned at all times it's used for a
3069     // memory operation, which in practice means at *all* times and in
3070     // particular across call boundaries. Therefore our own arguments started at
3071     // a 16-byte aligned SP and the delta applied for the tail call should
3072     // satisfy the same constraint.
3073     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3074   }
3075 
3076   // Adjust the stack pointer for the new arguments...
3077   // These operations are automatically eliminated by the prolog/epilog pass
3078   if (!IsSibCall)
3079     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3080                                                               true),
3081                                  DL);
3082 
3083   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3084                                         getPointerTy(DAG.getDataLayout()));
3085 
3086   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3087   SmallVector<SDValue, 8> MemOpChains;
3088   auto PtrVT = getPointerTy(DAG.getDataLayout());
3089 
3090   // Walk the register/memloc assignments, inserting copies/loads.
3091   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3092        ++i, ++realArgIdx) {
3093     CCValAssign &VA = ArgLocs[i];
3094     SDValue Arg = OutVals[realArgIdx];
3095     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3096 
3097     // Promote the value if needed.
3098     switch (VA.getLocInfo()) {
3099     default:
3100       llvm_unreachable("Unknown loc info!");
3101     case CCValAssign::Full:
3102       break;
3103     case CCValAssign::SExt:
3104       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3105       break;
3106     case CCValAssign::ZExt:
3107       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3108       break;
3109     case CCValAssign::AExt:
3110       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3111         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3112         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3113         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3114       }
3115       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3116       break;
3117     case CCValAssign::BCvt:
3118       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3119       break;
3120     case CCValAssign::FPExt:
3121       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3122       break;
3123     }
3124 
3125     if (VA.isRegLoc()) {
3126       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3127         assert(VA.getLocVT() == MVT::i64 &&
3128                "unexpected calling convention register assignment");
3129         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3130                "unexpected use of 'returned'");
3131         IsThisReturn = true;
3132       }
3133       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3134     } else {
3135       assert(VA.isMemLoc());
3136 
3137       SDValue DstAddr;
3138       MachinePointerInfo DstInfo;
3139 
3140       // FIXME: This works on big-endian for composite byvals, which are the
3141       // common case. It should also work for fundamental types too.
3142       uint32_t BEAlign = 0;
3143       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3144                                         : VA.getValVT().getSizeInBits();
3145       OpSize = (OpSize + 7) / 8;
3146       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3147           !Flags.isInConsecutiveRegs()) {
3148         if (OpSize < 8)
3149           BEAlign = 8 - OpSize;
3150       }
3151       unsigned LocMemOffset = VA.getLocMemOffset();
3152       int32_t Offset = LocMemOffset + BEAlign;
3153       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3154       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3155 
3156       if (IsTailCall) {
3157         Offset = Offset + FPDiff;
3158         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3159 
3160         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3161         DstInfo =
3162             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3163 
3164         // Make sure any stack arguments overlapping with where we're storing
3165         // are loaded before this eventual operation. Otherwise they'll be
3166         // clobbered.
3167         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3168       } else {
3169         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3170 
3171         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3172         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3173                                                LocMemOffset);
3174       }
3175 
3176       if (Outs[i].Flags.isByVal()) {
3177         SDValue SizeNode =
3178             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3179         SDValue Cpy = DAG.getMemcpy(
3180             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3181             /*isVol = */ false, /*AlwaysInline = */ false,
3182             /*isTailCall = */ false,
3183             DstInfo, MachinePointerInfo());
3184 
3185         MemOpChains.push_back(Cpy);
3186       } else {
3187         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3188         // promoted to a legal register type i32, we should truncate Arg back to
3189         // i1/i8/i16.
3190         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3191             VA.getValVT() == MVT::i16)
3192           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3193 
3194         SDValue Store =
3195             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3196         MemOpChains.push_back(Store);
3197       }
3198     }
3199   }
3200 
3201   if (!MemOpChains.empty())
3202     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3203 
3204   // Build a sequence of copy-to-reg nodes chained together with token chain
3205   // and flag operands which copy the outgoing args into the appropriate regs.
3206   SDValue InFlag;
3207   for (auto &RegToPass : RegsToPass) {
3208     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3209                              RegToPass.second, InFlag);
3210     InFlag = Chain.getValue(1);
3211   }
3212 
3213   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3214   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3215   // node so that legalize doesn't hack it.
3216   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3217       Subtarget->isTargetMachO()) {
3218     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3219       const GlobalValue *GV = G->getGlobal();
3220       bool InternalLinkage = GV->hasInternalLinkage();
3221       if (InternalLinkage)
3222         Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3223       else {
3224         Callee =
3225             DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3226         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3227       }
3228     } else if (ExternalSymbolSDNode *S =
3229                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
3230       const char *Sym = S->getSymbol();
3231       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3232       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3233     }
3234   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3235     const GlobalValue *GV = G->getGlobal();
3236     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3237   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3238     const char *Sym = S->getSymbol();
3239     Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3240   }
3241 
3242   // We don't usually want to end the call-sequence here because we would tidy
3243   // the frame up *after* the call, however in the ABI-changing tail-call case
3244   // we've carefully laid out the parameters so that when sp is reset they'll be
3245   // in the correct location.
3246   if (IsTailCall && !IsSibCall) {
3247     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3248                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3249     InFlag = Chain.getValue(1);
3250   }
3251 
3252   std::vector<SDValue> Ops;
3253   Ops.push_back(Chain);
3254   Ops.push_back(Callee);
3255 
3256   if (IsTailCall) {
3257     // Each tail call may have to adjust the stack by a different amount, so
3258     // this information must travel along with the operation for eventual
3259     // consumption by emitEpilogue.
3260     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3261   }
3262 
3263   // Add argument registers to the end of the list so that they are known live
3264   // into the call.
3265   for (auto &RegToPass : RegsToPass)
3266     Ops.push_back(DAG.getRegister(RegToPass.first,
3267                                   RegToPass.second.getValueType()));
3268 
3269   // Add a register mask operand representing the call-preserved registers.
3270   const uint32_t *Mask;
3271   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3272   if (IsThisReturn) {
3273     // For 'this' returns, use the X0-preserving mask if applicable
3274     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3275     if (!Mask) {
3276       IsThisReturn = false;
3277       Mask = TRI->getCallPreservedMask(MF, CallConv);
3278     }
3279   } else
3280     Mask = TRI->getCallPreservedMask(MF, CallConv);
3281 
3282   assert(Mask && "Missing call preserved mask for calling convention");
3283   Ops.push_back(DAG.getRegisterMask(Mask));
3284 
3285   if (InFlag.getNode())
3286     Ops.push_back(InFlag);
3287 
3288   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3289 
3290   // If we're doing a tall call, use a TC_RETURN here rather than an
3291   // actual call instruction.
3292   if (IsTailCall) {
3293     MF.getFrameInfo()->setHasTailCall();
3294     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3295   }
3296 
3297   // Returns a chain and a flag for retval copy to use.
3298   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3299   InFlag = Chain.getValue(1);
3300 
3301   uint64_t CalleePopBytes =
3302       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3303 
3304   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3305                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3306                              InFlag, DL);
3307   if (!Ins.empty())
3308     InFlag = Chain.getValue(1);
3309 
3310   // Handle result values, copying them out of physregs into vregs that we
3311   // return.
3312   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3313                          InVals, IsThisReturn,
3314                          IsThisReturn ? OutVals[0] : SDValue());
3315 }
3316 
3317 bool AArch64TargetLowering::CanLowerReturn(
3318     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3319     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3320   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3321                           ? RetCC_AArch64_WebKit_JS
3322                           : RetCC_AArch64_AAPCS;
3323   SmallVector<CCValAssign, 16> RVLocs;
3324   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3325   return CCInfo.CheckReturn(Outs, RetCC);
3326 }
3327 
3328 SDValue
3329 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3330                                    bool isVarArg,
3331                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3332                                    const SmallVectorImpl<SDValue> &OutVals,
3333                                    SDLoc DL, SelectionDAG &DAG) const {
3334   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3335                           ? RetCC_AArch64_WebKit_JS
3336                           : RetCC_AArch64_AAPCS;
3337   SmallVector<CCValAssign, 16> RVLocs;
3338   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3339                  *DAG.getContext());
3340   CCInfo.AnalyzeReturn(Outs, RetCC);
3341 
3342   // Copy the result values into the output registers.
3343   SDValue Flag;
3344   SmallVector<SDValue, 4> RetOps(1, Chain);
3345   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3346        ++i, ++realRVLocIdx) {
3347     CCValAssign &VA = RVLocs[i];
3348     assert(VA.isRegLoc() && "Can only return in registers!");
3349     SDValue Arg = OutVals[realRVLocIdx];
3350 
3351     switch (VA.getLocInfo()) {
3352     default:
3353       llvm_unreachable("Unknown loc info!");
3354     case CCValAssign::Full:
3355       if (Outs[i].ArgVT == MVT::i1) {
3356         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3357         // value. This is strictly redundant on Darwin (which uses "zeroext
3358         // i1"), but will be optimised out before ISel.
3359         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3360         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3361       }
3362       break;
3363     case CCValAssign::BCvt:
3364       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3365       break;
3366     }
3367 
3368     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3369     Flag = Chain.getValue(1);
3370     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3371   }
3372   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3373   const MCPhysReg *I =
3374       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3375   if (I) {
3376     for (; *I; ++I) {
3377       if (AArch64::GPR64RegClass.contains(*I))
3378         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3379       else if (AArch64::FPR64RegClass.contains(*I))
3380         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3381       else
3382         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3383     }
3384   }
3385 
3386   RetOps[0] = Chain; // Update chain.
3387 
3388   // Add the flag if we have it.
3389   if (Flag.getNode())
3390     RetOps.push_back(Flag);
3391 
3392   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3393 }
3394 
3395 //===----------------------------------------------------------------------===//
3396 //  Other Lowering Code
3397 //===----------------------------------------------------------------------===//
3398 
3399 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3400                                                   SelectionDAG &DAG) const {
3401   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3402   SDLoc DL(Op);
3403   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3404   const GlobalValue *GV = GN->getGlobal();
3405   unsigned char OpFlags =
3406       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3407 
3408   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3409          "unexpected offset in global node");
3410 
3411   // This also catched the large code model case for Darwin.
3412   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3413     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3414     // FIXME: Once remat is capable of dealing with instructions with register
3415     // operands, expand this into two nodes instead of using a wrapper node.
3416     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3417   }
3418 
3419   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3420     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3421            "use of MO_CONSTPOOL only supported on small model");
3422     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3423     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3424     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3425     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3426     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3427     SDValue GlobalAddr = DAG.getLoad(
3428         PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3429         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3430         /*isVolatile=*/false,
3431         /*isNonTemporal=*/true,
3432         /*isInvariant=*/true, 8);
3433     if (GN->getOffset() != 0)
3434       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3435                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3436     return GlobalAddr;
3437   }
3438 
3439   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3440     const unsigned char MO_NC = AArch64II::MO_NC;
3441     return DAG.getNode(
3442         AArch64ISD::WrapperLarge, DL, PtrVT,
3443         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3444         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3445         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3446         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3447   } else {
3448     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3449     // the only correct model on Darwin.
3450     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3451                                             OpFlags | AArch64II::MO_PAGE);
3452     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3453     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3454 
3455     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3456     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3457   }
3458 }
3459 
3460 /// \brief Convert a TLS address reference into the correct sequence of loads
3461 /// and calls to compute the variable's address (for Darwin, currently) and
3462 /// return an SDValue containing the final node.
3463 
3464 /// Darwin only has one TLS scheme which must be capable of dealing with the
3465 /// fully general situation, in the worst case. This means:
3466 ///     + "extern __thread" declaration.
3467 ///     + Defined in a possibly unknown dynamic library.
3468 ///
3469 /// The general system is that each __thread variable has a [3 x i64] descriptor
3470 /// which contains information used by the runtime to calculate the address. The
3471 /// only part of this the compiler needs to know about is the first xword, which
3472 /// contains a function pointer that must be called with the address of the
3473 /// entire descriptor in "x0".
3474 ///
3475 /// Since this descriptor may be in a different unit, in general even the
3476 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3477 /// is:
3478 ///     adrp x0, _var@TLVPPAGE
3479 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3480 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3481 ///                                      ; the function pointer
3482 ///     blr x1                           ; Uses descriptor address in x0
3483 ///     ; Address of _var is now in x0.
3484 ///
3485 /// If the address of _var's descriptor *is* known to the linker, then it can
3486 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3487 /// a slight efficiency gain.
3488 SDValue
3489 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3490                                                    SelectionDAG &DAG) const {
3491   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3492 
3493   SDLoc DL(Op);
3494   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3495   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3496 
3497   SDValue TLVPAddr =
3498       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3499   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3500 
3501   // The first entry in the descriptor is a function pointer that we must call
3502   // to obtain the address of the variable.
3503   SDValue Chain = DAG.getEntryNode();
3504   SDValue FuncTLVGet =
3505       DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3506                   MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3507                   true, true, 8);
3508   Chain = FuncTLVGet.getValue(1);
3509 
3510   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3511   MFI->setAdjustsStack(true);
3512 
3513   // TLS calls preserve all registers except those that absolutely must be
3514   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3515   // silly).
3516   const uint32_t *Mask =
3517       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3518 
3519   // Finally, we can make the call. This is just a degenerate version of a
3520   // normal AArch64 call node: x0 takes the address of the descriptor, and
3521   // returns the address of the variable in this thread.
3522   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3523   Chain =
3524       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3525                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3526                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3527   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3528 }
3529 
3530 /// When accessing thread-local variables under either the general-dynamic or
3531 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3532 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3533 /// is a function pointer to carry out the resolution.
3534 ///
3535 /// The sequence is:
3536 ///    adrp  x0, :tlsdesc:var
3537 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3538 ///    add   x0, x0, #:tlsdesc_lo12:var
3539 ///    .tlsdesccall var
3540 ///    blr   x1
3541 ///    (TPIDR_EL0 offset now in x0)
3542 ///
3543 ///  The above sequence must be produced unscheduled, to enable the linker to
3544 ///  optimize/relax this sequence.
3545 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3546 ///  above sequence, and expanded really late in the compilation flow, to ensure
3547 ///  the sequence is produced as per above.
3548 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3549                                                       SelectionDAG &DAG) const {
3550   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3551 
3552   SDValue Chain = DAG.getEntryNode();
3553   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3554 
3555   SmallVector<SDValue, 2> Ops;
3556   Ops.push_back(Chain);
3557   Ops.push_back(SymAddr);
3558 
3559   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3560   SDValue Glue = Chain.getValue(1);
3561 
3562   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3563 }
3564 
3565 SDValue
3566 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3567                                                 SelectionDAG &DAG) const {
3568   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3569   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3570          "ELF TLS only supported in small memory model");
3571   // Different choices can be made for the maximum size of the TLS area for a
3572   // module. For the small address model, the default TLS size is 16MiB and the
3573   // maximum TLS size is 4GiB.
3574   // FIXME: add -mtls-size command line option and make it control the 16MiB
3575   // vs. 4GiB code sequence generation.
3576   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3577 
3578   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3579 
3580   if (DAG.getTarget().Options.EmulatedTLS)
3581     return LowerToTLSEmulatedModel(GA, DAG);
3582 
3583   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3584     if (Model == TLSModel::LocalDynamic)
3585       Model = TLSModel::GeneralDynamic;
3586   }
3587 
3588   SDValue TPOff;
3589   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3590   SDLoc DL(Op);
3591   const GlobalValue *GV = GA->getGlobal();
3592 
3593   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3594 
3595   if (Model == TLSModel::LocalExec) {
3596     SDValue HiVar = DAG.getTargetGlobalAddress(
3597         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3598     SDValue LoVar = DAG.getTargetGlobalAddress(
3599         GV, DL, PtrVT, 0,
3600         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3601 
3602     SDValue TPWithOff_lo =
3603         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3604                                    HiVar,
3605                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3606                 0);
3607     SDValue TPWithOff =
3608         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3609                                    LoVar,
3610                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3611                 0);
3612     return TPWithOff;
3613   } else if (Model == TLSModel::InitialExec) {
3614     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3615     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3616   } else if (Model == TLSModel::LocalDynamic) {
3617     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3618     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3619     // the beginning of the module's TLS region, followed by a DTPREL offset
3620     // calculation.
3621 
3622     // These accesses will need deduplicating if there's more than one.
3623     AArch64FunctionInfo *MFI =
3624         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3625     MFI->incNumLocalDynamicTLSAccesses();
3626 
3627     // The call needs a relocation too for linker relaxation. It doesn't make
3628     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3629     // the address.
3630     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3631                                                   AArch64II::MO_TLS);
3632 
3633     // Now we can calculate the offset from TPIDR_EL0 to this module's
3634     // thread-local area.
3635     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3636 
3637     // Now use :dtprel_whatever: operations to calculate this variable's offset
3638     // in its thread-storage area.
3639     SDValue HiVar = DAG.getTargetGlobalAddress(
3640         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3641     SDValue LoVar = DAG.getTargetGlobalAddress(
3642         GV, DL, MVT::i64, 0,
3643         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3644 
3645     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3646                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3647                     0);
3648     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3649                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3650                     0);
3651   } else if (Model == TLSModel::GeneralDynamic) {
3652     // The call needs a relocation too for linker relaxation. It doesn't make
3653     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3654     // the address.
3655     SDValue SymAddr =
3656         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3657 
3658     // Finally we can make a call to calculate the offset from tpidr_el0.
3659     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3660   } else
3661     llvm_unreachable("Unsupported ELF TLS access model");
3662 
3663   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3664 }
3665 
3666 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3667                                                      SelectionDAG &DAG) const {
3668   if (Subtarget->isTargetDarwin())
3669     return LowerDarwinGlobalTLSAddress(Op, DAG);
3670   else if (Subtarget->isTargetELF())
3671     return LowerELFGlobalTLSAddress(Op, DAG);
3672 
3673   llvm_unreachable("Unexpected platform trying to use TLS");
3674 }
3675 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3676   SDValue Chain = Op.getOperand(0);
3677   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3678   SDValue LHS = Op.getOperand(2);
3679   SDValue RHS = Op.getOperand(3);
3680   SDValue Dest = Op.getOperand(4);
3681   SDLoc dl(Op);
3682 
3683   // Handle f128 first, since lowering it will result in comparing the return
3684   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3685   // is expecting to deal with.
3686   if (LHS.getValueType() == MVT::f128) {
3687     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3688 
3689     // If softenSetCCOperands returned a scalar, we need to compare the result
3690     // against zero to select between true and false values.
3691     if (!RHS.getNode()) {
3692       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3693       CC = ISD::SETNE;
3694     }
3695   }
3696 
3697   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3698   // instruction.
3699   unsigned Opc = LHS.getOpcode();
3700   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3701       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3702        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3703     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3704            "Unexpected condition code.");
3705     // Only lower legal XALUO ops.
3706     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3707       return SDValue();
3708 
3709     // The actual operation with overflow check.
3710     AArch64CC::CondCode OFCC;
3711     SDValue Value, Overflow;
3712     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3713 
3714     if (CC == ISD::SETNE)
3715       OFCC = getInvertedCondCode(OFCC);
3716     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3717 
3718     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3719                        Overflow);
3720   }
3721 
3722   if (LHS.getValueType().isInteger()) {
3723     assert((LHS.getValueType() == RHS.getValueType()) &&
3724            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3725 
3726     // If the RHS of the comparison is zero, we can potentially fold this
3727     // to a specialized branch.
3728     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3729     if (RHSC && RHSC->getZExtValue() == 0) {
3730       if (CC == ISD::SETEQ) {
3731         // See if we can use a TBZ to fold in an AND as well.
3732         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3733         // out of bounds, a late MI-layer pass rewrites branches.
3734         // 403.gcc is an example that hits this case.
3735         if (LHS.getOpcode() == ISD::AND &&
3736             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3737             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3738           SDValue Test = LHS.getOperand(0);
3739           uint64_t Mask = LHS.getConstantOperandVal(1);
3740           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3741                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3742                              Dest);
3743         }
3744 
3745         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3746       } else if (CC == ISD::SETNE) {
3747         // See if we can use a TBZ to fold in an AND as well.
3748         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3749         // out of bounds, a late MI-layer pass rewrites branches.
3750         // 403.gcc is an example that hits this case.
3751         if (LHS.getOpcode() == ISD::AND &&
3752             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3753             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3754           SDValue Test = LHS.getOperand(0);
3755           uint64_t Mask = LHS.getConstantOperandVal(1);
3756           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3757                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3758                              Dest);
3759         }
3760 
3761         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3762       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3763         // Don't combine AND since emitComparison converts the AND to an ANDS
3764         // (a.k.a. TST) and the test in the test bit and branch instruction
3765         // becomes redundant.  This would also increase register pressure.
3766         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3767         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3768                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3769       }
3770     }
3771     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3772         LHS.getOpcode() != ISD::AND) {
3773       // Don't combine AND since emitComparison converts the AND to an ANDS
3774       // (a.k.a. TST) and the test in the test bit and branch instruction
3775       // becomes redundant.  This would also increase register pressure.
3776       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3777       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3778                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3779     }
3780 
3781     SDValue CCVal;
3782     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3783     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3784                        Cmp);
3785   }
3786 
3787   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3788 
3789   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3790   // clean.  Some of them require two branches to implement.
3791   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3792   AArch64CC::CondCode CC1, CC2;
3793   changeFPCCToAArch64CC(CC, CC1, CC2);
3794   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3795   SDValue BR1 =
3796       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3797   if (CC2 != AArch64CC::AL) {
3798     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3799     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3800                        Cmp);
3801   }
3802 
3803   return BR1;
3804 }
3805 
3806 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3807                                               SelectionDAG &DAG) const {
3808   EVT VT = Op.getValueType();
3809   SDLoc DL(Op);
3810 
3811   SDValue In1 = Op.getOperand(0);
3812   SDValue In2 = Op.getOperand(1);
3813   EVT SrcVT = In2.getValueType();
3814 
3815   if (SrcVT.bitsLT(VT))
3816     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3817   else if (SrcVT.bitsGT(VT))
3818     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3819 
3820   EVT VecVT;
3821   EVT EltVT;
3822   uint64_t EltMask;
3823   SDValue VecVal1, VecVal2;
3824   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3825     EltVT = MVT::i32;
3826     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3827     EltMask = 0x80000000ULL;
3828 
3829     if (!VT.isVector()) {
3830       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3831                                           DAG.getUNDEF(VecVT), In1);
3832       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3833                                           DAG.getUNDEF(VecVT), In2);
3834     } else {
3835       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3836       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3837     }
3838   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3839     EltVT = MVT::i64;
3840     VecVT = MVT::v2i64;
3841 
3842     // We want to materialize a mask with the high bit set, but the AdvSIMD
3843     // immediate moves cannot materialize that in a single instruction for
3844     // 64-bit elements. Instead, materialize zero and then negate it.
3845     EltMask = 0;
3846 
3847     if (!VT.isVector()) {
3848       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3849                                           DAG.getUNDEF(VecVT), In1);
3850       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3851                                           DAG.getUNDEF(VecVT), In2);
3852     } else {
3853       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3854       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3855     }
3856   } else {
3857     llvm_unreachable("Invalid type for copysign!");
3858   }
3859 
3860   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3861 
3862   // If we couldn't materialize the mask above, then the mask vector will be
3863   // the zero vector, and we need to negate it here.
3864   if (VT == MVT::f64 || VT == MVT::v2f64) {
3865     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3866     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3867     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3868   }
3869 
3870   SDValue Sel =
3871       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3872 
3873   if (VT == MVT::f32)
3874     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3875   else if (VT == MVT::f64)
3876     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3877   else
3878     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3879 }
3880 
3881 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3882   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3883           Attribute::NoImplicitFloat))
3884     return SDValue();
3885 
3886   if (!Subtarget->hasNEON())
3887     return SDValue();
3888 
3889   // While there is no integer popcount instruction, it can
3890   // be more efficiently lowered to the following sequence that uses
3891   // AdvSIMD registers/instructions as long as the copies to/from
3892   // the AdvSIMD registers are cheap.
3893   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3894   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3895   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3896   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3897   SDValue Val = Op.getOperand(0);
3898   SDLoc DL(Op);
3899   EVT VT = Op.getValueType();
3900 
3901   if (VT == MVT::i32)
3902     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3903   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3904 
3905   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3906   SDValue UaddLV = DAG.getNode(
3907       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3908       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3909 
3910   if (VT == MVT::i64)
3911     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3912   return UaddLV;
3913 }
3914 
3915 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3916 
3917   if (Op.getValueType().isVector())
3918     return LowerVSETCC(Op, DAG);
3919 
3920   SDValue LHS = Op.getOperand(0);
3921   SDValue RHS = Op.getOperand(1);
3922   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3923   SDLoc dl(Op);
3924 
3925   // We chose ZeroOrOneBooleanContents, so use zero and one.
3926   EVT VT = Op.getValueType();
3927   SDValue TVal = DAG.getConstant(1, dl, VT);
3928   SDValue FVal = DAG.getConstant(0, dl, VT);
3929 
3930   // Handle f128 first, since one possible outcome is a normal integer
3931   // comparison which gets picked up by the next if statement.
3932   if (LHS.getValueType() == MVT::f128) {
3933     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3934 
3935     // If softenSetCCOperands returned a scalar, use it.
3936     if (!RHS.getNode()) {
3937       assert(LHS.getValueType() == Op.getValueType() &&
3938              "Unexpected setcc expansion!");
3939       return LHS;
3940     }
3941   }
3942 
3943   if (LHS.getValueType().isInteger()) {
3944     SDValue CCVal;
3945     SDValue Cmp =
3946         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3947 
3948     // Note that we inverted the condition above, so we reverse the order of
3949     // the true and false operands here.  This will allow the setcc to be
3950     // matched to a single CSINC instruction.
3951     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3952   }
3953 
3954   // Now we know we're dealing with FP values.
3955   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3956 
3957   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3958   // and do the comparison.
3959   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3960 
3961   AArch64CC::CondCode CC1, CC2;
3962   changeFPCCToAArch64CC(CC, CC1, CC2);
3963   if (CC2 == AArch64CC::AL) {
3964     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3965     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3966 
3967     // Note that we inverted the condition above, so we reverse the order of
3968     // the true and false operands here.  This will allow the setcc to be
3969     // matched to a single CSINC instruction.
3970     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3971   } else {
3972     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3973     // totally clean.  Some of them require two CSELs to implement.  As is in
3974     // this case, we emit the first CSEL and then emit a second using the output
3975     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3976 
3977     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3978     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3979     SDValue CS1 =
3980         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3981 
3982     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3983     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3984   }
3985 }
3986 
3987 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3988                                               SDValue RHS, SDValue TVal,
3989                                               SDValue FVal, SDLoc dl,
3990                                               SelectionDAG &DAG) const {
3991   // Handle f128 first, because it will result in a comparison of some RTLIB
3992   // call result against zero.
3993   if (LHS.getValueType() == MVT::f128) {
3994     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3995 
3996     // If softenSetCCOperands returned a scalar, we need to compare the result
3997     // against zero to select between true and false values.
3998     if (!RHS.getNode()) {
3999       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4000       CC = ISD::SETNE;
4001     }
4002   }
4003 
4004   // Also handle f16, for which we need to do a f32 comparison.
4005   if (LHS.getValueType() == MVT::f16) {
4006     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4007     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4008   }
4009 
4010   // Next, handle integers.
4011   if (LHS.getValueType().isInteger()) {
4012     assert((LHS.getValueType() == RHS.getValueType()) &&
4013            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4014 
4015     unsigned Opcode = AArch64ISD::CSEL;
4016 
4017     // If both the TVal and the FVal are constants, see if we can swap them in
4018     // order to for a CSINV or CSINC out of them.
4019     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4020     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4021 
4022     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4023       std::swap(TVal, FVal);
4024       std::swap(CTVal, CFVal);
4025       CC = ISD::getSetCCInverse(CC, true);
4026     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4027       std::swap(TVal, FVal);
4028       std::swap(CTVal, CFVal);
4029       CC = ISD::getSetCCInverse(CC, true);
4030     } else if (TVal.getOpcode() == ISD::XOR) {
4031       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4032       // with a CSINV rather than a CSEL.
4033       if (isAllOnesConstant(TVal.getOperand(1))) {
4034         std::swap(TVal, FVal);
4035         std::swap(CTVal, CFVal);
4036         CC = ISD::getSetCCInverse(CC, true);
4037       }
4038     } else if (TVal.getOpcode() == ISD::SUB) {
4039       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4040       // that we can match with a CSNEG rather than a CSEL.
4041       if (isNullConstant(TVal.getOperand(0))) {
4042         std::swap(TVal, FVal);
4043         std::swap(CTVal, CFVal);
4044         CC = ISD::getSetCCInverse(CC, true);
4045       }
4046     } else if (CTVal && CFVal) {
4047       const int64_t TrueVal = CTVal->getSExtValue();
4048       const int64_t FalseVal = CFVal->getSExtValue();
4049       bool Swap = false;
4050 
4051       // If both TVal and FVal are constants, see if FVal is the
4052       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4053       // instead of a CSEL in that case.
4054       if (TrueVal == ~FalseVal) {
4055         Opcode = AArch64ISD::CSINV;
4056       } else if (TrueVal == -FalseVal) {
4057         Opcode = AArch64ISD::CSNEG;
4058       } else if (TVal.getValueType() == MVT::i32) {
4059         // If our operands are only 32-bit wide, make sure we use 32-bit
4060         // arithmetic for the check whether we can use CSINC. This ensures that
4061         // the addition in the check will wrap around properly in case there is
4062         // an overflow (which would not be the case if we do the check with
4063         // 64-bit arithmetic).
4064         const uint32_t TrueVal32 = CTVal->getZExtValue();
4065         const uint32_t FalseVal32 = CFVal->getZExtValue();
4066 
4067         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4068           Opcode = AArch64ISD::CSINC;
4069 
4070           if (TrueVal32 > FalseVal32) {
4071             Swap = true;
4072           }
4073         }
4074         // 64-bit check whether we can use CSINC.
4075       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4076         Opcode = AArch64ISD::CSINC;
4077 
4078         if (TrueVal > FalseVal) {
4079           Swap = true;
4080         }
4081       }
4082 
4083       // Swap TVal and FVal if necessary.
4084       if (Swap) {
4085         std::swap(TVal, FVal);
4086         std::swap(CTVal, CFVal);
4087         CC = ISD::getSetCCInverse(CC, true);
4088       }
4089 
4090       if (Opcode != AArch64ISD::CSEL) {
4091         // Drop FVal since we can get its value by simply inverting/negating
4092         // TVal.
4093         FVal = TVal;
4094       }
4095     }
4096 
4097     SDValue CCVal;
4098     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4099 
4100     EVT VT = TVal.getValueType();
4101     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4102   }
4103 
4104   // Now we know we're dealing with FP values.
4105   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4106   assert(LHS.getValueType() == RHS.getValueType());
4107   EVT VT = TVal.getValueType();
4108   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4109 
4110   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4111   // clean.  Some of them require two CSELs to implement.
4112   AArch64CC::CondCode CC1, CC2;
4113   changeFPCCToAArch64CC(CC, CC1, CC2);
4114   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4115   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4116 
4117   // If we need a second CSEL, emit it, using the output of the first as the
4118   // RHS.  We're effectively OR'ing the two CC's together.
4119   if (CC2 != AArch64CC::AL) {
4120     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4121     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4122   }
4123 
4124   // Otherwise, return the output of the first CSEL.
4125   return CS1;
4126 }
4127 
4128 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4129                                               SelectionDAG &DAG) const {
4130   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4131   SDValue LHS = Op.getOperand(0);
4132   SDValue RHS = Op.getOperand(1);
4133   SDValue TVal = Op.getOperand(2);
4134   SDValue FVal = Op.getOperand(3);
4135   SDLoc DL(Op);
4136   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4137 }
4138 
4139 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4140                                            SelectionDAG &DAG) const {
4141   SDValue CCVal = Op->getOperand(0);
4142   SDValue TVal = Op->getOperand(1);
4143   SDValue FVal = Op->getOperand(2);
4144   SDLoc DL(Op);
4145 
4146   unsigned Opc = CCVal.getOpcode();
4147   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4148   // instruction.
4149   if (CCVal.getResNo() == 1 &&
4150       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4151        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4152     // Only lower legal XALUO ops.
4153     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4154       return SDValue();
4155 
4156     AArch64CC::CondCode OFCC;
4157     SDValue Value, Overflow;
4158     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4159     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4160 
4161     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4162                        CCVal, Overflow);
4163   }
4164 
4165   // Lower it the same way as we would lower a SELECT_CC node.
4166   ISD::CondCode CC;
4167   SDValue LHS, RHS;
4168   if (CCVal.getOpcode() == ISD::SETCC) {
4169     LHS = CCVal.getOperand(0);
4170     RHS = CCVal.getOperand(1);
4171     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4172   } else {
4173     LHS = CCVal;
4174     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4175     CC = ISD::SETNE;
4176   }
4177   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4178 }
4179 
4180 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4181                                               SelectionDAG &DAG) const {
4182   // Jump table entries as PC relative offsets. No additional tweaking
4183   // is necessary here. Just get the address of the jump table.
4184   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4185   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4186   SDLoc DL(Op);
4187 
4188   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4189       !Subtarget->isTargetMachO()) {
4190     const unsigned char MO_NC = AArch64II::MO_NC;
4191     return DAG.getNode(
4192         AArch64ISD::WrapperLarge, DL, PtrVT,
4193         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4194         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4195         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4196         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4197                                AArch64II::MO_G0 | MO_NC));
4198   }
4199 
4200   SDValue Hi =
4201       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4202   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4203                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4204   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4205   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4206 }
4207 
4208 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4209                                                  SelectionDAG &DAG) const {
4210   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4211   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4212   SDLoc DL(Op);
4213 
4214   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4215     // Use the GOT for the large code model on iOS.
4216     if (Subtarget->isTargetMachO()) {
4217       SDValue GotAddr = DAG.getTargetConstantPool(
4218           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4219           AArch64II::MO_GOT);
4220       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4221     }
4222 
4223     const unsigned char MO_NC = AArch64II::MO_NC;
4224     return DAG.getNode(
4225         AArch64ISD::WrapperLarge, DL, PtrVT,
4226         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4227                                   CP->getOffset(), AArch64II::MO_G3),
4228         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4229                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4230         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4231                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4232         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4233                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4234   } else {
4235     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4236     // ELF, the only valid one on Darwin.
4237     SDValue Hi =
4238         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4239                                   CP->getOffset(), AArch64II::MO_PAGE);
4240     SDValue Lo = DAG.getTargetConstantPool(
4241         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4242         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4243 
4244     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4245     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4246   }
4247 }
4248 
4249 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4250                                                SelectionDAG &DAG) const {
4251   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4252   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4253   SDLoc DL(Op);
4254   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4255       !Subtarget->isTargetMachO()) {
4256     const unsigned char MO_NC = AArch64II::MO_NC;
4257     return DAG.getNode(
4258         AArch64ISD::WrapperLarge, DL, PtrVT,
4259         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4260         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4261         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4262         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4263   } else {
4264     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4265     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4266                                                              AArch64II::MO_NC);
4267     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4268     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4269   }
4270 }
4271 
4272 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4273                                                  SelectionDAG &DAG) const {
4274   AArch64FunctionInfo *FuncInfo =
4275       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4276 
4277   SDLoc DL(Op);
4278   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4279                                  getPointerTy(DAG.getDataLayout()));
4280   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4281   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4282                       MachinePointerInfo(SV), false, false, 0);
4283 }
4284 
4285 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4286                                                 SelectionDAG &DAG) const {
4287   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4288   // Standard, section B.3.
4289   MachineFunction &MF = DAG.getMachineFunction();
4290   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4291   auto PtrVT = getPointerTy(DAG.getDataLayout());
4292   SDLoc DL(Op);
4293 
4294   SDValue Chain = Op.getOperand(0);
4295   SDValue VAList = Op.getOperand(1);
4296   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4297   SmallVector<SDValue, 4> MemOps;
4298 
4299   // void *__stack at offset 0
4300   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4301   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4302                                 MachinePointerInfo(SV), false, false, 8));
4303 
4304   // void *__gr_top at offset 8
4305   int GPRSize = FuncInfo->getVarArgsGPRSize();
4306   if (GPRSize > 0) {
4307     SDValue GRTop, GRTopAddr;
4308 
4309     GRTopAddr =
4310         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4311 
4312     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4313     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4314                         DAG.getConstant(GPRSize, DL, PtrVT));
4315 
4316     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4317                                   MachinePointerInfo(SV, 8), false, false, 8));
4318   }
4319 
4320   // void *__vr_top at offset 16
4321   int FPRSize = FuncInfo->getVarArgsFPRSize();
4322   if (FPRSize > 0) {
4323     SDValue VRTop, VRTopAddr;
4324     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4325                             DAG.getConstant(16, DL, PtrVT));
4326 
4327     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4328     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4329                         DAG.getConstant(FPRSize, DL, PtrVT));
4330 
4331     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4332                                   MachinePointerInfo(SV, 16), false, false, 8));
4333   }
4334 
4335   // int __gr_offs at offset 24
4336   SDValue GROffsAddr =
4337       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4338   MemOps.push_back(DAG.getStore(Chain, DL,
4339                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
4340                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
4341                                 false, 4));
4342 
4343   // int __vr_offs at offset 28
4344   SDValue VROffsAddr =
4345       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4346   MemOps.push_back(DAG.getStore(Chain, DL,
4347                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
4348                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
4349                                 false, 4));
4350 
4351   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4352 }
4353 
4354 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4355                                             SelectionDAG &DAG) const {
4356   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4357                                      : LowerAAPCS_VASTART(Op, DAG);
4358 }
4359 
4360 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4361                                            SelectionDAG &DAG) const {
4362   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4363   // pointer.
4364   SDLoc DL(Op);
4365   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4366   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4367   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4368 
4369   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4370                        Op.getOperand(2),
4371                        DAG.getConstant(VaListSize, DL, MVT::i32),
4372                        8, false, false, false, MachinePointerInfo(DestSV),
4373                        MachinePointerInfo(SrcSV));
4374 }
4375 
4376 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4377   assert(Subtarget->isTargetDarwin() &&
4378          "automatic va_arg instruction only works on Darwin");
4379 
4380   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4381   EVT VT = Op.getValueType();
4382   SDLoc DL(Op);
4383   SDValue Chain = Op.getOperand(0);
4384   SDValue Addr = Op.getOperand(1);
4385   unsigned Align = Op.getConstantOperandVal(3);
4386   auto PtrVT = getPointerTy(DAG.getDataLayout());
4387 
4388   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4389                                false, false, false, 0);
4390   Chain = VAList.getValue(1);
4391 
4392   if (Align > 8) {
4393     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4394     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4395                          DAG.getConstant(Align - 1, DL, PtrVT));
4396     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4397                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4398   }
4399 
4400   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4401   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4402 
4403   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4404   // up to 64 bits.  At the very least, we have to increase the striding of the
4405   // vaargs list to match this, and for FP values we need to introduce
4406   // FP_ROUND nodes as well.
4407   if (VT.isInteger() && !VT.isVector())
4408     ArgSize = 8;
4409   bool NeedFPTrunc = false;
4410   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4411     ArgSize = 8;
4412     NeedFPTrunc = true;
4413   }
4414 
4415   // Increment the pointer, VAList, to the next vaarg
4416   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4417                                DAG.getConstant(ArgSize, DL, PtrVT));
4418   // Store the incremented VAList to the legalized pointer
4419   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4420                                  false, false, 0);
4421 
4422   // Load the actual argument out of the pointer VAList
4423   if (NeedFPTrunc) {
4424     // Load the value as an f64.
4425     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4426                                  MachinePointerInfo(), false, false, false, 0);
4427     // Round the value down to an f32.
4428     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4429                                    DAG.getIntPtrConstant(1, DL));
4430     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4431     // Merge the rounded value with the chain output of the load.
4432     return DAG.getMergeValues(Ops, DL);
4433   }
4434 
4435   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4436                      false, false, 0);
4437 }
4438 
4439 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4440                                               SelectionDAG &DAG) const {
4441   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4442   MFI->setFrameAddressIsTaken(true);
4443 
4444   EVT VT = Op.getValueType();
4445   SDLoc DL(Op);
4446   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4447   SDValue FrameAddr =
4448       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4449   while (Depth--)
4450     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4451                             MachinePointerInfo(), false, false, false, 0);
4452   return FrameAddr;
4453 }
4454 
4455 // FIXME? Maybe this could be a TableGen attribute on some registers and
4456 // this table could be generated automatically from RegInfo.
4457 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4458                                                   SelectionDAG &DAG) const {
4459   unsigned Reg = StringSwitch<unsigned>(RegName)
4460                        .Case("sp", AArch64::SP)
4461                        .Default(0);
4462   if (Reg)
4463     return Reg;
4464   report_fatal_error(Twine("Invalid register name \""
4465                               + StringRef(RegName)  + "\"."));
4466 }
4467 
4468 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4469                                                SelectionDAG &DAG) const {
4470   MachineFunction &MF = DAG.getMachineFunction();
4471   MachineFrameInfo *MFI = MF.getFrameInfo();
4472   MFI->setReturnAddressIsTaken(true);
4473 
4474   EVT VT = Op.getValueType();
4475   SDLoc DL(Op);
4476   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4477   if (Depth) {
4478     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4479     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4480     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4481                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4482                        MachinePointerInfo(), false, false, false, 0);
4483   }
4484 
4485   // Return LR, which contains the return address. Mark it an implicit live-in.
4486   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4487   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4488 }
4489 
4490 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4491 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4492 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4493                                                     SelectionDAG &DAG) const {
4494   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4495   EVT VT = Op.getValueType();
4496   unsigned VTBits = VT.getSizeInBits();
4497   SDLoc dl(Op);
4498   SDValue ShOpLo = Op.getOperand(0);
4499   SDValue ShOpHi = Op.getOperand(1);
4500   SDValue ShAmt = Op.getOperand(2);
4501   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4502 
4503   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4504 
4505   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4506                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4507   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4508 
4509   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4510   // is "undef". We wanted 0, so CSEL it directly.
4511   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4512                                ISD::SETEQ, dl, DAG);
4513   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4514   HiBitsForLo =
4515       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4516                   HiBitsForLo, CCVal, Cmp);
4517 
4518   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4519                                    DAG.getConstant(VTBits, dl, MVT::i64));
4520 
4521   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4522   SDValue LoForNormalShift =
4523       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4524 
4525   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4526                        dl, DAG);
4527   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4528   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4529   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4530                            LoForNormalShift, CCVal, Cmp);
4531 
4532   // AArch64 shifts larger than the register width are wrapped rather than
4533   // clamped, so we can't just emit "hi >> x".
4534   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4535   SDValue HiForBigShift =
4536       Opc == ISD::SRA
4537           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4538                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4539           : DAG.getConstant(0, dl, VT);
4540   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4541                            HiForNormalShift, CCVal, Cmp);
4542 
4543   SDValue Ops[2] = { Lo, Hi };
4544   return DAG.getMergeValues(Ops, dl);
4545 }
4546 
4547 
4548 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4549 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4550 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4551                                                    SelectionDAG &DAG) const {
4552   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4553   EVT VT = Op.getValueType();
4554   unsigned VTBits = VT.getSizeInBits();
4555   SDLoc dl(Op);
4556   SDValue ShOpLo = Op.getOperand(0);
4557   SDValue ShOpHi = Op.getOperand(1);
4558   SDValue ShAmt = Op.getOperand(2);
4559 
4560   assert(Op.getOpcode() == ISD::SHL_PARTS);
4561   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4562                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4563   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4564 
4565   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4566   // is "undef". We wanted 0, so CSEL it directly.
4567   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4568                                ISD::SETEQ, dl, DAG);
4569   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4570   LoBitsForHi =
4571       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4572                   LoBitsForHi, CCVal, Cmp);
4573 
4574   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4575                                    DAG.getConstant(VTBits, dl, MVT::i64));
4576   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4577   SDValue HiForNormalShift =
4578       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4579 
4580   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4581 
4582   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4583                        dl, DAG);
4584   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4585   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4586                            HiForNormalShift, CCVal, Cmp);
4587 
4588   // AArch64 shifts of larger than register sizes are wrapped rather than
4589   // clamped, so we can't just emit "lo << a" if a is too big.
4590   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4591   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4592   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4593                            LoForNormalShift, CCVal, Cmp);
4594 
4595   SDValue Ops[2] = { Lo, Hi };
4596   return DAG.getMergeValues(Ops, dl);
4597 }
4598 
4599 bool AArch64TargetLowering::isOffsetFoldingLegal(
4600     const GlobalAddressSDNode *GA) const {
4601   // The AArch64 target doesn't support folding offsets into global addresses.
4602   return false;
4603 }
4604 
4605 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4606   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4607   // FIXME: We should be able to handle f128 as well with a clever lowering.
4608   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4609     return true;
4610 
4611   if (VT == MVT::f64)
4612     return AArch64_AM::getFP64Imm(Imm) != -1;
4613   else if (VT == MVT::f32)
4614     return AArch64_AM::getFP32Imm(Imm) != -1;
4615   return false;
4616 }
4617 
4618 //===----------------------------------------------------------------------===//
4619 //                          AArch64 Optimization Hooks
4620 //===----------------------------------------------------------------------===//
4621 
4622 //===----------------------------------------------------------------------===//
4623 //                          AArch64 Inline Assembly Support
4624 //===----------------------------------------------------------------------===//
4625 
4626 // Table of Constraints
4627 // TODO: This is the current set of constraints supported by ARM for the
4628 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4629 //
4630 // r - A general register
4631 // w - An FP/SIMD register of some size in the range v0-v31
4632 // x - An FP/SIMD register of some size in the range v0-v15
4633 // I - Constant that can be used with an ADD instruction
4634 // J - Constant that can be used with a SUB instruction
4635 // K - Constant that can be used with a 32-bit logical instruction
4636 // L - Constant that can be used with a 64-bit logical instruction
4637 // M - Constant that can be used as a 32-bit MOV immediate
4638 // N - Constant that can be used as a 64-bit MOV immediate
4639 // Q - A memory reference with base register and no offset
4640 // S - A symbolic address
4641 // Y - Floating point constant zero
4642 // Z - Integer constant zero
4643 //
4644 //   Note that general register operands will be output using their 64-bit x
4645 // register name, whatever the size of the variable, unless the asm operand
4646 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4647 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4648 // %q modifier.
4649 
4650 /// getConstraintType - Given a constraint letter, return the type of
4651 /// constraint it is for this target.
4652 AArch64TargetLowering::ConstraintType
4653 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4654   if (Constraint.size() == 1) {
4655     switch (Constraint[0]) {
4656     default:
4657       break;
4658     case 'z':
4659       return C_Other;
4660     case 'x':
4661     case 'w':
4662       return C_RegisterClass;
4663     // An address with a single base register. Due to the way we
4664     // currently handle addresses it is the same as 'r'.
4665     case 'Q':
4666       return C_Memory;
4667     }
4668   }
4669   return TargetLowering::getConstraintType(Constraint);
4670 }
4671 
4672 /// Examine constraint type and operand type and determine a weight value.
4673 /// This object must already have been set up with the operand type
4674 /// and the current alternative constraint selected.
4675 TargetLowering::ConstraintWeight
4676 AArch64TargetLowering::getSingleConstraintMatchWeight(
4677     AsmOperandInfo &info, const char *constraint) const {
4678   ConstraintWeight weight = CW_Invalid;
4679   Value *CallOperandVal = info.CallOperandVal;
4680   // If we don't have a value, we can't do a match,
4681   // but allow it at the lowest weight.
4682   if (!CallOperandVal)
4683     return CW_Default;
4684   Type *type = CallOperandVal->getType();
4685   // Look at the constraint type.
4686   switch (*constraint) {
4687   default:
4688     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4689     break;
4690   case 'x':
4691   case 'w':
4692     if (type->isFloatingPointTy() || type->isVectorTy())
4693       weight = CW_Register;
4694     break;
4695   case 'z':
4696     weight = CW_Constant;
4697     break;
4698   }
4699   return weight;
4700 }
4701 
4702 std::pair<unsigned, const TargetRegisterClass *>
4703 AArch64TargetLowering::getRegForInlineAsmConstraint(
4704     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4705   if (Constraint.size() == 1) {
4706     switch (Constraint[0]) {
4707     case 'r':
4708       if (VT.getSizeInBits() == 64)
4709         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4710       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4711     case 'w':
4712       if (VT == MVT::f32)
4713         return std::make_pair(0U, &AArch64::FPR32RegClass);
4714       if (VT.getSizeInBits() == 64)
4715         return std::make_pair(0U, &AArch64::FPR64RegClass);
4716       if (VT.getSizeInBits() == 128)
4717         return std::make_pair(0U, &AArch64::FPR128RegClass);
4718       break;
4719     // The instructions that this constraint is designed for can
4720     // only take 128-bit registers so just use that regclass.
4721     case 'x':
4722       if (VT.getSizeInBits() == 128)
4723         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4724       break;
4725     }
4726   }
4727   if (StringRef("{cc}").equals_lower(Constraint))
4728     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4729 
4730   // Use the default implementation in TargetLowering to convert the register
4731   // constraint into a member of a register class.
4732   std::pair<unsigned, const TargetRegisterClass *> Res;
4733   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4734 
4735   // Not found as a standard register?
4736   if (!Res.second) {
4737     unsigned Size = Constraint.size();
4738     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4739         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4740       int RegNo;
4741       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4742       if (!Failed && RegNo >= 0 && RegNo <= 31) {
4743         // v0 - v31 are aliases of q0 - q31.
4744         // By default we'll emit v0-v31 for this unless there's a modifier where
4745         // we'll emit the correct register as well.
4746         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4747         Res.second = &AArch64::FPR128RegClass;
4748       }
4749     }
4750   }
4751 
4752   return Res;
4753 }
4754 
4755 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4756 /// vector.  If it is invalid, don't add anything to Ops.
4757 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4758     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4759     SelectionDAG &DAG) const {
4760   SDValue Result;
4761 
4762   // Currently only support length 1 constraints.
4763   if (Constraint.length() != 1)
4764     return;
4765 
4766   char ConstraintLetter = Constraint[0];
4767   switch (ConstraintLetter) {
4768   default:
4769     break;
4770 
4771   // This set of constraints deal with valid constants for various instructions.
4772   // Validate and return a target constant for them if we can.
4773   case 'z': {
4774     // 'z' maps to xzr or wzr so it needs an input of 0.
4775     if (!isNullConstant(Op))
4776       return;
4777 
4778     if (Op.getValueType() == MVT::i64)
4779       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4780     else
4781       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4782     break;
4783   }
4784 
4785   case 'I':
4786   case 'J':
4787   case 'K':
4788   case 'L':
4789   case 'M':
4790   case 'N':
4791     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4792     if (!C)
4793       return;
4794 
4795     // Grab the value and do some validation.
4796     uint64_t CVal = C->getZExtValue();
4797     switch (ConstraintLetter) {
4798     // The I constraint applies only to simple ADD or SUB immediate operands:
4799     // i.e. 0 to 4095 with optional shift by 12
4800     // The J constraint applies only to ADD or SUB immediates that would be
4801     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4802     // instruction [or vice versa], in other words -1 to -4095 with optional
4803     // left shift by 12.
4804     case 'I':
4805       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4806         break;
4807       return;
4808     case 'J': {
4809       uint64_t NVal = -C->getSExtValue();
4810       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4811         CVal = C->getSExtValue();
4812         break;
4813       }
4814       return;
4815     }
4816     // The K and L constraints apply *only* to logical immediates, including
4817     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4818     // been removed and MOV should be used). So these constraints have to
4819     // distinguish between bit patterns that are valid 32-bit or 64-bit
4820     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4821     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4822     // versa.
4823     case 'K':
4824       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4825         break;
4826       return;
4827     case 'L':
4828       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4829         break;
4830       return;
4831     // The M and N constraints are a superset of K and L respectively, for use
4832     // with the MOV (immediate) alias. As well as the logical immediates they
4833     // also match 32 or 64-bit immediates that can be loaded either using a
4834     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4835     // (M) or 64-bit 0x1234000000000000 (N) etc.
4836     // As a note some of this code is liberally stolen from the asm parser.
4837     case 'M': {
4838       if (!isUInt<32>(CVal))
4839         return;
4840       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4841         break;
4842       if ((CVal & 0xFFFF) == CVal)
4843         break;
4844       if ((CVal & 0xFFFF0000ULL) == CVal)
4845         break;
4846       uint64_t NCVal = ~(uint32_t)CVal;
4847       if ((NCVal & 0xFFFFULL) == NCVal)
4848         break;
4849       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4850         break;
4851       return;
4852     }
4853     case 'N': {
4854       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4855         break;
4856       if ((CVal & 0xFFFFULL) == CVal)
4857         break;
4858       if ((CVal & 0xFFFF0000ULL) == CVal)
4859         break;
4860       if ((CVal & 0xFFFF00000000ULL) == CVal)
4861         break;
4862       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4863         break;
4864       uint64_t NCVal = ~CVal;
4865       if ((NCVal & 0xFFFFULL) == NCVal)
4866         break;
4867       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4868         break;
4869       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4870         break;
4871       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4872         break;
4873       return;
4874     }
4875     default:
4876       return;
4877     }
4878 
4879     // All assembler immediates are 64-bit integers.
4880     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4881     break;
4882   }
4883 
4884   if (Result.getNode()) {
4885     Ops.push_back(Result);
4886     return;
4887   }
4888 
4889   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4890 }
4891 
4892 //===----------------------------------------------------------------------===//
4893 //                     AArch64 Advanced SIMD Support
4894 //===----------------------------------------------------------------------===//
4895 
4896 /// WidenVector - Given a value in the V64 register class, produce the
4897 /// equivalent value in the V128 register class.
4898 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4899   EVT VT = V64Reg.getValueType();
4900   unsigned NarrowSize = VT.getVectorNumElements();
4901   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4902   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4903   SDLoc DL(V64Reg);
4904 
4905   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4906                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4907 }
4908 
4909 /// getExtFactor - Determine the adjustment factor for the position when
4910 /// generating an "extract from vector registers" instruction.
4911 static unsigned getExtFactor(SDValue &V) {
4912   EVT EltType = V.getValueType().getVectorElementType();
4913   return EltType.getSizeInBits() / 8;
4914 }
4915 
4916 /// NarrowVector - Given a value in the V128 register class, produce the
4917 /// equivalent value in the V64 register class.
4918 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4919   EVT VT = V128Reg.getValueType();
4920   unsigned WideSize = VT.getVectorNumElements();
4921   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4922   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4923   SDLoc DL(V128Reg);
4924 
4925   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4926 }
4927 
4928 // Gather data to see if the operation can be modelled as a
4929 // shuffle in combination with VEXTs.
4930 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4931                                                   SelectionDAG &DAG) const {
4932   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4933   SDLoc dl(Op);
4934   EVT VT = Op.getValueType();
4935   unsigned NumElts = VT.getVectorNumElements();
4936 
4937   struct ShuffleSourceInfo {
4938     SDValue Vec;
4939     unsigned MinElt;
4940     unsigned MaxElt;
4941 
4942     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4943     // be compatible with the shuffle we intend to construct. As a result
4944     // ShuffleVec will be some sliding window into the original Vec.
4945     SDValue ShuffleVec;
4946 
4947     // Code should guarantee that element i in Vec starts at element "WindowBase
4948     // + i * WindowScale in ShuffleVec".
4949     int WindowBase;
4950     int WindowScale;
4951 
4952     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4953     ShuffleSourceInfo(SDValue Vec)
4954         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4955           WindowScale(1) {}
4956   };
4957 
4958   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4959   // node.
4960   SmallVector<ShuffleSourceInfo, 2> Sources;
4961   for (unsigned i = 0; i < NumElts; ++i) {
4962     SDValue V = Op.getOperand(i);
4963     if (V.getOpcode() == ISD::UNDEF)
4964       continue;
4965     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4966              !isa<ConstantSDNode>(V.getOperand(1))) {
4967       // A shuffle can only come from building a vector from various
4968       // elements of other vectors, provided their indices are constant.
4969       return SDValue();
4970     }
4971 
4972     // Add this element source to the list if it's not already there.
4973     SDValue SourceVec = V.getOperand(0);
4974     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4975     if (Source == Sources.end())
4976       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4977 
4978     // Update the minimum and maximum lane number seen.
4979     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4980     Source->MinElt = std::min(Source->MinElt, EltNo);
4981     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4982   }
4983 
4984   // Currently only do something sane when at most two source vectors
4985   // are involved.
4986   if (Sources.size() > 2)
4987     return SDValue();
4988 
4989   // Find out the smallest element size among result and two sources, and use
4990   // it as element size to build the shuffle_vector.
4991   EVT SmallestEltTy = VT.getVectorElementType();
4992   for (auto &Source : Sources) {
4993     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4994     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4995       SmallestEltTy = SrcEltTy;
4996     }
4997   }
4998   unsigned ResMultiplier =
4999       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5000   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5001   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5002 
5003   // If the source vector is too wide or too narrow, we may nevertheless be able
5004   // to construct a compatible shuffle either by concatenating it with UNDEF or
5005   // extracting a suitable range of elements.
5006   for (auto &Src : Sources) {
5007     EVT SrcVT = Src.ShuffleVec.getValueType();
5008 
5009     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5010       continue;
5011 
5012     // This stage of the search produces a source with the same element type as
5013     // the original, but with a total width matching the BUILD_VECTOR output.
5014     EVT EltVT = SrcVT.getVectorElementType();
5015     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5016     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5017 
5018     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5019       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5020       // We can pad out the smaller vector for free, so if it's part of a
5021       // shuffle...
5022       Src.ShuffleVec =
5023           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5024                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5025       continue;
5026     }
5027 
5028     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5029 
5030     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5031       // Span too large for a VEXT to cope
5032       return SDValue();
5033     }
5034 
5035     if (Src.MinElt >= NumSrcElts) {
5036       // The extraction can just take the second half
5037       Src.ShuffleVec =
5038           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5039                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5040       Src.WindowBase = -NumSrcElts;
5041     } else if (Src.MaxElt < NumSrcElts) {
5042       // The extraction can just take the first half
5043       Src.ShuffleVec =
5044           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5045                       DAG.getConstant(0, dl, MVT::i64));
5046     } else {
5047       // An actual VEXT is needed
5048       SDValue VEXTSrc1 =
5049           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5050                       DAG.getConstant(0, dl, MVT::i64));
5051       SDValue VEXTSrc2 =
5052           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5053                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5054       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5055 
5056       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5057                                    VEXTSrc2,
5058                                    DAG.getConstant(Imm, dl, MVT::i32));
5059       Src.WindowBase = -Src.MinElt;
5060     }
5061   }
5062 
5063   // Another possible incompatibility occurs from the vector element types. We
5064   // can fix this by bitcasting the source vectors to the same type we intend
5065   // for the shuffle.
5066   for (auto &Src : Sources) {
5067     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5068     if (SrcEltTy == SmallestEltTy)
5069       continue;
5070     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5071     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5072     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5073     Src.WindowBase *= Src.WindowScale;
5074   }
5075 
5076   // Final sanity check before we try to actually produce a shuffle.
5077   DEBUG(
5078     for (auto Src : Sources)
5079       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5080   );
5081 
5082   // The stars all align, our next step is to produce the mask for the shuffle.
5083   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5084   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5085   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5086     SDValue Entry = Op.getOperand(i);
5087     if (Entry.getOpcode() == ISD::UNDEF)
5088       continue;
5089 
5090     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5091     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5092 
5093     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5094     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5095     // segment.
5096     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5097     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5098                                VT.getVectorElementType().getSizeInBits());
5099     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5100 
5101     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5102     // starting at the appropriate offset.
5103     int *LaneMask = &Mask[i * ResMultiplier];
5104 
5105     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5106     ExtractBase += NumElts * (Src - Sources.begin());
5107     for (int j = 0; j < LanesDefined; ++j)
5108       LaneMask[j] = ExtractBase + j;
5109   }
5110 
5111   // Final check before we try to produce nonsense...
5112   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5113     return SDValue();
5114 
5115   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5116   for (unsigned i = 0; i < Sources.size(); ++i)
5117     ShuffleOps[i] = Sources[i].ShuffleVec;
5118 
5119   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5120                                          ShuffleOps[1], &Mask[0]);
5121   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5122 }
5123 
5124 // check if an EXT instruction can handle the shuffle mask when the
5125 // vector sources of the shuffle are the same.
5126 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5127   unsigned NumElts = VT.getVectorNumElements();
5128 
5129   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5130   if (M[0] < 0)
5131     return false;
5132 
5133   Imm = M[0];
5134 
5135   // If this is a VEXT shuffle, the immediate value is the index of the first
5136   // element.  The other shuffle indices must be the successive elements after
5137   // the first one.
5138   unsigned ExpectedElt = Imm;
5139   for (unsigned i = 1; i < NumElts; ++i) {
5140     // Increment the expected index.  If it wraps around, just follow it
5141     // back to index zero and keep going.
5142     ++ExpectedElt;
5143     if (ExpectedElt == NumElts)
5144       ExpectedElt = 0;
5145 
5146     if (M[i] < 0)
5147       continue; // ignore UNDEF indices
5148     if (ExpectedElt != static_cast<unsigned>(M[i]))
5149       return false;
5150   }
5151 
5152   return true;
5153 }
5154 
5155 // check if an EXT instruction can handle the shuffle mask when the
5156 // vector sources of the shuffle are different.
5157 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5158                       unsigned &Imm) {
5159   // Look for the first non-undef element.
5160   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5161       [](int Elt) {return Elt >= 0;});
5162 
5163   // Benefit form APInt to handle overflow when calculating expected element.
5164   unsigned NumElts = VT.getVectorNumElements();
5165   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5166   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5167   // The following shuffle indices must be the successive elements after the
5168   // first real element.
5169   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5170       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5171   if (FirstWrongElt != M.end())
5172     return false;
5173 
5174   // The index of an EXT is the first element if it is not UNDEF.
5175   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5176   // value of the first element.  E.g.
5177   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5178   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5179   // ExpectedElt is the last mask index plus 1.
5180   Imm = ExpectedElt.getZExtValue();
5181 
5182   // There are two difference cases requiring to reverse input vectors.
5183   // For example, for vector <4 x i32> we have the following cases,
5184   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5185   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5186   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5187   // to reverse two input vectors.
5188   if (Imm < NumElts)
5189     ReverseEXT = true;
5190   else
5191     Imm -= NumElts;
5192 
5193   return true;
5194 }
5195 
5196 /// isREVMask - Check if a vector shuffle corresponds to a REV
5197 /// instruction with the specified blocksize.  (The order of the elements
5198 /// within each block of the vector is reversed.)
5199 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5200   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5201          "Only possible block sizes for REV are: 16, 32, 64");
5202 
5203   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5204   if (EltSz == 64)
5205     return false;
5206 
5207   unsigned NumElts = VT.getVectorNumElements();
5208   unsigned BlockElts = M[0] + 1;
5209   // If the first shuffle index is UNDEF, be optimistic.
5210   if (M[0] < 0)
5211     BlockElts = BlockSize / EltSz;
5212 
5213   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5214     return false;
5215 
5216   for (unsigned i = 0; i < NumElts; ++i) {
5217     if (M[i] < 0)
5218       continue; // ignore UNDEF indices
5219     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5220       return false;
5221   }
5222 
5223   return true;
5224 }
5225 
5226 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5227   unsigned NumElts = VT.getVectorNumElements();
5228   WhichResult = (M[0] == 0 ? 0 : 1);
5229   unsigned Idx = WhichResult * NumElts / 2;
5230   for (unsigned i = 0; i != NumElts; i += 2) {
5231     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5232         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5233       return false;
5234     Idx += 1;
5235   }
5236 
5237   return true;
5238 }
5239 
5240 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5241   unsigned NumElts = VT.getVectorNumElements();
5242   WhichResult = (M[0] == 0 ? 0 : 1);
5243   for (unsigned i = 0; i != NumElts; ++i) {
5244     if (M[i] < 0)
5245       continue; // ignore UNDEF indices
5246     if ((unsigned)M[i] != 2 * i + WhichResult)
5247       return false;
5248   }
5249 
5250   return true;
5251 }
5252 
5253 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5254   unsigned NumElts = VT.getVectorNumElements();
5255   WhichResult = (M[0] == 0 ? 0 : 1);
5256   for (unsigned i = 0; i < NumElts; i += 2) {
5257     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5258         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5259       return false;
5260   }
5261   return true;
5262 }
5263 
5264 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5265 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5266 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5267 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5268   unsigned NumElts = VT.getVectorNumElements();
5269   WhichResult = (M[0] == 0 ? 0 : 1);
5270   unsigned Idx = WhichResult * NumElts / 2;
5271   for (unsigned i = 0; i != NumElts; i += 2) {
5272     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5273         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5274       return false;
5275     Idx += 1;
5276   }
5277 
5278   return true;
5279 }
5280 
5281 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5282 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5283 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5284 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5285   unsigned Half = VT.getVectorNumElements() / 2;
5286   WhichResult = (M[0] == 0 ? 0 : 1);
5287   for (unsigned j = 0; j != 2; ++j) {
5288     unsigned Idx = WhichResult;
5289     for (unsigned i = 0; i != Half; ++i) {
5290       int MIdx = M[i + j * Half];
5291       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5292         return false;
5293       Idx += 2;
5294     }
5295   }
5296 
5297   return true;
5298 }
5299 
5300 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5301 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5302 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5303 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5304   unsigned NumElts = VT.getVectorNumElements();
5305   WhichResult = (M[0] == 0 ? 0 : 1);
5306   for (unsigned i = 0; i < NumElts; i += 2) {
5307     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5308         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5309       return false;
5310   }
5311   return true;
5312 }
5313 
5314 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5315                       bool &DstIsLeft, int &Anomaly) {
5316   if (M.size() != static_cast<size_t>(NumInputElements))
5317     return false;
5318 
5319   int NumLHSMatch = 0, NumRHSMatch = 0;
5320   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5321 
5322   for (int i = 0; i < NumInputElements; ++i) {
5323     if (M[i] == -1) {
5324       ++NumLHSMatch;
5325       ++NumRHSMatch;
5326       continue;
5327     }
5328 
5329     if (M[i] == i)
5330       ++NumLHSMatch;
5331     else
5332       LastLHSMismatch = i;
5333 
5334     if (M[i] == i + NumInputElements)
5335       ++NumRHSMatch;
5336     else
5337       LastRHSMismatch = i;
5338   }
5339 
5340   if (NumLHSMatch == NumInputElements - 1) {
5341     DstIsLeft = true;
5342     Anomaly = LastLHSMismatch;
5343     return true;
5344   } else if (NumRHSMatch == NumInputElements - 1) {
5345     DstIsLeft = false;
5346     Anomaly = LastRHSMismatch;
5347     return true;
5348   }
5349 
5350   return false;
5351 }
5352 
5353 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5354   if (VT.getSizeInBits() != 128)
5355     return false;
5356 
5357   unsigned NumElts = VT.getVectorNumElements();
5358 
5359   for (int I = 0, E = NumElts / 2; I != E; I++) {
5360     if (Mask[I] != I)
5361       return false;
5362   }
5363 
5364   int Offset = NumElts / 2;
5365   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5366     if (Mask[I] != I + SplitLHS * Offset)
5367       return false;
5368   }
5369 
5370   return true;
5371 }
5372 
5373 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5374   SDLoc DL(Op);
5375   EVT VT = Op.getValueType();
5376   SDValue V0 = Op.getOperand(0);
5377   SDValue V1 = Op.getOperand(1);
5378   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5379 
5380   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5381       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5382     return SDValue();
5383 
5384   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5385 
5386   if (!isConcatMask(Mask, VT, SplitV0))
5387     return SDValue();
5388 
5389   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5390                                 VT.getVectorNumElements() / 2);
5391   if (SplitV0) {
5392     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5393                      DAG.getConstant(0, DL, MVT::i64));
5394   }
5395   if (V1.getValueType().getSizeInBits() == 128) {
5396     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5397                      DAG.getConstant(0, DL, MVT::i64));
5398   }
5399   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5400 }
5401 
5402 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5403 /// the specified operations to build the shuffle.
5404 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5405                                       SDValue RHS, SelectionDAG &DAG,
5406                                       SDLoc dl) {
5407   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5408   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5409   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5410 
5411   enum {
5412     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5413     OP_VREV,
5414     OP_VDUP0,
5415     OP_VDUP1,
5416     OP_VDUP2,
5417     OP_VDUP3,
5418     OP_VEXT1,
5419     OP_VEXT2,
5420     OP_VEXT3,
5421     OP_VUZPL, // VUZP, left result
5422     OP_VUZPR, // VUZP, right result
5423     OP_VZIPL, // VZIP, left result
5424     OP_VZIPR, // VZIP, right result
5425     OP_VTRNL, // VTRN, left result
5426     OP_VTRNR  // VTRN, right result
5427   };
5428 
5429   if (OpNum == OP_COPY) {
5430     if (LHSID == (1 * 9 + 2) * 9 + 3)
5431       return LHS;
5432     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5433     return RHS;
5434   }
5435 
5436   SDValue OpLHS, OpRHS;
5437   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5438   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5439   EVT VT = OpLHS.getValueType();
5440 
5441   switch (OpNum) {
5442   default:
5443     llvm_unreachable("Unknown shuffle opcode!");
5444   case OP_VREV:
5445     // VREV divides the vector in half and swaps within the half.
5446     if (VT.getVectorElementType() == MVT::i32 ||
5447         VT.getVectorElementType() == MVT::f32)
5448       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5449     // vrev <4 x i16> -> REV32
5450     if (VT.getVectorElementType() == MVT::i16 ||
5451         VT.getVectorElementType() == MVT::f16)
5452       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5453     // vrev <4 x i8> -> REV16
5454     assert(VT.getVectorElementType() == MVT::i8);
5455     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5456   case OP_VDUP0:
5457   case OP_VDUP1:
5458   case OP_VDUP2:
5459   case OP_VDUP3: {
5460     EVT EltTy = VT.getVectorElementType();
5461     unsigned Opcode;
5462     if (EltTy == MVT::i8)
5463       Opcode = AArch64ISD::DUPLANE8;
5464     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5465       Opcode = AArch64ISD::DUPLANE16;
5466     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5467       Opcode = AArch64ISD::DUPLANE32;
5468     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5469       Opcode = AArch64ISD::DUPLANE64;
5470     else
5471       llvm_unreachable("Invalid vector element type?");
5472 
5473     if (VT.getSizeInBits() == 64)
5474       OpLHS = WidenVector(OpLHS, DAG);
5475     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5476     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5477   }
5478   case OP_VEXT1:
5479   case OP_VEXT2:
5480   case OP_VEXT3: {
5481     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5482     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5483                        DAG.getConstant(Imm, dl, MVT::i32));
5484   }
5485   case OP_VUZPL:
5486     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5487                        OpRHS);
5488   case OP_VUZPR:
5489     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5490                        OpRHS);
5491   case OP_VZIPL:
5492     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5493                        OpRHS);
5494   case OP_VZIPR:
5495     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5496                        OpRHS);
5497   case OP_VTRNL:
5498     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5499                        OpRHS);
5500   case OP_VTRNR:
5501     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5502                        OpRHS);
5503   }
5504 }
5505 
5506 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5507                            SelectionDAG &DAG) {
5508   // Check to see if we can use the TBL instruction.
5509   SDValue V1 = Op.getOperand(0);
5510   SDValue V2 = Op.getOperand(1);
5511   SDLoc DL(Op);
5512 
5513   EVT EltVT = Op.getValueType().getVectorElementType();
5514   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5515 
5516   SmallVector<SDValue, 8> TBLMask;
5517   for (int Val : ShuffleMask) {
5518     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5519       unsigned Offset = Byte + Val * BytesPerElt;
5520       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5521     }
5522   }
5523 
5524   MVT IndexVT = MVT::v8i8;
5525   unsigned IndexLen = 8;
5526   if (Op.getValueType().getSizeInBits() == 128) {
5527     IndexVT = MVT::v16i8;
5528     IndexLen = 16;
5529   }
5530 
5531   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5532   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5533 
5534   SDValue Shuffle;
5535   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5536     if (IndexLen == 8)
5537       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5538     Shuffle = DAG.getNode(
5539         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5540         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5541         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5542                     makeArrayRef(TBLMask.data(), IndexLen)));
5543   } else {
5544     if (IndexLen == 8) {
5545       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5546       Shuffle = DAG.getNode(
5547           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5548           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5549           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5550                       makeArrayRef(TBLMask.data(), IndexLen)));
5551     } else {
5552       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5553       // cannot currently represent the register constraints on the input
5554       // table registers.
5555       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5556       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5557       //                               &TBLMask[0], IndexLen));
5558       Shuffle = DAG.getNode(
5559           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5560           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5561           V1Cst, V2Cst,
5562           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5563                       makeArrayRef(TBLMask.data(), IndexLen)));
5564     }
5565   }
5566   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5567 }
5568 
5569 static unsigned getDUPLANEOp(EVT EltType) {
5570   if (EltType == MVT::i8)
5571     return AArch64ISD::DUPLANE8;
5572   if (EltType == MVT::i16 || EltType == MVT::f16)
5573     return AArch64ISD::DUPLANE16;
5574   if (EltType == MVT::i32 || EltType == MVT::f32)
5575     return AArch64ISD::DUPLANE32;
5576   if (EltType == MVT::i64 || EltType == MVT::f64)
5577     return AArch64ISD::DUPLANE64;
5578 
5579   llvm_unreachable("Invalid vector element type?");
5580 }
5581 
5582 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5583                                                    SelectionDAG &DAG) const {
5584   SDLoc dl(Op);
5585   EVT VT = Op.getValueType();
5586 
5587   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5588 
5589   // Convert shuffles that are directly supported on NEON to target-specific
5590   // DAG nodes, instead of keeping them as shuffles and matching them again
5591   // during code selection.  This is more efficient and avoids the possibility
5592   // of inconsistencies between legalization and selection.
5593   ArrayRef<int> ShuffleMask = SVN->getMask();
5594 
5595   SDValue V1 = Op.getOperand(0);
5596   SDValue V2 = Op.getOperand(1);
5597 
5598   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5599                                        V1.getValueType().getSimpleVT())) {
5600     int Lane = SVN->getSplatIndex();
5601     // If this is undef splat, generate it via "just" vdup, if possible.
5602     if (Lane == -1)
5603       Lane = 0;
5604 
5605     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5606       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5607                          V1.getOperand(0));
5608     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5609     // constant. If so, we can just reference the lane's definition directly.
5610     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5611         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5612       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5613 
5614     // Otherwise, duplicate from the lane of the input vector.
5615     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5616 
5617     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5618     // to make a vector of the same size as this SHUFFLE. We can ignore the
5619     // extract entirely, and canonicalise the concat using WidenVector.
5620     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5621       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5622       V1 = V1.getOperand(0);
5623     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5624       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5625       Lane -= Idx * VT.getVectorNumElements() / 2;
5626       V1 = WidenVector(V1.getOperand(Idx), DAG);
5627     } else if (VT.getSizeInBits() == 64)
5628       V1 = WidenVector(V1, DAG);
5629 
5630     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5631   }
5632 
5633   if (isREVMask(ShuffleMask, VT, 64))
5634     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5635   if (isREVMask(ShuffleMask, VT, 32))
5636     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5637   if (isREVMask(ShuffleMask, VT, 16))
5638     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5639 
5640   bool ReverseEXT = false;
5641   unsigned Imm;
5642   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5643     if (ReverseEXT)
5644       std::swap(V1, V2);
5645     Imm *= getExtFactor(V1);
5646     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5647                        DAG.getConstant(Imm, dl, MVT::i32));
5648   } else if (V2->getOpcode() == ISD::UNDEF &&
5649              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5650     Imm *= getExtFactor(V1);
5651     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5652                        DAG.getConstant(Imm, dl, MVT::i32));
5653   }
5654 
5655   unsigned WhichResult;
5656   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5657     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5658     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5659   }
5660   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5661     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5662     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5663   }
5664   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5665     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5666     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5667   }
5668 
5669   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5670     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5671     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5672   }
5673   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5674     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5675     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5676   }
5677   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5678     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5679     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5680   }
5681 
5682   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5683     return Concat;
5684 
5685   bool DstIsLeft;
5686   int Anomaly;
5687   int NumInputElements = V1.getValueType().getVectorNumElements();
5688   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5689     SDValue DstVec = DstIsLeft ? V1 : V2;
5690     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5691 
5692     SDValue SrcVec = V1;
5693     int SrcLane = ShuffleMask[Anomaly];
5694     if (SrcLane >= NumInputElements) {
5695       SrcVec = V2;
5696       SrcLane -= VT.getVectorNumElements();
5697     }
5698     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5699 
5700     EVT ScalarVT = VT.getVectorElementType();
5701 
5702     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5703       ScalarVT = MVT::i32;
5704 
5705     return DAG.getNode(
5706         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5707         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5708         DstLaneV);
5709   }
5710 
5711   // If the shuffle is not directly supported and it has 4 elements, use
5712   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5713   unsigned NumElts = VT.getVectorNumElements();
5714   if (NumElts == 4) {
5715     unsigned PFIndexes[4];
5716     for (unsigned i = 0; i != 4; ++i) {
5717       if (ShuffleMask[i] < 0)
5718         PFIndexes[i] = 8;
5719       else
5720         PFIndexes[i] = ShuffleMask[i];
5721     }
5722 
5723     // Compute the index in the perfect shuffle table.
5724     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5725                             PFIndexes[2] * 9 + PFIndexes[3];
5726     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5727     unsigned Cost = (PFEntry >> 30);
5728 
5729     if (Cost <= 4)
5730       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5731   }
5732 
5733   return GenerateTBL(Op, ShuffleMask, DAG);
5734 }
5735 
5736 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5737                                APInt &UndefBits) {
5738   EVT VT = BVN->getValueType(0);
5739   APInt SplatBits, SplatUndef;
5740   unsigned SplatBitSize;
5741   bool HasAnyUndefs;
5742   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5743     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5744 
5745     for (unsigned i = 0; i < NumSplats; ++i) {
5746       CnstBits <<= SplatBitSize;
5747       UndefBits <<= SplatBitSize;
5748       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5749       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5750     }
5751 
5752     return true;
5753   }
5754 
5755   return false;
5756 }
5757 
5758 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5759                                               SelectionDAG &DAG) const {
5760   BuildVectorSDNode *BVN =
5761       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5762   SDValue LHS = Op.getOperand(0);
5763   SDLoc dl(Op);
5764   EVT VT = Op.getValueType();
5765 
5766   if (!BVN)
5767     return Op;
5768 
5769   APInt CnstBits(VT.getSizeInBits(), 0);
5770   APInt UndefBits(VT.getSizeInBits(), 0);
5771   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5772     // We only have BIC vector immediate instruction, which is and-not.
5773     CnstBits = ~CnstBits;
5774 
5775     // We make use of a little bit of goto ickiness in order to avoid having to
5776     // duplicate the immediate matching logic for the undef toggled case.
5777     bool SecondTry = false;
5778   AttemptModImm:
5779 
5780     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5781       CnstBits = CnstBits.zextOrTrunc(64);
5782       uint64_t CnstVal = CnstBits.getZExtValue();
5783 
5784       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5785         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5786         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5787         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5788                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5789                                   DAG.getConstant(0, dl, MVT::i32));
5790         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5791       }
5792 
5793       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5794         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5795         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5796         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5797                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5798                                   DAG.getConstant(8, dl, MVT::i32));
5799         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5800       }
5801 
5802       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5803         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5804         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5805         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5806                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5807                                   DAG.getConstant(16, dl, MVT::i32));
5808         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5809       }
5810 
5811       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5812         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5813         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5814         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5815                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5816                                   DAG.getConstant(24, dl, MVT::i32));
5817         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5818       }
5819 
5820       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5821         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5822         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5823         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5824                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5825                                   DAG.getConstant(0, dl, MVT::i32));
5826         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5827       }
5828 
5829       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5830         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5831         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5832         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5833                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5834                                   DAG.getConstant(8, dl, MVT::i32));
5835         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5836       }
5837     }
5838 
5839     if (SecondTry)
5840       goto FailedModImm;
5841     SecondTry = true;
5842     CnstBits = ~UndefBits;
5843     goto AttemptModImm;
5844   }
5845 
5846 // We can always fall back to a non-immediate AND.
5847 FailedModImm:
5848   return Op;
5849 }
5850 
5851 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5852 // consists of only the same constant int value, returned in reference arg
5853 // ConstVal
5854 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5855                                      uint64_t &ConstVal) {
5856   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5857   if (!Bvec)
5858     return false;
5859   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5860   if (!FirstElt)
5861     return false;
5862   EVT VT = Bvec->getValueType(0);
5863   unsigned NumElts = VT.getVectorNumElements();
5864   for (unsigned i = 1; i < NumElts; ++i)
5865     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5866       return false;
5867   ConstVal = FirstElt->getZExtValue();
5868   return true;
5869 }
5870 
5871 static unsigned getIntrinsicID(const SDNode *N) {
5872   unsigned Opcode = N->getOpcode();
5873   switch (Opcode) {
5874   default:
5875     return Intrinsic::not_intrinsic;
5876   case ISD::INTRINSIC_WO_CHAIN: {
5877     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5878     if (IID < Intrinsic::num_intrinsics)
5879       return IID;
5880     return Intrinsic::not_intrinsic;
5881   }
5882   }
5883 }
5884 
5885 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5886 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5887 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5888 // Also, logical shift right -> sri, with the same structure.
5889 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5890   EVT VT = N->getValueType(0);
5891 
5892   if (!VT.isVector())
5893     return SDValue();
5894 
5895   SDLoc DL(N);
5896 
5897   // Is the first op an AND?
5898   const SDValue And = N->getOperand(0);
5899   if (And.getOpcode() != ISD::AND)
5900     return SDValue();
5901 
5902   // Is the second op an shl or lshr?
5903   SDValue Shift = N->getOperand(1);
5904   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5905   // or AArch64ISD::VLSHR vector, #shift
5906   unsigned ShiftOpc = Shift.getOpcode();
5907   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5908     return SDValue();
5909   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5910 
5911   // Is the shift amount constant?
5912   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5913   if (!C2node)
5914     return SDValue();
5915 
5916   // Is the and mask vector all constant?
5917   uint64_t C1;
5918   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5919     return SDValue();
5920 
5921   // Is C1 == ~C2, taking into account how much one can shift elements of a
5922   // particular size?
5923   uint64_t C2 = C2node->getZExtValue();
5924   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5925   if (C2 > ElemSizeInBits)
5926     return SDValue();
5927   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5928   if ((C1 & ElemMask) != (~C2 & ElemMask))
5929     return SDValue();
5930 
5931   SDValue X = And.getOperand(0);
5932   SDValue Y = Shift.getOperand(0);
5933 
5934   unsigned Intrin =
5935       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5936   SDValue ResultSLI =
5937       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5938                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5939                   Shift.getOperand(1));
5940 
5941   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5942   DEBUG(N->dump(&DAG));
5943   DEBUG(dbgs() << "into: \n");
5944   DEBUG(ResultSLI->dump(&DAG));
5945 
5946   ++NumShiftInserts;
5947   return ResultSLI;
5948 }
5949 
5950 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5951                                              SelectionDAG &DAG) const {
5952   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5953   if (EnableAArch64SlrGeneration) {
5954     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
5955       return Res;
5956   }
5957 
5958   BuildVectorSDNode *BVN =
5959       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5960   SDValue LHS = Op.getOperand(1);
5961   SDLoc dl(Op);
5962   EVT VT = Op.getValueType();
5963 
5964   // OR commutes, so try swapping the operands.
5965   if (!BVN) {
5966     LHS = Op.getOperand(0);
5967     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5968   }
5969   if (!BVN)
5970     return Op;
5971 
5972   APInt CnstBits(VT.getSizeInBits(), 0);
5973   APInt UndefBits(VT.getSizeInBits(), 0);
5974   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5975     // We make use of a little bit of goto ickiness in order to avoid having to
5976     // duplicate the immediate matching logic for the undef toggled case.
5977     bool SecondTry = false;
5978   AttemptModImm:
5979 
5980     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5981       CnstBits = CnstBits.zextOrTrunc(64);
5982       uint64_t CnstVal = CnstBits.getZExtValue();
5983 
5984       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5985         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5986         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5987         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5988                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5989                                   DAG.getConstant(0, dl, MVT::i32));
5990         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5991       }
5992 
5993       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5994         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5995         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5996         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5997                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5998                                   DAG.getConstant(8, dl, MVT::i32));
5999         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6000       }
6001 
6002       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6003         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6004         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6005         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6006                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6007                                   DAG.getConstant(16, dl, MVT::i32));
6008         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6009       }
6010 
6011       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6012         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6013         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6014         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6015                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6016                                   DAG.getConstant(24, dl, MVT::i32));
6017         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6018       }
6019 
6020       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6021         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6022         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6023         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6024                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6025                                   DAG.getConstant(0, dl, MVT::i32));
6026         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6027       }
6028 
6029       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6030         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6031         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6032         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6033                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6034                                   DAG.getConstant(8, dl, MVT::i32));
6035         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6036       }
6037     }
6038 
6039     if (SecondTry)
6040       goto FailedModImm;
6041     SecondTry = true;
6042     CnstBits = UndefBits;
6043     goto AttemptModImm;
6044   }
6045 
6046 // We can always fall back to a non-immediate OR.
6047 FailedModImm:
6048   return Op;
6049 }
6050 
6051 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6052 // be truncated to fit element width.
6053 static SDValue NormalizeBuildVector(SDValue Op,
6054                                     SelectionDAG &DAG) {
6055   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6056   SDLoc dl(Op);
6057   EVT VT = Op.getValueType();
6058   EVT EltTy= VT.getVectorElementType();
6059 
6060   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6061     return Op;
6062 
6063   SmallVector<SDValue, 16> Ops;
6064   for (SDValue Lane : Op->ops()) {
6065     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6066       APInt LowBits(EltTy.getSizeInBits(),
6067                     CstLane->getZExtValue());
6068       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6069     }
6070     Ops.push_back(Lane);
6071   }
6072   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6073 }
6074 
6075 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6076                                                  SelectionDAG &DAG) const {
6077   SDLoc dl(Op);
6078   EVT VT = Op.getValueType();
6079   Op = NormalizeBuildVector(Op, DAG);
6080   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6081 
6082   APInt CnstBits(VT.getSizeInBits(), 0);
6083   APInt UndefBits(VT.getSizeInBits(), 0);
6084   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6085     // We make use of a little bit of goto ickiness in order to avoid having to
6086     // duplicate the immediate matching logic for the undef toggled case.
6087     bool SecondTry = false;
6088   AttemptModImm:
6089 
6090     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6091       CnstBits = CnstBits.zextOrTrunc(64);
6092       uint64_t CnstVal = CnstBits.getZExtValue();
6093 
6094       // Certain magic vector constants (used to express things like NOT
6095       // and NEG) are passed through unmodified.  This allows codegen patterns
6096       // for these operations to match.  Special-purpose patterns will lower
6097       // these immediates to MOVIs if it proves necessary.
6098       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6099         return Op;
6100 
6101       // The many faces of MOVI...
6102       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6103         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6104         if (VT.getSizeInBits() == 128) {
6105           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6106                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6107           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6108         }
6109 
6110         // Support the V64 version via subregister insertion.
6111         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6112                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6113         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6114       }
6115 
6116       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6117         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6118         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6119         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6120                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6121                                   DAG.getConstant(0, dl, MVT::i32));
6122         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6123       }
6124 
6125       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6126         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6127         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6128         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6129                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6130                                   DAG.getConstant(8, dl, MVT::i32));
6131         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6132       }
6133 
6134       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6135         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6136         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6137         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6138                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6139                                   DAG.getConstant(16, dl, MVT::i32));
6140         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6141       }
6142 
6143       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6144         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6145         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6146         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6147                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6148                                   DAG.getConstant(24, dl, MVT::i32));
6149         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6150       }
6151 
6152       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6153         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6154         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6155         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6156                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6157                                   DAG.getConstant(0, dl, MVT::i32));
6158         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6159       }
6160 
6161       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6162         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6163         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6164         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6165                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6166                                   DAG.getConstant(8, dl, MVT::i32));
6167         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6168       }
6169 
6170       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6171         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6172         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6173         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6174                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6175                                   DAG.getConstant(264, dl, MVT::i32));
6176         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6177       }
6178 
6179       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6180         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6181         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6182         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6183                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6184                                   DAG.getConstant(272, dl, MVT::i32));
6185         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6186       }
6187 
6188       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6189         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6190         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6191         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6192                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6193         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6194       }
6195 
6196       // The few faces of FMOV...
6197       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6198         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6199         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6200         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6201                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6202         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6203       }
6204 
6205       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6206           VT.getSizeInBits() == 128) {
6207         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6208         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6209                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6210         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6211       }
6212 
6213       // The many faces of MVNI...
6214       CnstVal = ~CnstVal;
6215       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6216         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6217         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6218         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6219                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6220                                   DAG.getConstant(0, dl, MVT::i32));
6221         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6222       }
6223 
6224       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6225         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6226         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6227         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6228                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6229                                   DAG.getConstant(8, dl, MVT::i32));
6230         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6231       }
6232 
6233       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6234         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6235         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6236         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6237                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6238                                   DAG.getConstant(16, dl, MVT::i32));
6239         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6240       }
6241 
6242       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6243         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6244         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6245         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6246                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6247                                   DAG.getConstant(24, dl, MVT::i32));
6248         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6249       }
6250 
6251       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6252         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6253         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6254         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6255                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6256                                   DAG.getConstant(0, dl, MVT::i32));
6257         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6258       }
6259 
6260       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6261         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6262         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6263         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6264                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6265                                   DAG.getConstant(8, dl, MVT::i32));
6266         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6267       }
6268 
6269       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6270         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6271         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6272         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6273                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6274                                   DAG.getConstant(264, dl, MVT::i32));
6275         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6276       }
6277 
6278       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6279         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6280         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6281         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6282                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6283                                   DAG.getConstant(272, dl, MVT::i32));
6284         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6285       }
6286     }
6287 
6288     if (SecondTry)
6289       goto FailedModImm;
6290     SecondTry = true;
6291     CnstBits = UndefBits;
6292     goto AttemptModImm;
6293   }
6294 FailedModImm:
6295 
6296   // Scan through the operands to find some interesting properties we can
6297   // exploit:
6298   //   1) If only one value is used, we can use a DUP, or
6299   //   2) if only the low element is not undef, we can just insert that, or
6300   //   3) if only one constant value is used (w/ some non-constant lanes),
6301   //      we can splat the constant value into the whole vector then fill
6302   //      in the non-constant lanes.
6303   //   4) FIXME: If different constant values are used, but we can intelligently
6304   //             select the values we'll be overwriting for the non-constant
6305   //             lanes such that we can directly materialize the vector
6306   //             some other way (MOVI, e.g.), we can be sneaky.
6307   unsigned NumElts = VT.getVectorNumElements();
6308   bool isOnlyLowElement = true;
6309   bool usesOnlyOneValue = true;
6310   bool usesOnlyOneConstantValue = true;
6311   bool isConstant = true;
6312   unsigned NumConstantLanes = 0;
6313   SDValue Value;
6314   SDValue ConstantValue;
6315   for (unsigned i = 0; i < NumElts; ++i) {
6316     SDValue V = Op.getOperand(i);
6317     if (V.getOpcode() == ISD::UNDEF)
6318       continue;
6319     if (i > 0)
6320       isOnlyLowElement = false;
6321     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6322       isConstant = false;
6323 
6324     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6325       ++NumConstantLanes;
6326       if (!ConstantValue.getNode())
6327         ConstantValue = V;
6328       else if (ConstantValue != V)
6329         usesOnlyOneConstantValue = false;
6330     }
6331 
6332     if (!Value.getNode())
6333       Value = V;
6334     else if (V != Value)
6335       usesOnlyOneValue = false;
6336   }
6337 
6338   if (!Value.getNode())
6339     return DAG.getUNDEF(VT);
6340 
6341   if (isOnlyLowElement)
6342     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6343 
6344   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6345   // i32 and try again.
6346   if (usesOnlyOneValue) {
6347     if (!isConstant) {
6348       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6349           Value.getValueType() != VT)
6350         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6351 
6352       // This is actually a DUPLANExx operation, which keeps everything vectory.
6353 
6354       // DUPLANE works on 128-bit vectors, widen it if necessary.
6355       SDValue Lane = Value.getOperand(1);
6356       Value = Value.getOperand(0);
6357       if (Value.getValueType().getSizeInBits() == 64)
6358         Value = WidenVector(Value, DAG);
6359 
6360       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6361       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6362     }
6363 
6364     if (VT.getVectorElementType().isFloatingPoint()) {
6365       SmallVector<SDValue, 8> Ops;
6366       EVT EltTy = VT.getVectorElementType();
6367       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6368               "Unsupported floating-point vector type");
6369       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6370       for (unsigned i = 0; i < NumElts; ++i)
6371         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6372       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6373       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6374       Val = LowerBUILD_VECTOR(Val, DAG);
6375       if (Val.getNode())
6376         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6377     }
6378   }
6379 
6380   // If there was only one constant value used and for more than one lane,
6381   // start by splatting that value, then replace the non-constant lanes. This
6382   // is better than the default, which will perform a separate initialization
6383   // for each lane.
6384   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6385     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6386     // Now insert the non-constant lanes.
6387     for (unsigned i = 0; i < NumElts; ++i) {
6388       SDValue V = Op.getOperand(i);
6389       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6390       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6391         // Note that type legalization likely mucked about with the VT of the
6392         // source operand, so we may have to convert it here before inserting.
6393         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6394       }
6395     }
6396     return Val;
6397   }
6398 
6399   // If all elements are constants and the case above didn't get hit, fall back
6400   // to the default expansion, which will generate a load from the constant
6401   // pool.
6402   if (isConstant)
6403     return SDValue();
6404 
6405   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6406   if (NumElts >= 4) {
6407     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6408       return shuffle;
6409   }
6410 
6411   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6412   // know the default expansion would otherwise fall back on something even
6413   // worse. For a vector with one or two non-undef values, that's
6414   // scalar_to_vector for the elements followed by a shuffle (provided the
6415   // shuffle is valid for the target) and materialization element by element
6416   // on the stack followed by a load for everything else.
6417   if (!isConstant && !usesOnlyOneValue) {
6418     SDValue Vec = DAG.getUNDEF(VT);
6419     SDValue Op0 = Op.getOperand(0);
6420     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6421     unsigned i = 0;
6422     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6423     // a) Avoid a RMW dependency on the full vector register, and
6424     // b) Allow the register coalescer to fold away the copy if the
6425     //    value is already in an S or D register.
6426     // Do not do this for UNDEF/LOAD nodes because we have better patterns
6427     // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6428     if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6429         (ElemSize == 32 || ElemSize == 64)) {
6430       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6431       MachineSDNode *N =
6432           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6433                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6434       Vec = SDValue(N, 0);
6435       ++i;
6436     }
6437     for (; i < NumElts; ++i) {
6438       SDValue V = Op.getOperand(i);
6439       if (V.getOpcode() == ISD::UNDEF)
6440         continue;
6441       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6442       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6443     }
6444     return Vec;
6445   }
6446 
6447   // Just use the default expansion. We failed to find a better alternative.
6448   return SDValue();
6449 }
6450 
6451 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6452                                                       SelectionDAG &DAG) const {
6453   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6454 
6455   // Check for non-constant or out of range lane.
6456   EVT VT = Op.getOperand(0).getValueType();
6457   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6458   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6459     return SDValue();
6460 
6461 
6462   // Insertion/extraction are legal for V128 types.
6463   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6464       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6465       VT == MVT::v8f16)
6466     return Op;
6467 
6468   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6469       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6470     return SDValue();
6471 
6472   // For V64 types, we perform insertion by expanding the value
6473   // to a V128 type and perform the insertion on that.
6474   SDLoc DL(Op);
6475   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6476   EVT WideTy = WideVec.getValueType();
6477 
6478   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6479                              Op.getOperand(1), Op.getOperand(2));
6480   // Re-narrow the resultant vector.
6481   return NarrowVector(Node, DAG);
6482 }
6483 
6484 SDValue
6485 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6486                                                SelectionDAG &DAG) const {
6487   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6488 
6489   // Check for non-constant or out of range lane.
6490   EVT VT = Op.getOperand(0).getValueType();
6491   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6492   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6493     return SDValue();
6494 
6495 
6496   // Insertion/extraction are legal for V128 types.
6497   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6498       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6499       VT == MVT::v8f16)
6500     return Op;
6501 
6502   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6503       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6504     return SDValue();
6505 
6506   // For V64 types, we perform extraction by expanding the value
6507   // to a V128 type and perform the extraction on that.
6508   SDLoc DL(Op);
6509   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6510   EVT WideTy = WideVec.getValueType();
6511 
6512   EVT ExtrTy = WideTy.getVectorElementType();
6513   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6514     ExtrTy = MVT::i32;
6515 
6516   // For extractions, we just return the result directly.
6517   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6518                      Op.getOperand(1));
6519 }
6520 
6521 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6522                                                       SelectionDAG &DAG) const {
6523   EVT VT = Op.getOperand(0).getValueType();
6524   SDLoc dl(Op);
6525   // Just in case...
6526   if (!VT.isVector())
6527     return SDValue();
6528 
6529   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6530   if (!Cst)
6531     return SDValue();
6532   unsigned Val = Cst->getZExtValue();
6533 
6534   unsigned Size = Op.getValueType().getSizeInBits();
6535 
6536   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6537   if (Val == 0)
6538     return Op;
6539 
6540   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6541   // that directly.
6542   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6543     return Op;
6544 
6545   return SDValue();
6546 }
6547 
6548 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6549                                                EVT VT) const {
6550   if (VT.getVectorNumElements() == 4 &&
6551       (VT.is128BitVector() || VT.is64BitVector())) {
6552     unsigned PFIndexes[4];
6553     for (unsigned i = 0; i != 4; ++i) {
6554       if (M[i] < 0)
6555         PFIndexes[i] = 8;
6556       else
6557         PFIndexes[i] = M[i];
6558     }
6559 
6560     // Compute the index in the perfect shuffle table.
6561     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6562                             PFIndexes[2] * 9 + PFIndexes[3];
6563     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6564     unsigned Cost = (PFEntry >> 30);
6565 
6566     if (Cost <= 4)
6567       return true;
6568   }
6569 
6570   bool DummyBool;
6571   int DummyInt;
6572   unsigned DummyUnsigned;
6573 
6574   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6575           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6576           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6577           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6578           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6579           isZIPMask(M, VT, DummyUnsigned) ||
6580           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6581           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6582           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6583           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6584           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6585 }
6586 
6587 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6588 /// operand of a vector shift operation, where all the elements of the
6589 /// build_vector must have the same constant integer value.
6590 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6591   // Ignore bit_converts.
6592   while (Op.getOpcode() == ISD::BITCAST)
6593     Op = Op.getOperand(0);
6594   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6595   APInt SplatBits, SplatUndef;
6596   unsigned SplatBitSize;
6597   bool HasAnyUndefs;
6598   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6599                                     HasAnyUndefs, ElementBits) ||
6600       SplatBitSize > ElementBits)
6601     return false;
6602   Cnt = SplatBits.getSExtValue();
6603   return true;
6604 }
6605 
6606 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6607 /// operand of a vector shift left operation.  That value must be in the range:
6608 ///   0 <= Value < ElementBits for a left shift; or
6609 ///   0 <= Value <= ElementBits for a long left shift.
6610 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6611   assert(VT.isVector() && "vector shift count is not a vector type");
6612   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6613   if (!getVShiftImm(Op, ElementBits, Cnt))
6614     return false;
6615   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6616 }
6617 
6618 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6619 /// operand of a vector shift right operation. The value must be in the range:
6620 ///   1 <= Value <= ElementBits for a right shift; or
6621 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6622   assert(VT.isVector() && "vector shift count is not a vector type");
6623   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6624   if (!getVShiftImm(Op, ElementBits, Cnt))
6625     return false;
6626   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6627 }
6628 
6629 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6630                                                       SelectionDAG &DAG) const {
6631   EVT VT = Op.getValueType();
6632   SDLoc DL(Op);
6633   int64_t Cnt;
6634 
6635   if (!Op.getOperand(1).getValueType().isVector())
6636     return Op;
6637   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6638 
6639   switch (Op.getOpcode()) {
6640   default:
6641     llvm_unreachable("unexpected shift opcode");
6642 
6643   case ISD::SHL:
6644     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6645       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6646                          DAG.getConstant(Cnt, DL, MVT::i32));
6647     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6648                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6649                                        MVT::i32),
6650                        Op.getOperand(0), Op.getOperand(1));
6651   case ISD::SRA:
6652   case ISD::SRL:
6653     // Right shift immediate
6654     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6655       unsigned Opc =
6656           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6657       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6658                          DAG.getConstant(Cnt, DL, MVT::i32));
6659     }
6660 
6661     // Right shift register.  Note, there is not a shift right register
6662     // instruction, but the shift left register instruction takes a signed
6663     // value, where negative numbers specify a right shift.
6664     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6665                                                 : Intrinsic::aarch64_neon_ushl;
6666     // negate the shift amount
6667     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6668     SDValue NegShiftLeft =
6669         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6670                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6671                     NegShift);
6672     return NegShiftLeft;
6673   }
6674 
6675   return SDValue();
6676 }
6677 
6678 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6679                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6680                                     SDLoc dl, SelectionDAG &DAG) {
6681   EVT SrcVT = LHS.getValueType();
6682   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6683          "function only supposed to emit natural comparisons");
6684 
6685   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6686   APInt CnstBits(VT.getSizeInBits(), 0);
6687   APInt UndefBits(VT.getSizeInBits(), 0);
6688   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6689   bool IsZero = IsCnst && (CnstBits == 0);
6690 
6691   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6692     switch (CC) {
6693     default:
6694       return SDValue();
6695     case AArch64CC::NE: {
6696       SDValue Fcmeq;
6697       if (IsZero)
6698         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6699       else
6700         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6701       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6702     }
6703     case AArch64CC::EQ:
6704       if (IsZero)
6705         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6706       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6707     case AArch64CC::GE:
6708       if (IsZero)
6709         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6710       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6711     case AArch64CC::GT:
6712       if (IsZero)
6713         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6714       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6715     case AArch64CC::LS:
6716       if (IsZero)
6717         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6718       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6719     case AArch64CC::LT:
6720       if (!NoNans)
6721         return SDValue();
6722     // If we ignore NaNs then we can use to the MI implementation.
6723     // Fallthrough.
6724     case AArch64CC::MI:
6725       if (IsZero)
6726         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6727       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6728     }
6729   }
6730 
6731   switch (CC) {
6732   default:
6733     return SDValue();
6734   case AArch64CC::NE: {
6735     SDValue Cmeq;
6736     if (IsZero)
6737       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6738     else
6739       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6740     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6741   }
6742   case AArch64CC::EQ:
6743     if (IsZero)
6744       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6745     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6746   case AArch64CC::GE:
6747     if (IsZero)
6748       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6749     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6750   case AArch64CC::GT:
6751     if (IsZero)
6752       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6753     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6754   case AArch64CC::LE:
6755     if (IsZero)
6756       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6757     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6758   case AArch64CC::LS:
6759     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6760   case AArch64CC::LO:
6761     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6762   case AArch64CC::LT:
6763     if (IsZero)
6764       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6765     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6766   case AArch64CC::HI:
6767     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6768   case AArch64CC::HS:
6769     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6770   }
6771 }
6772 
6773 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6774                                            SelectionDAG &DAG) const {
6775   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6776   SDValue LHS = Op.getOperand(0);
6777   SDValue RHS = Op.getOperand(1);
6778   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6779   SDLoc dl(Op);
6780 
6781   if (LHS.getValueType().getVectorElementType().isInteger()) {
6782     assert(LHS.getValueType() == RHS.getValueType());
6783     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6784     SDValue Cmp =
6785         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6786     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6787   }
6788 
6789   if (LHS.getValueType().getVectorElementType() == MVT::f16)
6790     return SDValue();
6791 
6792   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6793          LHS.getValueType().getVectorElementType() == MVT::f64);
6794 
6795   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6796   // clean.  Some of them require two branches to implement.
6797   AArch64CC::CondCode CC1, CC2;
6798   bool ShouldInvert;
6799   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6800 
6801   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6802   SDValue Cmp =
6803       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6804   if (!Cmp.getNode())
6805     return SDValue();
6806 
6807   if (CC2 != AArch64CC::AL) {
6808     SDValue Cmp2 =
6809         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6810     if (!Cmp2.getNode())
6811       return SDValue();
6812 
6813     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6814   }
6815 
6816   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6817 
6818   if (ShouldInvert)
6819     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6820 
6821   return Cmp;
6822 }
6823 
6824 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6825 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6826 /// specified in the intrinsic calls.
6827 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6828                                                const CallInst &I,
6829                                                unsigned Intrinsic) const {
6830   auto &DL = I.getModule()->getDataLayout();
6831   switch (Intrinsic) {
6832   case Intrinsic::aarch64_neon_ld2:
6833   case Intrinsic::aarch64_neon_ld3:
6834   case Intrinsic::aarch64_neon_ld4:
6835   case Intrinsic::aarch64_neon_ld1x2:
6836   case Intrinsic::aarch64_neon_ld1x3:
6837   case Intrinsic::aarch64_neon_ld1x4:
6838   case Intrinsic::aarch64_neon_ld2lane:
6839   case Intrinsic::aarch64_neon_ld3lane:
6840   case Intrinsic::aarch64_neon_ld4lane:
6841   case Intrinsic::aarch64_neon_ld2r:
6842   case Intrinsic::aarch64_neon_ld3r:
6843   case Intrinsic::aarch64_neon_ld4r: {
6844     Info.opc = ISD::INTRINSIC_W_CHAIN;
6845     // Conservatively set memVT to the entire set of vectors loaded.
6846     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6847     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6848     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6849     Info.offset = 0;
6850     Info.align = 0;
6851     Info.vol = false; // volatile loads with NEON intrinsics not supported
6852     Info.readMem = true;
6853     Info.writeMem = false;
6854     return true;
6855   }
6856   case Intrinsic::aarch64_neon_st2:
6857   case Intrinsic::aarch64_neon_st3:
6858   case Intrinsic::aarch64_neon_st4:
6859   case Intrinsic::aarch64_neon_st1x2:
6860   case Intrinsic::aarch64_neon_st1x3:
6861   case Intrinsic::aarch64_neon_st1x4:
6862   case Intrinsic::aarch64_neon_st2lane:
6863   case Intrinsic::aarch64_neon_st3lane:
6864   case Intrinsic::aarch64_neon_st4lane: {
6865     Info.opc = ISD::INTRINSIC_VOID;
6866     // Conservatively set memVT to the entire set of vectors stored.
6867     unsigned NumElts = 0;
6868     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6869       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6870       if (!ArgTy->isVectorTy())
6871         break;
6872       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6873     }
6874     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6875     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6876     Info.offset = 0;
6877     Info.align = 0;
6878     Info.vol = false; // volatile stores with NEON intrinsics not supported
6879     Info.readMem = false;
6880     Info.writeMem = true;
6881     return true;
6882   }
6883   case Intrinsic::aarch64_ldaxr:
6884   case Intrinsic::aarch64_ldxr: {
6885     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6886     Info.opc = ISD::INTRINSIC_W_CHAIN;
6887     Info.memVT = MVT::getVT(PtrTy->getElementType());
6888     Info.ptrVal = I.getArgOperand(0);
6889     Info.offset = 0;
6890     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6891     Info.vol = true;
6892     Info.readMem = true;
6893     Info.writeMem = false;
6894     return true;
6895   }
6896   case Intrinsic::aarch64_stlxr:
6897   case Intrinsic::aarch64_stxr: {
6898     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6899     Info.opc = ISD::INTRINSIC_W_CHAIN;
6900     Info.memVT = MVT::getVT(PtrTy->getElementType());
6901     Info.ptrVal = I.getArgOperand(1);
6902     Info.offset = 0;
6903     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6904     Info.vol = true;
6905     Info.readMem = false;
6906     Info.writeMem = true;
6907     return true;
6908   }
6909   case Intrinsic::aarch64_ldaxp:
6910   case Intrinsic::aarch64_ldxp: {
6911     Info.opc = ISD::INTRINSIC_W_CHAIN;
6912     Info.memVT = MVT::i128;
6913     Info.ptrVal = I.getArgOperand(0);
6914     Info.offset = 0;
6915     Info.align = 16;
6916     Info.vol = true;
6917     Info.readMem = true;
6918     Info.writeMem = false;
6919     return true;
6920   }
6921   case Intrinsic::aarch64_stlxp:
6922   case Intrinsic::aarch64_stxp: {
6923     Info.opc = ISD::INTRINSIC_W_CHAIN;
6924     Info.memVT = MVT::i128;
6925     Info.ptrVal = I.getArgOperand(2);
6926     Info.offset = 0;
6927     Info.align = 16;
6928     Info.vol = true;
6929     Info.readMem = false;
6930     Info.writeMem = true;
6931     return true;
6932   }
6933   default:
6934     break;
6935   }
6936 
6937   return false;
6938 }
6939 
6940 // Truncations from 64-bit GPR to 32-bit GPR is free.
6941 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6942   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6943     return false;
6944   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6945   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6946   return NumBits1 > NumBits2;
6947 }
6948 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6949   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6950     return false;
6951   unsigned NumBits1 = VT1.getSizeInBits();
6952   unsigned NumBits2 = VT2.getSizeInBits();
6953   return NumBits1 > NumBits2;
6954 }
6955 
6956 /// Check if it is profitable to hoist instruction in then/else to if.
6957 /// Not profitable if I and it's user can form a FMA instruction
6958 /// because we prefer FMSUB/FMADD.
6959 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6960   if (I->getOpcode() != Instruction::FMul)
6961     return true;
6962 
6963   if (I->getNumUses() != 1)
6964     return true;
6965 
6966   Instruction *User = I->user_back();
6967 
6968   if (User &&
6969       !(User->getOpcode() == Instruction::FSub ||
6970         User->getOpcode() == Instruction::FAdd))
6971     return true;
6972 
6973   const TargetOptions &Options = getTargetMachine().Options;
6974   const DataLayout &DL = I->getModule()->getDataLayout();
6975   EVT VT = getValueType(DL, User->getOperand(0)->getType());
6976 
6977   if (isFMAFasterThanFMulAndFAdd(VT) &&
6978       isOperationLegalOrCustom(ISD::FMA, VT) &&
6979       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6980     return false;
6981 
6982   return true;
6983 }
6984 
6985 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6986 // 64-bit GPR.
6987 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6988   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6989     return false;
6990   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6991   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6992   return NumBits1 == 32 && NumBits2 == 64;
6993 }
6994 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6995   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6996     return false;
6997   unsigned NumBits1 = VT1.getSizeInBits();
6998   unsigned NumBits2 = VT2.getSizeInBits();
6999   return NumBits1 == 32 && NumBits2 == 64;
7000 }
7001 
7002 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7003   EVT VT1 = Val.getValueType();
7004   if (isZExtFree(VT1, VT2)) {
7005     return true;
7006   }
7007 
7008   if (Val.getOpcode() != ISD::LOAD)
7009     return false;
7010 
7011   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7012   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7013           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7014           VT1.getSizeInBits() <= 32);
7015 }
7016 
7017 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7018   if (isa<FPExtInst>(Ext))
7019     return false;
7020 
7021   // Vector types are next free.
7022   if (Ext->getType()->isVectorTy())
7023     return false;
7024 
7025   for (const Use &U : Ext->uses()) {
7026     // The extension is free if we can fold it with a left shift in an
7027     // addressing mode or an arithmetic operation: add, sub, and cmp.
7028 
7029     // Is there a shift?
7030     const Instruction *Instr = cast<Instruction>(U.getUser());
7031 
7032     // Is this a constant shift?
7033     switch (Instr->getOpcode()) {
7034     case Instruction::Shl:
7035       if (!isa<ConstantInt>(Instr->getOperand(1)))
7036         return false;
7037       break;
7038     case Instruction::GetElementPtr: {
7039       gep_type_iterator GTI = gep_type_begin(Instr);
7040       auto &DL = Ext->getModule()->getDataLayout();
7041       std::advance(GTI, U.getOperandNo());
7042       Type *IdxTy = *GTI;
7043       // This extension will end up with a shift because of the scaling factor.
7044       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7045       // Get the shift amount based on the scaling factor:
7046       // log2(sizeof(IdxTy)) - log2(8).
7047       uint64_t ShiftAmt =
7048           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7049       // Is the constant foldable in the shift of the addressing mode?
7050       // I.e., shift amount is between 1 and 4 inclusive.
7051       if (ShiftAmt == 0 || ShiftAmt > 4)
7052         return false;
7053       break;
7054     }
7055     case Instruction::Trunc:
7056       // Check if this is a noop.
7057       // trunc(sext ty1 to ty2) to ty1.
7058       if (Instr->getType() == Ext->getOperand(0)->getType())
7059         continue;
7060     // FALL THROUGH.
7061     default:
7062       return false;
7063     }
7064 
7065     // At this point we can use the bfm family, so this extension is free
7066     // for that use.
7067   }
7068   return true;
7069 }
7070 
7071 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7072                                           unsigned &RequiredAligment) const {
7073   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7074     return false;
7075   // Cyclone supports unaligned accesses.
7076   RequiredAligment = 0;
7077   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7078   return NumBits == 32 || NumBits == 64;
7079 }
7080 
7081 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7082                                           unsigned &RequiredAligment) const {
7083   if (!LoadedType.isSimple() ||
7084       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7085     return false;
7086   // Cyclone supports unaligned accesses.
7087   RequiredAligment = 0;
7088   unsigned NumBits = LoadedType.getSizeInBits();
7089   return NumBits == 32 || NumBits == 64;
7090 }
7091 
7092 /// \brief Lower an interleaved load into a ldN intrinsic.
7093 ///
7094 /// E.g. Lower an interleaved load (Factor = 2):
7095 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7096 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7097 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7098 ///
7099 ///      Into:
7100 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7101 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7102 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7103 bool AArch64TargetLowering::lowerInterleavedLoad(
7104     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7105     ArrayRef<unsigned> Indices, unsigned Factor) const {
7106   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7107          "Invalid interleave factor");
7108   assert(!Shuffles.empty() && "Empty shufflevector input");
7109   assert(Shuffles.size() == Indices.size() &&
7110          "Unmatched number of shufflevectors and indices");
7111 
7112   const DataLayout &DL = LI->getModule()->getDataLayout();
7113 
7114   VectorType *VecTy = Shuffles[0]->getType();
7115   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7116 
7117   // Skip if we do not have NEON and skip illegal vector types.
7118   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7119     return false;
7120 
7121   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7122   // load integer vectors first and then convert to pointer vectors.
7123   Type *EltTy = VecTy->getVectorElementType();
7124   if (EltTy->isPointerTy())
7125     VecTy =
7126         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7127 
7128   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7129   Type *Tys[2] = {VecTy, PtrTy};
7130   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7131                                             Intrinsic::aarch64_neon_ld3,
7132                                             Intrinsic::aarch64_neon_ld4};
7133   Function *LdNFunc =
7134       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7135 
7136   IRBuilder<> Builder(LI);
7137   Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7138 
7139   CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7140 
7141   // Replace uses of each shufflevector with the corresponding vector loaded
7142   // by ldN.
7143   for (unsigned i = 0; i < Shuffles.size(); i++) {
7144     ShuffleVectorInst *SVI = Shuffles[i];
7145     unsigned Index = Indices[i];
7146 
7147     Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7148 
7149     // Convert the integer vector to pointer vector if the element is pointer.
7150     if (EltTy->isPointerTy())
7151       SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7152 
7153     SVI->replaceAllUsesWith(SubVec);
7154   }
7155 
7156   return true;
7157 }
7158 
7159 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7160 ///
7161 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7162 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7163                                    unsigned NumElts) {
7164   SmallVector<Constant *, 16> Mask;
7165   for (unsigned i = 0; i < NumElts; i++)
7166     Mask.push_back(Builder.getInt32(Start + i));
7167 
7168   return ConstantVector::get(Mask);
7169 }
7170 
7171 /// \brief Lower an interleaved store into a stN intrinsic.
7172 ///
7173 /// E.g. Lower an interleaved store (Factor = 3):
7174 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7175 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7176 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7177 ///
7178 ///      Into:
7179 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7180 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7181 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7182 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7183 ///
7184 /// Note that the new shufflevectors will be removed and we'll only generate one
7185 /// st3 instruction in CodeGen.
7186 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7187                                                   ShuffleVectorInst *SVI,
7188                                                   unsigned Factor) const {
7189   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7190          "Invalid interleave factor");
7191 
7192   VectorType *VecTy = SVI->getType();
7193   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7194          "Invalid interleaved store");
7195 
7196   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7197   Type *EltTy = VecTy->getVectorElementType();
7198   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7199 
7200   const DataLayout &DL = SI->getModule()->getDataLayout();
7201   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7202 
7203   // Skip if we do not have NEON and skip illegal vector types.
7204   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7205     return false;
7206 
7207   Value *Op0 = SVI->getOperand(0);
7208   Value *Op1 = SVI->getOperand(1);
7209   IRBuilder<> Builder(SI);
7210 
7211   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7212   // vectors to integer vectors.
7213   if (EltTy->isPointerTy()) {
7214     Type *IntTy = DL.getIntPtrType(EltTy);
7215     unsigned NumOpElts =
7216         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7217 
7218     // Convert to the corresponding integer vector.
7219     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7220     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7221     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7222 
7223     SubVecTy = VectorType::get(IntTy, NumSubElts);
7224   }
7225 
7226   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7227   Type *Tys[2] = {SubVecTy, PtrTy};
7228   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7229                                              Intrinsic::aarch64_neon_st3,
7230                                              Intrinsic::aarch64_neon_st4};
7231   Function *StNFunc =
7232       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7233 
7234   SmallVector<Value *, 5> Ops;
7235 
7236   // Split the shufflevector operands into sub vectors for the new stN call.
7237   for (unsigned i = 0; i < Factor; i++)
7238     Ops.push_back(Builder.CreateShuffleVector(
7239         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7240 
7241   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7242   Builder.CreateCall(StNFunc, Ops);
7243   return true;
7244 }
7245 
7246 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7247                        unsigned AlignCheck) {
7248   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7249           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7250 }
7251 
7252 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7253                                                unsigned SrcAlign, bool IsMemset,
7254                                                bool ZeroMemset,
7255                                                bool MemcpyStrSrc,
7256                                                MachineFunction &MF) const {
7257   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7258   // instruction to materialize the v2i64 zero and one store (with restrictive
7259   // addressing mode). Just do two i64 store of zero-registers.
7260   bool Fast;
7261   const Function *F = MF.getFunction();
7262   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7263       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7264       (memOpAlign(SrcAlign, DstAlign, 16) ||
7265        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7266     return MVT::f128;
7267 
7268   if (Size >= 8 &&
7269       (memOpAlign(SrcAlign, DstAlign, 8) ||
7270        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7271     return MVT::i64;
7272 
7273   if (Size >= 4 &&
7274       (memOpAlign(SrcAlign, DstAlign, 4) ||
7275        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7276     return MVT::i32;
7277 
7278   return MVT::Other;
7279 }
7280 
7281 // 12-bit optionally shifted immediates are legal for adds.
7282 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7283   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7284     return true;
7285   return false;
7286 }
7287 
7288 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7289 // immediates is the same as for an add or a sub.
7290 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7291   if (Immed < 0)
7292     Immed *= -1;
7293   return isLegalAddImmediate(Immed);
7294 }
7295 
7296 /// isLegalAddressingMode - Return true if the addressing mode represented
7297 /// by AM is legal for this target, for a load/store of the specified type.
7298 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7299                                                   const AddrMode &AM, Type *Ty,
7300                                                   unsigned AS) const {
7301   // AArch64 has five basic addressing modes:
7302   //  reg
7303   //  reg + 9-bit signed offset
7304   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7305   //  reg1 + reg2
7306   //  reg + SIZE_IN_BYTES * reg
7307 
7308   // No global is ever allowed as a base.
7309   if (AM.BaseGV)
7310     return false;
7311 
7312   // No reg+reg+imm addressing.
7313   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7314     return false;
7315 
7316   // check reg + imm case:
7317   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7318   uint64_t NumBytes = 0;
7319   if (Ty->isSized()) {
7320     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7321     NumBytes = NumBits / 8;
7322     if (!isPowerOf2_64(NumBits))
7323       NumBytes = 0;
7324   }
7325 
7326   if (!AM.Scale) {
7327     int64_t Offset = AM.BaseOffs;
7328 
7329     // 9-bit signed offset
7330     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7331       return true;
7332 
7333     // 12-bit unsigned offset
7334     unsigned shift = Log2_64(NumBytes);
7335     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7336         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7337         (Offset >> shift) << shift == Offset)
7338       return true;
7339     return false;
7340   }
7341 
7342   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7343 
7344   if (!AM.Scale || AM.Scale == 1 ||
7345       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7346     return true;
7347   return false;
7348 }
7349 
7350 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7351                                                 const AddrMode &AM, Type *Ty,
7352                                                 unsigned AS) const {
7353   // Scaling factors are not free at all.
7354   // Operands                     | Rt Latency
7355   // -------------------------------------------
7356   // Rt, [Xn, Xm]                 | 4
7357   // -------------------------------------------
7358   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7359   // Rt, [Xn, Wm, <extend> #imm]  |
7360   if (isLegalAddressingMode(DL, AM, Ty, AS))
7361     // Scale represents reg2 * scale, thus account for 1 if
7362     // it is not equal to 0 or 1.
7363     return AM.Scale != 0 && AM.Scale != 1;
7364   return -1;
7365 }
7366 
7367 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7368   VT = VT.getScalarType();
7369 
7370   if (!VT.isSimple())
7371     return false;
7372 
7373   switch (VT.getSimpleVT().SimpleTy) {
7374   case MVT::f32:
7375   case MVT::f64:
7376     return true;
7377   default:
7378     break;
7379   }
7380 
7381   return false;
7382 }
7383 
7384 const MCPhysReg *
7385 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7386   // LR is a callee-save register, but we must treat it as clobbered by any call
7387   // site. Hence we include LR in the scratch registers, which are in turn added
7388   // as implicit-defs for stackmaps and patchpoints.
7389   static const MCPhysReg ScratchRegs[] = {
7390     AArch64::X16, AArch64::X17, AArch64::LR, 0
7391   };
7392   return ScratchRegs;
7393 }
7394 
7395 bool
7396 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7397   EVT VT = N->getValueType(0);
7398     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7399     // it with shift to let it be lowered to UBFX.
7400   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7401       isa<ConstantSDNode>(N->getOperand(1))) {
7402     uint64_t TruncMask = N->getConstantOperandVal(1);
7403     if (isMask_64(TruncMask) &&
7404       N->getOperand(0).getOpcode() == ISD::SRL &&
7405       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7406       return false;
7407   }
7408   return true;
7409 }
7410 
7411 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7412                                                               Type *Ty) const {
7413   assert(Ty->isIntegerTy());
7414 
7415   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7416   if (BitSize == 0)
7417     return false;
7418 
7419   int64_t Val = Imm.getSExtValue();
7420   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7421     return true;
7422 
7423   if ((int64_t)Val < 0)
7424     Val = ~Val;
7425   if (BitSize == 32)
7426     Val &= (1LL << 32) - 1;
7427 
7428   unsigned LZ = countLeadingZeros((uint64_t)Val);
7429   unsigned Shift = (63 - LZ) / 16;
7430   // MOVZ is free so return true for one or fewer MOVK.
7431   return Shift < 3;
7432 }
7433 
7434 // Generate SUBS and CSEL for integer abs.
7435 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7436   EVT VT = N->getValueType(0);
7437 
7438   SDValue N0 = N->getOperand(0);
7439   SDValue N1 = N->getOperand(1);
7440   SDLoc DL(N);
7441 
7442   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7443   // and change it to SUB and CSEL.
7444   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7445       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7446       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7447     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7448       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7449         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7450                                   N0.getOperand(0));
7451         // Generate SUBS & CSEL.
7452         SDValue Cmp =
7453             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7454                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7455         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7456                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7457                            SDValue(Cmp.getNode(), 1));
7458       }
7459   return SDValue();
7460 }
7461 
7462 // performXorCombine - Attempts to handle integer ABS.
7463 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7464                                  TargetLowering::DAGCombinerInfo &DCI,
7465                                  const AArch64Subtarget *Subtarget) {
7466   if (DCI.isBeforeLegalizeOps())
7467     return SDValue();
7468 
7469   return performIntegerAbsCombine(N, DAG);
7470 }
7471 
7472 SDValue
7473 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7474                                      SelectionDAG &DAG,
7475                                      std::vector<SDNode *> *Created) const {
7476   // fold (sdiv X, pow2)
7477   EVT VT = N->getValueType(0);
7478   if ((VT != MVT::i32 && VT != MVT::i64) ||
7479       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7480     return SDValue();
7481 
7482   SDLoc DL(N);
7483   SDValue N0 = N->getOperand(0);
7484   unsigned Lg2 = Divisor.countTrailingZeros();
7485   SDValue Zero = DAG.getConstant(0, DL, VT);
7486   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7487 
7488   // Add (N0 < 0) ? Pow2 - 1 : 0;
7489   SDValue CCVal;
7490   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7491   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7492   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7493 
7494   if (Created) {
7495     Created->push_back(Cmp.getNode());
7496     Created->push_back(Add.getNode());
7497     Created->push_back(CSel.getNode());
7498   }
7499 
7500   // Divide by pow2.
7501   SDValue SRA =
7502       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7503 
7504   // If we're dividing by a positive value, we're done.  Otherwise, we must
7505   // negate the result.
7506   if (Divisor.isNonNegative())
7507     return SRA;
7508 
7509   if (Created)
7510     Created->push_back(SRA.getNode());
7511   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7512 }
7513 
7514 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7515                                  TargetLowering::DAGCombinerInfo &DCI,
7516                                  const AArch64Subtarget *Subtarget) {
7517   if (DCI.isBeforeLegalizeOps())
7518     return SDValue();
7519 
7520   // Multiplication of a power of two plus/minus one can be done more
7521   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7522   // future CPUs have a cheaper MADD instruction, this may need to be
7523   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7524   // 64-bit is 5 cycles, so this is always a win.
7525   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7526     APInt Value = C->getAPIntValue();
7527     EVT VT = N->getValueType(0);
7528     SDLoc DL(N);
7529     if (Value.isNonNegative()) {
7530       // (mul x, 2^N + 1) => (add (shl x, N), x)
7531       APInt VM1 = Value - 1;
7532       if (VM1.isPowerOf2()) {
7533         SDValue ShiftedVal =
7534             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7535                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7536         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7537                            N->getOperand(0));
7538       }
7539       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7540       APInt VP1 = Value + 1;
7541       if (VP1.isPowerOf2()) {
7542         SDValue ShiftedVal =
7543             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7544                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7545         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7546                            N->getOperand(0));
7547       }
7548     } else {
7549       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7550       APInt VNP1 = -Value + 1;
7551       if (VNP1.isPowerOf2()) {
7552         SDValue ShiftedVal =
7553             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7554                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7555         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7556                            ShiftedVal);
7557       }
7558       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7559       APInt VNM1 = -Value - 1;
7560       if (VNM1.isPowerOf2()) {
7561         SDValue ShiftedVal =
7562             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7563                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7564         SDValue Add =
7565             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7566         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7567       }
7568     }
7569   }
7570   return SDValue();
7571 }
7572 
7573 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7574                                                          SelectionDAG &DAG) {
7575   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7576   // optimize away operation when it's from a constant.
7577   //
7578   // The general transformation is:
7579   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7580   //       AND(VECTOR_CMP(x,y), constant2)
7581   //    constant2 = UNARYOP(constant)
7582 
7583   // Early exit if this isn't a vector operation, the operand of the
7584   // unary operation isn't a bitwise AND, or if the sizes of the operations
7585   // aren't the same.
7586   EVT VT = N->getValueType(0);
7587   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7588       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7589       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7590     return SDValue();
7591 
7592   // Now check that the other operand of the AND is a constant. We could
7593   // make the transformation for non-constant splats as well, but it's unclear
7594   // that would be a benefit as it would not eliminate any operations, just
7595   // perform one more step in scalar code before moving to the vector unit.
7596   if (BuildVectorSDNode *BV =
7597           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7598     // Bail out if the vector isn't a constant.
7599     if (!BV->isConstant())
7600       return SDValue();
7601 
7602     // Everything checks out. Build up the new and improved node.
7603     SDLoc DL(N);
7604     EVT IntVT = BV->getValueType(0);
7605     // Create a new constant of the appropriate type for the transformed
7606     // DAG.
7607     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7608     // The AND node needs bitcasts to/from an integer vector type around it.
7609     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7610     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7611                                  N->getOperand(0)->getOperand(0), MaskConst);
7612     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7613     return Res;
7614   }
7615 
7616   return SDValue();
7617 }
7618 
7619 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7620                                      const AArch64Subtarget *Subtarget) {
7621   // First try to optimize away the conversion when it's conditionally from
7622   // a constant. Vectors only.
7623   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7624     return Res;
7625 
7626   EVT VT = N->getValueType(0);
7627   if (VT != MVT::f32 && VT != MVT::f64)
7628     return SDValue();
7629 
7630   // Only optimize when the source and destination types have the same width.
7631   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7632     return SDValue();
7633 
7634   // If the result of an integer load is only used by an integer-to-float
7635   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7636   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7637   SDValue N0 = N->getOperand(0);
7638   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7639       // Do not change the width of a volatile load.
7640       !cast<LoadSDNode>(N0)->isVolatile()) {
7641     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7642     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7643                                LN0->getPointerInfo(), LN0->isVolatile(),
7644                                LN0->isNonTemporal(), LN0->isInvariant(),
7645                                LN0->getAlignment());
7646 
7647     // Make sure successors of the original load stay after it by updating them
7648     // to use the new Chain.
7649     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7650 
7651     unsigned Opcode =
7652         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7653     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7654   }
7655 
7656   return SDValue();
7657 }
7658 
7659 /// Fold a floating-point multiply by power of two into floating-point to
7660 /// fixed-point conversion.
7661 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7662                                      const AArch64Subtarget *Subtarget) {
7663   if (!Subtarget->hasNEON())
7664     return SDValue();
7665 
7666   SDValue Op = N->getOperand(0);
7667   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7668     return SDValue();
7669 
7670   SDValue ConstVec = Op->getOperand(1);
7671   if (!isa<BuildVectorSDNode>(ConstVec))
7672     return SDValue();
7673 
7674   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7675   uint32_t FloatBits = FloatTy.getSizeInBits();
7676   if (FloatBits != 32 && FloatBits != 64)
7677     return SDValue();
7678 
7679   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7680   uint32_t IntBits = IntTy.getSizeInBits();
7681   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7682     return SDValue();
7683 
7684   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7685   if (IntBits > FloatBits)
7686     return SDValue();
7687 
7688   BitVector UndefElements;
7689   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7690   int32_t Bits = IntBits == 64 ? 64 : 32;
7691   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7692   if (C == -1 || C == 0 || C > Bits)
7693     return SDValue();
7694 
7695   MVT ResTy;
7696   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7697   switch (NumLanes) {
7698   default:
7699     return SDValue();
7700   case 2:
7701     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7702     break;
7703   case 4:
7704     ResTy = MVT::v4i32;
7705     break;
7706   }
7707 
7708   SDLoc DL(N);
7709   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7710   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7711                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
7712   SDValue FixConv =
7713       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7714                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7715                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7716   // We can handle smaller integers by generating an extra trunc.
7717   if (IntBits < FloatBits)
7718     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7719 
7720   return FixConv;
7721 }
7722 
7723 /// Fold a floating-point divide by power of two into fixed-point to
7724 /// floating-point conversion.
7725 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7726                                   const AArch64Subtarget *Subtarget) {
7727   if (!Subtarget->hasNEON())
7728     return SDValue();
7729 
7730   SDValue Op = N->getOperand(0);
7731   unsigned Opc = Op->getOpcode();
7732   if (!Op.getValueType().isVector() ||
7733       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7734     return SDValue();
7735 
7736   SDValue ConstVec = N->getOperand(1);
7737   if (!isa<BuildVectorSDNode>(ConstVec))
7738     return SDValue();
7739 
7740   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7741   int32_t IntBits = IntTy.getSizeInBits();
7742   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7743     return SDValue();
7744 
7745   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7746   int32_t FloatBits = FloatTy.getSizeInBits();
7747   if (FloatBits != 32 && FloatBits != 64)
7748     return SDValue();
7749 
7750   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7751   if (IntBits > FloatBits)
7752     return SDValue();
7753 
7754   BitVector UndefElements;
7755   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7756   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7757   if (C == -1 || C == 0 || C > FloatBits)
7758     return SDValue();
7759 
7760   MVT ResTy;
7761   unsigned NumLanes = Op.getValueType().getVectorNumElements();
7762   switch (NumLanes) {
7763   default:
7764     return SDValue();
7765   case 2:
7766     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7767     break;
7768   case 4:
7769     ResTy = MVT::v4i32;
7770     break;
7771   }
7772 
7773   SDLoc DL(N);
7774   SDValue ConvInput = Op.getOperand(0);
7775   bool IsSigned = Opc == ISD::SINT_TO_FP;
7776   if (IntBits < FloatBits)
7777     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7778                             ResTy, ConvInput);
7779 
7780   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7781                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
7782   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7783                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7784                      DAG.getConstant(C, DL, MVT::i32));
7785 }
7786 
7787 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7788 /// searches for and classifies those shifts.
7789 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7790                          bool &FromHi) {
7791   if (N.getOpcode() == ISD::SHL)
7792     FromHi = false;
7793   else if (N.getOpcode() == ISD::SRL)
7794     FromHi = true;
7795   else
7796     return false;
7797 
7798   if (!isa<ConstantSDNode>(N.getOperand(1)))
7799     return false;
7800 
7801   ShiftAmount = N->getConstantOperandVal(1);
7802   Src = N->getOperand(0);
7803   return true;
7804 }
7805 
7806 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7807 /// registers viewed as a high/low pair. This function looks for the pattern:
7808 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7809 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7810 /// independent.
7811 static SDValue tryCombineToEXTR(SDNode *N,
7812                                 TargetLowering::DAGCombinerInfo &DCI) {
7813   SelectionDAG &DAG = DCI.DAG;
7814   SDLoc DL(N);
7815   EVT VT = N->getValueType(0);
7816 
7817   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7818 
7819   if (VT != MVT::i32 && VT != MVT::i64)
7820     return SDValue();
7821 
7822   SDValue LHS;
7823   uint32_t ShiftLHS = 0;
7824   bool LHSFromHi = 0;
7825   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7826     return SDValue();
7827 
7828   SDValue RHS;
7829   uint32_t ShiftRHS = 0;
7830   bool RHSFromHi = 0;
7831   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7832     return SDValue();
7833 
7834   // If they're both trying to come from the high part of the register, they're
7835   // not really an EXTR.
7836   if (LHSFromHi == RHSFromHi)
7837     return SDValue();
7838 
7839   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7840     return SDValue();
7841 
7842   if (LHSFromHi) {
7843     std::swap(LHS, RHS);
7844     std::swap(ShiftLHS, ShiftRHS);
7845   }
7846 
7847   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7848                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7849 }
7850 
7851 static SDValue tryCombineToBSL(SDNode *N,
7852                                 TargetLowering::DAGCombinerInfo &DCI) {
7853   EVT VT = N->getValueType(0);
7854   SelectionDAG &DAG = DCI.DAG;
7855   SDLoc DL(N);
7856 
7857   if (!VT.isVector())
7858     return SDValue();
7859 
7860   SDValue N0 = N->getOperand(0);
7861   if (N0.getOpcode() != ISD::AND)
7862     return SDValue();
7863 
7864   SDValue N1 = N->getOperand(1);
7865   if (N1.getOpcode() != ISD::AND)
7866     return SDValue();
7867 
7868   // We only have to look for constant vectors here since the general, variable
7869   // case can be handled in TableGen.
7870   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7871   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7872   for (int i = 1; i >= 0; --i)
7873     for (int j = 1; j >= 0; --j) {
7874       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7875       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7876       if (!BVN0 || !BVN1)
7877         continue;
7878 
7879       bool FoundMatch = true;
7880       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7881         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7882         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7883         if (!CN0 || !CN1 ||
7884             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7885           FoundMatch = false;
7886           break;
7887         }
7888       }
7889 
7890       if (FoundMatch)
7891         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7892                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7893     }
7894 
7895   return SDValue();
7896 }
7897 
7898 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7899                                 const AArch64Subtarget *Subtarget) {
7900   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7901   if (!EnableAArch64ExtrGeneration)
7902     return SDValue();
7903   SelectionDAG &DAG = DCI.DAG;
7904   EVT VT = N->getValueType(0);
7905 
7906   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7907     return SDValue();
7908 
7909   if (SDValue Res = tryCombineToEXTR(N, DCI))
7910     return Res;
7911 
7912   if (SDValue Res = tryCombineToBSL(N, DCI))
7913     return Res;
7914 
7915   return SDValue();
7916 }
7917 
7918 static SDValue performBitcastCombine(SDNode *N,
7919                                      TargetLowering::DAGCombinerInfo &DCI,
7920                                      SelectionDAG &DAG) {
7921   // Wait 'til after everything is legalized to try this. That way we have
7922   // legal vector types and such.
7923   if (DCI.isBeforeLegalizeOps())
7924     return SDValue();
7925 
7926   // Remove extraneous bitcasts around an extract_subvector.
7927   // For example,
7928   //    (v4i16 (bitconvert
7929   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7930   //  becomes
7931   //    (extract_subvector ((v8i16 ...), (i64 4)))
7932 
7933   // Only interested in 64-bit vectors as the ultimate result.
7934   EVT VT = N->getValueType(0);
7935   if (!VT.isVector())
7936     return SDValue();
7937   if (VT.getSimpleVT().getSizeInBits() != 64)
7938     return SDValue();
7939   // Is the operand an extract_subvector starting at the beginning or halfway
7940   // point of the vector? A low half may also come through as an
7941   // EXTRACT_SUBREG, so look for that, too.
7942   SDValue Op0 = N->getOperand(0);
7943   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7944       !(Op0->isMachineOpcode() &&
7945         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7946     return SDValue();
7947   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7948   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7949     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7950       return SDValue();
7951   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7952     if (idx != AArch64::dsub)
7953       return SDValue();
7954     // The dsub reference is equivalent to a lane zero subvector reference.
7955     idx = 0;
7956   }
7957   // Look through the bitcast of the input to the extract.
7958   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7959     return SDValue();
7960   SDValue Source = Op0->getOperand(0)->getOperand(0);
7961   // If the source type has twice the number of elements as our destination
7962   // type, we know this is an extract of the high or low half of the vector.
7963   EVT SVT = Source->getValueType(0);
7964   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7965     return SDValue();
7966 
7967   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7968 
7969   // Create the simplified form to just extract the low or high half of the
7970   // vector directly rather than bothering with the bitcasts.
7971   SDLoc dl(N);
7972   unsigned NumElements = VT.getVectorNumElements();
7973   if (idx) {
7974     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7975     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7976   } else {
7977     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7978     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7979                                       Source, SubReg),
7980                    0);
7981   }
7982 }
7983 
7984 static SDValue performConcatVectorsCombine(SDNode *N,
7985                                            TargetLowering::DAGCombinerInfo &DCI,
7986                                            SelectionDAG &DAG) {
7987   SDLoc dl(N);
7988   EVT VT = N->getValueType(0);
7989   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7990 
7991   // Optimize concat_vectors of truncated vectors, where the intermediate
7992   // type is illegal, to avoid said illegality,  e.g.,
7993   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7994   //                          (v2i16 (truncate (v2i64)))))
7995   // ->
7996   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7997   //                                    (v4i32 (bitcast (v2i64))),
7998   //                                    <0, 2, 4, 6>)))
7999   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8000   // on both input and result type, so we might generate worse code.
8001   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8002   if (N->getNumOperands() == 2 &&
8003       N0->getOpcode() == ISD::TRUNCATE &&
8004       N1->getOpcode() == ISD::TRUNCATE) {
8005     SDValue N00 = N0->getOperand(0);
8006     SDValue N10 = N1->getOperand(0);
8007     EVT N00VT = N00.getValueType();
8008 
8009     if (N00VT == N10.getValueType() &&
8010         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8011         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8012       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8013       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8014       for (size_t i = 0; i < Mask.size(); ++i)
8015         Mask[i] = i * 2;
8016       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8017                          DAG.getVectorShuffle(
8018                              MidVT, dl,
8019                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8020                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8021     }
8022   }
8023 
8024   // Wait 'til after everything is legalized to try this. That way we have
8025   // legal vector types and such.
8026   if (DCI.isBeforeLegalizeOps())
8027     return SDValue();
8028 
8029   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8030   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8031   // canonicalise to that.
8032   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8033     assert(VT.getVectorElementType().getSizeInBits() == 64);
8034     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8035                        DAG.getConstant(0, dl, MVT::i64));
8036   }
8037 
8038   // Canonicalise concat_vectors so that the right-hand vector has as few
8039   // bit-casts as possible before its real operation. The primary matching
8040   // destination for these operations will be the narrowing "2" instructions,
8041   // which depend on the operation being performed on this right-hand vector.
8042   // For example,
8043   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8044   // becomes
8045   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8046 
8047   if (N1->getOpcode() != ISD::BITCAST)
8048     return SDValue();
8049   SDValue RHS = N1->getOperand(0);
8050   MVT RHSTy = RHS.getValueType().getSimpleVT();
8051   // If the RHS is not a vector, this is not the pattern we're looking for.
8052   if (!RHSTy.isVector())
8053     return SDValue();
8054 
8055   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8056 
8057   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8058                                   RHSTy.getVectorNumElements() * 2);
8059   return DAG.getNode(ISD::BITCAST, dl, VT,
8060                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8061                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8062                                  RHS));
8063 }
8064 
8065 static SDValue tryCombineFixedPointConvert(SDNode *N,
8066                                            TargetLowering::DAGCombinerInfo &DCI,
8067                                            SelectionDAG &DAG) {
8068   // Wait 'til after everything is legalized to try this. That way we have
8069   // legal vector types and such.
8070   if (DCI.isBeforeLegalizeOps())
8071     return SDValue();
8072   // Transform a scalar conversion of a value from a lane extract into a
8073   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8074   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8075   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8076   //
8077   // The second form interacts better with instruction selection and the
8078   // register allocator to avoid cross-class register copies that aren't
8079   // coalescable due to a lane reference.
8080 
8081   // Check the operand and see if it originates from a lane extract.
8082   SDValue Op1 = N->getOperand(1);
8083   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8084     // Yep, no additional predication needed. Perform the transform.
8085     SDValue IID = N->getOperand(0);
8086     SDValue Shift = N->getOperand(2);
8087     SDValue Vec = Op1.getOperand(0);
8088     SDValue Lane = Op1.getOperand(1);
8089     EVT ResTy = N->getValueType(0);
8090     EVT VecResTy;
8091     SDLoc DL(N);
8092 
8093     // The vector width should be 128 bits by the time we get here, even
8094     // if it started as 64 bits (the extract_vector handling will have
8095     // done so).
8096     assert(Vec.getValueType().getSizeInBits() == 128 &&
8097            "unexpected vector size on extract_vector_elt!");
8098     if (Vec.getValueType() == MVT::v4i32)
8099       VecResTy = MVT::v4f32;
8100     else if (Vec.getValueType() == MVT::v2i64)
8101       VecResTy = MVT::v2f64;
8102     else
8103       llvm_unreachable("unexpected vector type!");
8104 
8105     SDValue Convert =
8106         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8107     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8108   }
8109   return SDValue();
8110 }
8111 
8112 // AArch64 high-vector "long" operations are formed by performing the non-high
8113 // version on an extract_subvector of each operand which gets the high half:
8114 //
8115 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8116 //
8117 // However, there are cases which don't have an extract_high explicitly, but
8118 // have another operation that can be made compatible with one for free. For
8119 // example:
8120 //
8121 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8122 //
8123 // This routine does the actual conversion of such DUPs, once outer routines
8124 // have determined that everything else is in order.
8125 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8126 // similarly here.
8127 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8128   switch (N.getOpcode()) {
8129   case AArch64ISD::DUP:
8130   case AArch64ISD::DUPLANE8:
8131   case AArch64ISD::DUPLANE16:
8132   case AArch64ISD::DUPLANE32:
8133   case AArch64ISD::DUPLANE64:
8134   case AArch64ISD::MOVI:
8135   case AArch64ISD::MOVIshift:
8136   case AArch64ISD::MOVIedit:
8137   case AArch64ISD::MOVImsl:
8138   case AArch64ISD::MVNIshift:
8139   case AArch64ISD::MVNImsl:
8140     break;
8141   default:
8142     // FMOV could be supported, but isn't very useful, as it would only occur
8143     // if you passed a bitcast' floating point immediate to an eligible long
8144     // integer op (addl, smull, ...).
8145     return SDValue();
8146   }
8147 
8148   MVT NarrowTy = N.getSimpleValueType();
8149   if (!NarrowTy.is64BitVector())
8150     return SDValue();
8151 
8152   MVT ElementTy = NarrowTy.getVectorElementType();
8153   unsigned NumElems = NarrowTy.getVectorNumElements();
8154   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8155 
8156   SDLoc dl(N);
8157   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8158                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8159                      DAG.getConstant(NumElems, dl, MVT::i64));
8160 }
8161 
8162 static bool isEssentiallyExtractSubvector(SDValue N) {
8163   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8164     return true;
8165 
8166   return N.getOpcode() == ISD::BITCAST &&
8167          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8168 }
8169 
8170 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8171 struct GenericSetCCInfo {
8172   const SDValue *Opnd0;
8173   const SDValue *Opnd1;
8174   ISD::CondCode CC;
8175 };
8176 
8177 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8178 struct AArch64SetCCInfo {
8179   const SDValue *Cmp;
8180   AArch64CC::CondCode CC;
8181 };
8182 
8183 /// \brief Helper structure to keep track of SetCC information.
8184 union SetCCInfo {
8185   GenericSetCCInfo Generic;
8186   AArch64SetCCInfo AArch64;
8187 };
8188 
8189 /// \brief Helper structure to be able to read SetCC information.  If set to
8190 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8191 /// GenericSetCCInfo.
8192 struct SetCCInfoAndKind {
8193   SetCCInfo Info;
8194   bool IsAArch64;
8195 };
8196 
8197 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8198 /// an
8199 /// AArch64 lowered one.
8200 /// \p SetCCInfo is filled accordingly.
8201 /// \post SetCCInfo is meanginfull only when this function returns true.
8202 /// \return True when Op is a kind of SET_CC operation.
8203 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8204   // If this is a setcc, this is straight forward.
8205   if (Op.getOpcode() == ISD::SETCC) {
8206     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8207     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8208     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8209     SetCCInfo.IsAArch64 = false;
8210     return true;
8211   }
8212   // Otherwise, check if this is a matching csel instruction.
8213   // In other words:
8214   // - csel 1, 0, cc
8215   // - csel 0, 1, !cc
8216   if (Op.getOpcode() != AArch64ISD::CSEL)
8217     return false;
8218   // Set the information about the operands.
8219   // TODO: we want the operands of the Cmp not the csel
8220   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8221   SetCCInfo.IsAArch64 = true;
8222   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8223       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8224 
8225   // Check that the operands matches the constraints:
8226   // (1) Both operands must be constants.
8227   // (2) One must be 1 and the other must be 0.
8228   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8229   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8230 
8231   // Check (1).
8232   if (!TValue || !FValue)
8233     return false;
8234 
8235   // Check (2).
8236   if (!TValue->isOne()) {
8237     // Update the comparison when we are interested in !cc.
8238     std::swap(TValue, FValue);
8239     SetCCInfo.Info.AArch64.CC =
8240         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8241   }
8242   return TValue->isOne() && FValue->isNullValue();
8243 }
8244 
8245 // Returns true if Op is setcc or zext of setcc.
8246 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8247   if (isSetCC(Op, Info))
8248     return true;
8249   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8250     isSetCC(Op->getOperand(0), Info));
8251 }
8252 
8253 // The folding we want to perform is:
8254 // (add x, [zext] (setcc cc ...) )
8255 //   -->
8256 // (csel x, (add x, 1), !cc ...)
8257 //
8258 // The latter will get matched to a CSINC instruction.
8259 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8260   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8261   SDValue LHS = Op->getOperand(0);
8262   SDValue RHS = Op->getOperand(1);
8263   SetCCInfoAndKind InfoAndKind;
8264 
8265   // If neither operand is a SET_CC, give up.
8266   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8267     std::swap(LHS, RHS);
8268     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8269       return SDValue();
8270   }
8271 
8272   // FIXME: This could be generatized to work for FP comparisons.
8273   EVT CmpVT = InfoAndKind.IsAArch64
8274                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8275                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8276   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8277     return SDValue();
8278 
8279   SDValue CCVal;
8280   SDValue Cmp;
8281   SDLoc dl(Op);
8282   if (InfoAndKind.IsAArch64) {
8283     CCVal = DAG.getConstant(
8284         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8285         MVT::i32);
8286     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8287   } else
8288     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8289                       *InfoAndKind.Info.Generic.Opnd1,
8290                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8291                       CCVal, DAG, dl);
8292 
8293   EVT VT = Op->getValueType(0);
8294   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8295   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8296 }
8297 
8298 // The basic add/sub long vector instructions have variants with "2" on the end
8299 // which act on the high-half of their inputs. They are normally matched by
8300 // patterns like:
8301 //
8302 // (add (zeroext (extract_high LHS)),
8303 //      (zeroext (extract_high RHS)))
8304 // -> uaddl2 vD, vN, vM
8305 //
8306 // However, if one of the extracts is something like a duplicate, this
8307 // instruction can still be used profitably. This function puts the DAG into a
8308 // more appropriate form for those patterns to trigger.
8309 static SDValue performAddSubLongCombine(SDNode *N,
8310                                         TargetLowering::DAGCombinerInfo &DCI,
8311                                         SelectionDAG &DAG) {
8312   if (DCI.isBeforeLegalizeOps())
8313     return SDValue();
8314 
8315   MVT VT = N->getSimpleValueType(0);
8316   if (!VT.is128BitVector()) {
8317     if (N->getOpcode() == ISD::ADD)
8318       return performSetccAddFolding(N, DAG);
8319     return SDValue();
8320   }
8321 
8322   // Make sure both branches are extended in the same way.
8323   SDValue LHS = N->getOperand(0);
8324   SDValue RHS = N->getOperand(1);
8325   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8326        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8327       LHS.getOpcode() != RHS.getOpcode())
8328     return SDValue();
8329 
8330   unsigned ExtType = LHS.getOpcode();
8331 
8332   // It's not worth doing if at least one of the inputs isn't already an
8333   // extract, but we don't know which it'll be so we have to try both.
8334   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8335     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8336     if (!RHS.getNode())
8337       return SDValue();
8338 
8339     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8340   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8341     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8342     if (!LHS.getNode())
8343       return SDValue();
8344 
8345     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8346   }
8347 
8348   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8349 }
8350 
8351 // Massage DAGs which we can use the high-half "long" operations on into
8352 // something isel will recognize better. E.g.
8353 //
8354 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8355 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8356 //                     (extract_high (v2i64 (dup128 scalar)))))
8357 //
8358 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8359                                        TargetLowering::DAGCombinerInfo &DCI,
8360                                        SelectionDAG &DAG) {
8361   if (DCI.isBeforeLegalizeOps())
8362     return SDValue();
8363 
8364   SDValue LHS = N->getOperand(1);
8365   SDValue RHS = N->getOperand(2);
8366   assert(LHS.getValueType().is64BitVector() &&
8367          RHS.getValueType().is64BitVector() &&
8368          "unexpected shape for long operation");
8369 
8370   // Either node could be a DUP, but it's not worth doing both of them (you'd
8371   // just as well use the non-high version) so look for a corresponding extract
8372   // operation on the other "wing".
8373   if (isEssentiallyExtractSubvector(LHS)) {
8374     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8375     if (!RHS.getNode())
8376       return SDValue();
8377   } else if (isEssentiallyExtractSubvector(RHS)) {
8378     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8379     if (!LHS.getNode())
8380       return SDValue();
8381   }
8382 
8383   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8384                      N->getOperand(0), LHS, RHS);
8385 }
8386 
8387 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8388   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8389   unsigned ElemBits = ElemTy.getSizeInBits();
8390 
8391   int64_t ShiftAmount;
8392   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8393     APInt SplatValue, SplatUndef;
8394     unsigned SplatBitSize;
8395     bool HasAnyUndefs;
8396     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8397                               HasAnyUndefs, ElemBits) ||
8398         SplatBitSize != ElemBits)
8399       return SDValue();
8400 
8401     ShiftAmount = SplatValue.getSExtValue();
8402   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8403     ShiftAmount = CVN->getSExtValue();
8404   } else
8405     return SDValue();
8406 
8407   unsigned Opcode;
8408   bool IsRightShift;
8409   switch (IID) {
8410   default:
8411     llvm_unreachable("Unknown shift intrinsic");
8412   case Intrinsic::aarch64_neon_sqshl:
8413     Opcode = AArch64ISD::SQSHL_I;
8414     IsRightShift = false;
8415     break;
8416   case Intrinsic::aarch64_neon_uqshl:
8417     Opcode = AArch64ISD::UQSHL_I;
8418     IsRightShift = false;
8419     break;
8420   case Intrinsic::aarch64_neon_srshl:
8421     Opcode = AArch64ISD::SRSHR_I;
8422     IsRightShift = true;
8423     break;
8424   case Intrinsic::aarch64_neon_urshl:
8425     Opcode = AArch64ISD::URSHR_I;
8426     IsRightShift = true;
8427     break;
8428   case Intrinsic::aarch64_neon_sqshlu:
8429     Opcode = AArch64ISD::SQSHLU_I;
8430     IsRightShift = false;
8431     break;
8432   }
8433 
8434   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8435     SDLoc dl(N);
8436     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8437                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8438   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8439     SDLoc dl(N);
8440     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8441                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
8442   }
8443 
8444   return SDValue();
8445 }
8446 
8447 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8448 // the intrinsics must be legal and take an i32, this means there's almost
8449 // certainly going to be a zext in the DAG which we can eliminate.
8450 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8451   SDValue AndN = N->getOperand(2);
8452   if (AndN.getOpcode() != ISD::AND)
8453     return SDValue();
8454 
8455   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8456   if (!CMask || CMask->getZExtValue() != Mask)
8457     return SDValue();
8458 
8459   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8460                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8461 }
8462 
8463 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8464                                            SelectionDAG &DAG) {
8465   SDLoc dl(N);
8466   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8467                      DAG.getNode(Opc, dl,
8468                                  N->getOperand(1).getSimpleValueType(),
8469                                  N->getOperand(1)),
8470                      DAG.getConstant(0, dl, MVT::i64));
8471 }
8472 
8473 static SDValue performIntrinsicCombine(SDNode *N,
8474                                        TargetLowering::DAGCombinerInfo &DCI,
8475                                        const AArch64Subtarget *Subtarget) {
8476   SelectionDAG &DAG = DCI.DAG;
8477   unsigned IID = getIntrinsicID(N);
8478   switch (IID) {
8479   default:
8480     break;
8481   case Intrinsic::aarch64_neon_vcvtfxs2fp:
8482   case Intrinsic::aarch64_neon_vcvtfxu2fp:
8483     return tryCombineFixedPointConvert(N, DCI, DAG);
8484   case Intrinsic::aarch64_neon_saddv:
8485     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8486   case Intrinsic::aarch64_neon_uaddv:
8487     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8488   case Intrinsic::aarch64_neon_sminv:
8489     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8490   case Intrinsic::aarch64_neon_uminv:
8491     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8492   case Intrinsic::aarch64_neon_smaxv:
8493     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8494   case Intrinsic::aarch64_neon_umaxv:
8495     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8496   case Intrinsic::aarch64_neon_fmax:
8497     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8498                        N->getOperand(1), N->getOperand(2));
8499   case Intrinsic::aarch64_neon_fmin:
8500     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8501                        N->getOperand(1), N->getOperand(2));
8502   case Intrinsic::aarch64_neon_fmaxnm:
8503     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8504                        N->getOperand(1), N->getOperand(2));
8505   case Intrinsic::aarch64_neon_fminnm:
8506     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8507                        N->getOperand(1), N->getOperand(2));
8508   case Intrinsic::aarch64_neon_smull:
8509   case Intrinsic::aarch64_neon_umull:
8510   case Intrinsic::aarch64_neon_pmull:
8511   case Intrinsic::aarch64_neon_sqdmull:
8512     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8513   case Intrinsic::aarch64_neon_sqshl:
8514   case Intrinsic::aarch64_neon_uqshl:
8515   case Intrinsic::aarch64_neon_sqshlu:
8516   case Intrinsic::aarch64_neon_srshl:
8517   case Intrinsic::aarch64_neon_urshl:
8518     return tryCombineShiftImm(IID, N, DAG);
8519   case Intrinsic::aarch64_crc32b:
8520   case Intrinsic::aarch64_crc32cb:
8521     return tryCombineCRC32(0xff, N, DAG);
8522   case Intrinsic::aarch64_crc32h:
8523   case Intrinsic::aarch64_crc32ch:
8524     return tryCombineCRC32(0xffff, N, DAG);
8525   }
8526   return SDValue();
8527 }
8528 
8529 static SDValue performExtendCombine(SDNode *N,
8530                                     TargetLowering::DAGCombinerInfo &DCI,
8531                                     SelectionDAG &DAG) {
8532   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8533   // we can convert that DUP into another extract_high (of a bigger DUP), which
8534   // helps the backend to decide that an sabdl2 would be useful, saving a real
8535   // extract_high operation.
8536   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8537       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8538     SDNode *ABDNode = N->getOperand(0).getNode();
8539     unsigned IID = getIntrinsicID(ABDNode);
8540     if (IID == Intrinsic::aarch64_neon_sabd ||
8541         IID == Intrinsic::aarch64_neon_uabd) {
8542       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8543       if (!NewABD.getNode())
8544         return SDValue();
8545 
8546       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8547                          NewABD);
8548     }
8549   }
8550 
8551   // This is effectively a custom type legalization for AArch64.
8552   //
8553   // Type legalization will split an extend of a small, legal, type to a larger
8554   // illegal type by first splitting the destination type, often creating
8555   // illegal source types, which then get legalized in isel-confusing ways,
8556   // leading to really terrible codegen. E.g.,
8557   //   %result = v8i32 sext v8i8 %value
8558   // becomes
8559   //   %losrc = extract_subreg %value, ...
8560   //   %hisrc = extract_subreg %value, ...
8561   //   %lo = v4i32 sext v4i8 %losrc
8562   //   %hi = v4i32 sext v4i8 %hisrc
8563   // Things go rapidly downhill from there.
8564   //
8565   // For AArch64, the [sz]ext vector instructions can only go up one element
8566   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8567   // take two instructions.
8568   //
8569   // This implies that the most efficient way to do the extend from v8i8
8570   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8571   // the normal splitting to happen for the v8i16->v8i32.
8572 
8573   // This is pre-legalization to catch some cases where the default
8574   // type legalization will create ill-tempered code.
8575   if (!DCI.isBeforeLegalizeOps())
8576     return SDValue();
8577 
8578   // We're only interested in cleaning things up for non-legal vector types
8579   // here. If both the source and destination are legal, things will just
8580   // work naturally without any fiddling.
8581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8582   EVT ResVT = N->getValueType(0);
8583   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8584     return SDValue();
8585   // If the vector type isn't a simple VT, it's beyond the scope of what
8586   // we're  worried about here. Let legalization do its thing and hope for
8587   // the best.
8588   SDValue Src = N->getOperand(0);
8589   EVT SrcVT = Src->getValueType(0);
8590   if (!ResVT.isSimple() || !SrcVT.isSimple())
8591     return SDValue();
8592 
8593   // If the source VT is a 64-bit vector, we can play games and get the
8594   // better results we want.
8595   if (SrcVT.getSizeInBits() != 64)
8596     return SDValue();
8597 
8598   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8599   unsigned ElementCount = SrcVT.getVectorNumElements();
8600   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8601   SDLoc DL(N);
8602   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8603 
8604   // Now split the rest of the operation into two halves, each with a 64
8605   // bit source.
8606   EVT LoVT, HiVT;
8607   SDValue Lo, Hi;
8608   unsigned NumElements = ResVT.getVectorNumElements();
8609   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8610   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8611                                  ResVT.getVectorElementType(), NumElements / 2);
8612 
8613   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8614                                LoVT.getVectorNumElements());
8615   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8616                    DAG.getConstant(0, DL, MVT::i64));
8617   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8618                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8619   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8620   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8621 
8622   // Now combine the parts back together so we still have a single result
8623   // like the combiner expects.
8624   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8625 }
8626 
8627 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8628 /// value. The load store optimizer pass will merge them to store pair stores.
8629 /// This has better performance than a splat of the scalar followed by a split
8630 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8631 /// followed by an ext.b and two stores.
8632 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8633   SDValue StVal = St->getValue();
8634   EVT VT = StVal.getValueType();
8635 
8636   // Don't replace floating point stores, they possibly won't be transformed to
8637   // stp because of the store pair suppress pass.
8638   if (VT.isFloatingPoint())
8639     return SDValue();
8640 
8641   // Check for insert vector elements.
8642   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8643     return SDValue();
8644 
8645   // We can express a splat as store pair(s) for 2 or 4 elements.
8646   unsigned NumVecElts = VT.getVectorNumElements();
8647   if (NumVecElts != 4 && NumVecElts != 2)
8648     return SDValue();
8649   SDValue SplatVal = StVal.getOperand(1);
8650   unsigned RemainInsertElts = NumVecElts - 1;
8651 
8652   // Check that this is a splat.
8653   while (--RemainInsertElts) {
8654     SDValue NextInsertElt = StVal.getOperand(0);
8655     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8656       return SDValue();
8657     if (NextInsertElt.getOperand(1) != SplatVal)
8658       return SDValue();
8659     StVal = NextInsertElt;
8660   }
8661   unsigned OrigAlignment = St->getAlignment();
8662   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8663   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8664 
8665   // Create scalar stores. This is at least as good as the code sequence for a
8666   // split unaligned store which is a dup.s, ext.b, and two stores.
8667   // Most of the time the three stores should be replaced by store pair
8668   // instructions (stp).
8669   SDLoc DL(St);
8670   SDValue BasePtr = St->getBasePtr();
8671   SDValue NewST1 =
8672       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8673                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8674 
8675   unsigned Offset = EltOffset;
8676   while (--NumVecElts) {
8677     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8678                                     DAG.getConstant(Offset, DL, MVT::i64));
8679     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8680                           St->getPointerInfo(), St->isVolatile(),
8681                           St->isNonTemporal(), Alignment);
8682     Offset += EltOffset;
8683   }
8684   return NewST1;
8685 }
8686 
8687 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8688                               SelectionDAG &DAG,
8689                               const AArch64Subtarget *Subtarget) {
8690   if (!DCI.isBeforeLegalize())
8691     return SDValue();
8692 
8693   StoreSDNode *S = cast<StoreSDNode>(N);
8694   if (S->isVolatile())
8695     return SDValue();
8696 
8697   // FIXME: The logic for deciding if an unaligned store should be split should
8698   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8699   // a call to that function here.
8700 
8701   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8702   // page boundaries. We want to split such stores.
8703   if (!Subtarget->isCyclone())
8704     return SDValue();
8705 
8706   // Don't split at -Oz.
8707   if (DAG.getMachineFunction().getFunction()->optForMinSize())
8708     return SDValue();
8709 
8710   SDValue StVal = S->getValue();
8711   EVT VT = StVal.getValueType();
8712 
8713   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8714   // those up regresses performance on micro-benchmarks and olden/bh.
8715   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8716     return SDValue();
8717 
8718   // Split unaligned 16B stores. They are terrible for performance.
8719   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8720   // extensions can use this to mark that it does not want splitting to happen
8721   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8722   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8723   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8724       S->getAlignment() <= 2)
8725     return SDValue();
8726 
8727   // If we get a splat of a scalar convert this vector store to a store of
8728   // scalars. They will be merged into store pairs thereby removing two
8729   // instructions.
8730   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8731     return ReplacedSplat;
8732 
8733   SDLoc DL(S);
8734   unsigned NumElts = VT.getVectorNumElements() / 2;
8735   // Split VT into two.
8736   EVT HalfVT =
8737       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8738   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8739                                    DAG.getConstant(0, DL, MVT::i64));
8740   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8741                                    DAG.getConstant(NumElts, DL, MVT::i64));
8742   SDValue BasePtr = S->getBasePtr();
8743   SDValue NewST1 =
8744       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8745                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8746   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8747                                   DAG.getConstant(8, DL, MVT::i64));
8748   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8749                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8750                       S->getAlignment());
8751 }
8752 
8753 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8754 /// post-increment LD1R.
8755 static SDValue performPostLD1Combine(SDNode *N,
8756                                      TargetLowering::DAGCombinerInfo &DCI,
8757                                      bool IsLaneOp) {
8758   if (DCI.isBeforeLegalizeOps())
8759     return SDValue();
8760 
8761   SelectionDAG &DAG = DCI.DAG;
8762   EVT VT = N->getValueType(0);
8763 
8764   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8765   SDNode *LD = N->getOperand(LoadIdx).getNode();
8766   // If it is not LOAD, can not do such combine.
8767   if (LD->getOpcode() != ISD::LOAD)
8768     return SDValue();
8769 
8770   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8771   EVT MemVT = LoadSDN->getMemoryVT();
8772   // Check if memory operand is the same type as the vector element.
8773   if (MemVT != VT.getVectorElementType())
8774     return SDValue();
8775 
8776   // Check if there are other uses. If so, do not combine as it will introduce
8777   // an extra load.
8778   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8779        ++UI) {
8780     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8781       continue;
8782     if (*UI != N)
8783       return SDValue();
8784   }
8785 
8786   SDValue Addr = LD->getOperand(1);
8787   SDValue Vector = N->getOperand(0);
8788   // Search for a use of the address operand that is an increment.
8789   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8790        Addr.getNode()->use_end(); UI != UE; ++UI) {
8791     SDNode *User = *UI;
8792     if (User->getOpcode() != ISD::ADD
8793         || UI.getUse().getResNo() != Addr.getResNo())
8794       continue;
8795 
8796     // Check that the add is independent of the load.  Otherwise, folding it
8797     // would create a cycle.
8798     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8799       continue;
8800     // Also check that add is not used in the vector operand.  This would also
8801     // create a cycle.
8802     if (User->isPredecessorOf(Vector.getNode()))
8803       continue;
8804 
8805     // If the increment is a constant, it must match the memory ref size.
8806     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8807     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8808       uint32_t IncVal = CInc->getZExtValue();
8809       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8810       if (IncVal != NumBytes)
8811         continue;
8812       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8813     }
8814 
8815     // Finally, check that the vector doesn't depend on the load.
8816     // Again, this would create a cycle.
8817     // The load depending on the vector is fine, as that's the case for the
8818     // LD1*post we'll eventually generate anyway.
8819     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8820       continue;
8821 
8822     SmallVector<SDValue, 8> Ops;
8823     Ops.push_back(LD->getOperand(0));  // Chain
8824     if (IsLaneOp) {
8825       Ops.push_back(Vector);           // The vector to be inserted
8826       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8827     }
8828     Ops.push_back(Addr);
8829     Ops.push_back(Inc);
8830 
8831     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8832     SDVTList SDTys = DAG.getVTList(Tys);
8833     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8834     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8835                                            MemVT,
8836                                            LoadSDN->getMemOperand());
8837 
8838     // Update the uses.
8839     SmallVector<SDValue, 2> NewResults;
8840     NewResults.push_back(SDValue(LD, 0));             // The result of load
8841     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8842     DCI.CombineTo(LD, NewResults);
8843     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8844     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8845 
8846     break;
8847   }
8848   return SDValue();
8849 }
8850 
8851 /// Simplify \Addr given that the top byte of it is ignored by HW during
8852 /// address translation.
8853 static bool performTBISimplification(SDValue Addr,
8854                                      TargetLowering::DAGCombinerInfo &DCI,
8855                                      SelectionDAG &DAG) {
8856   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8857   APInt KnownZero, KnownOne;
8858   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8859                                         DCI.isBeforeLegalizeOps());
8860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8861   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8862     DCI.CommitTargetLoweringOpt(TLO);
8863     return true;
8864   }
8865   return false;
8866 }
8867 
8868 static SDValue performSTORECombine(SDNode *N,
8869                                    TargetLowering::DAGCombinerInfo &DCI,
8870                                    SelectionDAG &DAG,
8871                                    const AArch64Subtarget *Subtarget) {
8872   if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
8873     return Split;
8874 
8875   if (Subtarget->supportsAddressTopByteIgnored() &&
8876       performTBISimplification(N->getOperand(2), DCI, DAG))
8877     return SDValue(N, 0);
8878 
8879   return SDValue();
8880 }
8881 
8882   /// This function handles the log2-shuffle pattern produced by the
8883 /// LoopVectorizer for the across vector reduction. It consists of
8884 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8885 /// are reduced, where s is an induction variable from 0 to
8886 /// log2(NumVectorElements).
8887 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8888                                                      unsigned Op,
8889                                                      SelectionDAG &DAG) {
8890   EVT VTy = OpV->getOperand(0).getValueType();
8891   if (!VTy.isVector())
8892     return SDValue();
8893 
8894   int NumVecElts = VTy.getVectorNumElements();
8895   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8896     if (NumVecElts != 4)
8897       return SDValue();
8898   } else {
8899     if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8900       return SDValue();
8901   }
8902 
8903   int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8904   SDValue PreOp = OpV;
8905   // Iterate over each step of the across vector reduction.
8906   for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8907     SDValue CurOp = PreOp.getOperand(0);
8908     SDValue Shuffle = PreOp.getOperand(1);
8909     if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8910       // Try to swap the 1st and 2nd operand as add and min/max instructions
8911       // are commutative.
8912       CurOp = PreOp.getOperand(1);
8913       Shuffle = PreOp.getOperand(0);
8914       if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8915         return SDValue();
8916     }
8917 
8918     // Check if the input vector is fed by the operator we want to handle,
8919     // except the last step; the very first input vector is not necessarily
8920     // the same operator we are handling.
8921     if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8922       return SDValue();
8923 
8924     // Check if it forms one step of the across vector reduction.
8925     // E.g.,
8926     //   %cur = add %1, %0
8927     //   %shuffle = vector_shuffle %cur, <2, 3, u, u>
8928     //   %pre = add %cur, %shuffle
8929     if (Shuffle.getOperand(0) != CurOp)
8930       return SDValue();
8931 
8932     int NumMaskElts = 1 << CurStep;
8933     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8934     // Check mask values in each step.
8935     // We expect the shuffle mask in each step follows a specific pattern
8936     // denoted here by the <M, U> form, where M is a sequence of integers
8937     // starting from NumMaskElts, increasing by 1, and the number integers
8938     // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8939     // of undef in U should be NumVecElts - NumMaskElts.
8940     // E.g., for <8 x i16>, mask values in each step should be :
8941     //   step 0 : <1,u,u,u,u,u,u,u>
8942     //   step 1 : <2,3,u,u,u,u,u,u>
8943     //   step 2 : <4,5,6,7,u,u,u,u>
8944     for (int i = 0; i < NumVecElts; ++i)
8945       if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8946           (i >= NumMaskElts && !(Mask[i] < 0)))
8947         return SDValue();
8948 
8949     PreOp = CurOp;
8950   }
8951   unsigned Opcode;
8952   bool IsIntrinsic = false;
8953 
8954   switch (Op) {
8955   default:
8956     llvm_unreachable("Unexpected operator for across vector reduction");
8957   case ISD::ADD:
8958     Opcode = AArch64ISD::UADDV;
8959     break;
8960   case ISD::SMAX:
8961     Opcode = AArch64ISD::SMAXV;
8962     break;
8963   case ISD::UMAX:
8964     Opcode = AArch64ISD::UMAXV;
8965     break;
8966   case ISD::SMIN:
8967     Opcode = AArch64ISD::SMINV;
8968     break;
8969   case ISD::UMIN:
8970     Opcode = AArch64ISD::UMINV;
8971     break;
8972   case ISD::FMAXNUM:
8973     Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8974     IsIntrinsic = true;
8975     break;
8976   case ISD::FMINNUM:
8977     Opcode = Intrinsic::aarch64_neon_fminnmv;
8978     IsIntrinsic = true;
8979     break;
8980   }
8981   SDLoc DL(N);
8982 
8983   return IsIntrinsic
8984              ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8985                            DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8986              : DAG.getNode(
8987                    ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8988                    DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8989                    DAG.getConstant(0, DL, MVT::i64));
8990 }
8991 
8992 /// Target-specific DAG combine for the across vector min/max reductions.
8993 /// This function specifically handles the final clean-up step of the vector
8994 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8995 /// pattern, which narrows down and finds the final min/max value from all
8996 /// elements of the vector.
8997 /// For example, for a <16 x i8> vector :
8998 ///   svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8999 ///   %smax0 = smax %arr, svn0
9000 ///   %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9001 ///   %smax1 = smax %smax0, %svn1
9002 ///   %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9003 ///   %smax2 = smax %smax1, svn2
9004 ///   %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9005 ///   %sc = setcc %smax2, %svn3, gt
9006 ///   %n0 = extract_vector_elt %sc, #0
9007 ///   %n1 = extract_vector_elt %smax2, #0
9008 ///   %n2 = extract_vector_elt $smax2, #1
9009 ///   %result = select %n0, %n1, n2
9010 ///     becomes :
9011 ///   %1 = smaxv %0
9012 ///   %result = extract_vector_elt %1, 0
9013 static SDValue
9014 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9015                                         const AArch64Subtarget *Subtarget) {
9016   if (!Subtarget->hasNEON())
9017     return SDValue();
9018 
9019   SDValue N0 = N->getOperand(0);
9020   SDValue IfTrue = N->getOperand(1);
9021   SDValue IfFalse = N->getOperand(2);
9022 
9023   // Check if the SELECT merges up the final result of the min/max
9024   // from a vector.
9025   if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9026       IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9027       IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9028     return SDValue();
9029 
9030   // Expect N0 is fed by SETCC.
9031   SDValue SetCC = N0.getOperand(0);
9032   EVT SetCCVT = SetCC.getValueType();
9033   if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9034       SetCCVT.getVectorElementType() != MVT::i1)
9035     return SDValue();
9036 
9037   SDValue VectorOp = SetCC.getOperand(0);
9038   unsigned Op = VectorOp->getOpcode();
9039   // Check if the input vector is fed by the operator we want to handle.
9040   if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9041       Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9042     return SDValue();
9043 
9044   EVT VTy = VectorOp.getValueType();
9045   if (!VTy.isVector())
9046     return SDValue();
9047 
9048   if (VTy.getSizeInBits() < 64)
9049     return SDValue();
9050 
9051   EVT EltTy = VTy.getVectorElementType();
9052   if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9053     if (EltTy != MVT::f32)
9054       return SDValue();
9055   } else {
9056     if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9057       return SDValue();
9058   }
9059 
9060   // Check if extracting from the same vector.
9061   // For example,
9062   //   %sc = setcc %vector, %svn1, gt
9063   //   %n0 = extract_vector_elt %sc, #0
9064   //   %n1 = extract_vector_elt %vector, #0
9065   //   %n2 = extract_vector_elt $vector, #1
9066   if (!(VectorOp == IfTrue->getOperand(0) &&
9067         VectorOp == IfFalse->getOperand(0)))
9068     return SDValue();
9069 
9070   // Check if the condition code is matched with the operator type.
9071   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9072   if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9073       (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9074       (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9075       (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9076       (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9077        CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9078        CC != ISD::SETGE) ||
9079       (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9080        CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9081        CC != ISD::SETLE))
9082     return SDValue();
9083 
9084   // Expect to check only lane 0 from the vector SETCC.
9085   if (!isNullConstant(N0.getOperand(1)))
9086     return SDValue();
9087 
9088   // Expect to extract the true value from lane 0.
9089   if (!isNullConstant(IfTrue.getOperand(1)))
9090     return SDValue();
9091 
9092   // Expect to extract the false value from lane 1.
9093   if (!isOneConstant(IfFalse.getOperand(1)))
9094     return SDValue();
9095 
9096   return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9097 }
9098 
9099 /// Target-specific DAG combine for the across vector add reduction.
9100 /// This function specifically handles the final clean-up step of the vector
9101 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9102 /// pattern, which adds all elements of a vector together.
9103 /// For example, for a <4 x i32> vector :
9104 ///   %1 = vector_shuffle %0, <2,3,u,u>
9105 ///   %2 = add %0, %1
9106 ///   %3 = vector_shuffle %2, <1,u,u,u>
9107 ///   %4 = add %2, %3
9108 ///   %result = extract_vector_elt %4, 0
9109 /// becomes :
9110 ///   %0 = uaddv %0
9111 ///   %result = extract_vector_elt %0, 0
9112 static SDValue
9113 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9114                                      const AArch64Subtarget *Subtarget) {
9115   if (!Subtarget->hasNEON())
9116     return SDValue();
9117   SDValue N0 = N->getOperand(0);
9118   SDValue N1 = N->getOperand(1);
9119 
9120   // Check if the input vector is fed by the ADD.
9121   if (N0->getOpcode() != ISD::ADD)
9122     return SDValue();
9123 
9124   // The vector extract idx must constant zero because we only expect the final
9125   // result of the reduction is placed in lane 0.
9126   if (!isNullConstant(N1))
9127     return SDValue();
9128 
9129   EVT VTy = N0.getValueType();
9130   if (!VTy.isVector())
9131     return SDValue();
9132 
9133   EVT EltTy = VTy.getVectorElementType();
9134   if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9135     return SDValue();
9136 
9137   if (VTy.getSizeInBits() < 64)
9138     return SDValue();
9139 
9140   return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9141 }
9142 
9143 /// Target-specific DAG combine function for NEON load/store intrinsics
9144 /// to merge base address updates.
9145 static SDValue performNEONPostLDSTCombine(SDNode *N,
9146                                           TargetLowering::DAGCombinerInfo &DCI,
9147                                           SelectionDAG &DAG) {
9148   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9149     return SDValue();
9150 
9151   unsigned AddrOpIdx = N->getNumOperands() - 1;
9152   SDValue Addr = N->getOperand(AddrOpIdx);
9153 
9154   // Search for a use of the address operand that is an increment.
9155   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9156        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9157     SDNode *User = *UI;
9158     if (User->getOpcode() != ISD::ADD ||
9159         UI.getUse().getResNo() != Addr.getResNo())
9160       continue;
9161 
9162     // Check that the add is independent of the load/store.  Otherwise, folding
9163     // it would create a cycle.
9164     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9165       continue;
9166 
9167     // Find the new opcode for the updating load/store.
9168     bool IsStore = false;
9169     bool IsLaneOp = false;
9170     bool IsDupOp = false;
9171     unsigned NewOpc = 0;
9172     unsigned NumVecs = 0;
9173     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9174     switch (IntNo) {
9175     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9176     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9177       NumVecs = 2; break;
9178     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9179       NumVecs = 3; break;
9180     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9181       NumVecs = 4; break;
9182     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9183       NumVecs = 2; IsStore = true; break;
9184     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9185       NumVecs = 3; IsStore = true; break;
9186     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9187       NumVecs = 4; IsStore = true; break;
9188     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9189       NumVecs = 2; break;
9190     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9191       NumVecs = 3; break;
9192     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9193       NumVecs = 4; break;
9194     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9195       NumVecs = 2; IsStore = true; break;
9196     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9197       NumVecs = 3; IsStore = true; break;
9198     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9199       NumVecs = 4; IsStore = true; break;
9200     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9201       NumVecs = 2; IsDupOp = true; break;
9202     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9203       NumVecs = 3; IsDupOp = true; break;
9204     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9205       NumVecs = 4; IsDupOp = true; break;
9206     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9207       NumVecs = 2; IsLaneOp = true; break;
9208     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9209       NumVecs = 3; IsLaneOp = true; break;
9210     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9211       NumVecs = 4; IsLaneOp = true; break;
9212     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9213       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9214     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9215       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9216     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9217       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9218     }
9219 
9220     EVT VecTy;
9221     if (IsStore)
9222       VecTy = N->getOperand(2).getValueType();
9223     else
9224       VecTy = N->getValueType(0);
9225 
9226     // If the increment is a constant, it must match the memory ref size.
9227     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9228     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9229       uint32_t IncVal = CInc->getZExtValue();
9230       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9231       if (IsLaneOp || IsDupOp)
9232         NumBytes /= VecTy.getVectorNumElements();
9233       if (IncVal != NumBytes)
9234         continue;
9235       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9236     }
9237     SmallVector<SDValue, 8> Ops;
9238     Ops.push_back(N->getOperand(0)); // Incoming chain
9239     // Load lane and store have vector list as input.
9240     if (IsLaneOp || IsStore)
9241       for (unsigned i = 2; i < AddrOpIdx; ++i)
9242         Ops.push_back(N->getOperand(i));
9243     Ops.push_back(Addr); // Base register
9244     Ops.push_back(Inc);
9245 
9246     // Return Types.
9247     EVT Tys[6];
9248     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9249     unsigned n;
9250     for (n = 0; n < NumResultVecs; ++n)
9251       Tys[n] = VecTy;
9252     Tys[n++] = MVT::i64;  // Type of write back register
9253     Tys[n] = MVT::Other;  // Type of the chain
9254     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9255 
9256     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9257     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9258                                            MemInt->getMemoryVT(),
9259                                            MemInt->getMemOperand());
9260 
9261     // Update the uses.
9262     std::vector<SDValue> NewResults;
9263     for (unsigned i = 0; i < NumResultVecs; ++i) {
9264       NewResults.push_back(SDValue(UpdN.getNode(), i));
9265     }
9266     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9267     DCI.CombineTo(N, NewResults);
9268     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9269 
9270     break;
9271   }
9272   return SDValue();
9273 }
9274 
9275 // Checks to see if the value is the prescribed width and returns information
9276 // about its extension mode.
9277 static
9278 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9279   ExtType = ISD::NON_EXTLOAD;
9280   switch(V.getNode()->getOpcode()) {
9281   default:
9282     return false;
9283   case ISD::LOAD: {
9284     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9285     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9286        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9287       ExtType = LoadNode->getExtensionType();
9288       return true;
9289     }
9290     return false;
9291   }
9292   case ISD::AssertSext: {
9293     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9294     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9295        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9296       ExtType = ISD::SEXTLOAD;
9297       return true;
9298     }
9299     return false;
9300   }
9301   case ISD::AssertZext: {
9302     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9303     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9304        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9305       ExtType = ISD::ZEXTLOAD;
9306       return true;
9307     }
9308     return false;
9309   }
9310   case ISD::Constant:
9311   case ISD::TargetConstant: {
9312     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9313         1LL << (width - 1))
9314       return true;
9315     return false;
9316   }
9317   }
9318 
9319   return true;
9320 }
9321 
9322 // This function does a whole lot of voodoo to determine if the tests are
9323 // equivalent without and with a mask. Essentially what happens is that given a
9324 // DAG resembling:
9325 //
9326 //  +-------------+ +-------------+ +-------------+ +-------------+
9327 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9328 //  +-------------+ +-------------+ +-------------+ +-------------+
9329 //           |           |           |               |
9330 //           V           V           |    +----------+
9331 //          +-------------+  +----+  |    |
9332 //          |     ADD     |  |0xff|  |    |
9333 //          +-------------+  +----+  |    |
9334 //                  |           |    |    |
9335 //                  V           V    |    |
9336 //                 +-------------+   |    |
9337 //                 |     AND     |   |    |
9338 //                 +-------------+   |    |
9339 //                      |            |    |
9340 //                      +-----+      |    |
9341 //                            |      |    |
9342 //                            V      V    V
9343 //                           +-------------+
9344 //                           |     CMP     |
9345 //                           +-------------+
9346 //
9347 // The AND node may be safely removed for some combinations of inputs. In
9348 // particular we need to take into account the extension type of the Input,
9349 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9350 // width of the input (this can work for any width inputs, the above graph is
9351 // specific to 8 bits.
9352 //
9353 // The specific equations were worked out by generating output tables for each
9354 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9355 // problem was simplified by working with 4 bit inputs, which means we only
9356 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9357 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9358 // patterns present in both extensions (0,7). For every distinct set of
9359 // AddConstant and CompConstants bit patterns we can consider the masked and
9360 // unmasked versions to be equivalent if the result of this function is true for
9361 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9362 //
9363 //   sub      w8, w0, w1
9364 //   and      w10, w8, #0x0f
9365 //   cmp      w8, w2
9366 //   cset     w9, AArch64CC
9367 //   cmp      w10, w2
9368 //   cset     w11, AArch64CC
9369 //   cmp      w9, w11
9370 //   cset     w0, eq
9371 //   ret
9372 //
9373 // Since the above function shows when the outputs are equivalent it defines
9374 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9375 // would be expensive to run during compiles. The equations below were written
9376 // in a test harness that confirmed they gave equivalent outputs to the above
9377 // for all inputs function, so they can be used determine if the removal is
9378 // legal instead.
9379 //
9380 // isEquivalentMaskless() is the code for testing if the AND can be removed
9381 // factored out of the DAG recognition as the DAG can take several forms.
9382 
9383 static
9384 bool isEquivalentMaskless(unsigned CC, unsigned width,
9385                           ISD::LoadExtType ExtType, signed AddConstant,
9386                           signed CompConstant) {
9387   // By being careful about our equations and only writing the in term
9388   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9389   // make them generally applicable to all bit widths.
9390   signed MaxUInt = (1 << width);
9391 
9392   // For the purposes of these comparisons sign extending the type is
9393   // equivalent to zero extending the add and displacing it by half the integer
9394   // width. Provided we are careful and make sure our equations are valid over
9395   // the whole range we can just adjust the input and avoid writing equations
9396   // for sign extended inputs.
9397   if (ExtType == ISD::SEXTLOAD)
9398     AddConstant -= (1 << (width-1));
9399 
9400   switch(CC) {
9401   case AArch64CC::LE:
9402   case AArch64CC::GT: {
9403     if ((AddConstant == 0) ||
9404         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9405         (AddConstant >= 0 && CompConstant < 0) ||
9406         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9407       return true;
9408   } break;
9409   case AArch64CC::LT:
9410   case AArch64CC::GE: {
9411     if ((AddConstant == 0) ||
9412         (AddConstant >= 0 && CompConstant <= 0) ||
9413         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9414       return true;
9415   } break;
9416   case AArch64CC::HI:
9417   case AArch64CC::LS: {
9418     if ((AddConstant >= 0 && CompConstant < 0) ||
9419        (AddConstant <= 0 && CompConstant >= -1 &&
9420         CompConstant < AddConstant + MaxUInt))
9421       return true;
9422   } break;
9423   case AArch64CC::PL:
9424   case AArch64CC::MI: {
9425     if ((AddConstant == 0) ||
9426         (AddConstant > 0 && CompConstant <= 0) ||
9427         (AddConstant < 0 && CompConstant <= AddConstant))
9428       return true;
9429   } break;
9430   case AArch64CC::LO:
9431   case AArch64CC::HS: {
9432     if ((AddConstant >= 0 && CompConstant <= 0) ||
9433         (AddConstant <= 0 && CompConstant >= 0 &&
9434          CompConstant <= AddConstant + MaxUInt))
9435       return true;
9436   } break;
9437   case AArch64CC::EQ:
9438   case AArch64CC::NE: {
9439     if ((AddConstant > 0 && CompConstant < 0) ||
9440         (AddConstant < 0 && CompConstant >= 0 &&
9441          CompConstant < AddConstant + MaxUInt) ||
9442         (AddConstant >= 0 && CompConstant >= 0 &&
9443          CompConstant >= AddConstant) ||
9444         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9445 
9446       return true;
9447   } break;
9448   case AArch64CC::VS:
9449   case AArch64CC::VC:
9450   case AArch64CC::AL:
9451   case AArch64CC::NV:
9452     return true;
9453   case AArch64CC::Invalid:
9454     break;
9455   }
9456 
9457   return false;
9458 }
9459 
9460 static
9461 SDValue performCONDCombine(SDNode *N,
9462                            TargetLowering::DAGCombinerInfo &DCI,
9463                            SelectionDAG &DAG, unsigned CCIndex,
9464                            unsigned CmpIndex) {
9465   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9466   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9467   unsigned CondOpcode = SubsNode->getOpcode();
9468 
9469   if (CondOpcode != AArch64ISD::SUBS)
9470     return SDValue();
9471 
9472   // There is a SUBS feeding this condition. Is it fed by a mask we can
9473   // use?
9474 
9475   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9476   unsigned MaskBits = 0;
9477 
9478   if (AndNode->getOpcode() != ISD::AND)
9479     return SDValue();
9480 
9481   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9482     uint32_t CNV = CN->getZExtValue();
9483     if (CNV == 255)
9484       MaskBits = 8;
9485     else if (CNV == 65535)
9486       MaskBits = 16;
9487   }
9488 
9489   if (!MaskBits)
9490     return SDValue();
9491 
9492   SDValue AddValue = AndNode->getOperand(0);
9493 
9494   if (AddValue.getOpcode() != ISD::ADD)
9495     return SDValue();
9496 
9497   // The basic dag structure is correct, grab the inputs and validate them.
9498 
9499   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9500   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9501   SDValue SubsInputValue = SubsNode->getOperand(1);
9502 
9503   // The mask is present and the provenance of all the values is a smaller type,
9504   // lets see if the mask is superfluous.
9505 
9506   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9507       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9508     return SDValue();
9509 
9510   ISD::LoadExtType ExtType;
9511 
9512   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9513       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9514       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9515     return SDValue();
9516 
9517   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9518                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9519                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9520     return SDValue();
9521 
9522   // The AND is not necessary, remove it.
9523 
9524   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9525                                SubsNode->getValueType(1));
9526   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9527 
9528   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9529   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9530 
9531   return SDValue(N, 0);
9532 }
9533 
9534 // Optimize compare with zero and branch.
9535 static SDValue performBRCONDCombine(SDNode *N,
9536                                     TargetLowering::DAGCombinerInfo &DCI,
9537                                     SelectionDAG &DAG) {
9538   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9539     N = NV.getNode();
9540   SDValue Chain = N->getOperand(0);
9541   SDValue Dest = N->getOperand(1);
9542   SDValue CCVal = N->getOperand(2);
9543   SDValue Cmp = N->getOperand(3);
9544 
9545   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9546   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9547   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9548     return SDValue();
9549 
9550   unsigned CmpOpc = Cmp.getOpcode();
9551   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9552     return SDValue();
9553 
9554   // Only attempt folding if there is only one use of the flag and no use of the
9555   // value.
9556   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9557     return SDValue();
9558 
9559   SDValue LHS = Cmp.getOperand(0);
9560   SDValue RHS = Cmp.getOperand(1);
9561 
9562   assert(LHS.getValueType() == RHS.getValueType() &&
9563          "Expected the value type to be the same for both operands!");
9564   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9565     return SDValue();
9566 
9567   if (isNullConstant(LHS))
9568     std::swap(LHS, RHS);
9569 
9570   if (!isNullConstant(RHS))
9571     return SDValue();
9572 
9573   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9574       LHS.getOpcode() == ISD::SRL)
9575     return SDValue();
9576 
9577   // Fold the compare into the branch instruction.
9578   SDValue BR;
9579   if (CC == AArch64CC::EQ)
9580     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9581   else
9582     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9583 
9584   // Do not add new nodes to DAG combiner worklist.
9585   DCI.CombineTo(N, BR, false);
9586 
9587   return SDValue();
9588 }
9589 
9590 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
9591 // as well as whether the test should be inverted.  This code is required to
9592 // catch these cases (as opposed to standard dag combines) because
9593 // AArch64ISD::TBZ is matched during legalization.
9594 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9595                                  SelectionDAG &DAG) {
9596 
9597   if (!Op->hasOneUse())
9598     return Op;
9599 
9600   // We don't handle undef/constant-fold cases below, as they should have
9601   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9602   // etc.)
9603 
9604   // (tbz (trunc x), b) -> (tbz x, b)
9605   // This case is just here to enable more of the below cases to be caught.
9606   if (Op->getOpcode() == ISD::TRUNCATE &&
9607       Bit < Op->getValueType(0).getSizeInBits()) {
9608     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9609   }
9610 
9611   if (Op->getNumOperands() != 2)
9612     return Op;
9613 
9614   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9615   if (!C)
9616     return Op;
9617 
9618   switch (Op->getOpcode()) {
9619   default:
9620     return Op;
9621 
9622   // (tbz (and x, m), b) -> (tbz x, b)
9623   case ISD::AND:
9624     if ((C->getZExtValue() >> Bit) & 1)
9625       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9626     return Op;
9627 
9628   // (tbz (shl x, c), b) -> (tbz x, b-c)
9629   case ISD::SHL:
9630     if (C->getZExtValue() <= Bit &&
9631         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9632       Bit = Bit - C->getZExtValue();
9633       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9634     }
9635     return Op;
9636 
9637   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9638   case ISD::SRA:
9639     Bit = Bit + C->getZExtValue();
9640     if (Bit >= Op->getValueType(0).getSizeInBits())
9641       Bit = Op->getValueType(0).getSizeInBits() - 1;
9642     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9643 
9644   // (tbz (srl x, c), b) -> (tbz x, b+c)
9645   case ISD::SRL:
9646     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9647       Bit = Bit + C->getZExtValue();
9648       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9649     }
9650     return Op;
9651 
9652   // (tbz (xor x, -1), b) -> (tbnz x, b)
9653   case ISD::XOR:
9654     if ((C->getZExtValue() >> Bit) & 1)
9655       Invert = !Invert;
9656     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9657   }
9658 }
9659 
9660 // Optimize test single bit zero/non-zero and branch.
9661 static SDValue performTBZCombine(SDNode *N,
9662                                  TargetLowering::DAGCombinerInfo &DCI,
9663                                  SelectionDAG &DAG) {
9664   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9665   bool Invert = false;
9666   SDValue TestSrc = N->getOperand(1);
9667   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9668 
9669   if (TestSrc == NewTestSrc)
9670     return SDValue();
9671 
9672   unsigned NewOpc = N->getOpcode();
9673   if (Invert) {
9674     if (NewOpc == AArch64ISD::TBZ)
9675       NewOpc = AArch64ISD::TBNZ;
9676     else {
9677       assert(NewOpc == AArch64ISD::TBNZ);
9678       NewOpc = AArch64ISD::TBZ;
9679     }
9680   }
9681 
9682   SDLoc DL(N);
9683   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9684                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9685 }
9686 
9687 // vselect (v1i1 setcc) ->
9688 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
9689 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9690 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9691 // such VSELECT.
9692 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9693   SDValue N0 = N->getOperand(0);
9694   EVT CCVT = N0.getValueType();
9695 
9696   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9697       CCVT.getVectorElementType() != MVT::i1)
9698     return SDValue();
9699 
9700   EVT ResVT = N->getValueType(0);
9701   EVT CmpVT = N0.getOperand(0).getValueType();
9702   // Only combine when the result type is of the same size as the compared
9703   // operands.
9704   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9705     return SDValue();
9706 
9707   SDValue IfTrue = N->getOperand(1);
9708   SDValue IfFalse = N->getOperand(2);
9709   SDValue SetCC =
9710       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9711                    N0.getOperand(0), N0.getOperand(1),
9712                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
9713   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9714                      IfTrue, IfFalse);
9715 }
9716 
9717 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9718 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9719 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9720 /// with a vector one followed by a DUP shuffle on the result.
9721 static SDValue performSelectCombine(SDNode *N,
9722                                     TargetLowering::DAGCombinerInfo &DCI) {
9723   SelectionDAG &DAG = DCI.DAG;
9724   SDValue N0 = N->getOperand(0);
9725   EVT ResVT = N->getValueType(0);
9726 
9727   if (N0.getOpcode() != ISD::SETCC)
9728     return SDValue();
9729 
9730   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9731   // scalar SetCCResultType. We also don't expect vectors, because we assume
9732   // that selects fed by vector SETCCs are canonicalized to VSELECT.
9733   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9734          "Scalar-SETCC feeding SELECT has unexpected result type!");
9735 
9736   // If NumMaskElts == 0, the comparison is larger than select result. The
9737   // largest real NEON comparison is 64-bits per lane, which means the result is
9738   // at most 32-bits and an illegal vector. Just bail out for now.
9739   EVT SrcVT = N0.getOperand(0).getValueType();
9740 
9741   // Don't try to do this optimization when the setcc itself has i1 operands.
9742   // There are no legal vectors of i1, so this would be pointless.
9743   if (SrcVT == MVT::i1)
9744     return SDValue();
9745 
9746   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9747   if (!ResVT.isVector() || NumMaskElts == 0)
9748     return SDValue();
9749 
9750   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9751   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9752 
9753   // Also bail out if the vector CCVT isn't the same size as ResVT.
9754   // This can happen if the SETCC operand size doesn't divide the ResVT size
9755   // (e.g., f64 vs v3f32).
9756   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9757     return SDValue();
9758 
9759   // Make sure we didn't create illegal types, if we're not supposed to.
9760   assert(DCI.isBeforeLegalize() ||
9761          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9762 
9763   // First perform a vector comparison, where lane 0 is the one we're interested
9764   // in.
9765   SDLoc DL(N0);
9766   SDValue LHS =
9767       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9768   SDValue RHS =
9769       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9770   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9771 
9772   // Now duplicate the comparison mask we want across all other lanes.
9773   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9774   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9775   Mask = DAG.getNode(ISD::BITCAST, DL,
9776                      ResVT.changeVectorElementTypeToInteger(), Mask);
9777 
9778   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9779 }
9780 
9781 /// Get rid of unnecessary NVCASTs (that don't change the type).
9782 static SDValue performNVCASTCombine(SDNode *N) {
9783   if (N->getValueType(0) == N->getOperand(0).getValueType())
9784     return N->getOperand(0);
9785 
9786   return SDValue();
9787 }
9788 
9789 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9790                                                  DAGCombinerInfo &DCI) const {
9791   SelectionDAG &DAG = DCI.DAG;
9792   switch (N->getOpcode()) {
9793   default:
9794     break;
9795   case ISD::ADD:
9796   case ISD::SUB:
9797     return performAddSubLongCombine(N, DCI, DAG);
9798   case ISD::XOR:
9799     return performXorCombine(N, DAG, DCI, Subtarget);
9800   case ISD::MUL:
9801     return performMulCombine(N, DAG, DCI, Subtarget);
9802   case ISD::SINT_TO_FP:
9803   case ISD::UINT_TO_FP:
9804     return performIntToFpCombine(N, DAG, Subtarget);
9805   case ISD::FP_TO_SINT:
9806   case ISD::FP_TO_UINT:
9807     return performFpToIntCombine(N, DAG, Subtarget);
9808   case ISD::FDIV:
9809     return performFDivCombine(N, DAG, Subtarget);
9810   case ISD::OR:
9811     return performORCombine(N, DCI, Subtarget);
9812   case ISD::INTRINSIC_WO_CHAIN:
9813     return performIntrinsicCombine(N, DCI, Subtarget);
9814   case ISD::ANY_EXTEND:
9815   case ISD::ZERO_EXTEND:
9816   case ISD::SIGN_EXTEND:
9817     return performExtendCombine(N, DCI, DAG);
9818   case ISD::BITCAST:
9819     return performBitcastCombine(N, DCI, DAG);
9820   case ISD::CONCAT_VECTORS:
9821     return performConcatVectorsCombine(N, DCI, DAG);
9822   case ISD::SELECT: {
9823     SDValue RV = performSelectCombine(N, DCI);
9824     if (!RV.getNode())
9825       RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9826     return RV;
9827   }
9828   case ISD::VSELECT:
9829     return performVSelectCombine(N, DCI.DAG);
9830   case ISD::LOAD:
9831     if (performTBISimplification(N->getOperand(1), DCI, DAG))
9832       return SDValue(N, 0);
9833     break;
9834   case ISD::STORE:
9835     return performSTORECombine(N, DCI, DAG, Subtarget);
9836   case AArch64ISD::BRCOND:
9837     return performBRCONDCombine(N, DCI, DAG);
9838   case AArch64ISD::TBNZ:
9839   case AArch64ISD::TBZ:
9840     return performTBZCombine(N, DCI, DAG);
9841   case AArch64ISD::CSEL:
9842     return performCONDCombine(N, DCI, DAG, 2, 3);
9843   case AArch64ISD::DUP:
9844     return performPostLD1Combine(N, DCI, false);
9845   case AArch64ISD::NVCAST:
9846     return performNVCASTCombine(N);
9847   case ISD::INSERT_VECTOR_ELT:
9848     return performPostLD1Combine(N, DCI, true);
9849   case ISD::EXTRACT_VECTOR_ELT:
9850     return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9851   case ISD::INTRINSIC_VOID:
9852   case ISD::INTRINSIC_W_CHAIN:
9853     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9854     case Intrinsic::aarch64_neon_ld2:
9855     case Intrinsic::aarch64_neon_ld3:
9856     case Intrinsic::aarch64_neon_ld4:
9857     case Intrinsic::aarch64_neon_ld1x2:
9858     case Intrinsic::aarch64_neon_ld1x3:
9859     case Intrinsic::aarch64_neon_ld1x4:
9860     case Intrinsic::aarch64_neon_ld2lane:
9861     case Intrinsic::aarch64_neon_ld3lane:
9862     case Intrinsic::aarch64_neon_ld4lane:
9863     case Intrinsic::aarch64_neon_ld2r:
9864     case Intrinsic::aarch64_neon_ld3r:
9865     case Intrinsic::aarch64_neon_ld4r:
9866     case Intrinsic::aarch64_neon_st2:
9867     case Intrinsic::aarch64_neon_st3:
9868     case Intrinsic::aarch64_neon_st4:
9869     case Intrinsic::aarch64_neon_st1x2:
9870     case Intrinsic::aarch64_neon_st1x3:
9871     case Intrinsic::aarch64_neon_st1x4:
9872     case Intrinsic::aarch64_neon_st2lane:
9873     case Intrinsic::aarch64_neon_st3lane:
9874     case Intrinsic::aarch64_neon_st4lane:
9875       return performNEONPostLDSTCombine(N, DCI, DAG);
9876     default:
9877       break;
9878     }
9879   }
9880   return SDValue();
9881 }
9882 
9883 // Check if the return value is used as only a return value, as otherwise
9884 // we can't perform a tail-call. In particular, we need to check for
9885 // target ISD nodes that are returns and any other "odd" constructs
9886 // that the generic analysis code won't necessarily catch.
9887 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9888                                                SDValue &Chain) const {
9889   if (N->getNumValues() != 1)
9890     return false;
9891   if (!N->hasNUsesOfValue(1, 0))
9892     return false;
9893 
9894   SDValue TCChain = Chain;
9895   SDNode *Copy = *N->use_begin();
9896   if (Copy->getOpcode() == ISD::CopyToReg) {
9897     // If the copy has a glue operand, we conservatively assume it isn't safe to
9898     // perform a tail call.
9899     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9900         MVT::Glue)
9901       return false;
9902     TCChain = Copy->getOperand(0);
9903   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9904     return false;
9905 
9906   bool HasRet = false;
9907   for (SDNode *Node : Copy->uses()) {
9908     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9909       return false;
9910     HasRet = true;
9911   }
9912 
9913   if (!HasRet)
9914     return false;
9915 
9916   Chain = TCChain;
9917   return true;
9918 }
9919 
9920 // Return whether the an instruction can potentially be optimized to a tail
9921 // call. This will cause the optimizers to attempt to move, or duplicate,
9922 // return instructions to help enable tail call optimizations for this
9923 // instruction.
9924 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9925   if (!CI->isTailCall())
9926     return false;
9927 
9928   return true;
9929 }
9930 
9931 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9932                                                    SDValue &Offset,
9933                                                    ISD::MemIndexedMode &AM,
9934                                                    bool &IsInc,
9935                                                    SelectionDAG &DAG) const {
9936   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9937     return false;
9938 
9939   Base = Op->getOperand(0);
9940   // All of the indexed addressing mode instructions take a signed
9941   // 9 bit immediate offset.
9942   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9943     int64_t RHSC = (int64_t)RHS->getZExtValue();
9944     if (RHSC >= 256 || RHSC <= -256)
9945       return false;
9946     IsInc = (Op->getOpcode() == ISD::ADD);
9947     Offset = Op->getOperand(1);
9948     return true;
9949   }
9950   return false;
9951 }
9952 
9953 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9954                                                       SDValue &Offset,
9955                                                       ISD::MemIndexedMode &AM,
9956                                                       SelectionDAG &DAG) const {
9957   EVT VT;
9958   SDValue Ptr;
9959   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9960     VT = LD->getMemoryVT();
9961     Ptr = LD->getBasePtr();
9962   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9963     VT = ST->getMemoryVT();
9964     Ptr = ST->getBasePtr();
9965   } else
9966     return false;
9967 
9968   bool IsInc;
9969   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9970     return false;
9971   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9972   return true;
9973 }
9974 
9975 bool AArch64TargetLowering::getPostIndexedAddressParts(
9976     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9977     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9978   EVT VT;
9979   SDValue Ptr;
9980   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9981     VT = LD->getMemoryVT();
9982     Ptr = LD->getBasePtr();
9983   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9984     VT = ST->getMemoryVT();
9985     Ptr = ST->getBasePtr();
9986   } else
9987     return false;
9988 
9989   bool IsInc;
9990   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9991     return false;
9992   // Post-indexing updates the base, so it's not a valid transform
9993   // if that's not the same as the load's pointer.
9994   if (Ptr != Base)
9995     return false;
9996   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9997   return true;
9998 }
9999 
10000 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10001                                   SelectionDAG &DAG) {
10002   SDLoc DL(N);
10003   SDValue Op = N->getOperand(0);
10004 
10005   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10006     return;
10007 
10008   Op = SDValue(
10009       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10010                          DAG.getUNDEF(MVT::i32), Op,
10011                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10012       0);
10013   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10014   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10015 }
10016 
10017 static void ReplaceReductionResults(SDNode *N,
10018                                     SmallVectorImpl<SDValue> &Results,
10019                                     SelectionDAG &DAG, unsigned InterOp,
10020                                     unsigned AcrossOp) {
10021   EVT LoVT, HiVT;
10022   SDValue Lo, Hi;
10023   SDLoc dl(N);
10024   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10025   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10026   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10027   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10028   Results.push_back(SplitVal);
10029 }
10030 
10031 void AArch64TargetLowering::ReplaceNodeResults(
10032     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10033   switch (N->getOpcode()) {
10034   default:
10035     llvm_unreachable("Don't know how to custom expand this");
10036   case ISD::BITCAST:
10037     ReplaceBITCASTResults(N, Results, DAG);
10038     return;
10039   case AArch64ISD::SADDV:
10040     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10041     return;
10042   case AArch64ISD::UADDV:
10043     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10044     return;
10045   case AArch64ISD::SMINV:
10046     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10047     return;
10048   case AArch64ISD::UMINV:
10049     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10050     return;
10051   case AArch64ISD::SMAXV:
10052     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10053     return;
10054   case AArch64ISD::UMAXV:
10055     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10056     return;
10057   case ISD::FP_TO_UINT:
10058   case ISD::FP_TO_SINT:
10059     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10060     // Let normal code take care of it by not adding anything to Results.
10061     return;
10062   }
10063 }
10064 
10065 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10066   return true;
10067 }
10068 
10069 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10070   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10071   // reciprocal if there are three or more FDIVs.
10072   return 3;
10073 }
10074 
10075 TargetLoweringBase::LegalizeTypeAction
10076 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10077   MVT SVT = VT.getSimpleVT();
10078   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10079   // v4i16, v2i32 instead of to promote.
10080   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10081       || SVT == MVT::v1f32)
10082     return TypeWidenVector;
10083 
10084   return TargetLoweringBase::getPreferredVectorAction(VT);
10085 }
10086 
10087 // Loads and stores less than 128-bits are already atomic; ones above that
10088 // are doomed anyway, so defer to the default libcall and blame the OS when
10089 // things go wrong.
10090 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10091   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10092   return Size == 128;
10093 }
10094 
10095 // Loads and stores less than 128-bits are already atomic; ones above that
10096 // are doomed anyway, so defer to the default libcall and blame the OS when
10097 // things go wrong.
10098 TargetLowering::AtomicExpansionKind
10099 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10100   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10101   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10102 }
10103 
10104 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10105 TargetLowering::AtomicExpansionKind
10106 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10107   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10108   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10109 }
10110 
10111 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10112     AtomicCmpXchgInst *AI) const {
10113   return true;
10114 }
10115 
10116 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10117                                              AtomicOrdering Ord) const {
10118   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10119   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10120   bool IsAcquire = isAtLeastAcquire(Ord);
10121 
10122   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10123   // intrinsic must return {i64, i64} and we have to recombine them into a
10124   // single i128 here.
10125   if (ValTy->getPrimitiveSizeInBits() == 128) {
10126     Intrinsic::ID Int =
10127         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10128     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10129 
10130     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10131     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10132 
10133     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10134     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10135     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10136     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10137     return Builder.CreateOr(
10138         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10139   }
10140 
10141   Type *Tys[] = { Addr->getType() };
10142   Intrinsic::ID Int =
10143       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10144   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10145 
10146   return Builder.CreateTruncOrBitCast(
10147       Builder.CreateCall(Ldxr, Addr),
10148       cast<PointerType>(Addr->getType())->getElementType());
10149 }
10150 
10151 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10152     IRBuilder<> &Builder) const {
10153   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10154   Builder.CreateCall(
10155       llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10156 }
10157 
10158 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10159                                                    Value *Val, Value *Addr,
10160                                                    AtomicOrdering Ord) const {
10161   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10162   bool IsRelease = isAtLeastRelease(Ord);
10163 
10164   // Since the intrinsics must have legal type, the i128 intrinsics take two
10165   // parameters: "i64, i64". We must marshal Val into the appropriate form
10166   // before the call.
10167   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10168     Intrinsic::ID Int =
10169         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10170     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10171     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10172 
10173     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10174     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10175     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10176     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10177   }
10178 
10179   Intrinsic::ID Int =
10180       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10181   Type *Tys[] = { Addr->getType() };
10182   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10183 
10184   return Builder.CreateCall(Stxr,
10185                             {Builder.CreateZExtOrBitCast(
10186                                  Val, Stxr->getFunctionType()->getParamType(0)),
10187                              Addr});
10188 }
10189 
10190 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10191     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10192   return Ty->isArrayTy();
10193 }
10194 
10195 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10196                                                             EVT) const {
10197   return false;
10198 }
10199 
10200 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10201   if (!Subtarget->isTargetAndroid())
10202     return TargetLowering::getSafeStackPointerLocation(IRB);
10203 
10204   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10205   // definition of TLS_SLOT_SAFESTACK in
10206   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10207   const unsigned TlsOffset = 0x48;
10208   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10209   Function *ThreadPointerFunc =
10210       Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10211   return IRB.CreatePointerCast(
10212       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10213       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10214 }
10215 
10216 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10217   // Update IsSplitCSR in AArch64unctionInfo.
10218   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10219   AFI->setIsSplitCSR(true);
10220 }
10221 
10222 void AArch64TargetLowering::insertCopiesSplitCSR(
10223     MachineBasicBlock *Entry,
10224     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10225   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10226   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10227   if (!IStart)
10228     return;
10229 
10230   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10231   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10232   MachineBasicBlock::iterator MBBI = Entry->begin();
10233   for (const MCPhysReg *I = IStart; *I; ++I) {
10234     const TargetRegisterClass *RC = nullptr;
10235     if (AArch64::GPR64RegClass.contains(*I))
10236       RC = &AArch64::GPR64RegClass;
10237     else if (AArch64::FPR64RegClass.contains(*I))
10238       RC = &AArch64::FPR64RegClass;
10239     else
10240       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10241 
10242     unsigned NewVR = MRI->createVirtualRegister(RC);
10243     // Create copy from CSR to a virtual register.
10244     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10245     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10246     // nounwind. If we want to generalize this later, we may need to emit
10247     // CFI pseudo-instructions.
10248     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10249                Attribute::NoUnwind) &&
10250            "Function should be nounwind in insertCopiesSplitCSR!");
10251     Entry->addLiveIn(*I);
10252     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10253         .addReg(*I);
10254 
10255     // Insert the copy-back instructions right before the terminator.
10256     for (auto *Exit : Exits)
10257       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10258               TII->get(TargetOpcode::COPY), *I)
10259           .addReg(NewVR);
10260   }
10261 }
10262