Change getTargetNodeName() to produce compiler warnings for missing cases, fix them
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
35 using namespace llvm;
36
37 #define DEBUG_TYPE "aarch64-lower"
38
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
41
42 namespace {
43 enum AlignMode {
44   StrictAlign,
45   NoStrictAlign
46 };
47 }
48
49 static cl::opt<AlignMode>
50 Align(cl::desc("Load/store alignment support"),
51       cl::Hidden, cl::init(NoStrictAlign),
52       cl::values(
53           clEnumValN(StrictAlign,   "aarch64-strict-align",
54                      "Disallow all unaligned memory accesses"),
55           clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
56                      "Allow unaligned memory accesses"),
57           clEnumValEnd));
58
59 // Place holder until extr generation is tested fully.
60 static cl::opt<bool>
61 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
62                           cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
63                           cl::init(true));
64
65 static cl::opt<bool>
66 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
67                            cl::desc("Allow AArch64 SLI/SRI formation"),
68                            cl::init(false));
69
70 // FIXME: The necessary dtprel relocations don't seem to be supported
71 // well in the GNU bfd and gold linkers at the moment. Therefore, by
72 // default, for now, fall back to GeneralDynamic code generation.
73 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
74     "aarch64-elf-ldtls-generation", cl::Hidden,
75     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
76     cl::init(false));
77
78 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
79                                              const AArch64Subtarget &STI)
80     : TargetLowering(TM), Subtarget(&STI) {
81
82   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
83   // we have to make something up. Arbitrarily, choose ZeroOrOne.
84   setBooleanContents(ZeroOrOneBooleanContent);
85   // When comparing vectors the result sets the different elements in the
86   // vector to all-one or all-zero.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // Set up the register classes.
90   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
91   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
92
93   if (Subtarget->hasFPARMv8()) {
94     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
95     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
96     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
97     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
98   }
99
100   if (Subtarget->hasNEON()) {
101     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
102     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
103     // Someone set us up the NEON.
104     addDRTypeForNEON(MVT::v2f32);
105     addDRTypeForNEON(MVT::v8i8);
106     addDRTypeForNEON(MVT::v4i16);
107     addDRTypeForNEON(MVT::v2i32);
108     addDRTypeForNEON(MVT::v1i64);
109     addDRTypeForNEON(MVT::v1f64);
110     addDRTypeForNEON(MVT::v4f16);
111
112     addQRTypeForNEON(MVT::v4f32);
113     addQRTypeForNEON(MVT::v2f64);
114     addQRTypeForNEON(MVT::v16i8);
115     addQRTypeForNEON(MVT::v8i16);
116     addQRTypeForNEON(MVT::v4i32);
117     addQRTypeForNEON(MVT::v2i64);
118     addQRTypeForNEON(MVT::v8f16);
119   }
120
121   // Compute derived properties from the register classes
122   computeRegisterProperties(Subtarget->getRegisterInfo());
123
124   // Provide all sorts of operation actions
125   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
126   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
127   setOperationAction(ISD::SETCC, MVT::i32, Custom);
128   setOperationAction(ISD::SETCC, MVT::i64, Custom);
129   setOperationAction(ISD::SETCC, MVT::f32, Custom);
130   setOperationAction(ISD::SETCC, MVT::f64, Custom);
131   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
132   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
133   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
134   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
135   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
136   setOperationAction(ISD::SELECT, MVT::i32, Custom);
137   setOperationAction(ISD::SELECT, MVT::i64, Custom);
138   setOperationAction(ISD::SELECT, MVT::f32, Custom);
139   setOperationAction(ISD::SELECT, MVT::f64, Custom);
140   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
141   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
142   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
143   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
144   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
145   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
146
147   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
148   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
149   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
150
151   setOperationAction(ISD::FREM, MVT::f32, Expand);
152   setOperationAction(ISD::FREM, MVT::f64, Expand);
153   setOperationAction(ISD::FREM, MVT::f80, Expand);
154
155   // Custom lowering hooks are needed for XOR
156   // to fold it into CSINC/CSINV.
157   setOperationAction(ISD::XOR, MVT::i32, Custom);
158   setOperationAction(ISD::XOR, MVT::i64, Custom);
159
160   // Virtually no operation on f128 is legal, but LLVM can't expand them when
161   // there's a valid register class, so we need custom operations in most cases.
162   setOperationAction(ISD::FABS, MVT::f128, Expand);
163   setOperationAction(ISD::FADD, MVT::f128, Custom);
164   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
165   setOperationAction(ISD::FCOS, MVT::f128, Expand);
166   setOperationAction(ISD::FDIV, MVT::f128, Custom);
167   setOperationAction(ISD::FMA, MVT::f128, Expand);
168   setOperationAction(ISD::FMUL, MVT::f128, Custom);
169   setOperationAction(ISD::FNEG, MVT::f128, Expand);
170   setOperationAction(ISD::FPOW, MVT::f128, Expand);
171   setOperationAction(ISD::FREM, MVT::f128, Expand);
172   setOperationAction(ISD::FRINT, MVT::f128, Expand);
173   setOperationAction(ISD::FSIN, MVT::f128, Expand);
174   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
175   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
176   setOperationAction(ISD::FSUB, MVT::f128, Custom);
177   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
178   setOperationAction(ISD::SETCC, MVT::f128, Custom);
179   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
180   setOperationAction(ISD::SELECT, MVT::f128, Custom);
181   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
182   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
183
184   // Lowering for many of the conversions is actually specified by the non-f128
185   // type. The LowerXXX function will be trivial when f128 isn't involved.
186   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
187   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
188   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
189   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
190   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
191   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
192   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
193   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
194   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
195   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
196   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
197   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
198   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
199   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
200
201   // Variable arguments.
202   setOperationAction(ISD::VASTART, MVT::Other, Custom);
203   setOperationAction(ISD::VAARG, MVT::Other, Custom);
204   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
205   setOperationAction(ISD::VAEND, MVT::Other, Expand);
206
207   // Variable-sized objects.
208   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
209   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
210   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
211
212   // Exception handling.
213   // FIXME: These are guesses. Has this been defined yet?
214   setExceptionPointerRegister(AArch64::X0);
215   setExceptionSelectorRegister(AArch64::X1);
216
217   // Constant pool entries
218   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
219
220   // BlockAddress
221   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
222
223   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
224   setOperationAction(ISD::ADDC, MVT::i32, Custom);
225   setOperationAction(ISD::ADDE, MVT::i32, Custom);
226   setOperationAction(ISD::SUBC, MVT::i32, Custom);
227   setOperationAction(ISD::SUBE, MVT::i32, Custom);
228   setOperationAction(ISD::ADDC, MVT::i64, Custom);
229   setOperationAction(ISD::ADDE, MVT::i64, Custom);
230   setOperationAction(ISD::SUBC, MVT::i64, Custom);
231   setOperationAction(ISD::SUBE, MVT::i64, Custom);
232
233   // AArch64 lacks both left-rotate and popcount instructions.
234   setOperationAction(ISD::ROTL, MVT::i32, Expand);
235   setOperationAction(ISD::ROTL, MVT::i64, Expand);
236
237   // AArch64 doesn't have {U|S}MUL_LOHI.
238   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
239   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
240
241
242   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
243   // counterparts, which AArch64 supports directly.
244   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
245   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
246   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
247   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
248
249   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
250   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
251
252   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
253   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
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
318   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
319   // known to be safe.
320   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
321   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
322   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
323   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
324   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
325   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
326   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
327   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
328   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
329   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
330   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
331   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
332
333   // Expand all other v4f16 operations.
334   // FIXME: We could generate better code by promoting some operations to
335   // a pair of v4f32s
336   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
337   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
338   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
339   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
340   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
341   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
342   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
343   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
344   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
345   setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
347   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
348   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
349   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
350   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
351   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
352   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
353   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
354   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
355   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
356   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
357   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
359   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
360   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
361   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
362
363
364   // v8f16 is also a storage-only type, so expand it.
365   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
366   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
367   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
368   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
369   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
370   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
371   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
372   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
373   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
374   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
375   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
376   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
377   setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
378   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
379   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
380   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
381   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
382   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
383   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
384   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
385   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
386   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
387   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
388   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
389   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
390   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
391   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
392   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
393   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
394   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
395   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
396
397   // AArch64 has implementations of a lot of rounding-like FP operations.
398   for (MVT Ty : {MVT::f32, MVT::f64}) {
399     setOperationAction(ISD::FFLOOR, Ty, Legal);
400     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
401     setOperationAction(ISD::FCEIL, Ty, Legal);
402     setOperationAction(ISD::FRINT, Ty, Legal);
403     setOperationAction(ISD::FTRUNC, Ty, Legal);
404     setOperationAction(ISD::FROUND, Ty, Legal);
405   }
406
407   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
408
409   if (Subtarget->isTargetMachO()) {
410     // For iOS, we don't want to the normal expansion of a libcall to
411     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
412     // traffic.
413     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
414     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
415   } else {
416     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
417     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
418   }
419
420   // Make floating-point constants legal for the large code model, so they don't
421   // become loads from the constant pool.
422   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
423     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
424     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
425   }
426
427   // AArch64 does not have floating-point extending loads, i1 sign-extending
428   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
429   for (MVT VT : MVT::fp_valuetypes()) {
430     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
431     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
432     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
433     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
434   }
435   for (MVT VT : MVT::integer_valuetypes())
436     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
437
438   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
439   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
441   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
442   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
443   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
444   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
445
446   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
447   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
448
449   // Indexed loads and stores are supported.
450   for (unsigned im = (unsigned)ISD::PRE_INC;
451        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452     setIndexedLoadAction(im, MVT::i8, Legal);
453     setIndexedLoadAction(im, MVT::i16, Legal);
454     setIndexedLoadAction(im, MVT::i32, Legal);
455     setIndexedLoadAction(im, MVT::i64, Legal);
456     setIndexedLoadAction(im, MVT::f64, Legal);
457     setIndexedLoadAction(im, MVT::f32, Legal);
458     setIndexedStoreAction(im, MVT::i8, Legal);
459     setIndexedStoreAction(im, MVT::i16, Legal);
460     setIndexedStoreAction(im, MVT::i32, Legal);
461     setIndexedStoreAction(im, MVT::i64, Legal);
462     setIndexedStoreAction(im, MVT::f64, Legal);
463     setIndexedStoreAction(im, MVT::f32, Legal);
464   }
465
466   // Trap.
467   setOperationAction(ISD::TRAP, MVT::Other, Legal);
468
469   // We combine OR nodes for bitfield operations.
470   setTargetDAGCombine(ISD::OR);
471
472   // Vector add and sub nodes may conceal a high-half opportunity.
473   // Also, try to fold ADD into CSINC/CSINV..
474   setTargetDAGCombine(ISD::ADD);
475   setTargetDAGCombine(ISD::SUB);
476
477   setTargetDAGCombine(ISD::XOR);
478   setTargetDAGCombine(ISD::SINT_TO_FP);
479   setTargetDAGCombine(ISD::UINT_TO_FP);
480
481   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
482
483   setTargetDAGCombine(ISD::ANY_EXTEND);
484   setTargetDAGCombine(ISD::ZERO_EXTEND);
485   setTargetDAGCombine(ISD::SIGN_EXTEND);
486   setTargetDAGCombine(ISD::BITCAST);
487   setTargetDAGCombine(ISD::CONCAT_VECTORS);
488   setTargetDAGCombine(ISD::STORE);
489
490   setTargetDAGCombine(ISD::MUL);
491
492   setTargetDAGCombine(ISD::SELECT);
493   setTargetDAGCombine(ISD::VSELECT);
494
495   setTargetDAGCombine(ISD::INTRINSIC_VOID);
496   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
498
499   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
500   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
501   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
502
503   setStackPointerRegisterToSaveRestore(AArch64::SP);
504
505   setSchedulingPreference(Sched::Hybrid);
506
507   // Enable TBZ/TBNZ
508   MaskAndBranchFoldingIsLegal = true;
509   EnableExtLdPromotion = true;
510
511   setMinFunctionAlignment(2);
512
513   RequireStrictAlign = (Align == StrictAlign);
514
515   setHasExtractBitsInsn(true);
516
517   if (Subtarget->hasNEON()) {
518     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
519     // silliness like this:
520     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
521     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
523     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
524     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
525     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
527     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
528     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
529     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
530     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
531     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
532     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
533     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
534     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
535     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
536     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
537     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
538     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
539     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
540     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
541     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
542     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
543     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
544     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
545
546     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
547     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
548     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
549     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
550     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
551
552     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
553
554     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
555     // elements smaller than i32, so promote the input to i32 first.
556     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
557     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
558     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
560     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
561     // -> v8f16 conversions.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
564     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
565     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
566     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
569     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
571     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
572     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
573     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
574     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
575
576     // AArch64 doesn't have MUL.2d:
577     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
578     // Custom handling for some quad-vector types to detect MULL.
579     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
580     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
581     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
582
583     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
584     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
585     // Likewise, narrowing and extending vector loads/stores aren't handled
586     // directly.
587     for (MVT VT : MVT::vector_valuetypes()) {
588       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
589
590       setOperationAction(ISD::MULHS, VT, Expand);
591       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
592       setOperationAction(ISD::MULHU, VT, Expand);
593       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
594
595       setOperationAction(ISD::BSWAP, VT, Expand);
596
597       for (MVT InnerVT : MVT::vector_valuetypes()) {
598         setTruncStoreAction(VT, InnerVT, Expand);
599         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
601         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
602       }
603     }
604
605     // AArch64 has implementations of a lot of rounding-like FP operations.
606     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
607       setOperationAction(ISD::FFLOOR, Ty, Legal);
608       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
609       setOperationAction(ISD::FCEIL, Ty, Legal);
610       setOperationAction(ISD::FRINT, Ty, Legal);
611       setOperationAction(ISD::FTRUNC, Ty, Legal);
612       setOperationAction(ISD::FROUND, Ty, Legal);
613     }
614   }
615
616   // Prefer likely predicted branches to selects on out-of-order cores.
617   if (Subtarget->isCortexA57())
618     PredictableSelectIsExpensive = true;
619 }
620
621 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
622   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
623     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
624     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
625
626     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
627     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
628   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
629     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
631
632     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
634   }
635
636   // Mark vector float intrinsics as expand.
637   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
638     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
639     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
640     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
641     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
642     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
643     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
644     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
645     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
646     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
647   }
648
649   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
650   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
651   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
652   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
653   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
654   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
655   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
656   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
657   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
658   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
659   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
660   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
661
662   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
663   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
664   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
665   for (MVT InnerVT : MVT::all_valuetypes())
666     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
667
668   // CNT supports only B element sizes.
669   if (VT != MVT::v8i8 && VT != MVT::v16i8)
670     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
671
672   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
673   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
674   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
675   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
676   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
677
678   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
679   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
680
681   if (Subtarget->isLittleEndian()) {
682     for (unsigned im = (unsigned)ISD::PRE_INC;
683          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
684       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
685       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
686     }
687   }
688 }
689
690 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
691   addRegisterClass(VT, &AArch64::FPR64RegClass);
692   addTypeForNEON(VT, MVT::v2i32);
693 }
694
695 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
696   addRegisterClass(VT, &AArch64::FPR128RegClass);
697   addTypeForNEON(VT, MVT::v4i32);
698 }
699
700 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
701   if (!VT.isVector())
702     return MVT::i32;
703   return VT.changeVectorElementTypeToInteger();
704 }
705
706 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
707 /// Mask are known to be either zero or one and return them in the
708 /// KnownZero/KnownOne bitsets.
709 void AArch64TargetLowering::computeKnownBitsForTargetNode(
710     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
711     const SelectionDAG &DAG, unsigned Depth) const {
712   switch (Op.getOpcode()) {
713   default:
714     break;
715   case AArch64ISD::CSEL: {
716     APInt KnownZero2, KnownOne2;
717     DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
718     DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
719     KnownZero &= KnownZero2;
720     KnownOne &= KnownOne2;
721     break;
722   }
723   case ISD::INTRINSIC_W_CHAIN: {
724    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
725     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
726     switch (IntID) {
727     default: return;
728     case Intrinsic::aarch64_ldaxr:
729     case Intrinsic::aarch64_ldxr: {
730       unsigned BitWidth = KnownOne.getBitWidth();
731       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
732       unsigned MemBits = VT.getScalarType().getSizeInBits();
733       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
734       return;
735     }
736     }
737     break;
738   }
739   case ISD::INTRINSIC_WO_CHAIN:
740   case ISD::INTRINSIC_VOID: {
741     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
742     switch (IntNo) {
743     default:
744       break;
745     case Intrinsic::aarch64_neon_umaxv:
746     case Intrinsic::aarch64_neon_uminv: {
747       // Figure out the datatype of the vector operand. The UMINV instruction
748       // will zero extend the result, so we can mark as known zero all the
749       // bits larger than the element datatype. 32-bit or larget doesn't need
750       // this as those are legal types and will be handled by isel directly.
751       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
752       unsigned BitWidth = KnownZero.getBitWidth();
753       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
754         assert(BitWidth >= 8 && "Unexpected width!");
755         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
756         KnownZero |= Mask;
757       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
758         assert(BitWidth >= 16 && "Unexpected width!");
759         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
760         KnownZero |= Mask;
761       }
762       break;
763     } break;
764     }
765   }
766   }
767 }
768
769 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
770   return MVT::i64;
771 }
772
773 FastISel *
774 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
775                                       const TargetLibraryInfo *libInfo) const {
776   return AArch64::createFastISel(funcInfo, libInfo);
777 }
778
779 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
780   switch ((AArch64ISD::NodeType)Opcode) {
781   case AArch64ISD::FIRST_NUMBER:      break;
782   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
783   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
784   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
785   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
786   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
787   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
788   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
789   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
790   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
791   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
792   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
793   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
794   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
795   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
796   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
797   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
798   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
799   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
800   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
801   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
802   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
803   case AArch64ISD::FMIN:              return "AArch64ISD::FMIN";
804   case AArch64ISD::FMAX:              return "AArch64ISD::FMAX";
805   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
806   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
807   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
808   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
809   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
810   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
811   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
812   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
813   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
814   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
815   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
816   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
817   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
818   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
819   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
820   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
821   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
822   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
823   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
824   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
825   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
826   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
827   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
828   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
829   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
830   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
831   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
832   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
833   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
834   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
835   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
836   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
837   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
838   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
839   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
840   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
841   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
842   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
843   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
844   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
845   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
846   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
847   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
848   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
849   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
850   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
851   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
852   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
853   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
854   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
855   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
856   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
857   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
858   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
859   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
860   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
861   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
862   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
863   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
864   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
865   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
866   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
867   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
868   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
869   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
870   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
871   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
872   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
873   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
874   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
875   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
876   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
877   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
878   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
879   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
880   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
881   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
882   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
883   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
884   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
885   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
886   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
887   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
888   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
889   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
890   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
891   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
892   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
893   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
894   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
895   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
896   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
897   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
898   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
899   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
900   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
901   }
902   return nullptr;
903 }
904
905 MachineBasicBlock *
906 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
907                                     MachineBasicBlock *MBB) const {
908   // We materialise the F128CSEL pseudo-instruction as some control flow and a
909   // phi node:
910
911   // OrigBB:
912   //     [... previous instrs leading to comparison ...]
913   //     b.ne TrueBB
914   //     b EndBB
915   // TrueBB:
916   //     ; Fallthrough
917   // EndBB:
918   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
919
920   MachineFunction *MF = MBB->getParent();
921   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
922   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
923   DebugLoc DL = MI->getDebugLoc();
924   MachineFunction::iterator It = MBB;
925   ++It;
926
927   unsigned DestReg = MI->getOperand(0).getReg();
928   unsigned IfTrueReg = MI->getOperand(1).getReg();
929   unsigned IfFalseReg = MI->getOperand(2).getReg();
930   unsigned CondCode = MI->getOperand(3).getImm();
931   bool NZCVKilled = MI->getOperand(4).isKill();
932
933   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
934   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
935   MF->insert(It, TrueBB);
936   MF->insert(It, EndBB);
937
938   // Transfer rest of current basic-block to EndBB
939   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
940                 MBB->end());
941   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
942
943   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
944   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
945   MBB->addSuccessor(TrueBB);
946   MBB->addSuccessor(EndBB);
947
948   // TrueBB falls through to the end.
949   TrueBB->addSuccessor(EndBB);
950
951   if (!NZCVKilled) {
952     TrueBB->addLiveIn(AArch64::NZCV);
953     EndBB->addLiveIn(AArch64::NZCV);
954   }
955
956   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
957       .addReg(IfTrueReg)
958       .addMBB(TrueBB)
959       .addReg(IfFalseReg)
960       .addMBB(MBB);
961
962   MI->eraseFromParent();
963   return EndBB;
964 }
965
966 MachineBasicBlock *
967 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
968                                                  MachineBasicBlock *BB) const {
969   switch (MI->getOpcode()) {
970   default:
971 #ifndef NDEBUG
972     MI->dump();
973 #endif
974     llvm_unreachable("Unexpected instruction for custom inserter!");
975
976   case AArch64::F128CSEL:
977     return EmitF128CSEL(MI, BB);
978
979   case TargetOpcode::STACKMAP:
980   case TargetOpcode::PATCHPOINT:
981     return emitPatchPoint(MI, BB);
982   }
983 }
984
985 //===----------------------------------------------------------------------===//
986 // AArch64 Lowering private implementation.
987 //===----------------------------------------------------------------------===//
988
989 //===----------------------------------------------------------------------===//
990 // Lowering Code
991 //===----------------------------------------------------------------------===//
992
993 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
994 /// CC
995 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
996   switch (CC) {
997   default:
998     llvm_unreachable("Unknown condition code!");
999   case ISD::SETNE:
1000     return AArch64CC::NE;
1001   case ISD::SETEQ:
1002     return AArch64CC::EQ;
1003   case ISD::SETGT:
1004     return AArch64CC::GT;
1005   case ISD::SETGE:
1006     return AArch64CC::GE;
1007   case ISD::SETLT:
1008     return AArch64CC::LT;
1009   case ISD::SETLE:
1010     return AArch64CC::LE;
1011   case ISD::SETUGT:
1012     return AArch64CC::HI;
1013   case ISD::SETUGE:
1014     return AArch64CC::HS;
1015   case ISD::SETULT:
1016     return AArch64CC::LO;
1017   case ISD::SETULE:
1018     return AArch64CC::LS;
1019   }
1020 }
1021
1022 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1023 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1024                                   AArch64CC::CondCode &CondCode,
1025                                   AArch64CC::CondCode &CondCode2) {
1026   CondCode2 = AArch64CC::AL;
1027   switch (CC) {
1028   default:
1029     llvm_unreachable("Unknown FP condition!");
1030   case ISD::SETEQ:
1031   case ISD::SETOEQ:
1032     CondCode = AArch64CC::EQ;
1033     break;
1034   case ISD::SETGT:
1035   case ISD::SETOGT:
1036     CondCode = AArch64CC::GT;
1037     break;
1038   case ISD::SETGE:
1039   case ISD::SETOGE:
1040     CondCode = AArch64CC::GE;
1041     break;
1042   case ISD::SETOLT:
1043     CondCode = AArch64CC::MI;
1044     break;
1045   case ISD::SETOLE:
1046     CondCode = AArch64CC::LS;
1047     break;
1048   case ISD::SETONE:
1049     CondCode = AArch64CC::MI;
1050     CondCode2 = AArch64CC::GT;
1051     break;
1052   case ISD::SETO:
1053     CondCode = AArch64CC::VC;
1054     break;
1055   case ISD::SETUO:
1056     CondCode = AArch64CC::VS;
1057     break;
1058   case ISD::SETUEQ:
1059     CondCode = AArch64CC::EQ;
1060     CondCode2 = AArch64CC::VS;
1061     break;
1062   case ISD::SETUGT:
1063     CondCode = AArch64CC::HI;
1064     break;
1065   case ISD::SETUGE:
1066     CondCode = AArch64CC::PL;
1067     break;
1068   case ISD::SETLT:
1069   case ISD::SETULT:
1070     CondCode = AArch64CC::LT;
1071     break;
1072   case ISD::SETLE:
1073   case ISD::SETULE:
1074     CondCode = AArch64CC::LE;
1075     break;
1076   case ISD::SETNE:
1077   case ISD::SETUNE:
1078     CondCode = AArch64CC::NE;
1079     break;
1080   }
1081 }
1082
1083 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1084 /// CC usable with the vector instructions. Fewer operations are available
1085 /// without a real NZCV register, so we have to use less efficient combinations
1086 /// to get the same effect.
1087 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1088                                         AArch64CC::CondCode &CondCode,
1089                                         AArch64CC::CondCode &CondCode2,
1090                                         bool &Invert) {
1091   Invert = false;
1092   switch (CC) {
1093   default:
1094     // Mostly the scalar mappings work fine.
1095     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1096     break;
1097   case ISD::SETUO:
1098     Invert = true; // Fallthrough
1099   case ISD::SETO:
1100     CondCode = AArch64CC::MI;
1101     CondCode2 = AArch64CC::GE;
1102     break;
1103   case ISD::SETUEQ:
1104   case ISD::SETULT:
1105   case ISD::SETULE:
1106   case ISD::SETUGT:
1107   case ISD::SETUGE:
1108     // All of the compare-mask comparisons are ordered, but we can switch
1109     // between the two by a double inversion. E.g. ULE == !OGT.
1110     Invert = true;
1111     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1112     break;
1113   }
1114 }
1115
1116 static bool isLegalArithImmed(uint64_t C) {
1117   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1118   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1119 }
1120
1121 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1122                               SDLoc dl, SelectionDAG &DAG) {
1123   EVT VT = LHS.getValueType();
1124
1125   if (VT.isFloatingPoint())
1126     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1127
1128   // The CMP instruction is just an alias for SUBS, and representing it as
1129   // SUBS means that it's possible to get CSE with subtract operations.
1130   // A later phase can perform the optimization of setting the destination
1131   // register to WZR/XZR if it ends up being unused.
1132   unsigned Opcode = AArch64ISD::SUBS;
1133
1134   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1135       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1136       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1137     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1138     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1139     // can be set differently by this operation. It comes down to whether
1140     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1141     // everything is fine. If not then the optimization is wrong. Thus general
1142     // comparisons are only valid if op2 != 0.
1143
1144     // So, finally, the only LLVM-native comparisons that don't mention C and V
1145     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1146     // the absence of information about op2.
1147     Opcode = AArch64ISD::ADDS;
1148     RHS = RHS.getOperand(1);
1149   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1150              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1151              !isUnsignedIntSetCC(CC)) {
1152     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1153     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1154     // of the signed comparisons.
1155     Opcode = AArch64ISD::ANDS;
1156     RHS = LHS.getOperand(1);
1157     LHS = LHS.getOperand(0);
1158   }
1159
1160   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1161       .getValue(1);
1162 }
1163
1164 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1165                              SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1166   SDValue Cmp;
1167   AArch64CC::CondCode AArch64CC;
1168   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1169     EVT VT = RHS.getValueType();
1170     uint64_t C = RHSC->getZExtValue();
1171     if (!isLegalArithImmed(C)) {
1172       // Constant does not fit, try adjusting it by one?
1173       switch (CC) {
1174       default:
1175         break;
1176       case ISD::SETLT:
1177       case ISD::SETGE:
1178         if ((VT == MVT::i32 && C != 0x80000000 &&
1179              isLegalArithImmed((uint32_t)(C - 1))) ||
1180             (VT == MVT::i64 && C != 0x80000000ULL &&
1181              isLegalArithImmed(C - 1ULL))) {
1182           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1183           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1184           RHS = DAG.getConstant(C, dl, VT);
1185         }
1186         break;
1187       case ISD::SETULT:
1188       case ISD::SETUGE:
1189         if ((VT == MVT::i32 && C != 0 &&
1190              isLegalArithImmed((uint32_t)(C - 1))) ||
1191             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1192           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1193           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1194           RHS = DAG.getConstant(C, dl, VT);
1195         }
1196         break;
1197       case ISD::SETLE:
1198       case ISD::SETGT:
1199         if ((VT == MVT::i32 && C != INT32_MAX &&
1200              isLegalArithImmed((uint32_t)(C + 1))) ||
1201             (VT == MVT::i64 && C != INT64_MAX &&
1202              isLegalArithImmed(C + 1ULL))) {
1203           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1204           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1205           RHS = DAG.getConstant(C, dl, VT);
1206         }
1207         break;
1208       case ISD::SETULE:
1209       case ISD::SETUGT:
1210         if ((VT == MVT::i32 && C != UINT32_MAX &&
1211              isLegalArithImmed((uint32_t)(C + 1))) ||
1212             (VT == MVT::i64 && C != UINT64_MAX &&
1213              isLegalArithImmed(C + 1ULL))) {
1214           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1215           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1216           RHS = DAG.getConstant(C, dl, VT);
1217         }
1218         break;
1219       }
1220     }
1221   }
1222   // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1223   // For the i8 operand, the largest immediate is 255, so this can be easily
1224   // encoded in the compare instruction. For the i16 operand, however, the
1225   // largest immediate cannot be encoded in the compare.
1226   // Therefore, use a sign extending load and cmn to avoid materializing the -1
1227   // constant. For example,
1228   // movz w1, #65535
1229   // ldrh w0, [x0, #0]
1230   // cmp w0, w1
1231   // >
1232   // ldrsh w0, [x0, #0]
1233   // cmn w0, #1
1234   // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1235   // if and only if (sext LHS) == (sext RHS). The checks are in place to ensure
1236   // both the LHS and RHS are truely zero extended and to make sure the
1237   // transformation is profitable.
1238   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1239     if ((cast<ConstantSDNode>(RHS)->getZExtValue() >> 16 == 0) &&
1240         isa<LoadSDNode>(LHS)) {
1241       if (cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1242           cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1243           LHS.getNode()->hasNUsesOfValue(1, 0)) {
1244         int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1245         if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1246           SDValue SExt =
1247               DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1248                           DAG.getValueType(MVT::i16));
1249           Cmp = emitComparison(SExt,
1250                                DAG.getConstant(ValueofRHS, dl,
1251                                                RHS.getValueType()),
1252                                CC, dl, DAG);
1253           AArch64CC = changeIntCCToAArch64CC(CC);
1254           AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
1255           return Cmp;
1256         }
1257       }
1258     }
1259   }
1260   Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1261   AArch64CC = changeIntCCToAArch64CC(CC);
1262   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
1263   return Cmp;
1264 }
1265
1266 static std::pair<SDValue, SDValue>
1267 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1268   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1269          "Unsupported value type");
1270   SDValue Value, Overflow;
1271   SDLoc DL(Op);
1272   SDValue LHS = Op.getOperand(0);
1273   SDValue RHS = Op.getOperand(1);
1274   unsigned Opc = 0;
1275   switch (Op.getOpcode()) {
1276   default:
1277     llvm_unreachable("Unknown overflow instruction!");
1278   case ISD::SADDO:
1279     Opc = AArch64ISD::ADDS;
1280     CC = AArch64CC::VS;
1281     break;
1282   case ISD::UADDO:
1283     Opc = AArch64ISD::ADDS;
1284     CC = AArch64CC::HS;
1285     break;
1286   case ISD::SSUBO:
1287     Opc = AArch64ISD::SUBS;
1288     CC = AArch64CC::VS;
1289     break;
1290   case ISD::USUBO:
1291     Opc = AArch64ISD::SUBS;
1292     CC = AArch64CC::LO;
1293     break;
1294   // Multiply needs a little bit extra work.
1295   case ISD::SMULO:
1296   case ISD::UMULO: {
1297     CC = AArch64CC::NE;
1298     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1299     if (Op.getValueType() == MVT::i32) {
1300       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1301       // For a 32 bit multiply with overflow check we want the instruction
1302       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1303       // need to generate the following pattern:
1304       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1305       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1306       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1307       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1308       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1309                                 DAG.getConstant(0, DL, MVT::i64));
1310       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1311       // operation. We need to clear out the upper 32 bits, because we used a
1312       // widening multiply that wrote all 64 bits. In the end this should be a
1313       // noop.
1314       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1315       if (IsSigned) {
1316         // The signed overflow check requires more than just a simple check for
1317         // any bit set in the upper 32 bits of the result. These bits could be
1318         // just the sign bits of a negative number. To perform the overflow
1319         // check we have to arithmetic shift right the 32nd bit of the result by
1320         // 31 bits. Then we compare the result to the upper 32 bits.
1321         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1322                                         DAG.getConstant(32, DL, MVT::i64));
1323         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1324         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1325                                         DAG.getConstant(31, DL, MVT::i64));
1326         // It is important that LowerBits is last, otherwise the arithmetic
1327         // shift will not be folded into the compare (SUBS).
1328         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1329         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1330                        .getValue(1);
1331       } else {
1332         // The overflow check for unsigned multiply is easy. We only need to
1333         // check if any of the upper 32 bits are set. This can be done with a
1334         // CMP (shifted register). For that we need to generate the following
1335         // pattern:
1336         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1337         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1338                                         DAG.getConstant(32, DL, MVT::i64));
1339         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1340         Overflow =
1341             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1342                         DAG.getConstant(0, DL, MVT::i64),
1343                         UpperBits).getValue(1);
1344       }
1345       break;
1346     }
1347     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1348     // For the 64 bit multiply
1349     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1350     if (IsSigned) {
1351       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1352       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1353                                       DAG.getConstant(63, DL, MVT::i64));
1354       // It is important that LowerBits is last, otherwise the arithmetic
1355       // shift will not be folded into the compare (SUBS).
1356       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1357       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1358                      .getValue(1);
1359     } else {
1360       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1361       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1362       Overflow =
1363           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1364                       DAG.getConstant(0, DL, MVT::i64),
1365                       UpperBits).getValue(1);
1366     }
1367     break;
1368   }
1369   } // switch (...)
1370
1371   if (Opc) {
1372     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1373
1374     // Emit the AArch64 operation with overflow check.
1375     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1376     Overflow = Value.getValue(1);
1377   }
1378   return std::make_pair(Value, Overflow);
1379 }
1380
1381 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1382                                              RTLIB::Libcall Call) const {
1383   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1384   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1385                      SDLoc(Op)).first;
1386 }
1387
1388 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1389   SDValue Sel = Op.getOperand(0);
1390   SDValue Other = Op.getOperand(1);
1391
1392   // If neither operand is a SELECT_CC, give up.
1393   if (Sel.getOpcode() != ISD::SELECT_CC)
1394     std::swap(Sel, Other);
1395   if (Sel.getOpcode() != ISD::SELECT_CC)
1396     return Op;
1397
1398   // The folding we want to perform is:
1399   // (xor x, (select_cc a, b, cc, 0, -1) )
1400   //   -->
1401   // (csel x, (xor x, -1), cc ...)
1402   //
1403   // The latter will get matched to a CSINV instruction.
1404
1405   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1406   SDValue LHS = Sel.getOperand(0);
1407   SDValue RHS = Sel.getOperand(1);
1408   SDValue TVal = Sel.getOperand(2);
1409   SDValue FVal = Sel.getOperand(3);
1410   SDLoc dl(Sel);
1411
1412   // FIXME: This could be generalized to non-integer comparisons.
1413   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1414     return Op;
1415
1416   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1417   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1418
1419   // The the values aren't constants, this isn't the pattern we're looking for.
1420   if (!CFVal || !CTVal)
1421     return Op;
1422
1423   // We can commute the SELECT_CC by inverting the condition.  This
1424   // might be needed to make this fit into a CSINV pattern.
1425   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1426     std::swap(TVal, FVal);
1427     std::swap(CTVal, CFVal);
1428     CC = ISD::getSetCCInverse(CC, true);
1429   }
1430
1431   // If the constants line up, perform the transform!
1432   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1433     SDValue CCVal;
1434     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1435
1436     FVal = Other;
1437     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1438                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
1439
1440     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1441                        CCVal, Cmp);
1442   }
1443
1444   return Op;
1445 }
1446
1447 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1448   EVT VT = Op.getValueType();
1449
1450   // Let legalize expand this if it isn't a legal type yet.
1451   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1452     return SDValue();
1453
1454   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1455
1456   unsigned Opc;
1457   bool ExtraOp = false;
1458   switch (Op.getOpcode()) {
1459   default:
1460     llvm_unreachable("Invalid code");
1461   case ISD::ADDC:
1462     Opc = AArch64ISD::ADDS;
1463     break;
1464   case ISD::SUBC:
1465     Opc = AArch64ISD::SUBS;
1466     break;
1467   case ISD::ADDE:
1468     Opc = AArch64ISD::ADCS;
1469     ExtraOp = true;
1470     break;
1471   case ISD::SUBE:
1472     Opc = AArch64ISD::SBCS;
1473     ExtraOp = true;
1474     break;
1475   }
1476
1477   if (!ExtraOp)
1478     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1479   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1480                      Op.getOperand(2));
1481 }
1482
1483 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1484   // Let legalize expand this if it isn't a legal type yet.
1485   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1486     return SDValue();
1487
1488   SDLoc dl(Op);
1489   AArch64CC::CondCode CC;
1490   // The actual operation that sets the overflow or carry flag.
1491   SDValue Value, Overflow;
1492   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1493
1494   // We use 0 and 1 as false and true values.
1495   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1496   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1497
1498   // We use an inverted condition, because the conditional select is inverted
1499   // too. This will allow it to be selected to a single instruction:
1500   // CSINC Wd, WZR, WZR, invert(cond).
1501   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1502   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1503                          CCVal, Overflow);
1504
1505   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1506   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1507 }
1508
1509 // Prefetch operands are:
1510 // 1: Address to prefetch
1511 // 2: bool isWrite
1512 // 3: int locality (0 = no locality ... 3 = extreme locality)
1513 // 4: bool isDataCache
1514 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1515   SDLoc DL(Op);
1516   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1517   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1518   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1519
1520   bool IsStream = !Locality;
1521   // When the locality number is set
1522   if (Locality) {
1523     // The front-end should have filtered out the out-of-range values
1524     assert(Locality <= 3 && "Prefetch locality out-of-range");
1525     // The locality degree is the opposite of the cache speed.
1526     // Put the number the other way around.
1527     // The encoding starts at 0 for level 1
1528     Locality = 3 - Locality;
1529   }
1530
1531   // built the mask value encoding the expected behavior.
1532   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1533                    (!IsData << 3) |     // IsDataCache bit
1534                    (Locality << 1) |    // Cache level bits
1535                    (unsigned)IsStream;  // Stream bit
1536   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1537                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1538 }
1539
1540 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1541                                               SelectionDAG &DAG) const {
1542   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1543
1544   RTLIB::Libcall LC;
1545   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1546
1547   return LowerF128Call(Op, DAG, LC);
1548 }
1549
1550 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1551                                              SelectionDAG &DAG) const {
1552   if (Op.getOperand(0).getValueType() != MVT::f128) {
1553     // It's legal except when f128 is involved
1554     return Op;
1555   }
1556
1557   RTLIB::Libcall LC;
1558   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1559
1560   // FP_ROUND node has a second operand indicating whether it is known to be
1561   // precise. That doesn't take part in the LibCall so we can't directly use
1562   // LowerF128Call.
1563   SDValue SrcVal = Op.getOperand(0);
1564   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1565                      /*isSigned*/ false, SDLoc(Op)).first;
1566 }
1567
1568 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1569   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1570   // Any additional optimization in this function should be recorded
1571   // in the cost tables.
1572   EVT InVT = Op.getOperand(0).getValueType();
1573   EVT VT = Op.getValueType();
1574
1575   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1576     SDLoc dl(Op);
1577     SDValue Cv =
1578         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1579                     Op.getOperand(0));
1580     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1581   }
1582
1583   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1584     SDLoc dl(Op);
1585     MVT ExtVT =
1586         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1587                          VT.getVectorNumElements());
1588     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1589     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1590   }
1591
1592   // Type changing conversions are illegal.
1593   return Op;
1594 }
1595
1596 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1597                                               SelectionDAG &DAG) const {
1598   if (Op.getOperand(0).getValueType().isVector())
1599     return LowerVectorFP_TO_INT(Op, DAG);
1600
1601   // f16 conversions are promoted to f32.
1602   if (Op.getOperand(0).getValueType() == MVT::f16) {
1603     SDLoc dl(Op);
1604     return DAG.getNode(
1605         Op.getOpcode(), dl, Op.getValueType(),
1606         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1607   }
1608
1609   if (Op.getOperand(0).getValueType() != MVT::f128) {
1610     // It's legal except when f128 is involved
1611     return Op;
1612   }
1613
1614   RTLIB::Libcall LC;
1615   if (Op.getOpcode() == ISD::FP_TO_SINT)
1616     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1617   else
1618     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1619
1620   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1621   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1622                      SDLoc(Op)).first;
1623 }
1624
1625 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1626   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1627   // Any additional optimization in this function should be recorded
1628   // in the cost tables.
1629   EVT VT = Op.getValueType();
1630   SDLoc dl(Op);
1631   SDValue In = Op.getOperand(0);
1632   EVT InVT = In.getValueType();
1633
1634   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1635     MVT CastVT =
1636         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1637                          InVT.getVectorNumElements());
1638     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1639     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1640   }
1641
1642   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1643     unsigned CastOpc =
1644         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1645     EVT CastVT = VT.changeVectorElementTypeToInteger();
1646     In = DAG.getNode(CastOpc, dl, CastVT, In);
1647     return DAG.getNode(Op.getOpcode(), dl, VT, In);
1648   }
1649
1650   return Op;
1651 }
1652
1653 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1654                                             SelectionDAG &DAG) const {
1655   if (Op.getValueType().isVector())
1656     return LowerVectorINT_TO_FP(Op, DAG);
1657
1658   // f16 conversions are promoted to f32.
1659   if (Op.getValueType() == MVT::f16) {
1660     SDLoc dl(Op);
1661     return DAG.getNode(
1662         ISD::FP_ROUND, dl, MVT::f16,
1663         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1664         DAG.getIntPtrConstant(0, dl));
1665   }
1666
1667   // i128 conversions are libcalls.
1668   if (Op.getOperand(0).getValueType() == MVT::i128)
1669     return SDValue();
1670
1671   // Other conversions are legal, unless it's to the completely software-based
1672   // fp128.
1673   if (Op.getValueType() != MVT::f128)
1674     return Op;
1675
1676   RTLIB::Libcall LC;
1677   if (Op.getOpcode() == ISD::SINT_TO_FP)
1678     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1679   else
1680     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1681
1682   return LowerF128Call(Op, DAG, LC);
1683 }
1684
1685 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1686                                             SelectionDAG &DAG) const {
1687   // For iOS, we want to call an alternative entry point: __sincos_stret,
1688   // which returns the values in two S / D registers.
1689   SDLoc dl(Op);
1690   SDValue Arg = Op.getOperand(0);
1691   EVT ArgVT = Arg.getValueType();
1692   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1693
1694   ArgListTy Args;
1695   ArgListEntry Entry;
1696
1697   Entry.Node = Arg;
1698   Entry.Ty = ArgTy;
1699   Entry.isSExt = false;
1700   Entry.isZExt = false;
1701   Args.push_back(Entry);
1702
1703   const char *LibcallName =
1704       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1705   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1706
1707   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1708   TargetLowering::CallLoweringInfo CLI(DAG);
1709   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1710     .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1711
1712   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1713   return CallResult.first;
1714 }
1715
1716 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1717   if (Op.getValueType() != MVT::f16)
1718     return SDValue();
1719
1720   assert(Op.getOperand(0).getValueType() == MVT::i16);
1721   SDLoc DL(Op);
1722
1723   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1724   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1725   return SDValue(
1726       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1727                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1728       0);
1729 }
1730
1731 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1732   if (OrigVT.getSizeInBits() >= 64)
1733     return OrigVT;
1734
1735   assert(OrigVT.isSimple() && "Expecting a simple value type");
1736
1737   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1738   switch (OrigSimpleTy) {
1739   default: llvm_unreachable("Unexpected Vector Type");
1740   case MVT::v2i8:
1741   case MVT::v2i16:
1742      return MVT::v2i32;
1743   case MVT::v4i8:
1744     return  MVT::v4i16;
1745   }
1746 }
1747
1748 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1749                                                  const EVT &OrigTy,
1750                                                  const EVT &ExtTy,
1751                                                  unsigned ExtOpcode) {
1752   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1753   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1754   // 64-bits we need to insert a new extension so that it will be 64-bits.
1755   assert(ExtTy.is128BitVector() && "Unexpected extension size");
1756   if (OrigTy.getSizeInBits() >= 64)
1757     return N;
1758
1759   // Must extend size to at least 64 bits to be used as an operand for VMULL.
1760   EVT NewVT = getExtensionTo64Bits(OrigTy);
1761
1762   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1763 }
1764
1765 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
1766                                    bool isSigned) {
1767   EVT VT = N->getValueType(0);
1768
1769   if (N->getOpcode() != ISD::BUILD_VECTOR)
1770     return false;
1771
1772   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1773     SDNode *Elt = N->getOperand(i).getNode();
1774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
1775       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1776       unsigned HalfSize = EltSize / 2;
1777       if (isSigned) {
1778         if (!isIntN(HalfSize, C->getSExtValue()))
1779           return false;
1780       } else {
1781         if (!isUIntN(HalfSize, C->getZExtValue()))
1782           return false;
1783       }
1784       continue;
1785     }
1786     return false;
1787   }
1788
1789   return true;
1790 }
1791
1792 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
1793   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
1794     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
1795                                              N->getOperand(0)->getValueType(0),
1796                                              N->getValueType(0),
1797                                              N->getOpcode());
1798
1799   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
1800   EVT VT = N->getValueType(0);
1801   SDLoc dl(N);
1802   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
1803   unsigned NumElts = VT.getVectorNumElements();
1804   MVT TruncVT = MVT::getIntegerVT(EltSize);
1805   SmallVector<SDValue, 8> Ops;
1806   for (unsigned i = 0; i != NumElts; ++i) {
1807     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
1808     const APInt &CInt = C->getAPIntValue();
1809     // Element types smaller than 32 bits are not legal, so use i32 elements.
1810     // The values are implicitly truncated so sext vs. zext doesn't matter.
1811     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
1812   }
1813   return DAG.getNode(ISD::BUILD_VECTOR, dl,
1814                      MVT::getVectorVT(TruncVT, NumElts), Ops);
1815 }
1816
1817 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
1818   if (N->getOpcode() == ISD::SIGN_EXTEND)
1819     return true;
1820   if (isExtendedBUILD_VECTOR(N, DAG, true))
1821     return true;
1822   return false;
1823 }
1824
1825 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
1826   if (N->getOpcode() == ISD::ZERO_EXTEND)
1827     return true;
1828   if (isExtendedBUILD_VECTOR(N, DAG, false))
1829     return true;
1830   return false;
1831 }
1832
1833 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
1834   unsigned Opcode = N->getOpcode();
1835   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1836     SDNode *N0 = N->getOperand(0).getNode();
1837     SDNode *N1 = N->getOperand(1).getNode();
1838     return N0->hasOneUse() && N1->hasOneUse() &&
1839       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
1840   }
1841   return false;
1842 }
1843
1844 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
1845   unsigned Opcode = N->getOpcode();
1846   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1847     SDNode *N0 = N->getOperand(0).getNode();
1848     SDNode *N1 = N->getOperand(1).getNode();
1849     return N0->hasOneUse() && N1->hasOneUse() &&
1850       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
1851   }
1852   return false;
1853 }
1854
1855 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
1856   // Multiplications are only custom-lowered for 128-bit vectors so that
1857   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
1858   EVT VT = Op.getValueType();
1859   assert(VT.is128BitVector() && VT.isInteger() &&
1860          "unexpected type for custom-lowering ISD::MUL");
1861   SDNode *N0 = Op.getOperand(0).getNode();
1862   SDNode *N1 = Op.getOperand(1).getNode();
1863   unsigned NewOpc = 0;
1864   bool isMLA = false;
1865   bool isN0SExt = isSignExtended(N0, DAG);
1866   bool isN1SExt = isSignExtended(N1, DAG);
1867   if (isN0SExt && isN1SExt)
1868     NewOpc = AArch64ISD::SMULL;
1869   else {
1870     bool isN0ZExt = isZeroExtended(N0, DAG);
1871     bool isN1ZExt = isZeroExtended(N1, DAG);
1872     if (isN0ZExt && isN1ZExt)
1873       NewOpc = AArch64ISD::UMULL;
1874     else if (isN1SExt || isN1ZExt) {
1875       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
1876       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
1877       if (isN1SExt && isAddSubSExt(N0, DAG)) {
1878         NewOpc = AArch64ISD::SMULL;
1879         isMLA = true;
1880       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
1881         NewOpc =  AArch64ISD::UMULL;
1882         isMLA = true;
1883       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
1884         std::swap(N0, N1);
1885         NewOpc =  AArch64ISD::UMULL;
1886         isMLA = true;
1887       }
1888     }
1889
1890     if (!NewOpc) {
1891       if (VT == MVT::v2i64)
1892         // Fall through to expand this.  It is not legal.
1893         return SDValue();
1894       else
1895         // Other vector multiplications are legal.
1896         return Op;
1897     }
1898   }
1899
1900   // Legalize to a S/UMULL instruction
1901   SDLoc DL(Op);
1902   SDValue Op0;
1903   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
1904   if (!isMLA) {
1905     Op0 = skipExtensionForVectorMULL(N0, DAG);
1906     assert(Op0.getValueType().is64BitVector() &&
1907            Op1.getValueType().is64BitVector() &&
1908            "unexpected types for extended operands to VMULL");
1909     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
1910   }
1911   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
1912   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
1913   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
1914   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
1915   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
1916   EVT Op1VT = Op1.getValueType();
1917   return DAG.getNode(N0->getOpcode(), DL, VT,
1918                      DAG.getNode(NewOpc, DL, VT,
1919                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
1920                      DAG.getNode(NewOpc, DL, VT,
1921                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
1922 }
1923
1924 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1925                                               SelectionDAG &DAG) const {
1926   switch (Op.getOpcode()) {
1927   default:
1928     llvm_unreachable("unimplemented operand");
1929     return SDValue();
1930   case ISD::BITCAST:
1931     return LowerBITCAST(Op, DAG);
1932   case ISD::GlobalAddress:
1933     return LowerGlobalAddress(Op, DAG);
1934   case ISD::GlobalTLSAddress:
1935     return LowerGlobalTLSAddress(Op, DAG);
1936   case ISD::SETCC:
1937     return LowerSETCC(Op, DAG);
1938   case ISD::BR_CC:
1939     return LowerBR_CC(Op, DAG);
1940   case ISD::SELECT:
1941     return LowerSELECT(Op, DAG);
1942   case ISD::SELECT_CC:
1943     return LowerSELECT_CC(Op, DAG);
1944   case ISD::JumpTable:
1945     return LowerJumpTable(Op, DAG);
1946   case ISD::ConstantPool:
1947     return LowerConstantPool(Op, DAG);
1948   case ISD::BlockAddress:
1949     return LowerBlockAddress(Op, DAG);
1950   case ISD::VASTART:
1951     return LowerVASTART(Op, DAG);
1952   case ISD::VACOPY:
1953     return LowerVACOPY(Op, DAG);
1954   case ISD::VAARG:
1955     return LowerVAARG(Op, DAG);
1956   case ISD::ADDC:
1957   case ISD::ADDE:
1958   case ISD::SUBC:
1959   case ISD::SUBE:
1960     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1961   case ISD::SADDO:
1962   case ISD::UADDO:
1963   case ISD::SSUBO:
1964   case ISD::USUBO:
1965   case ISD::SMULO:
1966   case ISD::UMULO:
1967     return LowerXALUO(Op, DAG);
1968   case ISD::FADD:
1969     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1970   case ISD::FSUB:
1971     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1972   case ISD::FMUL:
1973     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1974   case ISD::FDIV:
1975     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1976   case ISD::FP_ROUND:
1977     return LowerFP_ROUND(Op, DAG);
1978   case ISD::FP_EXTEND:
1979     return LowerFP_EXTEND(Op, DAG);
1980   case ISD::FRAMEADDR:
1981     return LowerFRAMEADDR(Op, DAG);
1982   case ISD::RETURNADDR:
1983     return LowerRETURNADDR(Op, DAG);
1984   case ISD::INSERT_VECTOR_ELT:
1985     return LowerINSERT_VECTOR_ELT(Op, DAG);
1986   case ISD::EXTRACT_VECTOR_ELT:
1987     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1988   case ISD::BUILD_VECTOR:
1989     return LowerBUILD_VECTOR(Op, DAG);
1990   case ISD::VECTOR_SHUFFLE:
1991     return LowerVECTOR_SHUFFLE(Op, DAG);
1992   case ISD::EXTRACT_SUBVECTOR:
1993     return LowerEXTRACT_SUBVECTOR(Op, DAG);
1994   case ISD::SRA:
1995   case ISD::SRL:
1996   case ISD::SHL:
1997     return LowerVectorSRA_SRL_SHL(Op, DAG);
1998   case ISD::SHL_PARTS:
1999     return LowerShiftLeftParts(Op, DAG);
2000   case ISD::SRL_PARTS:
2001   case ISD::SRA_PARTS:
2002     return LowerShiftRightParts(Op, DAG);
2003   case ISD::CTPOP:
2004     return LowerCTPOP(Op, DAG);
2005   case ISD::FCOPYSIGN:
2006     return LowerFCOPYSIGN(Op, DAG);
2007   case ISD::AND:
2008     return LowerVectorAND(Op, DAG);
2009   case ISD::OR:
2010     return LowerVectorOR(Op, DAG);
2011   case ISD::XOR:
2012     return LowerXOR(Op, DAG);
2013   case ISD::PREFETCH:
2014     return LowerPREFETCH(Op, DAG);
2015   case ISD::SINT_TO_FP:
2016   case ISD::UINT_TO_FP:
2017     return LowerINT_TO_FP(Op, DAG);
2018   case ISD::FP_TO_SINT:
2019   case ISD::FP_TO_UINT:
2020     return LowerFP_TO_INT(Op, DAG);
2021   case ISD::FSINCOS:
2022     return LowerFSINCOS(Op, DAG);
2023   case ISD::MUL:
2024     return LowerMUL(Op, DAG);
2025   }
2026 }
2027
2028 /// getFunctionAlignment - Return the Log2 alignment of this function.
2029 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2030   return 2;
2031 }
2032
2033 //===----------------------------------------------------------------------===//
2034 //                      Calling Convention Implementation
2035 //===----------------------------------------------------------------------===//
2036
2037 #include "AArch64GenCallingConv.inc"
2038
2039 /// Selects the correct CCAssignFn for a given CallingConvention value.
2040 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2041                                                      bool IsVarArg) const {
2042   switch (CC) {
2043   default:
2044     llvm_unreachable("Unsupported calling convention.");
2045   case CallingConv::WebKit_JS:
2046     return CC_AArch64_WebKit_JS;
2047   case CallingConv::GHC:
2048     return CC_AArch64_GHC;
2049   case CallingConv::C:
2050   case CallingConv::Fast:
2051     if (!Subtarget->isTargetDarwin())
2052       return CC_AArch64_AAPCS;
2053     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2054   }
2055 }
2056
2057 SDValue AArch64TargetLowering::LowerFormalArguments(
2058     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2059     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2060     SmallVectorImpl<SDValue> &InVals) const {
2061   MachineFunction &MF = DAG.getMachineFunction();
2062   MachineFrameInfo *MFI = MF.getFrameInfo();
2063
2064   // Assign locations to all of the incoming arguments.
2065   SmallVector<CCValAssign, 16> ArgLocs;
2066   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2067                  *DAG.getContext());
2068
2069   // At this point, Ins[].VT may already be promoted to i32. To correctly
2070   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2071   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2072   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2073   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2074   // LocVT.
2075   unsigned NumArgs = Ins.size();
2076   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2077   unsigned CurArgIdx = 0;
2078   for (unsigned i = 0; i != NumArgs; ++i) {
2079     MVT ValVT = Ins[i].VT;
2080     if (Ins[i].isOrigArg()) {
2081       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2082       CurArgIdx = Ins[i].getOrigArgIndex();
2083
2084       // Get type of the original argument.
2085       EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2086       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2087       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2088       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2089         ValVT = MVT::i8;
2090       else if (ActualMVT == MVT::i16)
2091         ValVT = MVT::i16;
2092     }
2093     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2094     bool Res =
2095         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2096     assert(!Res && "Call operand has unhandled type");
2097     (void)Res;
2098   }
2099   assert(ArgLocs.size() == Ins.size());
2100   SmallVector<SDValue, 16> ArgValues;
2101   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2102     CCValAssign &VA = ArgLocs[i];
2103
2104     if (Ins[i].Flags.isByVal()) {
2105       // Byval is used for HFAs in the PCS, but the system should work in a
2106       // non-compliant manner for larger structs.
2107       EVT PtrTy = getPointerTy();
2108       int Size = Ins[i].Flags.getByValSize();
2109       unsigned NumRegs = (Size + 7) / 8;
2110
2111       // FIXME: This works on big-endian for composite byvals, which are the common
2112       // case. It should also work for fundamental types too.
2113       unsigned FrameIdx =
2114         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2115       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
2116       InVals.push_back(FrameIdxN);
2117
2118       continue;
2119     }
2120     
2121     if (VA.isRegLoc()) {
2122       // Arguments stored in registers.
2123       EVT RegVT = VA.getLocVT();
2124
2125       SDValue ArgValue;
2126       const TargetRegisterClass *RC;
2127
2128       if (RegVT == MVT::i32)
2129         RC = &AArch64::GPR32RegClass;
2130       else if (RegVT == MVT::i64)
2131         RC = &AArch64::GPR64RegClass;
2132       else if (RegVT == MVT::f16)
2133         RC = &AArch64::FPR16RegClass;
2134       else if (RegVT == MVT::f32)
2135         RC = &AArch64::FPR32RegClass;
2136       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2137         RC = &AArch64::FPR64RegClass;
2138       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2139         RC = &AArch64::FPR128RegClass;
2140       else
2141         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2142
2143       // Transform the arguments in physical registers into virtual ones.
2144       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2145       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2146
2147       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2148       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2149       // truncate to the right size.
2150       switch (VA.getLocInfo()) {
2151       default:
2152         llvm_unreachable("Unknown loc info!");
2153       case CCValAssign::Full:
2154         break;
2155       case CCValAssign::BCvt:
2156         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2157         break;
2158       case CCValAssign::AExt:
2159       case CCValAssign::SExt:
2160       case CCValAssign::ZExt:
2161         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2162         // nodes after our lowering.
2163         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2164         break;
2165       }
2166
2167       InVals.push_back(ArgValue);
2168
2169     } else { // VA.isRegLoc()
2170       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2171       unsigned ArgOffset = VA.getLocMemOffset();
2172       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2173
2174       uint32_t BEAlign = 0;
2175       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2176           !Ins[i].Flags.isInConsecutiveRegs())
2177         BEAlign = 8 - ArgSize;
2178
2179       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2180
2181       // Create load nodes to retrieve arguments from the stack.
2182       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2183       SDValue ArgValue;
2184
2185       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2186       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2187       MVT MemVT = VA.getValVT();
2188
2189       switch (VA.getLocInfo()) {
2190       default:
2191         break;
2192       case CCValAssign::BCvt:
2193         MemVT = VA.getLocVT();
2194         break;
2195       case CCValAssign::SExt:
2196         ExtType = ISD::SEXTLOAD;
2197         break;
2198       case CCValAssign::ZExt:
2199         ExtType = ISD::ZEXTLOAD;
2200         break;
2201       case CCValAssign::AExt:
2202         ExtType = ISD::EXTLOAD;
2203         break;
2204       }
2205
2206       ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
2207                                 MachinePointerInfo::getFixedStack(FI),
2208                                 MemVT, false, false, false, 0);
2209
2210       InVals.push_back(ArgValue);
2211     }
2212   }
2213
2214   // varargs
2215   if (isVarArg) {
2216     if (!Subtarget->isTargetDarwin()) {
2217       // The AAPCS variadic function ABI is identical to the non-variadic
2218       // one. As a result there may be more arguments in registers and we should
2219       // save them for future reference.
2220       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2221     }
2222
2223     AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2224     // This will point to the next argument passed via stack.
2225     unsigned StackOffset = CCInfo.getNextStackOffset();
2226     // We currently pass all varargs at 8-byte alignment.
2227     StackOffset = ((StackOffset + 7) & ~7);
2228     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2229   }
2230
2231   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2232   unsigned StackArgSize = CCInfo.getNextStackOffset();
2233   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2234   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2235     // This is a non-standard ABI so by fiat I say we're allowed to make full
2236     // use of the stack area to be popped, which must be aligned to 16 bytes in
2237     // any case:
2238     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2239
2240     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2241     // a multiple of 16.
2242     FuncInfo->setArgumentStackToRestore(StackArgSize);
2243
2244     // This realignment carries over to the available bytes below. Our own
2245     // callers will guarantee the space is free by giving an aligned value to
2246     // CALLSEQ_START.
2247   }
2248   // Even if we're not expected to free up the space, it's useful to know how
2249   // much is there while considering tail calls (because we can reuse it).
2250   FuncInfo->setBytesInStackArgArea(StackArgSize);
2251
2252   return Chain;
2253 }
2254
2255 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2256                                                 SelectionDAG &DAG, SDLoc DL,
2257                                                 SDValue &Chain) const {
2258   MachineFunction &MF = DAG.getMachineFunction();
2259   MachineFrameInfo *MFI = MF.getFrameInfo();
2260   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2261
2262   SmallVector<SDValue, 8> MemOps;
2263
2264   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2265                                           AArch64::X3, AArch64::X4, AArch64::X5,
2266                                           AArch64::X6, AArch64::X7 };
2267   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2268   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2269
2270   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2271   int GPRIdx = 0;
2272   if (GPRSaveSize != 0) {
2273     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2274
2275     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2276
2277     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2278       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2279       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2280       SDValue Store =
2281           DAG.getStore(Val.getValue(1), DL, Val, FIN,
2282                        MachinePointerInfo::getStack(i * 8), false, false, 0);
2283       MemOps.push_back(Store);
2284       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2285                         DAG.getConstant(8, DL, getPointerTy()));
2286     }
2287   }
2288   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2289   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2290
2291   if (Subtarget->hasFPARMv8()) {
2292     static const MCPhysReg FPRArgRegs[] = {
2293         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2294         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2295     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2296     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2297
2298     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2299     int FPRIdx = 0;
2300     if (FPRSaveSize != 0) {
2301       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2302
2303       SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2304
2305       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2306         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2307         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2308
2309         SDValue Store =
2310             DAG.getStore(Val.getValue(1), DL, Val, FIN,
2311                          MachinePointerInfo::getStack(i * 16), false, false, 0);
2312         MemOps.push_back(Store);
2313         FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2314                           DAG.getConstant(16, DL, getPointerTy()));
2315       }
2316     }
2317     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2318     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2319   }
2320
2321   if (!MemOps.empty()) {
2322     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2323   }
2324 }
2325
2326 /// LowerCallResult - Lower the result values of a call into the
2327 /// appropriate copies out of appropriate physical registers.
2328 SDValue AArch64TargetLowering::LowerCallResult(
2329     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2330     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2331     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2332     SDValue ThisVal) const {
2333   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2334                           ? RetCC_AArch64_WebKit_JS
2335                           : RetCC_AArch64_AAPCS;
2336   // Assign locations to each value returned by this call.
2337   SmallVector<CCValAssign, 16> RVLocs;
2338   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2339                  *DAG.getContext());
2340   CCInfo.AnalyzeCallResult(Ins, RetCC);
2341
2342   // Copy all of the result registers out of their specified physreg.
2343   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2344     CCValAssign VA = RVLocs[i];
2345
2346     // Pass 'this' value directly from the argument to return value, to avoid
2347     // reg unit interference
2348     if (i == 0 && isThisReturn) {
2349       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2350              "unexpected return calling convention register assignment");
2351       InVals.push_back(ThisVal);
2352       continue;
2353     }
2354
2355     SDValue Val =
2356         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2357     Chain = Val.getValue(1);
2358     InFlag = Val.getValue(2);
2359
2360     switch (VA.getLocInfo()) {
2361     default:
2362       llvm_unreachable("Unknown loc info!");
2363     case CCValAssign::Full:
2364       break;
2365     case CCValAssign::BCvt:
2366       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2367       break;
2368     }
2369
2370     InVals.push_back(Val);
2371   }
2372
2373   return Chain;
2374 }
2375
2376 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2377     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2378     bool isCalleeStructRet, bool isCallerStructRet,
2379     const SmallVectorImpl<ISD::OutputArg> &Outs,
2380     const SmallVectorImpl<SDValue> &OutVals,
2381     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2382   // For CallingConv::C this function knows whether the ABI needs
2383   // changing. That's not true for other conventions so they will have to opt in
2384   // manually.
2385   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2386     return false;
2387
2388   const MachineFunction &MF = DAG.getMachineFunction();
2389   const Function *CallerF = MF.getFunction();
2390   CallingConv::ID CallerCC = CallerF->getCallingConv();
2391   bool CCMatch = CallerCC == CalleeCC;
2392
2393   // Byval parameters hand the function a pointer directly into the stack area
2394   // we want to reuse during a tail call. Working around this *is* possible (see
2395   // X86) but less efficient and uglier in LowerCall.
2396   for (Function::const_arg_iterator i = CallerF->arg_begin(),
2397                                     e = CallerF->arg_end();
2398        i != e; ++i)
2399     if (i->hasByValAttr())
2400       return false;
2401
2402   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2403     if (IsTailCallConvention(CalleeCC) && CCMatch)
2404       return true;
2405     return false;
2406   }
2407
2408   // Externally-defined functions with weak linkage should not be
2409   // tail-called on AArch64 when the OS does not support dynamic
2410   // pre-emption of symbols, as the AAELF spec requires normal calls
2411   // to undefined weak functions to be replaced with a NOP or jump to the
2412   // next instruction. The behaviour of branch instructions in this
2413   // situation (as used for tail calls) is implementation-defined, so we
2414   // cannot rely on the linker replacing the tail call with a return.
2415   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2416     const GlobalValue *GV = G->getGlobal();
2417     const Triple TT(getTargetMachine().getTargetTriple());
2418     if (GV->hasExternalWeakLinkage() &&
2419         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2420       return false;
2421   }
2422
2423   // Now we search for cases where we can use a tail call without changing the
2424   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2425   // concept.
2426
2427   // I want anyone implementing a new calling convention to think long and hard
2428   // about this assert.
2429   assert((!isVarArg || CalleeCC == CallingConv::C) &&
2430          "Unexpected variadic calling convention");
2431
2432   if (isVarArg && !Outs.empty()) {
2433     // At least two cases here: if caller is fastcc then we can't have any
2434     // memory arguments (we'd be expected to clean up the stack afterwards). If
2435     // caller is C then we could potentially use its argument area.
2436
2437     // FIXME: for now we take the most conservative of these in both cases:
2438     // disallow all variadic memory operands.
2439     SmallVector<CCValAssign, 16> ArgLocs;
2440     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2441                    *DAG.getContext());
2442
2443     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2444     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2445       if (!ArgLocs[i].isRegLoc())
2446         return false;
2447   }
2448
2449   // If the calling conventions do not match, then we'd better make sure the
2450   // results are returned in the same way as what the caller expects.
2451   if (!CCMatch) {
2452     SmallVector<CCValAssign, 16> RVLocs1;
2453     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2454                     *DAG.getContext());
2455     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2456
2457     SmallVector<CCValAssign, 16> RVLocs2;
2458     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2459                     *DAG.getContext());
2460     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2461
2462     if (RVLocs1.size() != RVLocs2.size())
2463       return false;
2464     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2465       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2466         return false;
2467       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2468         return false;
2469       if (RVLocs1[i].isRegLoc()) {
2470         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2471           return false;
2472       } else {
2473         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2474           return false;
2475       }
2476     }
2477   }
2478
2479   // Nothing more to check if the callee is taking no arguments
2480   if (Outs.empty())
2481     return true;
2482
2483   SmallVector<CCValAssign, 16> ArgLocs;
2484   CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2485                  *DAG.getContext());
2486
2487   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2488
2489   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2490
2491   // If the stack arguments for this call would fit into our own save area then
2492   // the call can be made tail.
2493   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2494 }
2495
2496 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2497                                                    SelectionDAG &DAG,
2498                                                    MachineFrameInfo *MFI,
2499                                                    int ClobberedFI) const {
2500   SmallVector<SDValue, 8> ArgChains;
2501   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2502   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2503
2504   // Include the original chain at the beginning of the list. When this is
2505   // used by target LowerCall hooks, this helps legalize find the
2506   // CALLSEQ_BEGIN node.
2507   ArgChains.push_back(Chain);
2508
2509   // Add a chain value for each stack argument corresponding
2510   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2511                             UE = DAG.getEntryNode().getNode()->use_end();
2512        U != UE; ++U)
2513     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2514       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2515         if (FI->getIndex() < 0) {
2516           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2517           int64_t InLastByte = InFirstByte;
2518           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2519
2520           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2521               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2522             ArgChains.push_back(SDValue(L, 1));
2523         }
2524
2525   // Build a tokenfactor for all the chains.
2526   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2527 }
2528
2529 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2530                                                    bool TailCallOpt) const {
2531   return CallCC == CallingConv::Fast && TailCallOpt;
2532 }
2533
2534 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2535   return CallCC == CallingConv::Fast;
2536 }
2537
2538 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2539 /// and add input and output parameter nodes.
2540 SDValue
2541 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2542                                  SmallVectorImpl<SDValue> &InVals) const {
2543   SelectionDAG &DAG = CLI.DAG;
2544   SDLoc &DL = CLI.DL;
2545   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2546   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2547   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2548   SDValue Chain = CLI.Chain;
2549   SDValue Callee = CLI.Callee;
2550   bool &IsTailCall = CLI.IsTailCall;
2551   CallingConv::ID CallConv = CLI.CallConv;
2552   bool IsVarArg = CLI.IsVarArg;
2553
2554   MachineFunction &MF = DAG.getMachineFunction();
2555   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2556   bool IsThisReturn = false;
2557
2558   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2559   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2560   bool IsSibCall = false;
2561
2562   if (IsTailCall) {
2563     // Check if it's really possible to do a tail call.
2564     IsTailCall = isEligibleForTailCallOptimization(
2565         Callee, CallConv, IsVarArg, IsStructRet,
2566         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2567     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2568       report_fatal_error("failed to perform tail call elimination on a call "
2569                          "site marked musttail");
2570
2571     // A sibling call is one where we're under the usual C ABI and not planning
2572     // to change that but can still do a tail call:
2573     if (!TailCallOpt && IsTailCall)
2574       IsSibCall = true;
2575
2576     if (IsTailCall)
2577       ++NumTailCalls;
2578   }
2579
2580   // Analyze operands of the call, assigning locations to each operand.
2581   SmallVector<CCValAssign, 16> ArgLocs;
2582   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2583                  *DAG.getContext());
2584
2585   if (IsVarArg) {
2586     // Handle fixed and variable vector arguments differently.
2587     // Variable vector arguments always go into memory.
2588     unsigned NumArgs = Outs.size();
2589
2590     for (unsigned i = 0; i != NumArgs; ++i) {
2591       MVT ArgVT = Outs[i].VT;
2592       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2593       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2594                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2595       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2596       assert(!Res && "Call operand has unhandled type");
2597       (void)Res;
2598     }
2599   } else {
2600     // At this point, Outs[].VT may already be promoted to i32. To correctly
2601     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2602     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2603     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2604     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2605     // LocVT.
2606     unsigned NumArgs = Outs.size();
2607     for (unsigned i = 0; i != NumArgs; ++i) {
2608       MVT ValVT = Outs[i].VT;
2609       // Get type of the original argument.
2610       EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2611                                   /*AllowUnknown*/ true);
2612       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2613       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2614       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2615       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2616         ValVT = MVT::i8;
2617       else if (ActualMVT == MVT::i16)
2618         ValVT = MVT::i16;
2619
2620       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2621       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2622       assert(!Res && "Call operand has unhandled type");
2623       (void)Res;
2624     }
2625   }
2626
2627   // Get a count of how many bytes are to be pushed on the stack.
2628   unsigned NumBytes = CCInfo.getNextStackOffset();
2629
2630   if (IsSibCall) {
2631     // Since we're not changing the ABI to make this a tail call, the memory
2632     // operands are already available in the caller's incoming argument space.
2633     NumBytes = 0;
2634   }
2635
2636   // FPDiff is the byte offset of the call's argument area from the callee's.
2637   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2638   // by this amount for a tail call. In a sibling call it must be 0 because the
2639   // caller will deallocate the entire stack and the callee still expects its
2640   // arguments to begin at SP+0. Completely unused for non-tail calls.
2641   int FPDiff = 0;
2642
2643   if (IsTailCall && !IsSibCall) {
2644     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2645
2646     // Since callee will pop argument stack as a tail call, we must keep the
2647     // popped size 16-byte aligned.
2648     NumBytes = RoundUpToAlignment(NumBytes, 16);
2649
2650     // FPDiff will be negative if this tail call requires more space than we
2651     // would automatically have in our incoming argument space. Positive if we
2652     // can actually shrink the stack.
2653     FPDiff = NumReusableBytes - NumBytes;
2654
2655     // The stack pointer must be 16-byte aligned at all times it's used for a
2656     // memory operation, which in practice means at *all* times and in
2657     // particular across call boundaries. Therefore our own arguments started at
2658     // a 16-byte aligned SP and the delta applied for the tail call should
2659     // satisfy the same constraint.
2660     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2661   }
2662
2663   // Adjust the stack pointer for the new arguments...
2664   // These operations are automatically eliminated by the prolog/epilog pass
2665   if (!IsSibCall)
2666     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2667                                                               true),
2668                                  DL);
2669
2670   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2671
2672   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673   SmallVector<SDValue, 8> MemOpChains;
2674
2675   // Walk the register/memloc assignments, inserting copies/loads.
2676   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2677        ++i, ++realArgIdx) {
2678     CCValAssign &VA = ArgLocs[i];
2679     SDValue Arg = OutVals[realArgIdx];
2680     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2681
2682     // Promote the value if needed.
2683     switch (VA.getLocInfo()) {
2684     default:
2685       llvm_unreachable("Unknown loc info!");
2686     case CCValAssign::Full:
2687       break;
2688     case CCValAssign::SExt:
2689       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2690       break;
2691     case CCValAssign::ZExt:
2692       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2693       break;
2694     case CCValAssign::AExt:
2695       if (Outs[realArgIdx].ArgVT == MVT::i1) {
2696         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2697         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2698         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2699       }
2700       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2701       break;
2702     case CCValAssign::BCvt:
2703       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2704       break;
2705     case CCValAssign::FPExt:
2706       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2707       break;
2708     }
2709
2710     if (VA.isRegLoc()) {
2711       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2712         assert(VA.getLocVT() == MVT::i64 &&
2713                "unexpected calling convention register assignment");
2714         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2715                "unexpected use of 'returned'");
2716         IsThisReturn = true;
2717       }
2718       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2719     } else {
2720       assert(VA.isMemLoc());
2721
2722       SDValue DstAddr;
2723       MachinePointerInfo DstInfo;
2724
2725       // FIXME: This works on big-endian for composite byvals, which are the
2726       // common case. It should also work for fundamental types too.
2727       uint32_t BEAlign = 0;
2728       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2729                                         : VA.getValVT().getSizeInBits();
2730       OpSize = (OpSize + 7) / 8;
2731       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2732           !Flags.isInConsecutiveRegs()) {
2733         if (OpSize < 8)
2734           BEAlign = 8 - OpSize;
2735       }
2736       unsigned LocMemOffset = VA.getLocMemOffset();
2737       int32_t Offset = LocMemOffset + BEAlign;
2738       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2739       PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2740
2741       if (IsTailCall) {
2742         Offset = Offset + FPDiff;
2743         int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2744
2745         DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2746         DstInfo = MachinePointerInfo::getFixedStack(FI);
2747
2748         // Make sure any stack arguments overlapping with where we're storing
2749         // are loaded before this eventual operation. Otherwise they'll be
2750         // clobbered.
2751         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2752       } else {
2753         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2754
2755         DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2756         DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2757       }
2758
2759       if (Outs[i].Flags.isByVal()) {
2760         SDValue SizeNode =
2761             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
2762         SDValue Cpy = DAG.getMemcpy(
2763             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2764             /*isVol = */ false, /*AlwaysInline = */ false,
2765             /*isTailCall = */ false,
2766             DstInfo, MachinePointerInfo());
2767
2768         MemOpChains.push_back(Cpy);
2769       } else {
2770         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2771         // promoted to a legal register type i32, we should truncate Arg back to
2772         // i1/i8/i16.
2773         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2774             VA.getValVT() == MVT::i16)
2775           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2776
2777         SDValue Store =
2778             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2779         MemOpChains.push_back(Store);
2780       }
2781     }
2782   }
2783
2784   if (!MemOpChains.empty())
2785     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2786
2787   // Build a sequence of copy-to-reg nodes chained together with token chain
2788   // and flag operands which copy the outgoing args into the appropriate regs.
2789   SDValue InFlag;
2790   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2791     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2792                              RegsToPass[i].second, InFlag);
2793     InFlag = Chain.getValue(1);
2794   }
2795
2796   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2797   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2798   // node so that legalize doesn't hack it.
2799   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2800       Subtarget->isTargetMachO()) {
2801     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2802       const GlobalValue *GV = G->getGlobal();
2803       bool InternalLinkage = GV->hasInternalLinkage();
2804       if (InternalLinkage)
2805         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2806       else {
2807         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2808                                             AArch64II::MO_GOT);
2809         Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2810       }
2811     } else if (ExternalSymbolSDNode *S =
2812                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
2813       const char *Sym = S->getSymbol();
2814       Callee =
2815           DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2816       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2817     }
2818   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2819     const GlobalValue *GV = G->getGlobal();
2820     Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2821   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2822     const char *Sym = S->getSymbol();
2823     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2824   }
2825
2826   // We don't usually want to end the call-sequence here because we would tidy
2827   // the frame up *after* the call, however in the ABI-changing tail-call case
2828   // we've carefully laid out the parameters so that when sp is reset they'll be
2829   // in the correct location.
2830   if (IsTailCall && !IsSibCall) {
2831     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2832                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2833     InFlag = Chain.getValue(1);
2834   }
2835
2836   std::vector<SDValue> Ops;
2837   Ops.push_back(Chain);
2838   Ops.push_back(Callee);
2839
2840   if (IsTailCall) {
2841     // Each tail call may have to adjust the stack by a different amount, so
2842     // this information must travel along with the operation for eventual
2843     // consumption by emitEpilogue.
2844     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2845   }
2846
2847   // Add argument registers to the end of the list so that they are known live
2848   // into the call.
2849   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2850     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2851                                   RegsToPass[i].second.getValueType()));
2852
2853   // Add a register mask operand representing the call-preserved registers.
2854   const uint32_t *Mask;
2855   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2856   if (IsThisReturn) {
2857     // For 'this' returns, use the X0-preserving mask if applicable
2858     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
2859     if (!Mask) {
2860       IsThisReturn = false;
2861       Mask = TRI->getCallPreservedMask(MF, CallConv);
2862     }
2863   } else
2864     Mask = TRI->getCallPreservedMask(MF, CallConv);
2865
2866   assert(Mask && "Missing call preserved mask for calling convention");
2867   Ops.push_back(DAG.getRegisterMask(Mask));
2868
2869   if (InFlag.getNode())
2870     Ops.push_back(InFlag);
2871
2872   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2873
2874   // If we're doing a tall call, use a TC_RETURN here rather than an
2875   // actual call instruction.
2876   if (IsTailCall)
2877     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2878
2879   // Returns a chain and a flag for retval copy to use.
2880   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2881   InFlag = Chain.getValue(1);
2882
2883   uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2884                                 ? RoundUpToAlignment(NumBytes, 16)
2885                                 : 0;
2886
2887   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2888                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
2889                              InFlag, DL);
2890   if (!Ins.empty())
2891     InFlag = Chain.getValue(1);
2892
2893   // Handle result values, copying them out of physregs into vregs that we
2894   // return.
2895   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2896                          InVals, IsThisReturn,
2897                          IsThisReturn ? OutVals[0] : SDValue());
2898 }
2899
2900 bool AArch64TargetLowering::CanLowerReturn(
2901     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2902     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2903   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2904                           ? RetCC_AArch64_WebKit_JS
2905                           : RetCC_AArch64_AAPCS;
2906   SmallVector<CCValAssign, 16> RVLocs;
2907   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2908   return CCInfo.CheckReturn(Outs, RetCC);
2909 }
2910
2911 SDValue
2912 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2913                                    bool isVarArg,
2914                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2915                                    const SmallVectorImpl<SDValue> &OutVals,
2916                                    SDLoc DL, SelectionDAG &DAG) const {
2917   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2918                           ? RetCC_AArch64_WebKit_JS
2919                           : RetCC_AArch64_AAPCS;
2920   SmallVector<CCValAssign, 16> RVLocs;
2921   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2922                  *DAG.getContext());
2923   CCInfo.AnalyzeReturn(Outs, RetCC);
2924
2925   // Copy the result values into the output registers.
2926   SDValue Flag;
2927   SmallVector<SDValue, 4> RetOps(1, Chain);
2928   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2929        ++i, ++realRVLocIdx) {
2930     CCValAssign &VA = RVLocs[i];
2931     assert(VA.isRegLoc() && "Can only return in registers!");
2932     SDValue Arg = OutVals[realRVLocIdx];
2933
2934     switch (VA.getLocInfo()) {
2935     default:
2936       llvm_unreachable("Unknown loc info!");
2937     case CCValAssign::Full:
2938       if (Outs[i].ArgVT == MVT::i1) {
2939         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2940         // value. This is strictly redundant on Darwin (which uses "zeroext
2941         // i1"), but will be optimised out before ISel.
2942         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2943         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2944       }
2945       break;
2946     case CCValAssign::BCvt:
2947       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2948       break;
2949     }
2950
2951     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2952     Flag = Chain.getValue(1);
2953     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2954   }
2955
2956   RetOps[0] = Chain; // Update chain.
2957
2958   // Add the flag if we have it.
2959   if (Flag.getNode())
2960     RetOps.push_back(Flag);
2961
2962   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2963 }
2964
2965 //===----------------------------------------------------------------------===//
2966 //  Other Lowering Code
2967 //===----------------------------------------------------------------------===//
2968
2969 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2970                                                   SelectionDAG &DAG) const {
2971   EVT PtrVT = getPointerTy();
2972   SDLoc DL(Op);
2973   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2974   const GlobalValue *GV = GN->getGlobal();
2975   unsigned char OpFlags =
2976       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2977
2978   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2979          "unexpected offset in global node");
2980
2981   // This also catched the large code model case for Darwin.
2982   if ((OpFlags & AArch64II::MO_GOT) != 0) {
2983     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2984     // FIXME: Once remat is capable of dealing with instructions with register
2985     // operands, expand this into two nodes instead of using a wrapper node.
2986     return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2987   }
2988
2989   if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
2990     assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2991            "use of MO_CONSTPOOL only supported on small model");
2992     SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
2993     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2994     unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2995     SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
2996     SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2997     SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
2998                                      MachinePointerInfo::getConstantPool(),
2999                                      /*isVolatile=*/ false,
3000                                      /*isNonTemporal=*/ true,
3001                                      /*isInvariant=*/ true, 8);
3002     if (GN->getOffset() != 0)
3003       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3004                          DAG.getConstant(GN->getOffset(), DL, PtrVT));
3005     return GlobalAddr;
3006   }
3007
3008   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3009     const unsigned char MO_NC = AArch64II::MO_NC;
3010     return DAG.getNode(
3011         AArch64ISD::WrapperLarge, DL, PtrVT,
3012         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3013         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3014         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3015         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3016   } else {
3017     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3018     // the only correct model on Darwin.
3019     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3020                                             OpFlags | AArch64II::MO_PAGE);
3021     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3022     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3023
3024     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3025     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3026   }
3027 }
3028
3029 /// \brief Convert a TLS address reference into the correct sequence of loads
3030 /// and calls to compute the variable's address (for Darwin, currently) and
3031 /// return an SDValue containing the final node.
3032
3033 /// Darwin only has one TLS scheme which must be capable of dealing with the
3034 /// fully general situation, in the worst case. This means:
3035 ///     + "extern __thread" declaration.
3036 ///     + Defined in a possibly unknown dynamic library.
3037 ///
3038 /// The general system is that each __thread variable has a [3 x i64] descriptor
3039 /// which contains information used by the runtime to calculate the address. The
3040 /// only part of this the compiler needs to know about is the first xword, which
3041 /// contains a function pointer that must be called with the address of the
3042 /// entire descriptor in "x0".
3043 ///
3044 /// Since this descriptor may be in a different unit, in general even the
3045 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3046 /// is:
3047 ///     adrp x0, _var@TLVPPAGE
3048 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3049 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3050 ///                                      ; the function pointer
3051 ///     blr x1                           ; Uses descriptor address in x0
3052 ///     ; Address of _var is now in x0.
3053 ///
3054 /// If the address of _var's descriptor *is* known to the linker, then it can
3055 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3056 /// a slight efficiency gain.
3057 SDValue
3058 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3059                                                    SelectionDAG &DAG) const {
3060   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3061
3062   SDLoc DL(Op);
3063   MVT PtrVT = getPointerTy();
3064   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3065
3066   SDValue TLVPAddr =
3067       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3068   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3069
3070   // The first entry in the descriptor is a function pointer that we must call
3071   // to obtain the address of the variable.
3072   SDValue Chain = DAG.getEntryNode();
3073   SDValue FuncTLVGet =
3074       DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3075                   false, true, true, 8);
3076   Chain = FuncTLVGet.getValue(1);
3077
3078   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3079   MFI->setAdjustsStack(true);
3080
3081   // TLS calls preserve all registers except those that absolutely must be
3082   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3083   // silly).
3084   const uint32_t *Mask =
3085       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3086
3087   // Finally, we can make the call. This is just a degenerate version of a
3088   // normal AArch64 call node: x0 takes the address of the descriptor, and
3089   // returns the address of the variable in this thread.
3090   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3091   Chain =
3092       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3093                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3094                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3095   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3096 }
3097
3098 /// When accessing thread-local variables under either the general-dynamic or
3099 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3100 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3101 /// is a function pointer to carry out the resolution.
3102 ///
3103 /// The sequence is:
3104 ///    adrp  x0, :tlsdesc:var
3105 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3106 ///    add   x0, x0, #:tlsdesc_lo12:var
3107 ///    .tlsdesccall var
3108 ///    blr   x1
3109 ///    (TPIDR_EL0 offset now in x0)
3110 ///
3111 ///  The above sequence must be produced unscheduled, to enable the linker to
3112 ///  optimize/relax this sequence.
3113 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3114 ///  above sequence, and expanded really late in the compilation flow, to ensure
3115 ///  the sequence is produced as per above.
3116 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3117                                                       SelectionDAG &DAG) const {
3118   EVT PtrVT = getPointerTy();
3119
3120   SDValue Chain = DAG.getEntryNode();
3121   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3122
3123   SmallVector<SDValue, 2> Ops;
3124   Ops.push_back(Chain);
3125   Ops.push_back(SymAddr);
3126
3127   Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3128   SDValue Glue = Chain.getValue(1);
3129
3130   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3131 }
3132
3133 SDValue
3134 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3135                                                 SelectionDAG &DAG) const {
3136   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3137   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3138          "ELF TLS only supported in small memory model");
3139   // Different choices can be made for the maximum size of the TLS area for a
3140   // module. For the small address model, the default TLS size is 16MiB and the
3141   // maximum TLS size is 4GiB.
3142   // FIXME: add -mtls-size command line option and make it control the 16MiB
3143   // vs. 4GiB code sequence generation.
3144   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3145
3146   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3147   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3148     if (Model == TLSModel::LocalDynamic)
3149       Model = TLSModel::GeneralDynamic;
3150   }
3151
3152   SDValue TPOff;
3153   EVT PtrVT = getPointerTy();
3154   SDLoc DL(Op);
3155   const GlobalValue *GV = GA->getGlobal();
3156
3157   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3158
3159   if (Model == TLSModel::LocalExec) {
3160     SDValue HiVar = DAG.getTargetGlobalAddress(
3161         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3162     SDValue LoVar = DAG.getTargetGlobalAddress(
3163         GV, DL, PtrVT, 0,
3164         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3165
3166     SDValue TPWithOff_lo =
3167         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3168                                    HiVar,
3169                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3170                 0);
3171     SDValue TPWithOff =
3172         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3173                                    LoVar,
3174                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3175                 0);
3176     return TPWithOff;
3177   } else if (Model == TLSModel::InitialExec) {
3178     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3179     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3180   } else if (Model == TLSModel::LocalDynamic) {
3181     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3182     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3183     // the beginning of the module's TLS region, followed by a DTPREL offset
3184     // calculation.
3185
3186     // These accesses will need deduplicating if there's more than one.
3187     AArch64FunctionInfo *MFI =
3188         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3189     MFI->incNumLocalDynamicTLSAccesses();
3190
3191     // The call needs a relocation too for linker relaxation. It doesn't make
3192     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3193     // the address.
3194     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3195                                                   AArch64II::MO_TLS);
3196
3197     // Now we can calculate the offset from TPIDR_EL0 to this module's
3198     // thread-local area.
3199     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3200
3201     // Now use :dtprel_whatever: operations to calculate this variable's offset
3202     // in its thread-storage area.
3203     SDValue HiVar = DAG.getTargetGlobalAddress(
3204         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3205     SDValue LoVar = DAG.getTargetGlobalAddress(
3206         GV, DL, MVT::i64, 0,
3207         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3208
3209     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3210                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3211                     0);
3212     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3213                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3214                     0);
3215   } else if (Model == TLSModel::GeneralDynamic) {
3216     // The call needs a relocation too for linker relaxation. It doesn't make
3217     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3218     // the address.
3219     SDValue SymAddr =
3220         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3221
3222     // Finally we can make a call to calculate the offset from tpidr_el0.
3223     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3224   } else
3225     llvm_unreachable("Unsupported ELF TLS access model");
3226
3227   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3228 }
3229
3230 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3231                                                      SelectionDAG &DAG) const {
3232   if (Subtarget->isTargetDarwin())
3233     return LowerDarwinGlobalTLSAddress(Op, DAG);
3234   else if (Subtarget->isTargetELF())
3235     return LowerELFGlobalTLSAddress(Op, DAG);
3236
3237   llvm_unreachable("Unexpected platform trying to use TLS");
3238 }
3239 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3240   SDValue Chain = Op.getOperand(0);
3241   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3242   SDValue LHS = Op.getOperand(2);
3243   SDValue RHS = Op.getOperand(3);
3244   SDValue Dest = Op.getOperand(4);
3245   SDLoc dl(Op);
3246
3247   // Handle f128 first, since lowering it will result in comparing the return
3248   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3249   // is expecting to deal with.
3250   if (LHS.getValueType() == MVT::f128) {
3251     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3252
3253     // If softenSetCCOperands returned a scalar, we need to compare the result
3254     // against zero to select between true and false values.
3255     if (!RHS.getNode()) {
3256       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3257       CC = ISD::SETNE;
3258     }
3259   }
3260
3261   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3262   // instruction.
3263   unsigned Opc = LHS.getOpcode();
3264   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3265       cast<ConstantSDNode>(RHS)->isOne() &&
3266       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3267        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3268     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3269            "Unexpected condition code.");
3270     // Only lower legal XALUO ops.
3271     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3272       return SDValue();
3273
3274     // The actual operation with overflow check.
3275     AArch64CC::CondCode OFCC;
3276     SDValue Value, Overflow;
3277     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3278
3279     if (CC == ISD::SETNE)
3280       OFCC = getInvertedCondCode(OFCC);
3281     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3282
3283     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3284                        Overflow);
3285   }
3286
3287   if (LHS.getValueType().isInteger()) {
3288     assert((LHS.getValueType() == RHS.getValueType()) &&
3289            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3290
3291     // If the RHS of the comparison is zero, we can potentially fold this
3292     // to a specialized branch.
3293     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3294     if (RHSC && RHSC->getZExtValue() == 0) {
3295       if (CC == ISD::SETEQ) {
3296         // See if we can use a TBZ to fold in an AND as well.
3297         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3298         // out of bounds, a late MI-layer pass rewrites branches.
3299         // 403.gcc is an example that hits this case.
3300         if (LHS.getOpcode() == ISD::AND &&
3301             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3302             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3303           SDValue Test = LHS.getOperand(0);
3304           uint64_t Mask = LHS.getConstantOperandVal(1);
3305           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3306                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3307                              Dest);
3308         }
3309
3310         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3311       } else if (CC == ISD::SETNE) {
3312         // See if we can use a TBZ to fold in an AND as well.
3313         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3314         // out of bounds, a late MI-layer pass rewrites branches.
3315         // 403.gcc is an example that hits this case.
3316         if (LHS.getOpcode() == ISD::AND &&
3317             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3318             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3319           SDValue Test = LHS.getOperand(0);
3320           uint64_t Mask = LHS.getConstantOperandVal(1);
3321           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3322                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3323                              Dest);
3324         }
3325
3326         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3327       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3328         // Don't combine AND since emitComparison converts the AND to an ANDS
3329         // (a.k.a. TST) and the test in the test bit and branch instruction
3330         // becomes redundant.  This would also increase register pressure.
3331         uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3332         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3333                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3334       }
3335     }
3336     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3337         LHS.getOpcode() != ISD::AND) {
3338       // Don't combine AND since emitComparison converts the AND to an ANDS
3339       // (a.k.a. TST) and the test in the test bit and branch instruction
3340       // becomes redundant.  This would also increase register pressure.
3341       uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3342       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3343                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3344     }
3345
3346     SDValue CCVal;
3347     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3348     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3349                        Cmp);
3350   }
3351
3352   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3353
3354   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3355   // clean.  Some of them require two branches to implement.
3356   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3357   AArch64CC::CondCode CC1, CC2;
3358   changeFPCCToAArch64CC(CC, CC1, CC2);
3359   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3360   SDValue BR1 =
3361       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3362   if (CC2 != AArch64CC::AL) {
3363     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3364     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3365                        Cmp);
3366   }
3367
3368   return BR1;
3369 }
3370
3371 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3372                                               SelectionDAG &DAG) const {
3373   EVT VT = Op.getValueType();
3374   SDLoc DL(Op);
3375
3376   SDValue In1 = Op.getOperand(0);
3377   SDValue In2 = Op.getOperand(1);
3378   EVT SrcVT = In2.getValueType();
3379   if (SrcVT != VT) {
3380     if (SrcVT == MVT::f32 && VT == MVT::f64)
3381       In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3382     else if (SrcVT == MVT::f64 && VT == MVT::f32)
3383       In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2,
3384                         DAG.getIntPtrConstant(0, DL));
3385     else
3386       // FIXME: Src type is different, bail out for now. Can VT really be a
3387       // vector type?
3388       return SDValue();
3389   }
3390
3391   EVT VecVT;
3392   EVT EltVT;
3393   uint64_t EltMask;
3394   SDValue VecVal1, VecVal2;
3395   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3396     EltVT = MVT::i32;
3397     VecVT = MVT::v4i32;
3398     EltMask = 0x80000000ULL;
3399
3400     if (!VT.isVector()) {
3401       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3402                                           DAG.getUNDEF(VecVT), In1);
3403       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3404                                           DAG.getUNDEF(VecVT), In2);
3405     } else {
3406       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3407       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3408     }
3409   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3410     EltVT = MVT::i64;
3411     VecVT = MVT::v2i64;
3412
3413     // We want to materialize a mask with the the high bit set, but the AdvSIMD
3414     // immediate moves cannot materialize that in a single instruction for
3415     // 64-bit elements. Instead, materialize zero and then negate it.
3416     EltMask = 0;
3417
3418     if (!VT.isVector()) {
3419       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3420                                           DAG.getUNDEF(VecVT), In1);
3421       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3422                                           DAG.getUNDEF(VecVT), In2);
3423     } else {
3424       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3425       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3426     }
3427   } else {
3428     llvm_unreachable("Invalid type for copysign!");
3429   }
3430
3431   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3432
3433   // If we couldn't materialize the mask above, then the mask vector will be
3434   // the zero vector, and we need to negate it here.
3435   if (VT == MVT::f64 || VT == MVT::v2f64) {
3436     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3437     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3438     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3439   }
3440
3441   SDValue Sel =
3442       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3443
3444   if (VT == MVT::f32)
3445     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3446   else if (VT == MVT::f64)
3447     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3448   else
3449     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3450 }
3451
3452 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3453   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3454           Attribute::NoImplicitFloat))
3455     return SDValue();
3456
3457   if (!Subtarget->hasNEON())
3458     return SDValue();
3459
3460   // While there is no integer popcount instruction, it can
3461   // be more efficiently lowered to the following sequence that uses
3462   // AdvSIMD registers/instructions as long as the copies to/from
3463   // the AdvSIMD registers are cheap.
3464   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3465   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3466   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3467   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3468   SDValue Val = Op.getOperand(0);
3469   SDLoc DL(Op);
3470   EVT VT = Op.getValueType();
3471
3472   if (VT == MVT::i32)
3473     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3474   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3475
3476   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3477   SDValue UaddLV = DAG.getNode(
3478       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3479       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3480
3481   if (VT == MVT::i64)
3482     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3483   return UaddLV;
3484 }
3485
3486 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3487
3488   if (Op.getValueType().isVector())
3489     return LowerVSETCC(Op, DAG);
3490
3491   SDValue LHS = Op.getOperand(0);
3492   SDValue RHS = Op.getOperand(1);
3493   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3494   SDLoc dl(Op);
3495
3496   // We chose ZeroOrOneBooleanContents, so use zero and one.
3497   EVT VT = Op.getValueType();
3498   SDValue TVal = DAG.getConstant(1, dl, VT);
3499   SDValue FVal = DAG.getConstant(0, dl, VT);
3500
3501   // Handle f128 first, since one possible outcome is a normal integer
3502   // comparison which gets picked up by the next if statement.
3503   if (LHS.getValueType() == MVT::f128) {
3504     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3505
3506     // If softenSetCCOperands returned a scalar, use it.
3507     if (!RHS.getNode()) {
3508       assert(LHS.getValueType() == Op.getValueType() &&
3509              "Unexpected setcc expansion!");
3510       return LHS;
3511     }
3512   }
3513
3514   if (LHS.getValueType().isInteger()) {
3515     SDValue CCVal;
3516     SDValue Cmp =
3517         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3518
3519     // Note that we inverted the condition above, so we reverse the order of
3520     // the true and false operands here.  This will allow the setcc to be
3521     // matched to a single CSINC instruction.
3522     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3523   }
3524
3525   // Now we know we're dealing with FP values.
3526   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3527
3528   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3529   // and do the comparison.
3530   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3531
3532   AArch64CC::CondCode CC1, CC2;
3533   changeFPCCToAArch64CC(CC, CC1, CC2);
3534   if (CC2 == AArch64CC::AL) {
3535     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3536     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3537
3538     // Note that we inverted the condition above, so we reverse the order of
3539     // the true and false operands here.  This will allow the setcc to be
3540     // matched to a single CSINC instruction.
3541     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3542   } else {
3543     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3544     // totally clean.  Some of them require two CSELs to implement.  As is in
3545     // this case, we emit the first CSEL and then emit a second using the output
3546     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
3547
3548     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3549     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3550     SDValue CS1 =
3551         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3552
3553     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3554     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3555   }
3556 }
3557
3558 /// A SELECT_CC operation is really some kind of max or min if both values being
3559 /// compared are, in some sense, equal to the results in either case. However,
3560 /// it is permissible to compare f32 values and produce directly extended f64
3561 /// values.
3562 ///
3563 /// Extending the comparison operands would also be allowed, but is less likely
3564 /// to happen in practice since their use is right here. Note that truncate
3565 /// operations would *not* be semantically equivalent.
3566 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3567   if (Cmp == Result)
3568     return true;
3569
3570   ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3571   ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3572   if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3573       Result.getValueType() == MVT::f64) {
3574     bool Lossy;
3575     APFloat CmpVal = CCmp->getValueAPF();
3576     CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3577     return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3578   }
3579
3580   return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3581 }
3582
3583 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3584                                               SDValue RHS, SDValue TVal,
3585                                               SDValue FVal, SDLoc dl,
3586                                               SelectionDAG &DAG) const {
3587   // Handle f128 first, because it will result in a comparison of some RTLIB
3588   // call result against zero.
3589   if (LHS.getValueType() == MVT::f128) {
3590     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3591
3592     // If softenSetCCOperands returned a scalar, we need to compare the result
3593     // against zero to select between true and false values.
3594     if (!RHS.getNode()) {
3595       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3596       CC = ISD::SETNE;
3597     }
3598   }
3599
3600   // Handle integers first.
3601   if (LHS.getValueType().isInteger()) {
3602     assert((LHS.getValueType() == RHS.getValueType()) &&
3603            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3604
3605     unsigned Opcode = AArch64ISD::CSEL;
3606
3607     // If both the TVal and the FVal are constants, see if we can swap them in
3608     // order to for a CSINV or CSINC out of them.
3609     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3610     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3611
3612     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3613       std::swap(TVal, FVal);
3614       std::swap(CTVal, CFVal);
3615       CC = ISD::getSetCCInverse(CC, true);
3616     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3617       std::swap(TVal, FVal);
3618       std::swap(CTVal, CFVal);
3619       CC = ISD::getSetCCInverse(CC, true);
3620     } else if (TVal.getOpcode() == ISD::XOR) {
3621       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3622       // with a CSINV rather than a CSEL.
3623       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3624
3625       if (CVal && CVal->isAllOnesValue()) {
3626         std::swap(TVal, FVal);
3627         std::swap(CTVal, CFVal);
3628         CC = ISD::getSetCCInverse(CC, true);
3629       }
3630     } else if (TVal.getOpcode() == ISD::SUB) {
3631       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3632       // that we can match with a CSNEG rather than a CSEL.
3633       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3634
3635       if (CVal && CVal->isNullValue()) {
3636         std::swap(TVal, FVal);
3637         std::swap(CTVal, CFVal);
3638         CC = ISD::getSetCCInverse(CC, true);
3639       }
3640     } else if (CTVal && CFVal) {
3641       const int64_t TrueVal = CTVal->getSExtValue();
3642       const int64_t FalseVal = CFVal->getSExtValue();
3643       bool Swap = false;
3644
3645       // If both TVal and FVal are constants, see if FVal is the
3646       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3647       // instead of a CSEL in that case.
3648       if (TrueVal == ~FalseVal) {
3649         Opcode = AArch64ISD::CSINV;
3650       } else if (TrueVal == -FalseVal) {
3651         Opcode = AArch64ISD::CSNEG;
3652       } else if (TVal.getValueType() == MVT::i32) {
3653         // If our operands are only 32-bit wide, make sure we use 32-bit
3654         // arithmetic for the check whether we can use CSINC. This ensures that
3655         // the addition in the check will wrap around properly in case there is
3656         // an overflow (which would not be the case if we do the check with
3657         // 64-bit arithmetic).
3658         const uint32_t TrueVal32 = CTVal->getZExtValue();
3659         const uint32_t FalseVal32 = CFVal->getZExtValue();
3660
3661         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3662           Opcode = AArch64ISD::CSINC;
3663
3664           if (TrueVal32 > FalseVal32) {
3665             Swap = true;
3666           }
3667         }
3668         // 64-bit check whether we can use CSINC.
3669       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3670         Opcode = AArch64ISD::CSINC;
3671
3672         if (TrueVal > FalseVal) {
3673           Swap = true;
3674         }
3675       }
3676
3677       // Swap TVal and FVal if necessary.
3678       if (Swap) {
3679         std::swap(TVal, FVal);
3680         std::swap(CTVal, CFVal);
3681         CC = ISD::getSetCCInverse(CC, true);
3682       }
3683
3684       if (Opcode != AArch64ISD::CSEL) {
3685         // Drop FVal since we can get its value by simply inverting/negating
3686         // TVal.
3687         FVal = TVal;
3688       }
3689     }
3690
3691     SDValue CCVal;
3692     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3693
3694     EVT VT = TVal.getValueType();
3695     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3696   }
3697
3698   // Now we know we're dealing with FP values.
3699   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3700   assert(LHS.getValueType() == RHS.getValueType());
3701   EVT VT = TVal.getValueType();
3702
3703   // Try to match this select into a max/min operation, which have dedicated
3704   // opcode in the instruction set.
3705   // FIXME: This is not correct in the presence of NaNs, so we only enable this
3706   // in no-NaNs mode.
3707   if (getTargetMachine().Options.NoNaNsFPMath) {
3708     SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3709     if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3710         selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3711       CC = ISD::getSetCCSwappedOperands(CC);
3712       std::swap(MinMaxLHS, MinMaxRHS);
3713     }
3714
3715     if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3716         selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3717       switch (CC) {
3718       default:
3719         break;
3720       case ISD::SETGT:
3721       case ISD::SETGE:
3722       case ISD::SETUGT:
3723       case ISD::SETUGE:
3724       case ISD::SETOGT:
3725       case ISD::SETOGE:
3726         return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3727         break;
3728       case ISD::SETLT:
3729       case ISD::SETLE:
3730       case ISD::SETULT:
3731       case ISD::SETULE:
3732       case ISD::SETOLT:
3733       case ISD::SETOLE:
3734         return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3735         break;
3736       }
3737     }
3738   }
3739
3740   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3741   // and do the comparison.
3742   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3743
3744   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3745   // clean.  Some of them require two CSELs to implement.
3746   AArch64CC::CondCode CC1, CC2;
3747   changeFPCCToAArch64CC(CC, CC1, CC2);
3748   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3749   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3750
3751   // If we need a second CSEL, emit it, using the output of the first as the
3752   // RHS.  We're effectively OR'ing the two CC's together.
3753   if (CC2 != AArch64CC::AL) {
3754     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3755     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3756   }
3757
3758   // Otherwise, return the output of the first CSEL.
3759   return CS1;
3760 }
3761
3762 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3763                                               SelectionDAG &DAG) const {
3764   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3765   SDValue LHS = Op.getOperand(0);
3766   SDValue RHS = Op.getOperand(1);
3767   SDValue TVal = Op.getOperand(2);
3768   SDValue FVal = Op.getOperand(3);
3769   SDLoc DL(Op);
3770   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3771 }
3772
3773 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3774                                            SelectionDAG &DAG) const {
3775   SDValue CCVal = Op->getOperand(0);
3776   SDValue TVal = Op->getOperand(1);
3777   SDValue FVal = Op->getOperand(2);
3778   SDLoc DL(Op);
3779
3780   unsigned Opc = CCVal.getOpcode();
3781   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3782   // instruction.
3783   if (CCVal.getResNo() == 1 &&
3784       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3785        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3786     // Only lower legal XALUO ops.
3787     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3788       return SDValue();
3789
3790     AArch64CC::CondCode OFCC;
3791     SDValue Value, Overflow;
3792     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
3793     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
3794
3795     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3796                        CCVal, Overflow);
3797   }
3798
3799   // Lower it the same way as we would lower a SELECT_CC node.
3800   ISD::CondCode CC;
3801   SDValue LHS, RHS;
3802   if (CCVal.getOpcode() == ISD::SETCC) {
3803     LHS = CCVal.getOperand(0);
3804     RHS = CCVal.getOperand(1);
3805     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
3806   } else {
3807     LHS = CCVal;
3808     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
3809     CC = ISD::SETNE;
3810   }
3811   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3812 }
3813
3814 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3815                                               SelectionDAG &DAG) const {
3816   // Jump table entries as PC relative offsets. No additional tweaking
3817   // is necessary here. Just get the address of the jump table.
3818   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3819   EVT PtrVT = getPointerTy();
3820   SDLoc DL(Op);
3821
3822   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3823       !Subtarget->isTargetMachO()) {
3824     const unsigned char MO_NC = AArch64II::MO_NC;
3825     return DAG.getNode(
3826         AArch64ISD::WrapperLarge, DL, PtrVT,
3827         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3828         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3829         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3830         DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3831                                AArch64II::MO_G0 | MO_NC));
3832   }
3833
3834   SDValue Hi =
3835       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3836   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3837                                       AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3838   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3839   return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3840 }
3841
3842 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3843                                                  SelectionDAG &DAG) const {
3844   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3845   EVT PtrVT = getPointerTy();
3846   SDLoc DL(Op);
3847
3848   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3849     // Use the GOT for the large code model on iOS.
3850     if (Subtarget->isTargetMachO()) {
3851       SDValue GotAddr = DAG.getTargetConstantPool(
3852           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3853           AArch64II::MO_GOT);
3854       return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3855     }
3856
3857     const unsigned char MO_NC = AArch64II::MO_NC;
3858     return DAG.getNode(
3859         AArch64ISD::WrapperLarge, DL, PtrVT,
3860         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3861                                   CP->getOffset(), AArch64II::MO_G3),
3862         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3863                                   CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3864         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3865                                   CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3866         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3867                                   CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3868   } else {
3869     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3870     // ELF, the only valid one on Darwin.
3871     SDValue Hi =
3872         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3873                                   CP->getOffset(), AArch64II::MO_PAGE);
3874     SDValue Lo = DAG.getTargetConstantPool(
3875         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3876         AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3877
3878     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3879     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3880   }
3881 }
3882
3883 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3884                                                SelectionDAG &DAG) const {
3885   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3886   EVT PtrVT = getPointerTy();
3887   SDLoc DL(Op);
3888   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3889       !Subtarget->isTargetMachO()) {
3890     const unsigned char MO_NC = AArch64II::MO_NC;
3891     return DAG.getNode(
3892         AArch64ISD::WrapperLarge, DL, PtrVT,
3893         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3894         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3895         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3896         DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3897   } else {
3898     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3899     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3900                                                              AArch64II::MO_NC);
3901     SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3902     return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3903   }
3904 }
3905
3906 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3907                                                  SelectionDAG &DAG) const {
3908   AArch64FunctionInfo *FuncInfo =
3909       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3910
3911   SDLoc DL(Op);
3912   SDValue FR =
3913       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3914   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3915   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3916                       MachinePointerInfo(SV), false, false, 0);
3917 }
3918
3919 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3920                                                 SelectionDAG &DAG) const {
3921   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3922   // Standard, section B.3.
3923   MachineFunction &MF = DAG.getMachineFunction();
3924   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3925   SDLoc DL(Op);
3926
3927   SDValue Chain = Op.getOperand(0);
3928   SDValue VAList = Op.getOperand(1);
3929   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3930   SmallVector<SDValue, 4> MemOps;
3931
3932   // void *__stack at offset 0
3933   SDValue Stack =
3934       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3935   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3936                                 MachinePointerInfo(SV), false, false, 8));
3937
3938   // void *__gr_top at offset 8
3939   int GPRSize = FuncInfo->getVarArgsGPRSize();
3940   if (GPRSize > 0) {
3941     SDValue GRTop, GRTopAddr;
3942
3943     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3944                             DAG.getConstant(8, DL, getPointerTy()));
3945
3946     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3947     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3948                         DAG.getConstant(GPRSize, DL, getPointerTy()));
3949
3950     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3951                                   MachinePointerInfo(SV, 8), false, false, 8));
3952   }
3953
3954   // void *__vr_top at offset 16
3955   int FPRSize = FuncInfo->getVarArgsFPRSize();
3956   if (FPRSize > 0) {
3957     SDValue VRTop, VRTopAddr;
3958     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3959                             DAG.getConstant(16, DL, getPointerTy()));
3960
3961     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3962     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3963                         DAG.getConstant(FPRSize, DL, getPointerTy()));
3964
3965     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3966                                   MachinePointerInfo(SV, 16), false, false, 8));
3967   }
3968
3969   // int __gr_offs at offset 24
3970   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3971                                    DAG.getConstant(24, DL, getPointerTy()));
3972   MemOps.push_back(DAG.getStore(Chain, DL,
3973                                 DAG.getConstant(-GPRSize, DL, MVT::i32),
3974                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
3975                                 false, 4));
3976
3977   // int __vr_offs at offset 28
3978   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3979                                    DAG.getConstant(28, DL, getPointerTy()));
3980   MemOps.push_back(DAG.getStore(Chain, DL,
3981                                 DAG.getConstant(-FPRSize, DL, MVT::i32),
3982                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
3983                                 false, 4));
3984
3985   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3986 }
3987
3988 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3989                                             SelectionDAG &DAG) const {
3990   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3991                                      : LowerAAPCS_VASTART(Op, DAG);
3992 }
3993
3994 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3995                                            SelectionDAG &DAG) const {
3996   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3997   // pointer.
3998   SDLoc DL(Op);
3999   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4000   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4001   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4002
4003   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4004                        Op.getOperand(2),
4005                        DAG.getConstant(VaListSize, DL, MVT::i32),
4006                        8, false, false, false, MachinePointerInfo(DestSV),
4007                        MachinePointerInfo(SrcSV));
4008 }
4009
4010 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4011   assert(Subtarget->isTargetDarwin() &&
4012          "automatic va_arg instruction only works on Darwin");
4013
4014   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4015   EVT VT = Op.getValueType();
4016   SDLoc DL(Op);
4017   SDValue Chain = Op.getOperand(0);
4018   SDValue Addr = Op.getOperand(1);
4019   unsigned Align = Op.getConstantOperandVal(3);
4020
4021   SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
4022                                MachinePointerInfo(V), false, false, false, 0);
4023   Chain = VAList.getValue(1);
4024
4025   if (Align > 8) {
4026     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4027     VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
4028                          DAG.getConstant(Align - 1, DL, getPointerTy()));
4029     VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
4030                          DAG.getConstant(-(int64_t)Align, DL, getPointerTy()));
4031   }
4032
4033   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4034   uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
4035
4036   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4037   // up to 64 bits.  At the very least, we have to increase the striding of the
4038   // vaargs list to match this, and for FP values we need to introduce
4039   // FP_ROUND nodes as well.
4040   if (VT.isInteger() && !VT.isVector())
4041     ArgSize = 8;
4042   bool NeedFPTrunc = false;
4043   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4044     ArgSize = 8;
4045     NeedFPTrunc = true;
4046   }
4047
4048   // Increment the pointer, VAList, to the next vaarg
4049   SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
4050                                DAG.getConstant(ArgSize, DL, getPointerTy()));
4051   // Store the incremented VAList to the legalized pointer
4052   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4053                                  false, false, 0);
4054
4055   // Load the actual argument out of the pointer VAList
4056   if (NeedFPTrunc) {
4057     // Load the value as an f64.
4058     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4059                                  MachinePointerInfo(), false, false, false, 0);
4060     // Round the value down to an f32.
4061     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4062                                    DAG.getIntPtrConstant(1, DL));
4063     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4064     // Merge the rounded value with the chain output of the load.
4065     return DAG.getMergeValues(Ops, DL);
4066   }
4067
4068   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4069                      false, false, 0);
4070 }
4071
4072 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4073                                               SelectionDAG &DAG) const {
4074   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4075   MFI->setFrameAddressIsTaken(true);
4076
4077   EVT VT = Op.getValueType();
4078   SDLoc DL(Op);
4079   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4080   SDValue FrameAddr =
4081       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4082   while (Depth--)
4083     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4084                             MachinePointerInfo(), false, false, false, 0);
4085   return FrameAddr;
4086 }
4087
4088 // FIXME? Maybe this could be a TableGen attribute on some registers and
4089 // this table could be generated automatically from RegInfo.
4090 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
4091                                                   EVT VT) const {
4092   unsigned Reg = StringSwitch<unsigned>(RegName)
4093                        .Case("sp", AArch64::SP)
4094                        .Default(0);
4095   if (Reg)
4096     return Reg;
4097   report_fatal_error("Invalid register name global variable");
4098 }
4099
4100 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4101                                                SelectionDAG &DAG) const {
4102   MachineFunction &MF = DAG.getMachineFunction();
4103   MachineFrameInfo *MFI = MF.getFrameInfo();
4104   MFI->setReturnAddressIsTaken(true);
4105
4106   EVT VT = Op.getValueType();
4107   SDLoc DL(Op);
4108   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4109   if (Depth) {
4110     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4111     SDValue Offset = DAG.getConstant(8, DL, getPointerTy());
4112     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4113                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4114                        MachinePointerInfo(), false, false, false, 0);
4115   }
4116
4117   // Return LR, which contains the return address. Mark it an implicit live-in.
4118   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4119   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4120 }
4121
4122 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4123 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4124 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4125                                                     SelectionDAG &DAG) const {
4126   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4127   EVT VT = Op.getValueType();
4128   unsigned VTBits = VT.getSizeInBits();
4129   SDLoc dl(Op);
4130   SDValue ShOpLo = Op.getOperand(0);
4131   SDValue ShOpHi = Op.getOperand(1);
4132   SDValue ShAmt = Op.getOperand(2);
4133   SDValue ARMcc;
4134   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4135
4136   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4137
4138   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4139                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4140   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4141   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4142                                    DAG.getConstant(VTBits, dl, MVT::i64));
4143   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4144
4145   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4146                                ISD::SETGE, dl, DAG);
4147   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4148
4149   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4150   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4151   SDValue Lo =
4152       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4153
4154   // AArch64 shifts larger than the register width are wrapped rather than
4155   // clamped, so we can't just emit "hi >> x".
4156   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4157   SDValue TrueValHi = Opc == ISD::SRA
4158                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4159                                         DAG.getConstant(VTBits - 1, dl,
4160                                                         MVT::i64))
4161                           : DAG.getConstant(0, dl, VT);
4162   SDValue Hi =
4163       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4164
4165   SDValue Ops[2] = { Lo, Hi };
4166   return DAG.getMergeValues(Ops, dl);
4167 }
4168
4169 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4170 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4171 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4172                                                  SelectionDAG &DAG) const {
4173   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4174   EVT VT = Op.getValueType();
4175   unsigned VTBits = VT.getSizeInBits();
4176   SDLoc dl(Op);
4177   SDValue ShOpLo = Op.getOperand(0);
4178   SDValue ShOpHi = Op.getOperand(1);
4179   SDValue ShAmt = Op.getOperand(2);
4180   SDValue ARMcc;
4181
4182   assert(Op.getOpcode() == ISD::SHL_PARTS);
4183   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4184                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4185   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4186   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4187                                    DAG.getConstant(VTBits, dl, MVT::i64));
4188   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4189   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4190
4191   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4192
4193   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4194                                ISD::SETGE, dl, DAG);
4195   SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4196   SDValue Hi =
4197       DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4198
4199   // AArch64 shifts of larger than register sizes are wrapped rather than
4200   // clamped, so we can't just emit "lo << a" if a is too big.
4201   SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4202   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4203   SDValue Lo =
4204       DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4205
4206   SDValue Ops[2] = { Lo, Hi };
4207   return DAG.getMergeValues(Ops, dl);
4208 }
4209
4210 bool AArch64TargetLowering::isOffsetFoldingLegal(
4211     const GlobalAddressSDNode *GA) const {
4212   // The AArch64 target doesn't support folding offsets into global addresses.
4213   return false;
4214 }
4215
4216 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4217   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4218   // FIXME: We should be able to handle f128 as well with a clever lowering.
4219   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4220     return true;
4221
4222   if (VT == MVT::f64)
4223     return AArch64_AM::getFP64Imm(Imm) != -1;
4224   else if (VT == MVT::f32)
4225     return AArch64_AM::getFP32Imm(Imm) != -1;
4226   return false;
4227 }
4228
4229 //===----------------------------------------------------------------------===//
4230 //                          AArch64 Optimization Hooks
4231 //===----------------------------------------------------------------------===//
4232
4233 //===----------------------------------------------------------------------===//
4234 //                          AArch64 Inline Assembly Support
4235 //===----------------------------------------------------------------------===//
4236
4237 // Table of Constraints
4238 // TODO: This is the current set of constraints supported by ARM for the
4239 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4240 //
4241 // r - A general register
4242 // w - An FP/SIMD register of some size in the range v0-v31
4243 // x - An FP/SIMD register of some size in the range v0-v15
4244 // I - Constant that can be used with an ADD instruction
4245 // J - Constant that can be used with a SUB instruction
4246 // K - Constant that can be used with a 32-bit logical instruction
4247 // L - Constant that can be used with a 64-bit logical instruction
4248 // M - Constant that can be used as a 32-bit MOV immediate
4249 // N - Constant that can be used as a 64-bit MOV immediate
4250 // Q - A memory reference with base register and no offset
4251 // S - A symbolic address
4252 // Y - Floating point constant zero
4253 // Z - Integer constant zero
4254 //
4255 //   Note that general register operands will be output using their 64-bit x
4256 // register name, whatever the size of the variable, unless the asm operand
4257 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4258 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4259 // %q modifier.
4260
4261 /// getConstraintType - Given a constraint letter, return the type of
4262 /// constraint it is for this target.
4263 AArch64TargetLowering::ConstraintType
4264 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4265   if (Constraint.size() == 1) {
4266     switch (Constraint[0]) {
4267     default:
4268       break;
4269     case 'z':
4270       return C_Other;
4271     case 'x':
4272     case 'w':
4273       return C_RegisterClass;
4274     // An address with a single base register. Due to the way we
4275     // currently handle addresses it is the same as 'r'.
4276     case 'Q':
4277       return C_Memory;
4278     }
4279   }
4280   return TargetLowering::getConstraintType(Constraint);
4281 }
4282
4283 /// Examine constraint type and operand type and determine a weight value.
4284 /// This object must already have been set up with the operand type
4285 /// and the current alternative constraint selected.
4286 TargetLowering::ConstraintWeight
4287 AArch64TargetLowering::getSingleConstraintMatchWeight(
4288     AsmOperandInfo &info, const char *constraint) const {
4289   ConstraintWeight weight = CW_Invalid;
4290   Value *CallOperandVal = info.CallOperandVal;
4291   // If we don't have a value, we can't do a match,
4292   // but allow it at the lowest weight.
4293   if (!CallOperandVal)
4294     return CW_Default;
4295   Type *type = CallOperandVal->getType();
4296   // Look at the constraint type.
4297   switch (*constraint) {
4298   default:
4299     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4300     break;
4301   case 'x':
4302   case 'w':
4303     if (type->isFloatingPointTy() || type->isVectorTy())
4304       weight = CW_Register;
4305     break;
4306   case 'z':
4307     weight = CW_Constant;
4308     break;
4309   }
4310   return weight;
4311 }
4312
4313 std::pair<unsigned, const TargetRegisterClass *>
4314 AArch64TargetLowering::getRegForInlineAsmConstraint(
4315     const TargetRegisterInfo *TRI, const std::string &Constraint,
4316     MVT VT) const {
4317   if (Constraint.size() == 1) {
4318     switch (Constraint[0]) {
4319     case 'r':
4320       if (VT.getSizeInBits() == 64)
4321         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4322       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4323     case 'w':
4324       if (VT == MVT::f32)
4325         return std::make_pair(0U, &AArch64::FPR32RegClass);
4326       if (VT.getSizeInBits() == 64)
4327         return std::make_pair(0U, &AArch64::FPR64RegClass);
4328       if (VT.getSizeInBits() == 128)
4329         return std::make_pair(0U, &AArch64::FPR128RegClass);
4330       break;
4331     // The instructions that this constraint is designed for can
4332     // only take 128-bit registers so just use that regclass.
4333     case 'x':
4334       if (VT.getSizeInBits() == 128)
4335         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4336       break;
4337     }
4338   }
4339   if (StringRef("{cc}").equals_lower(Constraint))
4340     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4341
4342   // Use the default implementation in TargetLowering to convert the register
4343   // constraint into a member of a register class.
4344   std::pair<unsigned, const TargetRegisterClass *> Res;
4345   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4346
4347   // Not found as a standard register?
4348   if (!Res.second) {
4349     unsigned Size = Constraint.size();
4350     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4351         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4352       const std::string Reg =
4353           std::string(&Constraint[2], &Constraint[Size - 1]);
4354       int RegNo = atoi(Reg.c_str());
4355       if (RegNo >= 0 && RegNo <= 31) {
4356         // v0 - v31 are aliases of q0 - q31.
4357         // By default we'll emit v0-v31 for this unless there's a modifier where
4358         // we'll emit the correct register as well.
4359         Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4360         Res.second = &AArch64::FPR128RegClass;
4361       }
4362     }
4363   }
4364
4365   return Res;
4366 }
4367
4368 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4369 /// vector.  If it is invalid, don't add anything to Ops.
4370 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4371     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4372     SelectionDAG &DAG) const {
4373   SDValue Result;
4374
4375   // Currently only support length 1 constraints.
4376   if (Constraint.length() != 1)
4377     return;
4378
4379   char ConstraintLetter = Constraint[0];
4380   switch (ConstraintLetter) {
4381   default:
4382     break;
4383
4384   // This set of constraints deal with valid constants for various instructions.
4385   // Validate and return a target constant for them if we can.
4386   case 'z': {
4387     // 'z' maps to xzr or wzr so it needs an input of 0.
4388     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4389     if (!C || C->getZExtValue() != 0)
4390       return;
4391
4392     if (Op.getValueType() == MVT::i64)
4393       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4394     else
4395       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4396     break;
4397   }
4398
4399   case 'I':
4400   case 'J':
4401   case 'K':
4402   case 'L':
4403   case 'M':
4404   case 'N':
4405     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4406     if (!C)
4407       return;
4408
4409     // Grab the value and do some validation.
4410     uint64_t CVal = C->getZExtValue();
4411     switch (ConstraintLetter) {
4412     // The I constraint applies only to simple ADD or SUB immediate operands:
4413     // i.e. 0 to 4095 with optional shift by 12
4414     // The J constraint applies only to ADD or SUB immediates that would be
4415     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4416     // instruction [or vice versa], in other words -1 to -4095 with optional
4417     // left shift by 12.
4418     case 'I':
4419       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4420         break;
4421       return;
4422     case 'J': {
4423       uint64_t NVal = -C->getSExtValue();
4424       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4425         CVal = C->getSExtValue();
4426         break;
4427       }
4428       return;
4429     }
4430     // The K and L constraints apply *only* to logical immediates, including
4431     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4432     // been removed and MOV should be used). So these constraints have to
4433     // distinguish between bit patterns that are valid 32-bit or 64-bit
4434     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4435     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4436     // versa.
4437     case 'K':
4438       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4439         break;
4440       return;
4441     case 'L':
4442       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4443         break;
4444       return;
4445     // The M and N constraints are a superset of K and L respectively, for use
4446     // with the MOV (immediate) alias. As well as the logical immediates they
4447     // also match 32 or 64-bit immediates that can be loaded either using a
4448     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4449     // (M) or 64-bit 0x1234000000000000 (N) etc.
4450     // As a note some of this code is liberally stolen from the asm parser.
4451     case 'M': {
4452       if (!isUInt<32>(CVal))
4453         return;
4454       if (AArch64_AM::isLogicalImmediate(CVal, 32))
4455         break;
4456       if ((CVal & 0xFFFF) == CVal)
4457         break;
4458       if ((CVal & 0xFFFF0000ULL) == CVal)
4459         break;
4460       uint64_t NCVal = ~(uint32_t)CVal;
4461       if ((NCVal & 0xFFFFULL) == NCVal)
4462         break;
4463       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4464         break;
4465       return;
4466     }
4467     case 'N': {
4468       if (AArch64_AM::isLogicalImmediate(CVal, 64))
4469         break;
4470       if ((CVal & 0xFFFFULL) == CVal)
4471         break;
4472       if ((CVal & 0xFFFF0000ULL) == CVal)
4473         break;
4474       if ((CVal & 0xFFFF00000000ULL) == CVal)
4475         break;
4476       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4477         break;
4478       uint64_t NCVal = ~CVal;
4479       if ((NCVal & 0xFFFFULL) == NCVal)
4480         break;
4481       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4482         break;
4483       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4484         break;
4485       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4486         break;
4487       return;
4488     }
4489     default:
4490       return;
4491     }
4492
4493     // All assembler immediates are 64-bit integers.
4494     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4495     break;
4496   }
4497
4498   if (Result.getNode()) {
4499     Ops.push_back(Result);
4500     return;
4501   }
4502
4503   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4504 }
4505
4506 //===----------------------------------------------------------------------===//
4507 //                     AArch64 Advanced SIMD Support
4508 //===----------------------------------------------------------------------===//
4509
4510 /// WidenVector - Given a value in the V64 register class, produce the
4511 /// equivalent value in the V128 register class.
4512 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4513   EVT VT = V64Reg.getValueType();
4514   unsigned NarrowSize = VT.getVectorNumElements();
4515   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4516   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4517   SDLoc DL(V64Reg);
4518
4519   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4520                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
4521 }
4522
4523 /// getExtFactor - Determine the adjustment factor for the position when
4524 /// generating an "extract from vector registers" instruction.
4525 static unsigned getExtFactor(SDValue &V) {
4526   EVT EltType = V.getValueType().getVectorElementType();
4527   return EltType.getSizeInBits() / 8;
4528 }
4529
4530 /// NarrowVector - Given a value in the V128 register class, produce the
4531 /// equivalent value in the V64 register class.
4532 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4533   EVT VT = V128Reg.getValueType();
4534   unsigned WideSize = VT.getVectorNumElements();
4535   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4536   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4537   SDLoc DL(V128Reg);
4538
4539   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4540 }
4541
4542 // Gather data to see if the operation can be modelled as a
4543 // shuffle in combination with VEXTs.
4544 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4545                                                   SelectionDAG &DAG) const {
4546   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4547   SDLoc dl(Op);
4548   EVT VT = Op.getValueType();
4549   unsigned NumElts = VT.getVectorNumElements();
4550
4551   struct ShuffleSourceInfo {
4552     SDValue Vec;
4553     unsigned MinElt;
4554     unsigned MaxElt;
4555
4556     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4557     // be compatible with the shuffle we intend to construct. As a result
4558     // ShuffleVec will be some sliding window into the original Vec.
4559     SDValue ShuffleVec;
4560
4561     // Code should guarantee that element i in Vec starts at element "WindowBase
4562     // + i * WindowScale in ShuffleVec".
4563     int WindowBase;
4564     int WindowScale;
4565
4566     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4567     ShuffleSourceInfo(SDValue Vec)
4568         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4569           WindowScale(1) {}
4570   };
4571
4572   // First gather all vectors used as an immediate source for this BUILD_VECTOR
4573   // node.
4574   SmallVector<ShuffleSourceInfo, 2> Sources;
4575   for (unsigned i = 0; i < NumElts; ++i) {
4576     SDValue V = Op.getOperand(i);
4577     if (V.getOpcode() == ISD::UNDEF)
4578       continue;
4579     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4580       // A shuffle can only come from building a vector from various
4581       // elements of other vectors.
4582       return SDValue();
4583     }
4584
4585     // Add this element source to the list if it's not already there.
4586     SDValue SourceVec = V.getOperand(0);
4587     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4588     if (Source == Sources.end())
4589       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4590
4591     // Update the minimum and maximum lane number seen.
4592     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4593     Source->MinElt = std::min(Source->MinElt, EltNo);
4594     Source->MaxElt = std::max(Source->MaxElt, EltNo);
4595   }
4596
4597   // Currently only do something sane when at most two source vectors
4598   // are involved.
4599   if (Sources.size() > 2)
4600     return SDValue();
4601
4602   // Find out the smallest element size among result and two sources, and use
4603   // it as element size to build the shuffle_vector.
4604   EVT SmallestEltTy = VT.getVectorElementType();
4605   for (auto &Source : Sources) {
4606     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4607     if (SrcEltTy.bitsLT(SmallestEltTy)) {
4608       SmallestEltTy = SrcEltTy;
4609     }
4610   }
4611   unsigned ResMultiplier =
4612       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4613   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4614   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4615
4616   // If the source vector is too wide or too narrow, we may nevertheless be able
4617   // to construct a compatible shuffle either by concatenating it with UNDEF or
4618   // extracting a suitable range of elements.
4619   for (auto &Src : Sources) {
4620     EVT SrcVT = Src.ShuffleVec.getValueType();
4621
4622     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4623       continue;
4624
4625     // This stage of the search produces a source with the same element type as
4626     // the original, but with a total width matching the BUILD_VECTOR output.
4627     EVT EltVT = SrcVT.getVectorElementType();
4628     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4629     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4630
4631     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4632       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4633       // We can pad out the smaller vector for free, so if it's part of a
4634       // shuffle...
4635       Src.ShuffleVec =
4636           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4637                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4638       continue;
4639     }
4640
4641     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4642
4643     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4644       // Span too large for a VEXT to cope
4645       return SDValue();
4646     }
4647
4648     if (Src.MinElt >= NumSrcElts) {
4649       // The extraction can just take the second half
4650       Src.ShuffleVec =
4651           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4652                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4653       Src.WindowBase = -NumSrcElts;
4654     } else if (Src.MaxElt < NumSrcElts) {
4655       // The extraction can just take the first half
4656       Src.ShuffleVec =
4657           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4658                       DAG.getConstant(0, dl, MVT::i64));
4659     } else {
4660       // An actual VEXT is needed
4661       SDValue VEXTSrc1 =
4662           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4663                       DAG.getConstant(0, dl, MVT::i64));
4664       SDValue VEXTSrc2 =
4665           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4666                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
4667       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4668
4669       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4670                                    VEXTSrc2,
4671                                    DAG.getConstant(Imm, dl, MVT::i32));
4672       Src.WindowBase = -Src.MinElt;
4673     }
4674   }
4675
4676   // Another possible incompatibility occurs from the vector element types. We
4677   // can fix this by bitcasting the source vectors to the same type we intend
4678   // for the shuffle.
4679   for (auto &Src : Sources) {
4680     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4681     if (SrcEltTy == SmallestEltTy)
4682       continue;
4683     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4684     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4685     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4686     Src.WindowBase *= Src.WindowScale;
4687   }
4688
4689   // Final sanity check before we try to actually produce a shuffle.
4690   DEBUG(
4691     for (auto Src : Sources)
4692       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4693   );
4694
4695   // The stars all align, our next step is to produce the mask for the shuffle.
4696   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4697   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4698   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4699     SDValue Entry = Op.getOperand(i);
4700     if (Entry.getOpcode() == ISD::UNDEF)
4701       continue;
4702
4703     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4704     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4705
4706     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4707     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4708     // segment.
4709     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4710     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4711                                VT.getVectorElementType().getSizeInBits());
4712     int LanesDefined = BitsDefined / BitsPerShuffleLane;
4713
4714     // This source is expected to fill ResMultiplier lanes of the final shuffle,
4715     // starting at the appropriate offset.
4716     int *LaneMask = &Mask[i * ResMultiplier];
4717
4718     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4719     ExtractBase += NumElts * (Src - Sources.begin());
4720     for (int j = 0; j < LanesDefined; ++j)
4721       LaneMask[j] = ExtractBase + j;
4722   }
4723
4724   // Final check before we try to produce nonsense...
4725   if (!isShuffleMaskLegal(Mask, ShuffleVT))
4726     return SDValue();
4727
4728   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4729   for (unsigned i = 0; i < Sources.size(); ++i)
4730     ShuffleOps[i] = Sources[i].ShuffleVec;
4731
4732   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4733                                          ShuffleOps[1], &Mask[0]);
4734   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4735 }
4736
4737 // check if an EXT instruction can handle the shuffle mask when the
4738 // vector sources of the shuffle are the same.
4739 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4740   unsigned NumElts = VT.getVectorNumElements();
4741
4742   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4743   if (M[0] < 0)
4744     return false;
4745
4746   Imm = M[0];
4747
4748   // If this is a VEXT shuffle, the immediate value is the index of the first
4749   // element.  The other shuffle indices must be the successive elements after
4750   // the first one.
4751   unsigned ExpectedElt = Imm;
4752   for (unsigned i = 1; i < NumElts; ++i) {
4753     // Increment the expected index.  If it wraps around, just follow it
4754     // back to index zero and keep going.
4755     ++ExpectedElt;
4756     if (ExpectedElt == NumElts)
4757       ExpectedElt = 0;
4758
4759     if (M[i] < 0)
4760       continue; // ignore UNDEF indices
4761     if (ExpectedElt != static_cast<unsigned>(M[i]))
4762       return false;
4763   }
4764
4765   return true;
4766 }
4767
4768 // check if an EXT instruction can handle the shuffle mask when the
4769 // vector sources of the shuffle are different.
4770 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4771                       unsigned &Imm) {
4772   // Look for the first non-undef element.
4773   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4774       [](int Elt) {return Elt >= 0;});
4775
4776   // Benefit form APInt to handle overflow when calculating expected element.
4777   unsigned NumElts = VT.getVectorNumElements();
4778   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4779   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4780   // The following shuffle indices must be the successive elements after the
4781   // first real element.
4782   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4783       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4784   if (FirstWrongElt != M.end())
4785     return false;
4786
4787   // The index of an EXT is the first element if it is not UNDEF.
4788   // Watch out for the beginning UNDEFs. The EXT index should be the expected
4789   // value of the first element.  E.g. 
4790   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4791   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4792   // ExpectedElt is the last mask index plus 1.
4793   Imm = ExpectedElt.getZExtValue();
4794
4795   // There are two difference cases requiring to reverse input vectors.
4796   // For example, for vector <4 x i32> we have the following cases,
4797   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4798   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4799   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4800   // to reverse two input vectors.
4801   if (Imm < NumElts)
4802     ReverseEXT = true;
4803   else
4804     Imm -= NumElts;
4805
4806   return true;
4807 }
4808
4809 /// isREVMask - Check if a vector shuffle corresponds to a REV
4810 /// instruction with the specified blocksize.  (The order of the elements
4811 /// within each block of the vector is reversed.)
4812 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4813   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4814          "Only possible block sizes for REV are: 16, 32, 64");
4815
4816   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4817   if (EltSz == 64)
4818     return false;
4819
4820   unsigned NumElts = VT.getVectorNumElements();
4821   unsigned BlockElts = M[0] + 1;
4822   // If the first shuffle index is UNDEF, be optimistic.
4823   if (M[0] < 0)
4824     BlockElts = BlockSize / EltSz;
4825
4826   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4827     return false;
4828
4829   for (unsigned i = 0; i < NumElts; ++i) {
4830     if (M[i] < 0)
4831       continue; // ignore UNDEF indices
4832     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4833       return false;
4834   }
4835
4836   return true;
4837 }
4838
4839 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4840   unsigned NumElts = VT.getVectorNumElements();
4841   WhichResult = (M[0] == 0 ? 0 : 1);
4842   unsigned Idx = WhichResult * NumElts / 2;
4843   for (unsigned i = 0; i != NumElts; i += 2) {
4844     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4845         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4846       return false;
4847     Idx += 1;
4848   }
4849
4850   return true;
4851 }
4852
4853 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4854   unsigned NumElts = VT.getVectorNumElements();
4855   WhichResult = (M[0] == 0 ? 0 : 1);
4856   for (unsigned i = 0; i != NumElts; ++i) {
4857     if (M[i] < 0)
4858       continue; // ignore UNDEF indices
4859     if ((unsigned)M[i] != 2 * i + WhichResult)
4860       return false;
4861   }
4862
4863   return true;
4864 }
4865
4866 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4867   unsigned NumElts = VT.getVectorNumElements();
4868   WhichResult = (M[0] == 0 ? 0 : 1);
4869   for (unsigned i = 0; i < NumElts; i += 2) {
4870     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4871         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4872       return false;
4873   }
4874   return true;
4875 }
4876
4877 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4878 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4879 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4880 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4881   unsigned NumElts = VT.getVectorNumElements();
4882   WhichResult = (M[0] == 0 ? 0 : 1);
4883   unsigned Idx = WhichResult * NumElts / 2;
4884   for (unsigned i = 0; i != NumElts; i += 2) {
4885     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4886         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4887       return false;
4888     Idx += 1;
4889   }
4890
4891   return true;
4892 }
4893
4894 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4895 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4896 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4897 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4898   unsigned Half = VT.getVectorNumElements() / 2;
4899   WhichResult = (M[0] == 0 ? 0 : 1);
4900   for (unsigned j = 0; j != 2; ++j) {
4901     unsigned Idx = WhichResult;
4902     for (unsigned i = 0; i != Half; ++i) {
4903       int MIdx = M[i + j * Half];
4904       if (MIdx >= 0 && (unsigned)MIdx != Idx)
4905         return false;
4906       Idx += 2;
4907     }
4908   }
4909
4910   return true;
4911 }
4912
4913 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4914 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4915 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4916 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4917   unsigned NumElts = VT.getVectorNumElements();
4918   WhichResult = (M[0] == 0 ? 0 : 1);
4919   for (unsigned i = 0; i < NumElts; i += 2) {
4920     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4921         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4922       return false;
4923   }
4924   return true;
4925 }
4926
4927 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4928                       bool &DstIsLeft, int &Anomaly) {
4929   if (M.size() != static_cast<size_t>(NumInputElements))
4930     return false;
4931
4932   int NumLHSMatch = 0, NumRHSMatch = 0;
4933   int LastLHSMismatch = -1, LastRHSMismatch = -1;
4934
4935   for (int i = 0; i < NumInputElements; ++i) {
4936     if (M[i] == -1) {
4937       ++NumLHSMatch;
4938       ++NumRHSMatch;
4939       continue;
4940     }
4941
4942     if (M[i] == i)
4943       ++NumLHSMatch;
4944     else
4945       LastLHSMismatch = i;
4946
4947     if (M[i] == i + NumInputElements)
4948       ++NumRHSMatch;
4949     else
4950       LastRHSMismatch = i;
4951   }
4952
4953   if (NumLHSMatch == NumInputElements - 1) {
4954     DstIsLeft = true;
4955     Anomaly = LastLHSMismatch;
4956     return true;
4957   } else if (NumRHSMatch == NumInputElements - 1) {
4958     DstIsLeft = false;
4959     Anomaly = LastRHSMismatch;
4960     return true;
4961   }
4962
4963   return false;
4964 }
4965
4966 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4967   if (VT.getSizeInBits() != 128)
4968     return false;
4969
4970   unsigned NumElts = VT.getVectorNumElements();
4971
4972   for (int I = 0, E = NumElts / 2; I != E; I++) {
4973     if (Mask[I] != I)
4974       return false;
4975   }
4976
4977   int Offset = NumElts / 2;
4978   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4979     if (Mask[I] != I + SplitLHS * Offset)
4980       return false;
4981   }
4982
4983   return true;
4984 }
4985
4986 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4987   SDLoc DL(Op);
4988   EVT VT = Op.getValueType();
4989   SDValue V0 = Op.getOperand(0);
4990   SDValue V1 = Op.getOperand(1);
4991   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4992
4993   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4994       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4995     return SDValue();
4996
4997   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4998
4999   if (!isConcatMask(Mask, VT, SplitV0))
5000     return SDValue();
5001
5002   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5003                                 VT.getVectorNumElements() / 2);
5004   if (SplitV0) {
5005     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5006                      DAG.getConstant(0, DL, MVT::i64));
5007   }
5008   if (V1.getValueType().getSizeInBits() == 128) {
5009     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5010                      DAG.getConstant(0, DL, MVT::i64));
5011   }
5012   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5013 }
5014
5015 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5016 /// the specified operations to build the shuffle.
5017 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5018                                       SDValue RHS, SelectionDAG &DAG,
5019                                       SDLoc dl) {
5020   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5021   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5022   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5023
5024   enum {
5025     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5026     OP_VREV,
5027     OP_VDUP0,
5028     OP_VDUP1,
5029     OP_VDUP2,
5030     OP_VDUP3,
5031     OP_VEXT1,
5032     OP_VEXT2,
5033     OP_VEXT3,
5034     OP_VUZPL, // VUZP, left result
5035     OP_VUZPR, // VUZP, right result
5036     OP_VZIPL, // VZIP, left result
5037     OP_VZIPR, // VZIP, right result
5038     OP_VTRNL, // VTRN, left result
5039     OP_VTRNR  // VTRN, right result
5040   };
5041
5042   if (OpNum == OP_COPY) {
5043     if (LHSID == (1 * 9 + 2) * 9 + 3)
5044       return LHS;
5045     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5046     return RHS;
5047   }
5048
5049   SDValue OpLHS, OpRHS;
5050   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5051   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5052   EVT VT = OpLHS.getValueType();
5053
5054   switch (OpNum) {
5055   default:
5056     llvm_unreachable("Unknown shuffle opcode!");
5057   case OP_VREV:
5058     // VREV divides the vector in half and swaps within the half.
5059     if (VT.getVectorElementType() == MVT::i32 ||
5060         VT.getVectorElementType() == MVT::f32)
5061       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5062     // vrev <4 x i16> -> REV32
5063     if (VT.getVectorElementType() == MVT::i16 ||
5064         VT.getVectorElementType() == MVT::f16)
5065       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5066     // vrev <4 x i8> -> REV16
5067     assert(VT.getVectorElementType() == MVT::i8);
5068     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5069   case OP_VDUP0:
5070   case OP_VDUP1:
5071   case OP_VDUP2:
5072   case OP_VDUP3: {
5073     EVT EltTy = VT.getVectorElementType();
5074     unsigned Opcode;
5075     if (EltTy == MVT::i8)
5076       Opcode = AArch64ISD::DUPLANE8;
5077     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5078       Opcode = AArch64ISD::DUPLANE16;
5079     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5080       Opcode = AArch64ISD::DUPLANE32;
5081     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5082       Opcode = AArch64ISD::DUPLANE64;
5083     else
5084       llvm_unreachable("Invalid vector element type?");
5085
5086     if (VT.getSizeInBits() == 64)
5087       OpLHS = WidenVector(OpLHS, DAG);
5088     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5089     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5090   }
5091   case OP_VEXT1:
5092   case OP_VEXT2:
5093   case OP_VEXT3: {
5094     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5095     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5096                        DAG.getConstant(Imm, dl, MVT::i32));
5097   }
5098   case OP_VUZPL:
5099     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5100                        OpRHS);
5101   case OP_VUZPR:
5102     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5103                        OpRHS);
5104   case OP_VZIPL:
5105     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5106                        OpRHS);
5107   case OP_VZIPR:
5108     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5109                        OpRHS);
5110   case OP_VTRNL:
5111     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5112                        OpRHS);
5113   case OP_VTRNR:
5114     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5115                        OpRHS);
5116   }
5117 }
5118
5119 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5120                            SelectionDAG &DAG) {
5121   // Check to see if we can use the TBL instruction.
5122   SDValue V1 = Op.getOperand(0);
5123   SDValue V2 = Op.getOperand(1);
5124   SDLoc DL(Op);
5125
5126   EVT EltVT = Op.getValueType().getVectorElementType();
5127   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5128
5129   SmallVector<SDValue, 8> TBLMask;
5130   for (int Val : ShuffleMask) {
5131     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5132       unsigned Offset = Byte + Val * BytesPerElt;
5133       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5134     }
5135   }
5136
5137   MVT IndexVT = MVT::v8i8;
5138   unsigned IndexLen = 8;
5139   if (Op.getValueType().getSizeInBits() == 128) {
5140     IndexVT = MVT::v16i8;
5141     IndexLen = 16;
5142   }
5143
5144   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5145   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5146
5147   SDValue Shuffle;
5148   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5149     if (IndexLen == 8)
5150       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5151     Shuffle = DAG.getNode(
5152         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5153         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5154         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5155                     makeArrayRef(TBLMask.data(), IndexLen)));
5156   } else {
5157     if (IndexLen == 8) {
5158       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5159       Shuffle = DAG.getNode(
5160           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5161           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5162           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5163                       makeArrayRef(TBLMask.data(), IndexLen)));
5164     } else {
5165       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5166       // cannot currently represent the register constraints on the input
5167       // table registers.
5168       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5169       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5170       //                               &TBLMask[0], IndexLen));
5171       Shuffle = DAG.getNode(
5172           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5173           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5174           V1Cst, V2Cst,
5175           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5176                       makeArrayRef(TBLMask.data(), IndexLen)));
5177     }
5178   }
5179   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5180 }
5181
5182 static unsigned getDUPLANEOp(EVT EltType) {
5183   if (EltType == MVT::i8)
5184     return AArch64ISD::DUPLANE8;
5185   if (EltType == MVT::i16 || EltType == MVT::f16)
5186     return AArch64ISD::DUPLANE16;
5187   if (EltType == MVT::i32 || EltType == MVT::f32)
5188     return AArch64ISD::DUPLANE32;
5189   if (EltType == MVT::i64 || EltType == MVT::f64)
5190     return AArch64ISD::DUPLANE64;
5191
5192   llvm_unreachable("Invalid vector element type?");
5193 }
5194
5195 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5196                                                    SelectionDAG &DAG) const {
5197   SDLoc dl(Op);
5198   EVT VT = Op.getValueType();
5199
5200   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5201
5202   // Convert shuffles that are directly supported on NEON to target-specific
5203   // DAG nodes, instead of keeping them as shuffles and matching them again
5204   // during code selection.  This is more efficient and avoids the possibility
5205   // of inconsistencies between legalization and selection.
5206   ArrayRef<int> ShuffleMask = SVN->getMask();
5207
5208   SDValue V1 = Op.getOperand(0);
5209   SDValue V2 = Op.getOperand(1);
5210
5211   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5212                                        V1.getValueType().getSimpleVT())) {
5213     int Lane = SVN->getSplatIndex();
5214     // If this is undef splat, generate it via "just" vdup, if possible.
5215     if (Lane == -1)
5216       Lane = 0;
5217
5218     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5219       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5220                          V1.getOperand(0));
5221     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5222     // constant. If so, we can just reference the lane's definition directly.
5223     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5224         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5225       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5226
5227     // Otherwise, duplicate from the lane of the input vector.
5228     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5229
5230     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5231     // to make a vector of the same size as this SHUFFLE. We can ignore the
5232     // extract entirely, and canonicalise the concat using WidenVector.
5233     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5234       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5235       V1 = V1.getOperand(0);
5236     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5237       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5238       Lane -= Idx * VT.getVectorNumElements() / 2;
5239       V1 = WidenVector(V1.getOperand(Idx), DAG);
5240     } else if (VT.getSizeInBits() == 64)
5241       V1 = WidenVector(V1, DAG);
5242
5243     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5244   }
5245
5246   if (isREVMask(ShuffleMask, VT, 64))
5247     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5248   if (isREVMask(ShuffleMask, VT, 32))
5249     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5250   if (isREVMask(ShuffleMask, VT, 16))
5251     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5252
5253   bool ReverseEXT = false;
5254   unsigned Imm;
5255   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5256     if (ReverseEXT)
5257       std::swap(V1, V2);
5258     Imm *= getExtFactor(V1);
5259     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5260                        DAG.getConstant(Imm, dl, MVT::i32));
5261   } else if (V2->getOpcode() == ISD::UNDEF &&
5262              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5263     Imm *= getExtFactor(V1);
5264     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5265                        DAG.getConstant(Imm, dl, MVT::i32));
5266   }
5267
5268   unsigned WhichResult;
5269   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5270     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5271     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5272   }
5273   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5274     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5275     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5276   }
5277   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5278     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5279     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5280   }
5281
5282   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5283     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5284     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5285   }
5286   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5287     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5288     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5289   }
5290   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5291     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5292     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5293   }
5294
5295   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5296   if (Concat.getNode())
5297     return Concat;
5298
5299   bool DstIsLeft;
5300   int Anomaly;
5301   int NumInputElements = V1.getValueType().getVectorNumElements();
5302   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5303     SDValue DstVec = DstIsLeft ? V1 : V2;
5304     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5305
5306     SDValue SrcVec = V1;
5307     int SrcLane = ShuffleMask[Anomaly];
5308     if (SrcLane >= NumInputElements) {
5309       SrcVec = V2;
5310       SrcLane -= VT.getVectorNumElements();
5311     }
5312     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5313
5314     EVT ScalarVT = VT.getVectorElementType();
5315
5316     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5317       ScalarVT = MVT::i32;
5318
5319     return DAG.getNode(
5320         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5321         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5322         DstLaneV);
5323   }
5324
5325   // If the shuffle is not directly supported and it has 4 elements, use
5326   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5327   unsigned NumElts = VT.getVectorNumElements();
5328   if (NumElts == 4) {
5329     unsigned PFIndexes[4];
5330     for (unsigned i = 0; i != 4; ++i) {
5331       if (ShuffleMask[i] < 0)
5332         PFIndexes[i] = 8;
5333       else
5334         PFIndexes[i] = ShuffleMask[i];
5335     }
5336
5337     // Compute the index in the perfect shuffle table.
5338     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5339                             PFIndexes[2] * 9 + PFIndexes[3];
5340     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5341     unsigned Cost = (PFEntry >> 30);
5342
5343     if (Cost <= 4)
5344       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5345   }
5346
5347   return GenerateTBL(Op, ShuffleMask, DAG);
5348 }
5349
5350 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5351                                APInt &UndefBits) {
5352   EVT VT = BVN->getValueType(0);
5353   APInt SplatBits, SplatUndef;
5354   unsigned SplatBitSize;
5355   bool HasAnyUndefs;
5356   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5357     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5358
5359     for (unsigned i = 0; i < NumSplats; ++i) {
5360       CnstBits <<= SplatBitSize;
5361       UndefBits <<= SplatBitSize;
5362       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5363       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5364     }
5365
5366     return true;
5367   }
5368
5369   return false;
5370 }
5371
5372 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5373                                               SelectionDAG &DAG) const {
5374   BuildVectorSDNode *BVN =
5375       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5376   SDValue LHS = Op.getOperand(0);
5377   SDLoc dl(Op);
5378   EVT VT = Op.getValueType();
5379
5380   if (!BVN)
5381     return Op;
5382
5383   APInt CnstBits(VT.getSizeInBits(), 0);
5384   APInt UndefBits(VT.getSizeInBits(), 0);
5385   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5386     // We only have BIC vector immediate instruction, which is and-not.
5387     CnstBits = ~CnstBits;
5388
5389     // We make use of a little bit of goto ickiness in order to avoid having to
5390     // duplicate the immediate matching logic for the undef toggled case.
5391     bool SecondTry = false;
5392   AttemptModImm:
5393
5394     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5395       CnstBits = CnstBits.zextOrTrunc(64);
5396       uint64_t CnstVal = CnstBits.getZExtValue();
5397
5398       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5399         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5400         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5401         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5402                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5403                                   DAG.getConstant(0, dl, MVT::i32));
5404         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5405       }
5406
5407       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5408         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5409         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5410         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5411                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5412                                   DAG.getConstant(8, dl, MVT::i32));
5413         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5414       }
5415
5416       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5417         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5418         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5419         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5420                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5421                                   DAG.getConstant(16, dl, MVT::i32));
5422         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5423       }
5424
5425       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5426         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5427         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5428         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5429                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5430                                   DAG.getConstant(24, dl, MVT::i32));
5431         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5432       }
5433
5434       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5435         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5436         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5437         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5438                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5439                                   DAG.getConstant(0, dl, MVT::i32));
5440         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5441       }
5442
5443       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5444         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5445         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5446         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5447                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5448                                   DAG.getConstant(8, dl, MVT::i32));
5449         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5450       }
5451     }
5452
5453     if (SecondTry)
5454       goto FailedModImm;
5455     SecondTry = true;
5456     CnstBits = ~UndefBits;
5457     goto AttemptModImm;
5458   }
5459
5460 // We can always fall back to a non-immediate AND.
5461 FailedModImm:
5462   return Op;
5463 }
5464
5465 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5466 // consists of only the same constant int value, returned in reference arg
5467 // ConstVal
5468 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5469                                      uint64_t &ConstVal) {
5470   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5471   if (!Bvec)
5472     return false;
5473   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5474   if (!FirstElt)
5475     return false;
5476   EVT VT = Bvec->getValueType(0);
5477   unsigned NumElts = VT.getVectorNumElements();
5478   for (unsigned i = 1; i < NumElts; ++i)
5479     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5480       return false;
5481   ConstVal = FirstElt->getZExtValue();
5482   return true;
5483 }
5484
5485 static unsigned getIntrinsicID(const SDNode *N) {
5486   unsigned Opcode = N->getOpcode();
5487   switch (Opcode) {
5488   default:
5489     return Intrinsic::not_intrinsic;
5490   case ISD::INTRINSIC_WO_CHAIN: {
5491     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5492     if (IID < Intrinsic::num_intrinsics)
5493       return IID;
5494     return Intrinsic::not_intrinsic;
5495   }
5496   }
5497 }
5498
5499 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5500 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5501 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5502 // Also, logical shift right -> sri, with the same structure.
5503 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5504   EVT VT = N->getValueType(0);
5505
5506   if (!VT.isVector())
5507     return SDValue();
5508
5509   SDLoc DL(N);
5510
5511   // Is the first op an AND?
5512   const SDValue And = N->getOperand(0);
5513   if (And.getOpcode() != ISD::AND)
5514     return SDValue();
5515
5516   // Is the second op an shl or lshr?
5517   SDValue Shift = N->getOperand(1);
5518   // This will have been turned into: AArch64ISD::VSHL vector, #shift
5519   // or AArch64ISD::VLSHR vector, #shift
5520   unsigned ShiftOpc = Shift.getOpcode();
5521   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5522     return SDValue();
5523   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5524
5525   // Is the shift amount constant?
5526   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5527   if (!C2node)
5528     return SDValue();
5529
5530   // Is the and mask vector all constant?
5531   uint64_t C1;
5532   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5533     return SDValue();
5534
5535   // Is C1 == ~C2, taking into account how much one can shift elements of a
5536   // particular size?
5537   uint64_t C2 = C2node->getZExtValue();
5538   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5539   if (C2 > ElemSizeInBits)
5540     return SDValue();
5541   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5542   if ((C1 & ElemMask) != (~C2 & ElemMask))
5543     return SDValue();
5544
5545   SDValue X = And.getOperand(0);
5546   SDValue Y = Shift.getOperand(0);
5547
5548   unsigned Intrin =
5549       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5550   SDValue ResultSLI =
5551       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5552                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5553                   Shift.getOperand(1));
5554
5555   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5556   DEBUG(N->dump(&DAG));
5557   DEBUG(dbgs() << "into: \n");
5558   DEBUG(ResultSLI->dump(&DAG));
5559
5560   ++NumShiftInserts;
5561   return ResultSLI;
5562 }
5563
5564 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5565                                              SelectionDAG &DAG) const {
5566   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5567   if (EnableAArch64SlrGeneration) {
5568     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5569     if (Res.getNode())
5570       return Res;
5571   }
5572
5573   BuildVectorSDNode *BVN =
5574       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5575   SDValue LHS = Op.getOperand(1);
5576   SDLoc dl(Op);
5577   EVT VT = Op.getValueType();
5578
5579   // OR commutes, so try swapping the operands.
5580   if (!BVN) {
5581     LHS = Op.getOperand(0);
5582     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5583   }
5584   if (!BVN)
5585     return Op;
5586
5587   APInt CnstBits(VT.getSizeInBits(), 0);
5588   APInt UndefBits(VT.getSizeInBits(), 0);
5589   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5590     // We make use of a little bit of goto ickiness in order to avoid having to
5591     // duplicate the immediate matching logic for the undef toggled case.
5592     bool SecondTry = false;
5593   AttemptModImm:
5594
5595     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5596       CnstBits = CnstBits.zextOrTrunc(64);
5597       uint64_t CnstVal = CnstBits.getZExtValue();
5598
5599       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5600         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5601         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5602         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5603                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5604                                   DAG.getConstant(0, dl, MVT::i32));
5605         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5606       }
5607
5608       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5609         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5610         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5611         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5612                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5613                                   DAG.getConstant(8, dl, MVT::i32));
5614         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5615       }
5616
5617       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5618         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5619         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5620         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5621                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5622                                   DAG.getConstant(16, dl, MVT::i32));
5623         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5624       }
5625
5626       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5627         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5628         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5629         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5630                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5631                                   DAG.getConstant(24, dl, MVT::i32));
5632         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5633       }
5634
5635       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5636         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5637         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5638         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5639                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5640                                   DAG.getConstant(0, dl, MVT::i32));
5641         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5642       }
5643
5644       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5645         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5646         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5647         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5648                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5649                                   DAG.getConstant(8, dl, MVT::i32));
5650         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5651       }
5652     }
5653
5654     if (SecondTry)
5655       goto FailedModImm;
5656     SecondTry = true;
5657     CnstBits = UndefBits;
5658     goto AttemptModImm;
5659   }
5660
5661 // We can always fall back to a non-immediate OR.
5662 FailedModImm:
5663   return Op;
5664 }
5665
5666 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5667 // be truncated to fit element width.
5668 static SDValue NormalizeBuildVector(SDValue Op,
5669                                     SelectionDAG &DAG) {
5670   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5671   SDLoc dl(Op);
5672   EVT VT = Op.getValueType();
5673   EVT EltTy= VT.getVectorElementType();
5674
5675   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5676     return Op;
5677
5678   SmallVector<SDValue, 16> Ops;
5679   for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5680     SDValue Lane = Op.getOperand(I);
5681     if (Lane.getOpcode() == ISD::Constant) {
5682       APInt LowBits(EltTy.getSizeInBits(),
5683                     cast<ConstantSDNode>(Lane)->getZExtValue());
5684       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5685     }
5686     Ops.push_back(Lane);
5687   }
5688   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5689 }
5690
5691 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5692                                                  SelectionDAG &DAG) const {
5693   SDLoc dl(Op);
5694   EVT VT = Op.getValueType();
5695   Op = NormalizeBuildVector(Op, DAG);
5696   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5697
5698   APInt CnstBits(VT.getSizeInBits(), 0);
5699   APInt UndefBits(VT.getSizeInBits(), 0);
5700   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5701     // We make use of a little bit of goto ickiness in order to avoid having to
5702     // duplicate the immediate matching logic for the undef toggled case.
5703     bool SecondTry = false;
5704   AttemptModImm:
5705
5706     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5707       CnstBits = CnstBits.zextOrTrunc(64);
5708       uint64_t CnstVal = CnstBits.getZExtValue();
5709
5710       // Certain magic vector constants (used to express things like NOT
5711       // and NEG) are passed through unmodified.  This allows codegen patterns
5712       // for these operations to match.  Special-purpose patterns will lower
5713       // these immediates to MOVIs if it proves necessary.
5714       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5715         return Op;
5716
5717       // The many faces of MOVI...
5718       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5719         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5720         if (VT.getSizeInBits() == 128) {
5721           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5722                                     DAG.getConstant(CnstVal, dl, MVT::i32));
5723           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5724         }
5725
5726         // Support the V64 version via subregister insertion.
5727         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5728                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5729         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5730       }
5731
5732       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5733         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5734         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5735         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5736                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5737                                   DAG.getConstant(0, dl, MVT::i32));
5738         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5739       }
5740
5741       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5742         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5743         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5744         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5745                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5746                                   DAG.getConstant(8, dl, MVT::i32));
5747         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5748       }
5749
5750       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5751         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5752         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5753         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5754                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5755                                   DAG.getConstant(16, dl, MVT::i32));
5756         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5757       }
5758
5759       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5760         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5761         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5762         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5763                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5764                                   DAG.getConstant(24, dl, MVT::i32));
5765         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5766       }
5767
5768       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5769         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5770         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5771         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5772                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5773                                   DAG.getConstant(0, dl, MVT::i32));
5774         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5775       }
5776
5777       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5778         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5779         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5780         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5781                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5782                                   DAG.getConstant(8, dl, MVT::i32));
5783         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5784       }
5785
5786       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5787         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5788         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5789         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5790                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5791                                   DAG.getConstant(264, dl, MVT::i32));
5792         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5793       }
5794
5795       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5796         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5797         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5798         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5799                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5800                                   DAG.getConstant(272, dl, MVT::i32));
5801         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5802       }
5803
5804       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5805         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5806         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5807         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5808                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5809         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5810       }
5811
5812       // The few faces of FMOV...
5813       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5814         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5815         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5816         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5817                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5818         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5819       }
5820
5821       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5822           VT.getSizeInBits() == 128) {
5823         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5824         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5825                                   DAG.getConstant(CnstVal, dl, MVT::i32));
5826         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5827       }
5828
5829       // The many faces of MVNI...
5830       CnstVal = ~CnstVal;
5831       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5832         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5833         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5834         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5835                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5836                                   DAG.getConstant(0, dl, MVT::i32));
5837         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5838       }
5839
5840       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5841         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5842         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5843         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5844                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5845                                   DAG.getConstant(8, dl, MVT::i32));
5846         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5847       }
5848
5849       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5850         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5851         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5852         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5853                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5854                                   DAG.getConstant(16, dl, MVT::i32));
5855         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5856       }
5857
5858       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5859         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5860         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5861         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5862                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5863                                   DAG.getConstant(24, dl, MVT::i32));
5864         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5865       }
5866
5867       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5868         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5869         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5870         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5871                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5872                                   DAG.getConstant(0, dl, MVT::i32));
5873         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5874       }
5875
5876       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5877         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5878         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5879         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5880                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5881                                   DAG.getConstant(8, dl, MVT::i32));
5882         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5883       }
5884
5885       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5886         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5887         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5888         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5889                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5890                                   DAG.getConstant(264, dl, MVT::i32));
5891         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5892       }
5893
5894       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5895         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5896         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5897         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5898                                   DAG.getConstant(CnstVal, dl, MVT::i32),
5899                                   DAG.getConstant(272, dl, MVT::i32));
5900         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5901       }
5902     }
5903
5904     if (SecondTry)
5905       goto FailedModImm;
5906     SecondTry = true;
5907     CnstBits = UndefBits;
5908     goto AttemptModImm;
5909   }
5910 FailedModImm:
5911
5912   // Scan through the operands to find some interesting properties we can
5913   // exploit:
5914   //   1) If only one value is used, we can use a DUP, or
5915   //   2) if only the low element is not undef, we can just insert that, or
5916   //   3) if only one constant value is used (w/ some non-constant lanes),
5917   //      we can splat the constant value into the whole vector then fill
5918   //      in the non-constant lanes.
5919   //   4) FIXME: If different constant values are used, but we can intelligently
5920   //             select the values we'll be overwriting for the non-constant
5921   //             lanes such that we can directly materialize the vector
5922   //             some other way (MOVI, e.g.), we can be sneaky.
5923   unsigned NumElts = VT.getVectorNumElements();
5924   bool isOnlyLowElement = true;
5925   bool usesOnlyOneValue = true;
5926   bool usesOnlyOneConstantValue = true;
5927   bool isConstant = true;
5928   unsigned NumConstantLanes = 0;
5929   SDValue Value;
5930   SDValue ConstantValue;
5931   for (unsigned i = 0; i < NumElts; ++i) {
5932     SDValue V = Op.getOperand(i);
5933     if (V.getOpcode() == ISD::UNDEF)
5934       continue;
5935     if (i > 0)
5936       isOnlyLowElement = false;
5937     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5938       isConstant = false;
5939
5940     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5941       ++NumConstantLanes;
5942       if (!ConstantValue.getNode())
5943         ConstantValue = V;
5944       else if (ConstantValue != V)
5945         usesOnlyOneConstantValue = false;
5946     }
5947
5948     if (!Value.getNode())
5949       Value = V;
5950     else if (V != Value)
5951       usesOnlyOneValue = false;
5952   }
5953
5954   if (!Value.getNode())
5955     return DAG.getUNDEF(VT);
5956
5957   if (isOnlyLowElement)
5958     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5959
5960   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
5961   // i32 and try again.
5962   if (usesOnlyOneValue) {
5963     if (!isConstant) {
5964       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5965           Value.getValueType() != VT)
5966         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5967
5968       // This is actually a DUPLANExx operation, which keeps everything vectory.
5969
5970       // DUPLANE works on 128-bit vectors, widen it if necessary.
5971       SDValue Lane = Value.getOperand(1);
5972       Value = Value.getOperand(0);
5973       if (Value.getValueType().getSizeInBits() == 64)
5974         Value = WidenVector(Value, DAG);
5975
5976       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5977       return DAG.getNode(Opcode, dl, VT, Value, Lane);
5978     }
5979
5980     if (VT.getVectorElementType().isFloatingPoint()) {
5981       SmallVector<SDValue, 8> Ops;
5982       EVT EltTy = VT.getVectorElementType();
5983       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
5984               "Unsupported floating-point vector type");
5985       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
5986       for (unsigned i = 0; i < NumElts; ++i)
5987         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5988       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5989       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5990       Val = LowerBUILD_VECTOR(Val, DAG);
5991       if (Val.getNode())
5992         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5993     }
5994   }
5995
5996   // If there was only one constant value used and for more than one lane,
5997   // start by splatting that value, then replace the non-constant lanes. This
5998   // is better than the default, which will perform a separate initialization
5999   // for each lane.
6000   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6001     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6002     // Now insert the non-constant lanes.
6003     for (unsigned i = 0; i < NumElts; ++i) {
6004       SDValue V = Op.getOperand(i);
6005       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6006       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6007         // Note that type legalization likely mucked about with the VT of the
6008         // source operand, so we may have to convert it here before inserting.
6009         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6010       }
6011     }
6012     return Val;
6013   }
6014
6015   // If all elements are constants and the case above didn't get hit, fall back
6016   // to the default expansion, which will generate a load from the constant
6017   // pool.
6018   if (isConstant)
6019     return SDValue();
6020
6021   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6022   if (NumElts >= 4) {
6023     SDValue shuffle = ReconstructShuffle(Op, DAG);
6024     if (shuffle != SDValue())
6025       return shuffle;
6026   }
6027
6028   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6029   // know the default expansion would otherwise fall back on something even
6030   // worse. For a vector with one or two non-undef values, that's
6031   // scalar_to_vector for the elements followed by a shuffle (provided the
6032   // shuffle is valid for the target) and materialization element by element
6033   // on the stack followed by a load for everything else.
6034   if (!isConstant && !usesOnlyOneValue) {
6035     SDValue Vec = DAG.getUNDEF(VT);
6036     SDValue Op0 = Op.getOperand(0);
6037     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6038     unsigned i = 0;
6039     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6040     // a) Avoid a RMW dependency on the full vector register, and
6041     // b) Allow the register coalescer to fold away the copy if the
6042     //    value is already in an S or D register.
6043     if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6044       unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6045       MachineSDNode *N =
6046           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6047                              DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6048       Vec = SDValue(N, 0);
6049       ++i;
6050     }
6051     for (; i < NumElts; ++i) {
6052       SDValue V = Op.getOperand(i);
6053       if (V.getOpcode() == ISD::UNDEF)
6054         continue;
6055       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6056       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6057     }
6058     return Vec;
6059   }
6060
6061   // Just use the default expansion. We failed to find a better alternative.
6062   return SDValue();
6063 }
6064
6065 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6066                                                       SelectionDAG &DAG) const {
6067   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6068
6069   // Check for non-constant or out of range lane.
6070   EVT VT = Op.getOperand(0).getValueType();
6071   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6072   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6073     return SDValue();
6074
6075
6076   // Insertion/extraction are legal for V128 types.
6077   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6078       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6079       VT == MVT::v8f16)
6080     return Op;
6081
6082   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6083       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6084     return SDValue();
6085
6086   // For V64 types, we perform insertion by expanding the value
6087   // to a V128 type and perform the insertion on that.
6088   SDLoc DL(Op);
6089   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6090   EVT WideTy = WideVec.getValueType();
6091
6092   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6093                              Op.getOperand(1), Op.getOperand(2));
6094   // Re-narrow the resultant vector.
6095   return NarrowVector(Node, DAG);
6096 }
6097
6098 SDValue
6099 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6100                                                SelectionDAG &DAG) const {
6101   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6102
6103   // Check for non-constant or out of range lane.
6104   EVT VT = Op.getOperand(0).getValueType();
6105   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6106   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6107     return SDValue();
6108
6109
6110   // Insertion/extraction are legal for V128 types.
6111   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6112       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6113       VT == MVT::v8f16)
6114     return Op;
6115
6116   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6117       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6118     return SDValue();
6119
6120   // For V64 types, we perform extraction by expanding the value
6121   // to a V128 type and perform the extraction on that.
6122   SDLoc DL(Op);
6123   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6124   EVT WideTy = WideVec.getValueType();
6125
6126   EVT ExtrTy = WideTy.getVectorElementType();
6127   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6128     ExtrTy = MVT::i32;
6129
6130   // For extractions, we just return the result directly.
6131   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6132                      Op.getOperand(1));
6133 }
6134
6135 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6136                                                       SelectionDAG &DAG) const {
6137   EVT VT = Op.getOperand(0).getValueType();
6138   SDLoc dl(Op);
6139   // Just in case...
6140   if (!VT.isVector())
6141     return SDValue();
6142
6143   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6144   if (!Cst)
6145     return SDValue();
6146   unsigned Val = Cst->getZExtValue();
6147
6148   unsigned Size = Op.getValueType().getSizeInBits();
6149   if (Val == 0) {
6150     switch (Size) {
6151     case 8:
6152       return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6153                                         Op.getOperand(0));
6154     case 16:
6155       return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6156                                         Op.getOperand(0));
6157     case 32:
6158       return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6159                                         Op.getOperand(0));
6160     case 64:
6161       return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6162                                         Op.getOperand(0));
6163     default:
6164       llvm_unreachable("Unexpected vector type in extract_subvector!");
6165     }
6166   }
6167   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6168   // that directly.
6169   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6170     return Op;
6171
6172   return SDValue();
6173 }
6174
6175 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6176                                                EVT VT) const {
6177   if (VT.getVectorNumElements() == 4 &&
6178       (VT.is128BitVector() || VT.is64BitVector())) {
6179     unsigned PFIndexes[4];
6180     for (unsigned i = 0; i != 4; ++i) {
6181       if (M[i] < 0)
6182         PFIndexes[i] = 8;
6183       else
6184         PFIndexes[i] = M[i];
6185     }
6186
6187     // Compute the index in the perfect shuffle table.
6188     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6189                             PFIndexes[2] * 9 + PFIndexes[3];
6190     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6191     unsigned Cost = (PFEntry >> 30);
6192
6193     if (Cost <= 4)
6194       return true;
6195   }
6196
6197   bool DummyBool;
6198   int DummyInt;
6199   unsigned DummyUnsigned;
6200
6201   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6202           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6203           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6204           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6205           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6206           isZIPMask(M, VT, DummyUnsigned) ||
6207           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6208           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6209           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6210           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6211           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6212 }
6213
6214 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6215 /// operand of a vector shift operation, where all the elements of the
6216 /// build_vector must have the same constant integer value.
6217 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6218   // Ignore bit_converts.
6219   while (Op.getOpcode() == ISD::BITCAST)
6220     Op = Op.getOperand(0);
6221   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6222   APInt SplatBits, SplatUndef;
6223   unsigned SplatBitSize;
6224   bool HasAnyUndefs;
6225   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6226                                     HasAnyUndefs, ElementBits) ||
6227       SplatBitSize > ElementBits)
6228     return false;
6229   Cnt = SplatBits.getSExtValue();
6230   return true;
6231 }
6232
6233 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6234 /// operand of a vector shift left operation.  That value must be in the range:
6235 ///   0 <= Value < ElementBits for a left shift; or
6236 ///   0 <= Value <= ElementBits for a long left shift.
6237 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6238   assert(VT.isVector() && "vector shift count is not a vector type");
6239   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6240   if (!getVShiftImm(Op, ElementBits, Cnt))
6241     return false;
6242   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6243 }
6244
6245 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6246 /// operand of a vector shift right operation.  For a shift opcode, the value
6247 /// is positive, but for an intrinsic the value count must be negative. The
6248 /// absolute value must be in the range:
6249 ///   1 <= |Value| <= ElementBits for a right shift; or
6250 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6251 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6252                          int64_t &Cnt) {
6253   assert(VT.isVector() && "vector shift count is not a vector type");
6254   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6255   if (!getVShiftImm(Op, ElementBits, Cnt))
6256     return false;
6257   if (isIntrinsic)
6258     Cnt = -Cnt;
6259   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6260 }
6261
6262 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6263                                                       SelectionDAG &DAG) const {
6264   EVT VT = Op.getValueType();
6265   SDLoc DL(Op);
6266   int64_t Cnt;
6267
6268   if (!Op.getOperand(1).getValueType().isVector())
6269     return Op;
6270   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6271
6272   switch (Op.getOpcode()) {
6273   default:
6274     llvm_unreachable("unexpected shift opcode");
6275
6276   case ISD::SHL:
6277     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6278       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6279                          DAG.getConstant(Cnt, DL, MVT::i32));
6280     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6281                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6282                                        MVT::i32),
6283                        Op.getOperand(0), Op.getOperand(1));
6284   case ISD::SRA:
6285   case ISD::SRL:
6286     // Right shift immediate
6287     if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6288         Cnt < EltSize) {
6289       unsigned Opc =
6290           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6291       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6292                          DAG.getConstant(Cnt, DL, MVT::i32));
6293     }
6294
6295     // Right shift register.  Note, there is not a shift right register
6296     // instruction, but the shift left register instruction takes a signed
6297     // value, where negative numbers specify a right shift.
6298     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6299                                                 : Intrinsic::aarch64_neon_ushl;
6300     // negate the shift amount
6301     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6302     SDValue NegShiftLeft =
6303         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6304                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6305                     NegShift);
6306     return NegShiftLeft;
6307   }
6308
6309   return SDValue();
6310 }
6311
6312 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6313                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
6314                                     SDLoc dl, SelectionDAG &DAG) {
6315   EVT SrcVT = LHS.getValueType();
6316   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6317          "function only supposed to emit natural comparisons");
6318
6319   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6320   APInt CnstBits(VT.getSizeInBits(), 0);
6321   APInt UndefBits(VT.getSizeInBits(), 0);
6322   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6323   bool IsZero = IsCnst && (CnstBits == 0);
6324
6325   if (SrcVT.getVectorElementType().isFloatingPoint()) {
6326     switch (CC) {
6327     default:
6328       return SDValue();
6329     case AArch64CC::NE: {
6330       SDValue Fcmeq;
6331       if (IsZero)
6332         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6333       else
6334         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6335       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6336     }
6337     case AArch64CC::EQ:
6338       if (IsZero)
6339         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6340       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6341     case AArch64CC::GE:
6342       if (IsZero)
6343         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6344       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6345     case AArch64CC::GT:
6346       if (IsZero)
6347         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6348       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6349     case AArch64CC::LS:
6350       if (IsZero)
6351         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6352       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6353     case AArch64CC::LT:
6354       if (!NoNans)
6355         return SDValue();
6356     // If we ignore NaNs then we can use to the MI implementation.
6357     // Fallthrough.
6358     case AArch64CC::MI:
6359       if (IsZero)
6360         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6361       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6362     }
6363   }
6364
6365   switch (CC) {
6366   default:
6367     return SDValue();
6368   case AArch64CC::NE: {
6369     SDValue Cmeq;
6370     if (IsZero)
6371       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6372     else
6373       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6374     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6375   }
6376   case AArch64CC::EQ:
6377     if (IsZero)
6378       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6379     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6380   case AArch64CC::GE:
6381     if (IsZero)
6382       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6383     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6384   case AArch64CC::GT:
6385     if (IsZero)
6386       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6387     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6388   case AArch64CC::LE:
6389     if (IsZero)
6390       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6391     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6392   case AArch64CC::LS:
6393     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6394   case AArch64CC::LO:
6395     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6396   case AArch64CC::LT:
6397     if (IsZero)
6398       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6399     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6400   case AArch64CC::HI:
6401     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6402   case AArch64CC::HS:
6403     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6404   }
6405 }
6406
6407 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6408                                            SelectionDAG &DAG) const {
6409   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6410   SDValue LHS = Op.getOperand(0);
6411   SDValue RHS = Op.getOperand(1);
6412   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6413   SDLoc dl(Op);
6414
6415   if (LHS.getValueType().getVectorElementType().isInteger()) {
6416     assert(LHS.getValueType() == RHS.getValueType());
6417     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6418     SDValue Cmp =
6419         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6420     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6421   }
6422
6423   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6424          LHS.getValueType().getVectorElementType() == MVT::f64);
6425
6426   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6427   // clean.  Some of them require two branches to implement.
6428   AArch64CC::CondCode CC1, CC2;
6429   bool ShouldInvert;
6430   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6431
6432   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6433   SDValue Cmp =
6434       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6435   if (!Cmp.getNode())
6436     return SDValue();
6437
6438   if (CC2 != AArch64CC::AL) {
6439     SDValue Cmp2 =
6440         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6441     if (!Cmp2.getNode())
6442       return SDValue();
6443
6444     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6445   }
6446
6447   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6448
6449   if (ShouldInvert)
6450     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6451
6452   return Cmp;
6453 }
6454
6455 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6456 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
6457 /// specified in the intrinsic calls.
6458 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6459                                                const CallInst &I,
6460                                                unsigned Intrinsic) const {
6461   switch (Intrinsic) {
6462   case Intrinsic::aarch64_neon_ld2:
6463   case Intrinsic::aarch64_neon_ld3:
6464   case Intrinsic::aarch64_neon_ld4:
6465   case Intrinsic::aarch64_neon_ld1x2:
6466   case Intrinsic::aarch64_neon_ld1x3:
6467   case Intrinsic::aarch64_neon_ld1x4:
6468   case Intrinsic::aarch64_neon_ld2lane:
6469   case Intrinsic::aarch64_neon_ld3lane:
6470   case Intrinsic::aarch64_neon_ld4lane:
6471   case Intrinsic::aarch64_neon_ld2r:
6472   case Intrinsic::aarch64_neon_ld3r:
6473   case Intrinsic::aarch64_neon_ld4r: {
6474     Info.opc = ISD::INTRINSIC_W_CHAIN;
6475     // Conservatively set memVT to the entire set of vectors loaded.
6476     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6477     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6478     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6479     Info.offset = 0;
6480     Info.align = 0;
6481     Info.vol = false; // volatile loads with NEON intrinsics not supported
6482     Info.readMem = true;
6483     Info.writeMem = false;
6484     return true;
6485   }
6486   case Intrinsic::aarch64_neon_st2:
6487   case Intrinsic::aarch64_neon_st3:
6488   case Intrinsic::aarch64_neon_st4:
6489   case Intrinsic::aarch64_neon_st1x2:
6490   case Intrinsic::aarch64_neon_st1x3:
6491   case Intrinsic::aarch64_neon_st1x4:
6492   case Intrinsic::aarch64_neon_st2lane:
6493   case Intrinsic::aarch64_neon_st3lane:
6494   case Intrinsic::aarch64_neon_st4lane: {
6495     Info.opc = ISD::INTRINSIC_VOID;
6496     // Conservatively set memVT to the entire set of vectors stored.
6497     unsigned NumElts = 0;
6498     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6499       Type *ArgTy = I.getArgOperand(ArgI)->getType();
6500       if (!ArgTy->isVectorTy())
6501         break;
6502       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6503     }
6504     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6505     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6506     Info.offset = 0;
6507     Info.align = 0;
6508     Info.vol = false; // volatile stores with NEON intrinsics not supported
6509     Info.readMem = false;
6510     Info.writeMem = true;
6511     return true;
6512   }
6513   case Intrinsic::aarch64_ldaxr:
6514   case Intrinsic::aarch64_ldxr: {
6515     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6516     Info.opc = ISD::INTRINSIC_W_CHAIN;
6517     Info.memVT = MVT::getVT(PtrTy->getElementType());
6518     Info.ptrVal = I.getArgOperand(0);
6519     Info.offset = 0;
6520     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6521     Info.vol = true;
6522     Info.readMem = true;
6523     Info.writeMem = false;
6524     return true;
6525   }
6526   case Intrinsic::aarch64_stlxr:
6527   case Intrinsic::aarch64_stxr: {
6528     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6529     Info.opc = ISD::INTRINSIC_W_CHAIN;
6530     Info.memVT = MVT::getVT(PtrTy->getElementType());
6531     Info.ptrVal = I.getArgOperand(1);
6532     Info.offset = 0;
6533     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6534     Info.vol = true;
6535     Info.readMem = false;
6536     Info.writeMem = true;
6537     return true;
6538   }
6539   case Intrinsic::aarch64_ldaxp:
6540   case Intrinsic::aarch64_ldxp: {
6541     Info.opc = ISD::INTRINSIC_W_CHAIN;
6542     Info.memVT = MVT::i128;
6543     Info.ptrVal = I.getArgOperand(0);
6544     Info.offset = 0;
6545     Info.align = 16;
6546     Info.vol = true;
6547     Info.readMem = true;
6548     Info.writeMem = false;
6549     return true;
6550   }
6551   case Intrinsic::aarch64_stlxp:
6552   case Intrinsic::aarch64_stxp: {
6553     Info.opc = ISD::INTRINSIC_W_CHAIN;
6554     Info.memVT = MVT::i128;
6555     Info.ptrVal = I.getArgOperand(2);
6556     Info.offset = 0;
6557     Info.align = 16;
6558     Info.vol = true;
6559     Info.readMem = false;
6560     Info.writeMem = true;
6561     return true;
6562   }
6563   default:
6564     break;
6565   }
6566
6567   return false;
6568 }
6569
6570 // Truncations from 64-bit GPR to 32-bit GPR is free.
6571 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6572   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6573     return false;
6574   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6575   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6576   return NumBits1 > NumBits2;
6577 }
6578 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6579   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6580     return false;
6581   unsigned NumBits1 = VT1.getSizeInBits();
6582   unsigned NumBits2 = VT2.getSizeInBits();
6583   return NumBits1 > NumBits2;
6584 }
6585
6586 /// Check if it is profitable to hoist instruction in then/else to if.
6587 /// Not profitable if I and it's user can form a FMA instruction
6588 /// because we prefer FMSUB/FMADD.
6589 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6590   if (I->getOpcode() != Instruction::FMul)
6591     return true;
6592
6593   if (I->getNumUses() != 1)
6594     return true;
6595
6596   Instruction *User = I->user_back();
6597
6598   if (User &&
6599       !(User->getOpcode() == Instruction::FSub ||
6600         User->getOpcode() == Instruction::FAdd))
6601     return true;
6602
6603   const TargetOptions &Options = getTargetMachine().Options;
6604   EVT VT = getValueType(User->getOperand(0)->getType());
6605
6606   if (isFMAFasterThanFMulAndFAdd(VT) &&
6607       isOperationLegalOrCustom(ISD::FMA, VT) &&
6608       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6609     return false;
6610
6611   return true;
6612 }
6613
6614 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6615 // 64-bit GPR.
6616 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6617   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6618     return false;
6619   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6620   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6621   return NumBits1 == 32 && NumBits2 == 64;
6622 }
6623 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6624   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6625     return false;
6626   unsigned NumBits1 = VT1.getSizeInBits();
6627   unsigned NumBits2 = VT2.getSizeInBits();
6628   return NumBits1 == 32 && NumBits2 == 64;
6629 }
6630
6631 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6632   EVT VT1 = Val.getValueType();
6633   if (isZExtFree(VT1, VT2)) {
6634     return true;
6635   }
6636
6637   if (Val.getOpcode() != ISD::LOAD)
6638     return false;
6639
6640   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6641   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6642           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6643           VT1.getSizeInBits() <= 32);
6644 }
6645
6646 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6647   if (isa<FPExtInst>(Ext))
6648     return false;
6649
6650   // Vector types are next free.
6651   if (Ext->getType()->isVectorTy())
6652     return false;
6653
6654   for (const Use &U : Ext->uses()) {
6655     // The extension is free if we can fold it with a left shift in an
6656     // addressing mode or an arithmetic operation: add, sub, and cmp.
6657
6658     // Is there a shift?
6659     const Instruction *Instr = cast<Instruction>(U.getUser());
6660
6661     // Is this a constant shift?
6662     switch (Instr->getOpcode()) {
6663     case Instruction::Shl:
6664       if (!isa<ConstantInt>(Instr->getOperand(1)))
6665         return false;
6666       break;
6667     case Instruction::GetElementPtr: {
6668       gep_type_iterator GTI = gep_type_begin(Instr);
6669       std::advance(GTI, U.getOperandNo());
6670       Type *IdxTy = *GTI;
6671       // This extension will end up with a shift because of the scaling factor.
6672       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6673       // Get the shift amount based on the scaling factor:
6674       // log2(sizeof(IdxTy)) - log2(8).
6675       uint64_t ShiftAmt =
6676         countTrailingZeros(getDataLayout()->getTypeStoreSizeInBits(IdxTy)) - 3;
6677       // Is the constant foldable in the shift of the addressing mode?
6678       // I.e., shift amount is between 1 and 4 inclusive.
6679       if (ShiftAmt == 0 || ShiftAmt > 4)
6680         return false;
6681       break;
6682     }
6683     case Instruction::Trunc:
6684       // Check if this is a noop.
6685       // trunc(sext ty1 to ty2) to ty1.
6686       if (Instr->getType() == Ext->getOperand(0)->getType())
6687         continue;
6688     // FALL THROUGH.
6689     default:
6690       return false;
6691     }
6692
6693     // At this point we can use the bfm family, so this extension is free
6694     // for that use.
6695   }
6696   return true;
6697 }
6698
6699 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6700                                           unsigned &RequiredAligment) const {
6701   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6702     return false;
6703   // Cyclone supports unaligned accesses.
6704   RequiredAligment = 0;
6705   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6706   return NumBits == 32 || NumBits == 64;
6707 }
6708
6709 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6710                                           unsigned &RequiredAligment) const {
6711   if (!LoadedType.isSimple() ||
6712       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6713     return false;
6714   // Cyclone supports unaligned accesses.
6715   RequiredAligment = 0;
6716   unsigned NumBits = LoadedType.getSizeInBits();
6717   return NumBits == 32 || NumBits == 64;
6718 }
6719
6720 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6721                        unsigned AlignCheck) {
6722   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6723           (DstAlign == 0 || DstAlign % AlignCheck == 0));
6724 }
6725
6726 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6727                                                unsigned SrcAlign, bool IsMemset,
6728                                                bool ZeroMemset,
6729                                                bool MemcpyStrSrc,
6730                                                MachineFunction &MF) const {
6731   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6732   // instruction to materialize the v2i64 zero and one store (with restrictive
6733   // addressing mode). Just do two i64 store of zero-registers.
6734   bool Fast;
6735   const Function *F = MF.getFunction();
6736   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6737       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
6738       (memOpAlign(SrcAlign, DstAlign, 16) ||
6739        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6740     return MVT::f128;
6741
6742   if (Size >= 8 &&
6743       (memOpAlign(SrcAlign, DstAlign, 8) ||
6744        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
6745     return MVT::i64;
6746
6747   if (Size >= 4 &&
6748       (memOpAlign(SrcAlign, DstAlign, 4) ||
6749        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
6750     return MVT::i32;
6751
6752   return MVT::Other;
6753 }
6754
6755 // 12-bit optionally shifted immediates are legal for adds.
6756 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6757   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6758     return true;
6759   return false;
6760 }
6761
6762 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6763 // immediates is the same as for an add or a sub.
6764 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6765   if (Immed < 0)
6766     Immed *= -1;
6767   return isLegalAddImmediate(Immed);
6768 }
6769
6770 /// isLegalAddressingMode - Return true if the addressing mode represented
6771 /// by AM is legal for this target, for a load/store of the specified type.
6772 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6773                                                   Type *Ty) const {
6774   // AArch64 has five basic addressing modes:
6775   //  reg
6776   //  reg + 9-bit signed offset
6777   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
6778   //  reg1 + reg2
6779   //  reg + SIZE_IN_BYTES * reg
6780
6781   // No global is ever allowed as a base.
6782   if (AM.BaseGV)
6783     return false;
6784
6785   // No reg+reg+imm addressing.
6786   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6787     return false;
6788
6789   // check reg + imm case:
6790   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6791   uint64_t NumBytes = 0;
6792   if (Ty->isSized()) {
6793     uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6794     NumBytes = NumBits / 8;
6795     if (!isPowerOf2_64(NumBits))
6796       NumBytes = 0;
6797   }
6798
6799   if (!AM.Scale) {
6800     int64_t Offset = AM.BaseOffs;
6801
6802     // 9-bit signed offset
6803     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6804       return true;
6805
6806     // 12-bit unsigned offset
6807     unsigned shift = Log2_64(NumBytes);
6808     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6809         // Must be a multiple of NumBytes (NumBytes is a power of 2)
6810         (Offset >> shift) << shift == Offset)
6811       return true;
6812     return false;
6813   }
6814
6815   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6816
6817   if (!AM.Scale || AM.Scale == 1 ||
6818       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6819     return true;
6820   return false;
6821 }
6822
6823 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6824                                                 Type *Ty) const {
6825   // Scaling factors are not free at all.
6826   // Operands                     | Rt Latency
6827   // -------------------------------------------
6828   // Rt, [Xn, Xm]                 | 4
6829   // -------------------------------------------
6830   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
6831   // Rt, [Xn, Wm, <extend> #imm]  |
6832   if (isLegalAddressingMode(AM, Ty))
6833     // Scale represents reg2 * scale, thus account for 1 if
6834     // it is not equal to 0 or 1.
6835     return AM.Scale != 0 && AM.Scale != 1;
6836   return -1;
6837 }
6838
6839 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6840   VT = VT.getScalarType();
6841
6842   if (!VT.isSimple())
6843     return false;
6844
6845   switch (VT.getSimpleVT().SimpleTy) {
6846   case MVT::f32:
6847   case MVT::f64:
6848     return true;
6849   default:
6850     break;
6851   }
6852
6853   return false;
6854 }
6855
6856 const MCPhysReg *
6857 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6858   // LR is a callee-save register, but we must treat it as clobbered by any call
6859   // site. Hence we include LR in the scratch registers, which are in turn added
6860   // as implicit-defs for stackmaps and patchpoints.
6861   static const MCPhysReg ScratchRegs[] = {
6862     AArch64::X16, AArch64::X17, AArch64::LR, 0
6863   };
6864   return ScratchRegs;
6865 }
6866
6867 bool
6868 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6869   EVT VT = N->getValueType(0);
6870     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6871     // it with shift to let it be lowered to UBFX.
6872   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6873       isa<ConstantSDNode>(N->getOperand(1))) {
6874     uint64_t TruncMask = N->getConstantOperandVal(1);
6875     if (isMask_64(TruncMask) &&
6876       N->getOperand(0).getOpcode() == ISD::SRL &&
6877       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6878       return false;
6879   }
6880   return true;
6881 }
6882
6883 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6884                                                               Type *Ty) const {
6885   assert(Ty->isIntegerTy());
6886
6887   unsigned BitSize = Ty->getPrimitiveSizeInBits();
6888   if (BitSize == 0)
6889     return false;
6890
6891   int64_t Val = Imm.getSExtValue();
6892   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6893     return true;
6894
6895   if ((int64_t)Val < 0)
6896     Val = ~Val;
6897   if (BitSize == 32)
6898     Val &= (1LL << 32) - 1;
6899
6900   unsigned LZ = countLeadingZeros((uint64_t)Val);
6901   unsigned Shift = (63 - LZ) / 16;
6902   // MOVZ is free so return true for one or fewer MOVK.
6903   return Shift < 3;
6904 }
6905
6906 // Generate SUBS and CSEL for integer abs.
6907 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6908   EVT VT = N->getValueType(0);
6909
6910   SDValue N0 = N->getOperand(0);
6911   SDValue N1 = N->getOperand(1);
6912   SDLoc DL(N);
6913
6914   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6915   // and change it to SUB and CSEL.
6916   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6917       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6918       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6919     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6920       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6921         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
6922                                   N0.getOperand(0));
6923         // Generate SUBS & CSEL.
6924         SDValue Cmp =
6925             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6926                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
6927         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6928                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
6929                            SDValue(Cmp.getNode(), 1));
6930       }
6931   return SDValue();
6932 }
6933
6934 // performXorCombine - Attempts to handle integer ABS.
6935 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6936                                  TargetLowering::DAGCombinerInfo &DCI,
6937                                  const AArch64Subtarget *Subtarget) {
6938   if (DCI.isBeforeLegalizeOps())
6939     return SDValue();
6940
6941   return performIntegerAbsCombine(N, DAG);
6942 }
6943
6944 SDValue
6945 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6946                                      SelectionDAG &DAG,
6947                                      std::vector<SDNode *> *Created) const {
6948   // fold (sdiv X, pow2)
6949   EVT VT = N->getValueType(0);
6950   if ((VT != MVT::i32 && VT != MVT::i64) ||
6951       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6952     return SDValue();
6953
6954   SDLoc DL(N);
6955   SDValue N0 = N->getOperand(0);
6956   unsigned Lg2 = Divisor.countTrailingZeros();
6957   SDValue Zero = DAG.getConstant(0, DL, VT);
6958   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
6959
6960   // Add (N0 < 0) ? Pow2 - 1 : 0;
6961   SDValue CCVal;
6962   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6963   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6964   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6965
6966   if (Created) {
6967     Created->push_back(Cmp.getNode());
6968     Created->push_back(Add.getNode());
6969     Created->push_back(CSel.getNode());
6970   }
6971
6972   // Divide by pow2.
6973   SDValue SRA =
6974       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
6975
6976   // If we're dividing by a positive value, we're done.  Otherwise, we must
6977   // negate the result.
6978   if (Divisor.isNonNegative())
6979     return SRA;
6980
6981   if (Created)
6982     Created->push_back(SRA.getNode());
6983   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
6984 }
6985
6986 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6987                                  TargetLowering::DAGCombinerInfo &DCI,
6988                                  const AArch64Subtarget *Subtarget) {
6989   if (DCI.isBeforeLegalizeOps())
6990     return SDValue();
6991
6992   // Multiplication of a power of two plus/minus one can be done more
6993   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6994   // future CPUs have a cheaper MADD instruction, this may need to be
6995   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6996   // 64-bit is 5 cycles, so this is always a win.
6997   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6998     APInt Value = C->getAPIntValue();
6999     EVT VT = N->getValueType(0);
7000     SDLoc DL(N);
7001     if (Value.isNonNegative()) {
7002       // (mul x, 2^N + 1) => (add (shl x, N), x)
7003       APInt VM1 = Value - 1;
7004       if (VM1.isPowerOf2()) {
7005         SDValue ShiftedVal =
7006             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7007                         DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7008         return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7009                            N->getOperand(0));
7010       }
7011       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7012       APInt VP1 = Value + 1;
7013       if (VP1.isPowerOf2()) {
7014         SDValue ShiftedVal =
7015             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7016                         DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7017         return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7018                            N->getOperand(0));
7019       }
7020     } else {
7021       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7022       APInt VNP1 = -Value + 1;
7023       if (VNP1.isPowerOf2()) {
7024         SDValue ShiftedVal =
7025             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7026                         DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7027         return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7028                            ShiftedVal);
7029       }
7030       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7031       APInt VNM1 = -Value - 1;
7032       if (VNM1.isPowerOf2()) {
7033         SDValue ShiftedVal =
7034             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7035                         DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7036         SDValue Add =
7037             DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7038         return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7039       }
7040     }
7041   }
7042   return SDValue();
7043 }
7044
7045 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7046                                                          SelectionDAG &DAG) {
7047   // Take advantage of vector comparisons producing 0 or -1 in each lane to
7048   // optimize away operation when it's from a constant.
7049   //
7050   // The general transformation is:
7051   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7052   //       AND(VECTOR_CMP(x,y), constant2)
7053   //    constant2 = UNARYOP(constant)
7054
7055   // Early exit if this isn't a vector operation, the operand of the
7056   // unary operation isn't a bitwise AND, or if the sizes of the operations
7057   // aren't the same.
7058   EVT VT = N->getValueType(0);
7059   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7060       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7061       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7062     return SDValue();
7063
7064   // Now check that the other operand of the AND is a constant. We could
7065   // make the transformation for non-constant splats as well, but it's unclear
7066   // that would be a benefit as it would not eliminate any operations, just
7067   // perform one more step in scalar code before moving to the vector unit.
7068   if (BuildVectorSDNode *BV =
7069           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7070     // Bail out if the vector isn't a constant.
7071     if (!BV->isConstant())
7072       return SDValue();
7073
7074     // Everything checks out. Build up the new and improved node.
7075     SDLoc DL(N);
7076     EVT IntVT = BV->getValueType(0);
7077     // Create a new constant of the appropriate type for the transformed
7078     // DAG.
7079     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7080     // The AND node needs bitcasts to/from an integer vector type around it.
7081     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7082     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7083                                  N->getOperand(0)->getOperand(0), MaskConst);
7084     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7085     return Res;
7086   }
7087
7088   return SDValue();
7089 }
7090
7091 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7092                                      const AArch64Subtarget *Subtarget) {
7093   // First try to optimize away the conversion when it's conditionally from
7094   // a constant. Vectors only.
7095   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
7096   if (Res != SDValue())
7097     return Res;
7098
7099   EVT VT = N->getValueType(0);
7100   if (VT != MVT::f32 && VT != MVT::f64)
7101     return SDValue();
7102
7103   // Only optimize when the source and destination types have the same width.
7104   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7105     return SDValue();
7106
7107   // If the result of an integer load is only used by an integer-to-float
7108   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7109   // This eliminates an "integer-to-vector-move UOP and improve throughput.
7110   SDValue N0 = N->getOperand(0);
7111   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7112       // Do not change the width of a volatile load.
7113       !cast<LoadSDNode>(N0)->isVolatile()) {
7114     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7115     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7116                                LN0->getPointerInfo(), LN0->isVolatile(),
7117                                LN0->isNonTemporal(), LN0->isInvariant(),
7118                                LN0->getAlignment());
7119
7120     // Make sure successors of the original load stay after it by updating them
7121     // to use the new Chain.
7122     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7123
7124     unsigned Opcode =
7125         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7126     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7127   }
7128
7129   return SDValue();
7130 }
7131
7132 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7133 /// searches for and classifies those shifts.
7134 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7135                          bool &FromHi) {
7136   if (N.getOpcode() == ISD::SHL)
7137     FromHi = false;
7138   else if (N.getOpcode() == ISD::SRL)
7139     FromHi = true;
7140   else
7141     return false;
7142
7143   if (!isa<ConstantSDNode>(N.getOperand(1)))
7144     return false;
7145
7146   ShiftAmount = N->getConstantOperandVal(1);
7147   Src = N->getOperand(0);
7148   return true;
7149 }
7150
7151 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7152 /// registers viewed as a high/low pair. This function looks for the pattern:
7153 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7154 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7155 /// independent.
7156 static SDValue tryCombineToEXTR(SDNode *N,
7157                                 TargetLowering::DAGCombinerInfo &DCI) {
7158   SelectionDAG &DAG = DCI.DAG;
7159   SDLoc DL(N);
7160   EVT VT = N->getValueType(0);
7161
7162   assert(N->getOpcode() == ISD::OR && "Unexpected root");
7163
7164   if (VT != MVT::i32 && VT != MVT::i64)
7165     return SDValue();
7166
7167   SDValue LHS;
7168   uint32_t ShiftLHS = 0;
7169   bool LHSFromHi = 0;
7170   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7171     return SDValue();
7172
7173   SDValue RHS;
7174   uint32_t ShiftRHS = 0;
7175   bool RHSFromHi = 0;
7176   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7177     return SDValue();
7178
7179   // If they're both trying to come from the high part of the register, they're
7180   // not really an EXTR.
7181   if (LHSFromHi == RHSFromHi)
7182     return SDValue();
7183
7184   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7185     return SDValue();
7186
7187   if (LHSFromHi) {
7188     std::swap(LHS, RHS);
7189     std::swap(ShiftLHS, ShiftRHS);
7190   }
7191
7192   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7193                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
7194 }
7195
7196 static SDValue tryCombineToBSL(SDNode *N,
7197                                 TargetLowering::DAGCombinerInfo &DCI) {
7198   EVT VT = N->getValueType(0);
7199   SelectionDAG &DAG = DCI.DAG;
7200   SDLoc DL(N);
7201
7202   if (!VT.isVector())
7203     return SDValue();
7204
7205   SDValue N0 = N->getOperand(0);
7206   if (N0.getOpcode() != ISD::AND)
7207     return SDValue();
7208
7209   SDValue N1 = N->getOperand(1);
7210   if (N1.getOpcode() != ISD::AND)
7211     return SDValue();
7212
7213   // We only have to look for constant vectors here since the general, variable
7214   // case can be handled in TableGen.
7215   unsigned Bits = VT.getVectorElementType().getSizeInBits();
7216   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7217   for (int i = 1; i >= 0; --i)
7218     for (int j = 1; j >= 0; --j) {
7219       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7220       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7221       if (!BVN0 || !BVN1)
7222         continue;
7223
7224       bool FoundMatch = true;
7225       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7226         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7227         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7228         if (!CN0 || !CN1 ||
7229             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7230           FoundMatch = false;
7231           break;
7232         }
7233       }
7234
7235       if (FoundMatch)
7236         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7237                            N0->getOperand(1 - i), N1->getOperand(1 - j));
7238     }
7239
7240   return SDValue();
7241 }
7242
7243 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7244                                 const AArch64Subtarget *Subtarget) {
7245   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7246   if (!EnableAArch64ExtrGeneration)
7247     return SDValue();
7248   SelectionDAG &DAG = DCI.DAG;
7249   EVT VT = N->getValueType(0);
7250
7251   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7252     return SDValue();
7253
7254   SDValue Res = tryCombineToEXTR(N, DCI);
7255   if (Res.getNode())
7256     return Res;
7257
7258   Res = tryCombineToBSL(N, DCI);
7259   if (Res.getNode())
7260     return Res;
7261
7262   return SDValue();
7263 }
7264
7265 static SDValue performBitcastCombine(SDNode *N,
7266                                      TargetLowering::DAGCombinerInfo &DCI,
7267                                      SelectionDAG &DAG) {
7268   // Wait 'til after everything is legalized to try this. That way we have
7269   // legal vector types and such.
7270   if (DCI.isBeforeLegalizeOps())
7271     return SDValue();
7272
7273   // Remove extraneous bitcasts around an extract_subvector.
7274   // For example,
7275   //    (v4i16 (bitconvert
7276   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7277   //  becomes
7278   //    (extract_subvector ((v8i16 ...), (i64 4)))
7279
7280   // Only interested in 64-bit vectors as the ultimate result.
7281   EVT VT = N->getValueType(0);
7282   if (!VT.isVector())
7283     return SDValue();
7284   if (VT.getSimpleVT().getSizeInBits() != 64)
7285     return SDValue();
7286   // Is the operand an extract_subvector starting at the beginning or halfway
7287   // point of the vector? A low half may also come through as an
7288   // EXTRACT_SUBREG, so look for that, too.
7289   SDValue Op0 = N->getOperand(0);
7290   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7291       !(Op0->isMachineOpcode() &&
7292         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7293     return SDValue();
7294   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7295   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7296     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7297       return SDValue();
7298   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7299     if (idx != AArch64::dsub)
7300       return SDValue();
7301     // The dsub reference is equivalent to a lane zero subvector reference.
7302     idx = 0;
7303   }
7304   // Look through the bitcast of the input to the extract.
7305   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7306     return SDValue();
7307   SDValue Source = Op0->getOperand(0)->getOperand(0);
7308   // If the source type has twice the number of elements as our destination
7309   // type, we know this is an extract of the high or low half of the vector.
7310   EVT SVT = Source->getValueType(0);
7311   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7312     return SDValue();
7313
7314   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7315
7316   // Create the simplified form to just extract the low or high half of the
7317   // vector directly rather than bothering with the bitcasts.
7318   SDLoc dl(N);
7319   unsigned NumElements = VT.getVectorNumElements();
7320   if (idx) {
7321     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7322     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7323   } else {
7324     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7325     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7326                                       Source, SubReg),
7327                    0);
7328   }
7329 }
7330
7331 static SDValue performConcatVectorsCombine(SDNode *N,
7332                                            TargetLowering::DAGCombinerInfo &DCI,
7333                                            SelectionDAG &DAG) {
7334   SDLoc dl(N);
7335   EVT VT = N->getValueType(0);
7336   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7337
7338   // Optimize concat_vectors of truncated vectors, where the intermediate
7339   // type is illegal, to avoid said illegality,  e.g.,
7340   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7341   //                          (v2i16 (truncate (v2i64)))))
7342   // ->
7343   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7344   //                                    (v4i32 (bitcast (v2i64))),
7345   //                                    <0, 2, 4, 6>)))
7346   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7347   // on both input and result type, so we might generate worse code.
7348   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7349   if (N->getNumOperands() == 2 &&
7350       N0->getOpcode() == ISD::TRUNCATE &&
7351       N1->getOpcode() == ISD::TRUNCATE) {
7352     SDValue N00 = N0->getOperand(0);
7353     SDValue N10 = N1->getOperand(0);
7354     EVT N00VT = N00.getValueType();
7355
7356     if (N00VT == N10.getValueType() &&
7357         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7358         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7359       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7360       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7361       for (size_t i = 0; i < Mask.size(); ++i)
7362         Mask[i] = i * 2;
7363       return DAG.getNode(ISD::TRUNCATE, dl, VT,
7364                          DAG.getVectorShuffle(
7365                              MidVT, dl,
7366                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7367                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7368     }
7369   }
7370
7371   // Wait 'til after everything is legalized to try this. That way we have
7372   // legal vector types and such.
7373   if (DCI.isBeforeLegalizeOps())
7374     return SDValue();
7375
7376   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7377   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7378   // canonicalise to that.
7379   if (N0 == N1 && VT.getVectorNumElements() == 2) {
7380     assert(VT.getVectorElementType().getSizeInBits() == 64);
7381     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7382                        DAG.getConstant(0, dl, MVT::i64));
7383   }
7384
7385   // Canonicalise concat_vectors so that the right-hand vector has as few
7386   // bit-casts as possible before its real operation. The primary matching
7387   // destination for these operations will be the narrowing "2" instructions,
7388   // which depend on the operation being performed on this right-hand vector.
7389   // For example,
7390   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
7391   // becomes
7392   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7393
7394   if (N1->getOpcode() != ISD::BITCAST)
7395     return SDValue();
7396   SDValue RHS = N1->getOperand(0);
7397   MVT RHSTy = RHS.getValueType().getSimpleVT();
7398   // If the RHS is not a vector, this is not the pattern we're looking for.
7399   if (!RHSTy.isVector())
7400     return SDValue();
7401
7402   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7403
7404   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7405                                   RHSTy.getVectorNumElements() * 2);
7406   return DAG.getNode(ISD::BITCAST, dl, VT,
7407                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7408                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7409                                  RHS));
7410 }
7411
7412 static SDValue tryCombineFixedPointConvert(SDNode *N,
7413                                            TargetLowering::DAGCombinerInfo &DCI,
7414                                            SelectionDAG &DAG) {
7415   // Wait 'til after everything is legalized to try this. That way we have
7416   // legal vector types and such.
7417   if (DCI.isBeforeLegalizeOps())
7418     return SDValue();
7419   // Transform a scalar conversion of a value from a lane extract into a
7420   // lane extract of a vector conversion. E.g., from foo1 to foo2:
7421   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7422   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7423   //
7424   // The second form interacts better with instruction selection and the
7425   // register allocator to avoid cross-class register copies that aren't
7426   // coalescable due to a lane reference.
7427
7428   // Check the operand and see if it originates from a lane extract.
7429   SDValue Op1 = N->getOperand(1);
7430   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7431     // Yep, no additional predication needed. Perform the transform.
7432     SDValue IID = N->getOperand(0);
7433     SDValue Shift = N->getOperand(2);
7434     SDValue Vec = Op1.getOperand(0);
7435     SDValue Lane = Op1.getOperand(1);
7436     EVT ResTy = N->getValueType(0);
7437     EVT VecResTy;
7438     SDLoc DL(N);
7439
7440     // The vector width should be 128 bits by the time we get here, even
7441     // if it started as 64 bits (the extract_vector handling will have
7442     // done so).
7443     assert(Vec.getValueType().getSizeInBits() == 128 &&
7444            "unexpected vector size on extract_vector_elt!");
7445     if (Vec.getValueType() == MVT::v4i32)
7446       VecResTy = MVT::v4f32;
7447     else if (Vec.getValueType() == MVT::v2i64)
7448       VecResTy = MVT::v2f64;
7449     else
7450       llvm_unreachable("unexpected vector type!");
7451
7452     SDValue Convert =
7453         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7454     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7455   }
7456   return SDValue();
7457 }
7458
7459 // AArch64 high-vector "long" operations are formed by performing the non-high
7460 // version on an extract_subvector of each operand which gets the high half:
7461 //
7462 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7463 //
7464 // However, there are cases which don't have an extract_high explicitly, but
7465 // have another operation that can be made compatible with one for free. For
7466 // example:
7467 //
7468 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
7469 //
7470 // This routine does the actual conversion of such DUPs, once outer routines
7471 // have determined that everything else is in order.
7472 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7473   // We can handle most types of duplicate, but the lane ones have an extra
7474   // operand saying *which* lane, so we need to know.
7475   bool IsDUPLANE;
7476   switch (N.getOpcode()) {
7477   case AArch64ISD::DUP:
7478     IsDUPLANE = false;
7479     break;
7480   case AArch64ISD::DUPLANE8:
7481   case AArch64ISD::DUPLANE16:
7482   case AArch64ISD::DUPLANE32:
7483   case AArch64ISD::DUPLANE64:
7484     IsDUPLANE = true;
7485     break;
7486   default:
7487     return SDValue();
7488   }
7489
7490   MVT NarrowTy = N.getSimpleValueType();
7491   if (!NarrowTy.is64BitVector())
7492     return SDValue();
7493
7494   MVT ElementTy = NarrowTy.getVectorElementType();
7495   unsigned NumElems = NarrowTy.getVectorNumElements();
7496   MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7497
7498   SDLoc dl(N);
7499   SDValue NewDUP;
7500   if (IsDUPLANE)
7501     NewDUP = DAG.getNode(N.getOpcode(), dl, NewDUPVT, N.getOperand(0),
7502                          N.getOperand(1));
7503   else
7504     NewDUP = DAG.getNode(AArch64ISD::DUP, dl, NewDUPVT, N.getOperand(0));
7505
7506   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, NewDUP,
7507                      DAG.getConstant(NumElems, dl, MVT::i64));
7508 }
7509
7510 static bool isEssentiallyExtractSubvector(SDValue N) {
7511   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7512     return true;
7513
7514   return N.getOpcode() == ISD::BITCAST &&
7515          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7516 }
7517
7518 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7519 struct GenericSetCCInfo {
7520   const SDValue *Opnd0;
7521   const SDValue *Opnd1;
7522   ISD::CondCode CC;
7523 };
7524
7525 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7526 struct AArch64SetCCInfo {
7527   const SDValue *Cmp;
7528   AArch64CC::CondCode CC;
7529 };
7530
7531 /// \brief Helper structure to keep track of SetCC information.
7532 union SetCCInfo {
7533   GenericSetCCInfo Generic;
7534   AArch64SetCCInfo AArch64;
7535 };
7536
7537 /// \brief Helper structure to be able to read SetCC information.  If set to
7538 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7539 /// GenericSetCCInfo.
7540 struct SetCCInfoAndKind {
7541   SetCCInfo Info;
7542   bool IsAArch64;
7543 };
7544
7545 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7546 /// an
7547 /// AArch64 lowered one.
7548 /// \p SetCCInfo is filled accordingly.
7549 /// \post SetCCInfo is meanginfull only when this function returns true.
7550 /// \return True when Op is a kind of SET_CC operation.
7551 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7552   // If this is a setcc, this is straight forward.
7553   if (Op.getOpcode() == ISD::SETCC) {
7554     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7555     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7556     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7557     SetCCInfo.IsAArch64 = false;
7558     return true;
7559   }
7560   // Otherwise, check if this is a matching csel instruction.
7561   // In other words:
7562   // - csel 1, 0, cc
7563   // - csel 0, 1, !cc
7564   if (Op.getOpcode() != AArch64ISD::CSEL)
7565     return false;
7566   // Set the information about the operands.
7567   // TODO: we want the operands of the Cmp not the csel
7568   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7569   SetCCInfo.IsAArch64 = true;
7570   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7571       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7572
7573   // Check that the operands matches the constraints:
7574   // (1) Both operands must be constants.
7575   // (2) One must be 1 and the other must be 0.
7576   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7577   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7578
7579   // Check (1).
7580   if (!TValue || !FValue)
7581     return false;
7582
7583   // Check (2).
7584   if (!TValue->isOne()) {
7585     // Update the comparison when we are interested in !cc.
7586     std::swap(TValue, FValue);
7587     SetCCInfo.Info.AArch64.CC =
7588         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7589   }
7590   return TValue->isOne() && FValue->isNullValue();
7591 }
7592
7593 // Returns true if Op is setcc or zext of setcc.
7594 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7595   if (isSetCC(Op, Info))
7596     return true;
7597   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7598     isSetCC(Op->getOperand(0), Info));
7599 }
7600
7601 // The folding we want to perform is:
7602 // (add x, [zext] (setcc cc ...) )
7603 //   -->
7604 // (csel x, (add x, 1), !cc ...)
7605 //
7606 // The latter will get matched to a CSINC instruction.
7607 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7608   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7609   SDValue LHS = Op->getOperand(0);
7610   SDValue RHS = Op->getOperand(1);
7611   SetCCInfoAndKind InfoAndKind;
7612
7613   // If neither operand is a SET_CC, give up.
7614   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7615     std::swap(LHS, RHS);
7616     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7617       return SDValue();
7618   }
7619
7620   // FIXME: This could be generatized to work for FP comparisons.
7621   EVT CmpVT = InfoAndKind.IsAArch64
7622                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7623                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
7624   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7625     return SDValue();
7626
7627   SDValue CCVal;
7628   SDValue Cmp;
7629   SDLoc dl(Op);
7630   if (InfoAndKind.IsAArch64) {
7631     CCVal = DAG.getConstant(
7632         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7633         MVT::i32);
7634     Cmp = *InfoAndKind.Info.AArch64.Cmp;
7635   } else
7636     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7637                       *InfoAndKind.Info.Generic.Opnd1,
7638                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7639                       CCVal, DAG, dl);
7640
7641   EVT VT = Op->getValueType(0);
7642   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
7643   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7644 }
7645
7646 // The basic add/sub long vector instructions have variants with "2" on the end
7647 // which act on the high-half of their inputs. They are normally matched by
7648 // patterns like:
7649 //
7650 // (add (zeroext (extract_high LHS)),
7651 //      (zeroext (extract_high RHS)))
7652 // -> uaddl2 vD, vN, vM
7653 //
7654 // However, if one of the extracts is something like a duplicate, this
7655 // instruction can still be used profitably. This function puts the DAG into a
7656 // more appropriate form for those patterns to trigger.
7657 static SDValue performAddSubLongCombine(SDNode *N,
7658                                         TargetLowering::DAGCombinerInfo &DCI,
7659                                         SelectionDAG &DAG) {
7660   if (DCI.isBeforeLegalizeOps())
7661     return SDValue();
7662
7663   MVT VT = N->getSimpleValueType(0);
7664   if (!VT.is128BitVector()) {
7665     if (N->getOpcode() == ISD::ADD)
7666       return performSetccAddFolding(N, DAG);
7667     return SDValue();
7668   }
7669
7670   // Make sure both branches are extended in the same way.
7671   SDValue LHS = N->getOperand(0);
7672   SDValue RHS = N->getOperand(1);
7673   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7674        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7675       LHS.getOpcode() != RHS.getOpcode())
7676     return SDValue();
7677
7678   unsigned ExtType = LHS.getOpcode();
7679
7680   // It's not worth doing if at least one of the inputs isn't already an
7681   // extract, but we don't know which it'll be so we have to try both.
7682   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7683     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7684     if (!RHS.getNode())
7685       return SDValue();
7686
7687     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7688   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7689     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7690     if (!LHS.getNode())
7691       return SDValue();
7692
7693     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7694   }
7695
7696   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7697 }
7698
7699 // Massage DAGs which we can use the high-half "long" operations on into
7700 // something isel will recognize better. E.g.
7701 //
7702 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7703 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
7704 //                     (extract_high (v2i64 (dup128 scalar)))))
7705 //
7706 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7707                                        TargetLowering::DAGCombinerInfo &DCI,
7708                                        SelectionDAG &DAG) {
7709   if (DCI.isBeforeLegalizeOps())
7710     return SDValue();
7711
7712   SDValue LHS = N->getOperand(1);
7713   SDValue RHS = N->getOperand(2);
7714   assert(LHS.getValueType().is64BitVector() &&
7715          RHS.getValueType().is64BitVector() &&
7716          "unexpected shape for long operation");
7717
7718   // Either node could be a DUP, but it's not worth doing both of them (you'd
7719   // just as well use the non-high version) so look for a corresponding extract
7720   // operation on the other "wing".
7721   if (isEssentiallyExtractSubvector(LHS)) {
7722     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7723     if (!RHS.getNode())
7724       return SDValue();
7725   } else if (isEssentiallyExtractSubvector(RHS)) {
7726     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7727     if (!LHS.getNode())
7728       return SDValue();
7729   }
7730
7731   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7732                      N->getOperand(0), LHS, RHS);
7733 }
7734
7735 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7736   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7737   unsigned ElemBits = ElemTy.getSizeInBits();
7738
7739   int64_t ShiftAmount;
7740   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7741     APInt SplatValue, SplatUndef;
7742     unsigned SplatBitSize;
7743     bool HasAnyUndefs;
7744     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7745                               HasAnyUndefs, ElemBits) ||
7746         SplatBitSize != ElemBits)
7747       return SDValue();
7748
7749     ShiftAmount = SplatValue.getSExtValue();
7750   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7751     ShiftAmount = CVN->getSExtValue();
7752   } else
7753     return SDValue();
7754
7755   unsigned Opcode;
7756   bool IsRightShift;
7757   switch (IID) {
7758   default:
7759     llvm_unreachable("Unknown shift intrinsic");
7760   case Intrinsic::aarch64_neon_sqshl:
7761     Opcode = AArch64ISD::SQSHL_I;
7762     IsRightShift = false;
7763     break;
7764   case Intrinsic::aarch64_neon_uqshl:
7765     Opcode = AArch64ISD::UQSHL_I;
7766     IsRightShift = false;
7767     break;
7768   case Intrinsic::aarch64_neon_srshl:
7769     Opcode = AArch64ISD::SRSHR_I;
7770     IsRightShift = true;
7771     break;
7772   case Intrinsic::aarch64_neon_urshl:
7773     Opcode = AArch64ISD::URSHR_I;
7774     IsRightShift = true;
7775     break;
7776   case Intrinsic::aarch64_neon_sqshlu:
7777     Opcode = AArch64ISD::SQSHLU_I;
7778     IsRightShift = false;
7779     break;
7780   }
7781
7782   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
7783     SDLoc dl(N);
7784     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7785                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
7786   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
7787     SDLoc dl(N);
7788     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7789                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
7790   }
7791
7792   return SDValue();
7793 }
7794
7795 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7796 // the intrinsics must be legal and take an i32, this means there's almost
7797 // certainly going to be a zext in the DAG which we can eliminate.
7798 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7799   SDValue AndN = N->getOperand(2);
7800   if (AndN.getOpcode() != ISD::AND)
7801     return SDValue();
7802
7803   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7804   if (!CMask || CMask->getZExtValue() != Mask)
7805     return SDValue();
7806
7807   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7808                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7809 }
7810
7811 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
7812                                            SelectionDAG &DAG) {
7813   SDLoc dl(N);
7814   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
7815                      DAG.getNode(Opc, dl,
7816                                  N->getOperand(1).getSimpleValueType(),
7817                                  N->getOperand(1)),
7818                      DAG.getConstant(0, dl, MVT::i64));
7819 }
7820
7821 static SDValue performIntrinsicCombine(SDNode *N,
7822                                        TargetLowering::DAGCombinerInfo &DCI,
7823                                        const AArch64Subtarget *Subtarget) {
7824   SelectionDAG &DAG = DCI.DAG;
7825   unsigned IID = getIntrinsicID(N);
7826   switch (IID) {
7827   default:
7828     break;
7829   case Intrinsic::aarch64_neon_vcvtfxs2fp:
7830   case Intrinsic::aarch64_neon_vcvtfxu2fp:
7831     return tryCombineFixedPointConvert(N, DCI, DAG);
7832     break;
7833   case Intrinsic::aarch64_neon_saddv:
7834     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
7835   case Intrinsic::aarch64_neon_uaddv:
7836     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
7837   case Intrinsic::aarch64_neon_sminv:
7838     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
7839   case Intrinsic::aarch64_neon_uminv:
7840     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
7841   case Intrinsic::aarch64_neon_smaxv:
7842     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
7843   case Intrinsic::aarch64_neon_umaxv:
7844     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
7845   case Intrinsic::aarch64_neon_fmax:
7846     return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7847                        N->getOperand(1), N->getOperand(2));
7848   case Intrinsic::aarch64_neon_fmin:
7849     return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7850                        N->getOperand(1), N->getOperand(2));
7851   case Intrinsic::aarch64_neon_smull:
7852   case Intrinsic::aarch64_neon_umull:
7853   case Intrinsic::aarch64_neon_pmull:
7854   case Intrinsic::aarch64_neon_sqdmull:
7855     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7856   case Intrinsic::aarch64_neon_sqshl:
7857   case Intrinsic::aarch64_neon_uqshl:
7858   case Intrinsic::aarch64_neon_sqshlu:
7859   case Intrinsic::aarch64_neon_srshl:
7860   case Intrinsic::aarch64_neon_urshl:
7861     return tryCombineShiftImm(IID, N, DAG);
7862   case Intrinsic::aarch64_crc32b:
7863   case Intrinsic::aarch64_crc32cb:
7864     return tryCombineCRC32(0xff, N, DAG);
7865   case Intrinsic::aarch64_crc32h:
7866   case Intrinsic::aarch64_crc32ch:
7867     return tryCombineCRC32(0xffff, N, DAG);
7868   }
7869   return SDValue();
7870 }
7871
7872 static SDValue performExtendCombine(SDNode *N,
7873                                     TargetLowering::DAGCombinerInfo &DCI,
7874                                     SelectionDAG &DAG) {
7875   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7876   // we can convert that DUP into another extract_high (of a bigger DUP), which
7877   // helps the backend to decide that an sabdl2 would be useful, saving a real
7878   // extract_high operation.
7879   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7880       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7881     SDNode *ABDNode = N->getOperand(0).getNode();
7882     unsigned IID = getIntrinsicID(ABDNode);
7883     if (IID == Intrinsic::aarch64_neon_sabd ||
7884         IID == Intrinsic::aarch64_neon_uabd) {
7885       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7886       if (!NewABD.getNode())
7887         return SDValue();
7888
7889       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7890                          NewABD);
7891     }
7892   }
7893
7894   // This is effectively a custom type legalization for AArch64.
7895   //
7896   // Type legalization will split an extend of a small, legal, type to a larger
7897   // illegal type by first splitting the destination type, often creating
7898   // illegal source types, which then get legalized in isel-confusing ways,
7899   // leading to really terrible codegen. E.g.,
7900   //   %result = v8i32 sext v8i8 %value
7901   // becomes
7902   //   %losrc = extract_subreg %value, ...
7903   //   %hisrc = extract_subreg %value, ...
7904   //   %lo = v4i32 sext v4i8 %losrc
7905   //   %hi = v4i32 sext v4i8 %hisrc
7906   // Things go rapidly downhill from there.
7907   //
7908   // For AArch64, the [sz]ext vector instructions can only go up one element
7909   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7910   // take two instructions.
7911   //
7912   // This implies that the most efficient way to do the extend from v8i8
7913   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7914   // the normal splitting to happen for the v8i16->v8i32.
7915
7916   // This is pre-legalization to catch some cases where the default
7917   // type legalization will create ill-tempered code.
7918   if (!DCI.isBeforeLegalizeOps())
7919     return SDValue();
7920
7921   // We're only interested in cleaning things up for non-legal vector types
7922   // here. If both the source and destination are legal, things will just
7923   // work naturally without any fiddling.
7924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7925   EVT ResVT = N->getValueType(0);
7926   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7927     return SDValue();
7928   // If the vector type isn't a simple VT, it's beyond the scope of what
7929   // we're  worried about here. Let legalization do its thing and hope for
7930   // the best.
7931   SDValue Src = N->getOperand(0);
7932   EVT SrcVT = Src->getValueType(0);
7933   if (!ResVT.isSimple() || !SrcVT.isSimple())
7934     return SDValue();
7935
7936   // If the source VT is a 64-bit vector, we can play games and get the
7937   // better results we want.
7938   if (SrcVT.getSizeInBits() != 64)
7939     return SDValue();
7940
7941   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7942   unsigned ElementCount = SrcVT.getVectorNumElements();
7943   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7944   SDLoc DL(N);
7945   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7946
7947   // Now split the rest of the operation into two halves, each with a 64
7948   // bit source.
7949   EVT LoVT, HiVT;
7950   SDValue Lo, Hi;
7951   unsigned NumElements = ResVT.getVectorNumElements();
7952   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7953   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7954                                  ResVT.getVectorElementType(), NumElements / 2);
7955
7956   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7957                                LoVT.getVectorNumElements());
7958   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7959                    DAG.getConstant(0, DL, MVT::i64));
7960   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7961                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
7962   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7963   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7964
7965   // Now combine the parts back together so we still have a single result
7966   // like the combiner expects.
7967   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7968 }
7969
7970 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7971 /// value. The load store optimizer pass will merge them to store pair stores.
7972 /// This has better performance than a splat of the scalar followed by a split
7973 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7974 /// followed by an ext.b and two stores.
7975 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7976   SDValue StVal = St->getValue();
7977   EVT VT = StVal.getValueType();
7978
7979   // Don't replace floating point stores, they possibly won't be transformed to
7980   // stp because of the store pair suppress pass.
7981   if (VT.isFloatingPoint())
7982     return SDValue();
7983
7984   // Check for insert vector elements.
7985   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7986     return SDValue();
7987
7988   // We can express a splat as store pair(s) for 2 or 4 elements.
7989   unsigned NumVecElts = VT.getVectorNumElements();
7990   if (NumVecElts != 4 && NumVecElts != 2)
7991     return SDValue();
7992   SDValue SplatVal = StVal.getOperand(1);
7993   unsigned RemainInsertElts = NumVecElts - 1;
7994
7995   // Check that this is a splat.
7996   while (--RemainInsertElts) {
7997     SDValue NextInsertElt = StVal.getOperand(0);
7998     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7999       return SDValue();
8000     if (NextInsertElt.getOperand(1) != SplatVal)
8001       return SDValue();
8002     StVal = NextInsertElt;
8003   }
8004   unsigned OrigAlignment = St->getAlignment();
8005   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8006   unsigned Alignment = std::min(OrigAlignment, EltOffset);
8007
8008   // Create scalar stores. This is at least as good as the code sequence for a
8009   // split unaligned store wich is a dup.s, ext.b, and two stores.
8010   // Most of the time the three stores should be replaced by store pair
8011   // instructions (stp).
8012   SDLoc DL(St);
8013   SDValue BasePtr = St->getBasePtr();
8014   SDValue NewST1 =
8015       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8016                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8017
8018   unsigned Offset = EltOffset;
8019   while (--NumVecElts) {
8020     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8021                                     DAG.getConstant(Offset, DL, MVT::i64));
8022     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8023                           St->getPointerInfo(), St->isVolatile(),
8024                           St->isNonTemporal(), Alignment);
8025     Offset += EltOffset;
8026   }
8027   return NewST1;
8028 }
8029
8030 static SDValue performSTORECombine(SDNode *N,
8031                                    TargetLowering::DAGCombinerInfo &DCI,
8032                                    SelectionDAG &DAG,
8033                                    const AArch64Subtarget *Subtarget) {
8034   if (!DCI.isBeforeLegalize())
8035     return SDValue();
8036
8037   StoreSDNode *S = cast<StoreSDNode>(N);
8038   if (S->isVolatile())
8039     return SDValue();
8040
8041   // Cyclone has bad performance on unaligned 16B stores when crossing line and
8042   // page boundaries. We want to split such stores.
8043   if (!Subtarget->isCyclone())
8044     return SDValue();
8045
8046   // Don't split at Oz.
8047   MachineFunction &MF = DAG.getMachineFunction();
8048   bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
8049   if (IsMinSize)
8050     return SDValue();
8051
8052   SDValue StVal = S->getValue();
8053   EVT VT = StVal.getValueType();
8054
8055   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8056   // those up regresses performance on micro-benchmarks and olden/bh.
8057   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8058     return SDValue();
8059
8060   // Split unaligned 16B stores. They are terrible for performance.
8061   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8062   // extensions can use this to mark that it does not want splitting to happen
8063   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8064   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8065   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8066       S->getAlignment() <= 2)
8067     return SDValue();
8068
8069   // If we get a splat of a scalar convert this vector store to a store of
8070   // scalars. They will be merged into store pairs thereby removing two
8071   // instructions.
8072   SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
8073   if (ReplacedSplat != SDValue())
8074     return ReplacedSplat;
8075
8076   SDLoc DL(S);
8077   unsigned NumElts = VT.getVectorNumElements() / 2;
8078   // Split VT into two.
8079   EVT HalfVT =
8080       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8081   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8082                                    DAG.getConstant(0, DL, MVT::i64));
8083   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8084                                    DAG.getConstant(NumElts, DL, MVT::i64));
8085   SDValue BasePtr = S->getBasePtr();
8086   SDValue NewST1 =
8087       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8088                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8089   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8090                                   DAG.getConstant(8, DL, MVT::i64));
8091   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8092                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8093                       S->getAlignment());
8094 }
8095
8096 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8097 /// post-increment LD1R.
8098 static SDValue performPostLD1Combine(SDNode *N,
8099                                      TargetLowering::DAGCombinerInfo &DCI,
8100                                      bool IsLaneOp) {
8101   if (DCI.isBeforeLegalizeOps())
8102     return SDValue();
8103
8104   SelectionDAG &DAG = DCI.DAG;
8105   EVT VT = N->getValueType(0);
8106
8107   unsigned LoadIdx = IsLaneOp ? 1 : 0;
8108   SDNode *LD = N->getOperand(LoadIdx).getNode();
8109   // If it is not LOAD, can not do such combine.
8110   if (LD->getOpcode() != ISD::LOAD)
8111     return SDValue();
8112
8113   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8114   EVT MemVT = LoadSDN->getMemoryVT();
8115   // Check if memory operand is the same type as the vector element.
8116   if (MemVT != VT.getVectorElementType())
8117     return SDValue();
8118
8119   // Check if there are other uses. If so, do not combine as it will introduce
8120   // an extra load.
8121   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8122        ++UI) {
8123     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8124       continue;
8125     if (*UI != N)
8126       return SDValue();
8127   }
8128
8129   SDValue Addr = LD->getOperand(1);
8130   SDValue Vector = N->getOperand(0);
8131   // Search for a use of the address operand that is an increment.
8132   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8133        Addr.getNode()->use_end(); UI != UE; ++UI) {
8134     SDNode *User = *UI;
8135     if (User->getOpcode() != ISD::ADD
8136         || UI.getUse().getResNo() != Addr.getResNo())
8137       continue;
8138
8139     // Check that the add is independent of the load.  Otherwise, folding it
8140     // would create a cycle.
8141     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8142       continue;
8143     // Also check that add is not used in the vector operand.  This would also
8144     // create a cycle.
8145     if (User->isPredecessorOf(Vector.getNode()))
8146       continue;
8147
8148     // If the increment is a constant, it must match the memory ref size.
8149     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8150     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8151       uint32_t IncVal = CInc->getZExtValue();
8152       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8153       if (IncVal != NumBytes)
8154         continue;
8155       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8156     }
8157
8158     // Finally, check that the vector doesn't depend on the load.
8159     // Again, this would create a cycle.
8160     // The load depending on the vector is fine, as that's the case for the
8161     // LD1*post we'll eventually generate anyway.
8162     if (LoadSDN->isPredecessorOf(Vector.getNode()))
8163       continue;
8164
8165     SmallVector<SDValue, 8> Ops;
8166     Ops.push_back(LD->getOperand(0));  // Chain
8167     if (IsLaneOp) {
8168       Ops.push_back(Vector);           // The vector to be inserted
8169       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8170     }
8171     Ops.push_back(Addr);
8172     Ops.push_back(Inc);
8173
8174     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8175     SDVTList SDTys = DAG.getVTList(Tys);
8176     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8177     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8178                                            MemVT,
8179                                            LoadSDN->getMemOperand());
8180
8181     // Update the uses.
8182     SmallVector<SDValue, 2> NewResults;
8183     NewResults.push_back(SDValue(LD, 0));             // The result of load
8184     NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8185     DCI.CombineTo(LD, NewResults);
8186     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
8187     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
8188
8189     break;
8190   }
8191   return SDValue();
8192 }
8193
8194 /// Target-specific DAG combine function for NEON load/store intrinsics
8195 /// to merge base address updates.
8196 static SDValue performNEONPostLDSTCombine(SDNode *N,
8197                                           TargetLowering::DAGCombinerInfo &DCI,
8198                                           SelectionDAG &DAG) {
8199   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8200     return SDValue();
8201
8202   unsigned AddrOpIdx = N->getNumOperands() - 1;
8203   SDValue Addr = N->getOperand(AddrOpIdx);
8204
8205   // Search for a use of the address operand that is an increment.
8206   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8207        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8208     SDNode *User = *UI;
8209     if (User->getOpcode() != ISD::ADD ||
8210         UI.getUse().getResNo() != Addr.getResNo())
8211       continue;
8212
8213     // Check that the add is independent of the load/store.  Otherwise, folding
8214     // it would create a cycle.
8215     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8216       continue;
8217
8218     // Find the new opcode for the updating load/store.
8219     bool IsStore = false;
8220     bool IsLaneOp = false;
8221     bool IsDupOp = false;
8222     unsigned NewOpc = 0;
8223     unsigned NumVecs = 0;
8224     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8225     switch (IntNo) {
8226     default: llvm_unreachable("unexpected intrinsic for Neon base update");
8227     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
8228       NumVecs = 2; break;
8229     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
8230       NumVecs = 3; break;
8231     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
8232       NumVecs = 4; break;
8233     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
8234       NumVecs = 2; IsStore = true; break;
8235     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
8236       NumVecs = 3; IsStore = true; break;
8237     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
8238       NumVecs = 4; IsStore = true; break;
8239     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
8240       NumVecs = 2; break;
8241     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
8242       NumVecs = 3; break;
8243     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
8244       NumVecs = 4; break;
8245     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
8246       NumVecs = 2; IsStore = true; break;
8247     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
8248       NumVecs = 3; IsStore = true; break;
8249     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
8250       NumVecs = 4; IsStore = true; break;
8251     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
8252       NumVecs = 2; IsDupOp = true; break;
8253     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
8254       NumVecs = 3; IsDupOp = true; break;
8255     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
8256       NumVecs = 4; IsDupOp = true; break;
8257     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
8258       NumVecs = 2; IsLaneOp = true; break;
8259     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
8260       NumVecs = 3; IsLaneOp = true; break;
8261     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
8262       NumVecs = 4; IsLaneOp = true; break;
8263     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
8264       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8265     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
8266       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8267     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
8268       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8269     }
8270
8271     EVT VecTy;
8272     if (IsStore)
8273       VecTy = N->getOperand(2).getValueType();
8274     else
8275       VecTy = N->getValueType(0);
8276
8277     // If the increment is a constant, it must match the memory ref size.
8278     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8279     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8280       uint32_t IncVal = CInc->getZExtValue();
8281       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8282       if (IsLaneOp || IsDupOp)
8283         NumBytes /= VecTy.getVectorNumElements();
8284       if (IncVal != NumBytes)
8285         continue;
8286       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8287     }
8288     SmallVector<SDValue, 8> Ops;
8289     Ops.push_back(N->getOperand(0)); // Incoming chain
8290     // Load lane and store have vector list as input.
8291     if (IsLaneOp || IsStore)
8292       for (unsigned i = 2; i < AddrOpIdx; ++i)
8293         Ops.push_back(N->getOperand(i));
8294     Ops.push_back(Addr); // Base register
8295     Ops.push_back(Inc);
8296
8297     // Return Types.
8298     EVT Tys[6];
8299     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8300     unsigned n;
8301     for (n = 0; n < NumResultVecs; ++n)
8302       Tys[n] = VecTy;
8303     Tys[n++] = MVT::i64;  // Type of write back register
8304     Tys[n] = MVT::Other;  // Type of the chain
8305     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8306
8307     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8308     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8309                                            MemInt->getMemoryVT(),
8310                                            MemInt->getMemOperand());
8311
8312     // Update the uses.
8313     std::vector<SDValue> NewResults;
8314     for (unsigned i = 0; i < NumResultVecs; ++i) {
8315       NewResults.push_back(SDValue(UpdN.getNode(), i));
8316     }
8317     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8318     DCI.CombineTo(N, NewResults);
8319     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8320
8321     break;
8322   }
8323   return SDValue();
8324 }
8325
8326 // Checks to see if the value is the prescribed width and returns information
8327 // about its extension mode.
8328 static
8329 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8330   ExtType = ISD::NON_EXTLOAD;
8331   switch(V.getNode()->getOpcode()) {
8332   default:
8333     return false;
8334   case ISD::LOAD: {
8335     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8336     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8337        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8338       ExtType = LoadNode->getExtensionType();
8339       return true;
8340     }
8341     return false;
8342   }
8343   case ISD::AssertSext: {
8344     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8345     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8346        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8347       ExtType = ISD::SEXTLOAD;
8348       return true;
8349     }
8350     return false;
8351   }
8352   case ISD::AssertZext: {
8353     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8354     if ((TypeNode->getVT() == MVT::i8 && width == 8)
8355        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8356       ExtType = ISD::ZEXTLOAD;
8357       return true;
8358     }
8359     return false;
8360   }
8361   case ISD::Constant:
8362   case ISD::TargetConstant: {
8363     if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8364         1LL << (width - 1))
8365       return true;
8366     return false;
8367   }
8368   }
8369
8370   return true;
8371 }
8372
8373 // This function does a whole lot of voodoo to determine if the tests are
8374 // equivalent without and with a mask. Essentially what happens is that given a
8375 // DAG resembling:
8376 //
8377 //  +-------------+ +-------------+ +-------------+ +-------------+
8378 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
8379 //  +-------------+ +-------------+ +-------------+ +-------------+
8380 //           |           |           |               |
8381 //           V           V           |    +----------+
8382 //          +-------------+  +----+  |    |
8383 //          |     ADD     |  |0xff|  |    |
8384 //          +-------------+  +----+  |    |
8385 //                  |           |    |    |
8386 //                  V           V    |    |
8387 //                 +-------------+   |    |
8388 //                 |     AND     |   |    |
8389 //                 +-------------+   |    |
8390 //                      |            |    |
8391 //                      +-----+      |    |
8392 //                            |      |    |
8393 //                            V      V    V
8394 //                           +-------------+
8395 //                           |     CMP     |
8396 //                           +-------------+
8397 //
8398 // The AND node may be safely removed for some combinations of inputs. In
8399 // particular we need to take into account the extension type of the Input,
8400 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8401 // width of the input (this can work for any width inputs, the above graph is
8402 // specific to 8 bits.
8403 //
8404 // The specific equations were worked out by generating output tables for each
8405 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8406 // problem was simplified by working with 4 bit inputs, which means we only
8407 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8408 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8409 // patterns present in both extensions (0,7). For every distinct set of
8410 // AddConstant and CompConstants bit patterns we can consider the masked and
8411 // unmasked versions to be equivalent if the result of this function is true for
8412 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8413 //
8414 //   sub      w8, w0, w1
8415 //   and      w10, w8, #0x0f
8416 //   cmp      w8, w2
8417 //   cset     w9, AArch64CC
8418 //   cmp      w10, w2
8419 //   cset     w11, AArch64CC
8420 //   cmp      w9, w11
8421 //   cset     w0, eq
8422 //   ret
8423 //
8424 // Since the above function shows when the outputs are equivalent it defines
8425 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8426 // would be expensive to run during compiles. The equations below were written
8427 // in a test harness that confirmed they gave equivalent outputs to the above
8428 // for all inputs function, so they can be used determine if the removal is
8429 // legal instead.
8430 //
8431 // isEquivalentMaskless() is the code for testing if the AND can be removed
8432 // factored out of the DAG recognition as the DAG can take several forms.
8433
8434 static
8435 bool isEquivalentMaskless(unsigned CC, unsigned width,
8436                           ISD::LoadExtType ExtType, signed AddConstant,
8437                           signed CompConstant) {
8438   // By being careful about our equations and only writing the in term
8439   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8440   // make them generally applicable to all bit widths.
8441   signed MaxUInt = (1 << width);
8442
8443   // For the purposes of these comparisons sign extending the type is
8444   // equivalent to zero extending the add and displacing it by half the integer
8445   // width. Provided we are careful and make sure our equations are valid over
8446   // the whole range we can just adjust the input and avoid writing equations
8447   // for sign extended inputs.
8448   if (ExtType == ISD::SEXTLOAD)
8449     AddConstant -= (1 << (width-1));
8450
8451   switch(CC) {
8452   case AArch64CC::LE:
8453   case AArch64CC::GT: {
8454     if ((AddConstant == 0) ||
8455         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8456         (AddConstant >= 0 && CompConstant < 0) ||
8457         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8458       return true;
8459   } break;
8460   case AArch64CC::LT:
8461   case AArch64CC::GE: {
8462     if ((AddConstant == 0) ||
8463         (AddConstant >= 0 && CompConstant <= 0) ||
8464         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8465       return true;
8466   } break;
8467   case AArch64CC::HI:
8468   case AArch64CC::LS: {
8469     if ((AddConstant >= 0 && CompConstant < 0) ||
8470        (AddConstant <= 0 && CompConstant >= -1 &&
8471         CompConstant < AddConstant + MaxUInt))
8472       return true;
8473   } break;
8474   case AArch64CC::PL:
8475   case AArch64CC::MI: {
8476     if ((AddConstant == 0) ||
8477         (AddConstant > 0 && CompConstant <= 0) ||
8478         (AddConstant < 0 && CompConstant <= AddConstant))
8479       return true;
8480   } break;
8481   case AArch64CC::LO:
8482   case AArch64CC::HS: {
8483     if ((AddConstant >= 0 && CompConstant <= 0) ||
8484         (AddConstant <= 0 && CompConstant >= 0 &&
8485          CompConstant <= AddConstant + MaxUInt))
8486       return true;
8487   } break;
8488   case AArch64CC::EQ:
8489   case AArch64CC::NE: {
8490     if ((AddConstant > 0 && CompConstant < 0) ||
8491         (AddConstant < 0 && CompConstant >= 0 &&
8492          CompConstant < AddConstant + MaxUInt) ||
8493         (AddConstant >= 0 && CompConstant >= 0 &&
8494          CompConstant >= AddConstant) ||
8495         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8496
8497       return true;
8498   } break;
8499   case AArch64CC::VS:
8500   case AArch64CC::VC:
8501   case AArch64CC::AL:
8502   case AArch64CC::NV:
8503     return true;
8504   case AArch64CC::Invalid:
8505     break;
8506   }
8507
8508   return false;
8509 }
8510
8511 static
8512 SDValue performCONDCombine(SDNode *N,
8513                            TargetLowering::DAGCombinerInfo &DCI,
8514                            SelectionDAG &DAG, unsigned CCIndex,
8515                            unsigned CmpIndex) {
8516   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8517   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8518   unsigned CondOpcode = SubsNode->getOpcode();
8519
8520   if (CondOpcode != AArch64ISD::SUBS)
8521     return SDValue();
8522
8523   // There is a SUBS feeding this condition. Is it fed by a mask we can
8524   // use?
8525
8526   SDNode *AndNode = SubsNode->getOperand(0).getNode();
8527   unsigned MaskBits = 0;
8528
8529   if (AndNode->getOpcode() != ISD::AND)
8530     return SDValue();
8531
8532   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8533     uint32_t CNV = CN->getZExtValue();
8534     if (CNV == 255)
8535       MaskBits = 8;
8536     else if (CNV == 65535)
8537       MaskBits = 16;
8538   }
8539
8540   if (!MaskBits)
8541     return SDValue();
8542
8543   SDValue AddValue = AndNode->getOperand(0);
8544
8545   if (AddValue.getOpcode() != ISD::ADD)
8546     return SDValue();
8547
8548   // The basic dag structure is correct, grab the inputs and validate them.
8549
8550   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8551   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8552   SDValue SubsInputValue = SubsNode->getOperand(1);
8553
8554   // The mask is present and the provenance of all the values is a smaller type,
8555   // lets see if the mask is superfluous.
8556
8557   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8558       !isa<ConstantSDNode>(SubsInputValue.getNode()))
8559     return SDValue();
8560
8561   ISD::LoadExtType ExtType;
8562
8563   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8564       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8565       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8566     return SDValue();
8567
8568   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8569                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8570                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8571     return SDValue();
8572
8573   // The AND is not necessary, remove it.
8574
8575   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8576                                SubsNode->getValueType(1));
8577   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8578
8579   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8580   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8581
8582   return SDValue(N, 0);
8583 }
8584
8585 // Optimize compare with zero and branch.
8586 static SDValue performBRCONDCombine(SDNode *N,
8587                                     TargetLowering::DAGCombinerInfo &DCI,
8588                                     SelectionDAG &DAG) {
8589   SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8590   if (NV.getNode())
8591     N = NV.getNode();
8592   SDValue Chain = N->getOperand(0);
8593   SDValue Dest = N->getOperand(1);
8594   SDValue CCVal = N->getOperand(2);
8595   SDValue Cmp = N->getOperand(3);
8596
8597   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8598   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8599   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8600     return SDValue();
8601
8602   unsigned CmpOpc = Cmp.getOpcode();
8603   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8604     return SDValue();
8605
8606   // Only attempt folding if there is only one use of the flag and no use of the
8607   // value.
8608   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8609     return SDValue();
8610
8611   SDValue LHS = Cmp.getOperand(0);
8612   SDValue RHS = Cmp.getOperand(1);
8613
8614   assert(LHS.getValueType() == RHS.getValueType() &&
8615          "Expected the value type to be the same for both operands!");
8616   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8617     return SDValue();
8618
8619   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8620     std::swap(LHS, RHS);
8621
8622   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8623     return SDValue();
8624
8625   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8626       LHS.getOpcode() == ISD::SRL)
8627     return SDValue();
8628
8629   // Fold the compare into the branch instruction.
8630   SDValue BR;
8631   if (CC == AArch64CC::EQ)
8632     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8633   else
8634     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8635
8636   // Do not add new nodes to DAG combiner worklist.
8637   DCI.CombineTo(N, BR, false);
8638
8639   return SDValue();
8640 }
8641
8642 // vselect (v1i1 setcc) ->
8643 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
8644 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
8645 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
8646 // such VSELECT.
8647 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
8648   SDValue N0 = N->getOperand(0);
8649   EVT CCVT = N0.getValueType();
8650
8651   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
8652       CCVT.getVectorElementType() != MVT::i1)
8653     return SDValue();
8654
8655   EVT ResVT = N->getValueType(0);
8656   EVT CmpVT = N0.getOperand(0).getValueType();
8657   // Only combine when the result type is of the same size as the compared
8658   // operands.
8659   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
8660     return SDValue();
8661
8662   SDValue IfTrue = N->getOperand(1);
8663   SDValue IfFalse = N->getOperand(2);
8664   SDValue SetCC =
8665       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
8666                    N0.getOperand(0), N0.getOperand(1),
8667                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
8668   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
8669                      IfTrue, IfFalse);
8670 }
8671
8672 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
8673 /// the compare-mask instructions rather than going via NZCV, even if LHS and
8674 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
8675 /// with a vector one followed by a DUP shuffle on the result.
8676 static SDValue performSelectCombine(SDNode *N,
8677                                     TargetLowering::DAGCombinerInfo &DCI) {
8678   SelectionDAG &DAG = DCI.DAG;
8679   SDValue N0 = N->getOperand(0);
8680   EVT ResVT = N->getValueType(0);
8681
8682   if (N0.getOpcode() != ISD::SETCC)
8683     return SDValue();
8684
8685   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
8686   // scalar SetCCResultType. We also don't expect vectors, because we assume
8687   // that selects fed by vector SETCCs are canonicalized to VSELECT.
8688   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
8689          "Scalar-SETCC feeding SELECT has unexpected result type!");
8690
8691   // If NumMaskElts == 0, the comparison is larger than select result. The
8692   // largest real NEON comparison is 64-bits per lane, which means the result is
8693   // at most 32-bits and an illegal vector. Just bail out for now.
8694   EVT SrcVT = N0.getOperand(0).getValueType();
8695
8696   // Don't try to do this optimization when the setcc itself has i1 operands.
8697   // There are no legal vectors of i1, so this would be pointless.
8698   if (SrcVT == MVT::i1)
8699     return SDValue();
8700
8701   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
8702   if (!ResVT.isVector() || NumMaskElts == 0)
8703     return SDValue();
8704
8705   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
8706   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
8707
8708   // Also bail out if the vector CCVT isn't the same size as ResVT.
8709   // This can happen if the SETCC operand size doesn't divide the ResVT size
8710   // (e.g., f64 vs v3f32).
8711   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
8712     return SDValue();
8713
8714   // Make sure we didn't create illegal types, if we're not supposed to.
8715   assert(DCI.isBeforeLegalize() ||
8716          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
8717
8718   // First perform a vector comparison, where lane 0 is the one we're interested
8719   // in.
8720   SDLoc DL(N0);
8721   SDValue LHS =
8722       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
8723   SDValue RHS =
8724       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
8725   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
8726
8727   // Now duplicate the comparison mask we want across all other lanes.
8728   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
8729   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
8730   Mask = DAG.getNode(ISD::BITCAST, DL,
8731                      ResVT.changeVectorElementTypeToInteger(), Mask);
8732
8733   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
8734 }
8735
8736 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
8737                                                  DAGCombinerInfo &DCI) const {
8738   SelectionDAG &DAG = DCI.DAG;
8739   switch (N->getOpcode()) {
8740   default:
8741     break;
8742   case ISD::ADD:
8743   case ISD::SUB:
8744     return performAddSubLongCombine(N, DCI, DAG);
8745   case ISD::XOR:
8746     return performXorCombine(N, DAG, DCI, Subtarget);
8747   case ISD::MUL:
8748     return performMulCombine(N, DAG, DCI, Subtarget);
8749   case ISD::SINT_TO_FP:
8750   case ISD::UINT_TO_FP:
8751     return performIntToFpCombine(N, DAG, Subtarget);
8752   case ISD::OR:
8753     return performORCombine(N, DCI, Subtarget);
8754   case ISD::INTRINSIC_WO_CHAIN:
8755     return performIntrinsicCombine(N, DCI, Subtarget);
8756   case ISD::ANY_EXTEND:
8757   case ISD::ZERO_EXTEND:
8758   case ISD::SIGN_EXTEND:
8759     return performExtendCombine(N, DCI, DAG);
8760   case ISD::BITCAST:
8761     return performBitcastCombine(N, DCI, DAG);
8762   case ISD::CONCAT_VECTORS:
8763     return performConcatVectorsCombine(N, DCI, DAG);
8764   case ISD::SELECT:
8765     return performSelectCombine(N, DCI);
8766   case ISD::VSELECT:
8767     return performVSelectCombine(N, DCI.DAG);
8768   case ISD::STORE:
8769     return performSTORECombine(N, DCI, DAG, Subtarget);
8770   case AArch64ISD::BRCOND:
8771     return performBRCONDCombine(N, DCI, DAG);
8772   case AArch64ISD::CSEL:
8773     return performCONDCombine(N, DCI, DAG, 2, 3);
8774   case AArch64ISD::DUP:
8775     return performPostLD1Combine(N, DCI, false);
8776   case ISD::INSERT_VECTOR_ELT:
8777     return performPostLD1Combine(N, DCI, true);
8778   case ISD::INTRINSIC_VOID:
8779   case ISD::INTRINSIC_W_CHAIN:
8780     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8781     case Intrinsic::aarch64_neon_ld2:
8782     case Intrinsic::aarch64_neon_ld3:
8783     case Intrinsic::aarch64_neon_ld4:
8784     case Intrinsic::aarch64_neon_ld1x2:
8785     case Intrinsic::aarch64_neon_ld1x3:
8786     case Intrinsic::aarch64_neon_ld1x4:
8787     case Intrinsic::aarch64_neon_ld2lane:
8788     case Intrinsic::aarch64_neon_ld3lane:
8789     case Intrinsic::aarch64_neon_ld4lane:
8790     case Intrinsic::aarch64_neon_ld2r:
8791     case Intrinsic::aarch64_neon_ld3r:
8792     case Intrinsic::aarch64_neon_ld4r:
8793     case Intrinsic::aarch64_neon_st2:
8794     case Intrinsic::aarch64_neon_st3:
8795     case Intrinsic::aarch64_neon_st4:
8796     case Intrinsic::aarch64_neon_st1x2:
8797     case Intrinsic::aarch64_neon_st1x3:
8798     case Intrinsic::aarch64_neon_st1x4:
8799     case Intrinsic::aarch64_neon_st2lane:
8800     case Intrinsic::aarch64_neon_st3lane:
8801     case Intrinsic::aarch64_neon_st4lane:
8802       return performNEONPostLDSTCombine(N, DCI, DAG);
8803     default:
8804       break;
8805     }
8806   }
8807   return SDValue();
8808 }
8809
8810 // Check if the return value is used as only a return value, as otherwise
8811 // we can't perform a tail-call. In particular, we need to check for
8812 // target ISD nodes that are returns and any other "odd" constructs
8813 // that the generic analysis code won't necessarily catch.
8814 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
8815                                                SDValue &Chain) const {
8816   if (N->getNumValues() != 1)
8817     return false;
8818   if (!N->hasNUsesOfValue(1, 0))
8819     return false;
8820
8821   SDValue TCChain = Chain;
8822   SDNode *Copy = *N->use_begin();
8823   if (Copy->getOpcode() == ISD::CopyToReg) {
8824     // If the copy has a glue operand, we conservatively assume it isn't safe to
8825     // perform a tail call.
8826     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
8827         MVT::Glue)
8828       return false;
8829     TCChain = Copy->getOperand(0);
8830   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
8831     return false;
8832
8833   bool HasRet = false;
8834   for (SDNode *Node : Copy->uses()) {
8835     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8836       return false;
8837     HasRet = true;
8838   }
8839
8840   if (!HasRet)
8841     return false;
8842
8843   Chain = TCChain;
8844   return true;
8845 }
8846
8847 // Return whether the an instruction can potentially be optimized to a tail
8848 // call. This will cause the optimizers to attempt to move, or duplicate,
8849 // return instructions to help enable tail call optimizations for this
8850 // instruction.
8851 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8852   if (!CI->isTailCall())
8853     return false;
8854
8855   return true;
8856 }
8857
8858 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8859                                                    SDValue &Offset,
8860                                                    ISD::MemIndexedMode &AM,
8861                                                    bool &IsInc,
8862                                                    SelectionDAG &DAG) const {
8863   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8864     return false;
8865
8866   Base = Op->getOperand(0);
8867   // All of the indexed addressing mode instructions take a signed
8868   // 9 bit immediate offset.
8869   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8870     int64_t RHSC = (int64_t)RHS->getZExtValue();
8871     if (RHSC >= 256 || RHSC <= -256)
8872       return false;
8873     IsInc = (Op->getOpcode() == ISD::ADD);
8874     Offset = Op->getOperand(1);
8875     return true;
8876   }
8877   return false;
8878 }
8879
8880 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8881                                                       SDValue &Offset,
8882                                                       ISD::MemIndexedMode &AM,
8883                                                       SelectionDAG &DAG) const {
8884   EVT VT;
8885   SDValue Ptr;
8886   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8887     VT = LD->getMemoryVT();
8888     Ptr = LD->getBasePtr();
8889   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8890     VT = ST->getMemoryVT();
8891     Ptr = ST->getBasePtr();
8892   } else
8893     return false;
8894
8895   bool IsInc;
8896   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8897     return false;
8898   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8899   return true;
8900 }
8901
8902 bool AArch64TargetLowering::getPostIndexedAddressParts(
8903     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8904     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8905   EVT VT;
8906   SDValue Ptr;
8907   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8908     VT = LD->getMemoryVT();
8909     Ptr = LD->getBasePtr();
8910   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8911     VT = ST->getMemoryVT();
8912     Ptr = ST->getBasePtr();
8913   } else
8914     return false;
8915
8916   bool IsInc;
8917   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8918     return false;
8919   // Post-indexing updates the base, so it's not a valid transform
8920   // if that's not the same as the load's pointer.
8921   if (Ptr != Base)
8922     return false;
8923   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8924   return true;
8925 }
8926
8927 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8928                                   SelectionDAG &DAG) {
8929   SDLoc DL(N);
8930   SDValue Op = N->getOperand(0);
8931
8932   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
8933     return;
8934
8935   Op = SDValue(
8936       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8937                          DAG.getUNDEF(MVT::i32), Op,
8938                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
8939       0);
8940   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8941   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8942 }
8943
8944 void AArch64TargetLowering::ReplaceNodeResults(
8945     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8946   switch (N->getOpcode()) {
8947   default:
8948     llvm_unreachable("Don't know how to custom expand this");
8949   case ISD::BITCAST:
8950     ReplaceBITCASTResults(N, Results, DAG);
8951     return;
8952   case ISD::FP_TO_UINT:
8953   case ISD::FP_TO_SINT:
8954     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8955     // Let normal code take care of it by not adding anything to Results.
8956     return;
8957   }
8958 }
8959
8960 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8961   return true;
8962 }
8963
8964 bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8965   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8966   // reciprocal if there are three or more FDIVs.
8967   return NumUsers > 2;
8968 }
8969
8970 TargetLoweringBase::LegalizeTypeAction
8971 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8972   MVT SVT = VT.getSimpleVT();
8973   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
8974   // v4i16, v2i32 instead of to promote.
8975   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8976       || SVT == MVT::v1f32)
8977     return TypeWidenVector;
8978
8979   return TargetLoweringBase::getPreferredVectorAction(VT);
8980 }
8981
8982 // Loads and stores less than 128-bits are already atomic; ones above that
8983 // are doomed anyway, so defer to the default libcall and blame the OS when
8984 // things go wrong.
8985 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
8986   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
8987   return Size == 128;
8988 }
8989
8990 // Loads and stores less than 128-bits are already atomic; ones above that
8991 // are doomed anyway, so defer to the default libcall and blame the OS when
8992 // things go wrong.
8993 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
8994   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
8995   return Size == 128;
8996 }
8997
8998 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
8999 TargetLoweringBase::AtomicRMWExpansionKind
9000 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9001   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9002   return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9003                      : AtomicRMWExpansionKind::None;
9004 }
9005
9006 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9007   return true;
9008 }
9009
9010 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9011                                              AtomicOrdering Ord) const {
9012   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9013   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9014   bool IsAcquire = isAtLeastAcquire(Ord);
9015
9016   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9017   // intrinsic must return {i64, i64} and we have to recombine them into a
9018   // single i128 here.
9019   if (ValTy->getPrimitiveSizeInBits() == 128) {
9020     Intrinsic::ID Int =
9021         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9022     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9023
9024     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9025     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9026
9027     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9028     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9029     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9030     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9031     return Builder.CreateOr(
9032         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9033   }
9034
9035   Type *Tys[] = { Addr->getType() };
9036   Intrinsic::ID Int =
9037       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9038   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9039
9040   return Builder.CreateTruncOrBitCast(
9041       Builder.CreateCall(Ldxr, Addr),
9042       cast<PointerType>(Addr->getType())->getElementType());
9043 }
9044
9045 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9046                                                    Value *Val, Value *Addr,
9047                                                    AtomicOrdering Ord) const {
9048   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9049   bool IsRelease = isAtLeastRelease(Ord);
9050
9051   // Since the intrinsics must have legal type, the i128 intrinsics take two
9052   // parameters: "i64, i64". We must marshal Val into the appropriate form
9053   // before the call.
9054   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9055     Intrinsic::ID Int =
9056         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9057     Function *Stxr = Intrinsic::getDeclaration(M, Int);
9058     Type *Int64Ty = Type::getInt64Ty(M->getContext());
9059
9060     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9061     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9062     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9063     return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
9064   }
9065
9066   Intrinsic::ID Int =
9067       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9068   Type *Tys[] = { Addr->getType() };
9069   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9070
9071   return Builder.CreateCall2(
9072       Stxr, Builder.CreateZExtOrBitCast(
9073                 Val, Stxr->getFunctionType()->getParamType(0)),
9074       Addr);
9075 }
9076
9077 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9078     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9079   return Ty->isArrayTy();
9080 }