ARM64: scalarize v1i64 mul operation
[oota-llvm.git] / lib / Target / ARM64 / ARM64ISelLowering.cpp
1 //===-- ARM64ISelLowering.cpp - ARM64 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 ARM64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "arm64-lower"
15
16 #include "ARM64ISelLowering.h"
17 #include "ARM64PerfectShuffle.h"
18 #include "ARM64Subtarget.h"
19 #include "ARM64CallingConv.h"
20 #include "ARM64MachineFunctionInfo.h"
21 #include "ARM64TargetMachine.h"
22 #include "ARM64TargetObjectFile.h"
23 #include "MCTargetDesc/ARM64AddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
38
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
41
42 // This option should go away when tail calls fully work.
43 static cl::opt<bool>
44 EnableARM64TailCalls("arm64-tail-calls", cl::Hidden,
45                      cl::desc("Generate ARM64 tail calls (TEMPORARY OPTION)."),
46                      cl::init(true));
47
48 static cl::opt<bool>
49 StrictAlign("arm64-strict-align", cl::Hidden,
50             cl::desc("Disallow all unaligned memory accesses"));
51
52 // Place holder until extr generation is tested fully.
53 static cl::opt<bool>
54 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
55                           cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
56                           cl::init(true));
57
58 static cl::opt<bool>
59 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
60                          cl::desc("Allow ARM64 SLI/SRI formation"),
61                          cl::init(false));
62
63 //===----------------------------------------------------------------------===//
64 // ARM64 Lowering public interface.
65 //===----------------------------------------------------------------------===//
66 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
67   if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
68     return new ARM64_MachoTargetObjectFile();
69
70   return new ARM64_ELFTargetObjectFile();
71 }
72
73 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
74     : TargetLowering(TM, createTLOF(TM)) {
75   Subtarget = &TM.getSubtarget<ARM64Subtarget>();
76
77   // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
78   // we have to make something up. Arbitrarily, choose ZeroOrOne.
79   setBooleanContents(ZeroOrOneBooleanContent);
80   // When comparing vectors the result sets the different elements in the
81   // vector to all-one or all-zero.
82   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
83
84   // Set up the register classes.
85   addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
86   addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
87   addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
88   addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
89   addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
90   addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
91   addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
92
93   // Someone set us up the NEON.
94   addDRTypeForNEON(MVT::v2f32);
95   addDRTypeForNEON(MVT::v8i8);
96   addDRTypeForNEON(MVT::v4i16);
97   addDRTypeForNEON(MVT::v2i32);
98   addDRTypeForNEON(MVT::v1i64);
99   addDRTypeForNEON(MVT::v1f64);
100
101   addQRTypeForNEON(MVT::v4f32);
102   addQRTypeForNEON(MVT::v2f64);
103   addQRTypeForNEON(MVT::v16i8);
104   addQRTypeForNEON(MVT::v8i16);
105   addQRTypeForNEON(MVT::v4i32);
106   addQRTypeForNEON(MVT::v2i64);
107
108   // Compute derived properties from the register classes
109   computeRegisterProperties();
110
111   // Provide all sorts of operation actions
112   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114   setOperationAction(ISD::SETCC, MVT::i32, Custom);
115   setOperationAction(ISD::SETCC, MVT::i64, Custom);
116   setOperationAction(ISD::SETCC, MVT::f32, Custom);
117   setOperationAction(ISD::SETCC, MVT::f64, Custom);
118   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123   setOperationAction(ISD::SELECT, MVT::i32, Custom);
124   setOperationAction(ISD::SELECT, MVT::i64, Custom);
125   setOperationAction(ISD::SELECT, MVT::f32, Custom);
126   setOperationAction(ISD::SELECT, MVT::f64, Custom);
127   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138   setOperationAction(ISD::FREM, MVT::f32, Expand);
139   setOperationAction(ISD::FREM, MVT::f64, Expand);
140   setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142   // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
143   // silliness like this:
144   setOperationAction(ISD::FABS, MVT::v1f64, Expand);
145   setOperationAction(ISD::FADD, MVT::v1f64, Expand);
146   setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
147   setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
148   setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
149   setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
150   setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
151   setOperationAction(ISD::FMA, MVT::v1f64, Expand);
152   setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
153   setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
154   setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
155   setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
156   setOperationAction(ISD::FREM, MVT::v1f64, Expand);
157   setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
158   setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
159   setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
160   setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
161   setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
162   setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
163   setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
164   setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
165   setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
166   setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
167   setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
168   setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
169
170   setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
171   setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
172   setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
173   setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
174   setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
175
176   setOperationAction(ISD::MUL, MVT::v1i64, Expand);
177
178   // Custom lowering hooks are needed for XOR
179   // to fold it into CSINC/CSINV.
180   setOperationAction(ISD::XOR, MVT::i32, Custom);
181   setOperationAction(ISD::XOR, MVT::i64, Custom);
182
183   // Virtually no operation on f128 is legal, but LLVM can't expand them when
184   // there's a valid register class, so we need custom operations in most cases.
185   setOperationAction(ISD::FABS, MVT::f128, Expand);
186   setOperationAction(ISD::FADD, MVT::f128, Custom);
187   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
188   setOperationAction(ISD::FCOS, MVT::f128, Expand);
189   setOperationAction(ISD::FDIV, MVT::f128, Custom);
190   setOperationAction(ISD::FMA, MVT::f128, Expand);
191   setOperationAction(ISD::FMUL, MVT::f128, Custom);
192   setOperationAction(ISD::FNEG, MVT::f128, Expand);
193   setOperationAction(ISD::FPOW, MVT::f128, Expand);
194   setOperationAction(ISD::FREM, MVT::f128, Expand);
195   setOperationAction(ISD::FRINT, MVT::f128, Expand);
196   setOperationAction(ISD::FSIN, MVT::f128, Expand);
197   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
198   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
199   setOperationAction(ISD::FSUB, MVT::f128, Custom);
200   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
201   setOperationAction(ISD::SETCC, MVT::f128, Custom);
202   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
203   setOperationAction(ISD::SELECT, MVT::f128, Custom);
204   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
205   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
206
207   // Lowering for many of the conversions is actually specified by the non-f128
208   // type. The LowerXXX function will be trivial when f128 isn't involved.
209   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
210   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
211   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
212   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
213   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
214   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
215   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
216   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
217   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
218   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
219   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
220   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
221   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
222   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
223
224   // 128-bit atomics
225   setOperationAction(ISD::ATOMIC_SWAP, MVT::i128, Custom);
226   setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i128, Custom);
227   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
228   setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i128, Custom);
229   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i128, Custom);
230   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i128, Custom);
231   setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i128, Custom);
232   setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i128, Custom);
233   setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i128, Custom);
234   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i128, Custom);
235   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i128, Custom);
236   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i128, Custom);
237   // These are surprisingly difficult. The only single-copy atomic 128-bit
238   // instruction on AArch64 is stxp (when it succeeds). So a store can safely
239   // become a simple swap, but a load can only be determined to have been atomic
240   // if storing the same value back succeeds.
241   setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
242   setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Expand);
243
244   // Variable arguments.
245   setOperationAction(ISD::VASTART, MVT::Other, Custom);
246   setOperationAction(ISD::VAARG, MVT::Other, Custom);
247   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
248   setOperationAction(ISD::VAEND, MVT::Other, Expand);
249
250   // Variable-sized objects.
251   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
252   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
253   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
254
255   // Exception handling.
256   // FIXME: These are guesses. Has this been defined yet?
257   setExceptionPointerRegister(ARM64::X0);
258   setExceptionSelectorRegister(ARM64::X1);
259
260   // Constant pool entries
261   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
262
263   // BlockAddress
264   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
265
266   // Add/Sub overflow ops with MVT::Glues are lowered to CPSR dependences.
267   setOperationAction(ISD::ADDC, MVT::i32, Custom);
268   setOperationAction(ISD::ADDE, MVT::i32, Custom);
269   setOperationAction(ISD::SUBC, MVT::i32, Custom);
270   setOperationAction(ISD::SUBE, MVT::i32, Custom);
271   setOperationAction(ISD::ADDC, MVT::i64, Custom);
272   setOperationAction(ISD::ADDE, MVT::i64, Custom);
273   setOperationAction(ISD::SUBC, MVT::i64, Custom);
274   setOperationAction(ISD::SUBE, MVT::i64, Custom);
275
276   // ARM64 lacks both left-rotate and popcount instructions.
277   setOperationAction(ISD::ROTL, MVT::i32, Expand);
278   setOperationAction(ISD::ROTL, MVT::i64, Expand);
279
280   // ARM64 doesn't have a direct vector ->f32 conversion instructions for
281   // elements smaller than i32, so promote the input to i32 first.
282   setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
283   setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
284   setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
285   setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
286   // Similarly, there is no direct i32 -> f64 vector conversion instruction.
287   setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
288   setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
289   setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
290   setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
291
292   // ARM64 doesn't have {U|S}MUL_LOHI.
293   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
294   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
295
296   // ARM64 doesn't have MUL.2d:
297   setOperationAction(ISD::MUL, MVT::v2i64, Expand);
298
299   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
300   // counterparts, which ARM64 supports directly.
301   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
302   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
303   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
304   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
305
306   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
307   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
308
309   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
310   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
311   setOperationAction(ISD::SREM, MVT::i32, Expand);
312   setOperationAction(ISD::SREM, MVT::i64, Expand);
313   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
314   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
315   setOperationAction(ISD::UREM, MVT::i32, Expand);
316   setOperationAction(ISD::UREM, MVT::i64, Expand);
317
318   // Custom lower Add/Sub/Mul with overflow.
319   setOperationAction(ISD::SADDO, MVT::i32, Custom);
320   setOperationAction(ISD::SADDO, MVT::i64, Custom);
321   setOperationAction(ISD::UADDO, MVT::i32, Custom);
322   setOperationAction(ISD::UADDO, MVT::i64, Custom);
323   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
324   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
325   setOperationAction(ISD::USUBO, MVT::i32, Custom);
326   setOperationAction(ISD::USUBO, MVT::i64, Custom);
327   setOperationAction(ISD::SMULO, MVT::i32, Custom);
328   setOperationAction(ISD::SMULO, MVT::i64, Custom);
329   setOperationAction(ISD::UMULO, MVT::i32, Custom);
330   setOperationAction(ISD::UMULO, MVT::i64, Custom);
331
332   setOperationAction(ISD::FSIN, MVT::f32, Expand);
333   setOperationAction(ISD::FSIN, MVT::f64, Expand);
334   setOperationAction(ISD::FCOS, MVT::f32, Expand);
335   setOperationAction(ISD::FCOS, MVT::f64, Expand);
336   setOperationAction(ISD::FPOW, MVT::f32, Expand);
337   setOperationAction(ISD::FPOW, MVT::f64, Expand);
338   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
339   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
340
341   // ARM64 has implementations of a lot of rounding-like FP operations.
342   static MVT RoundingTypes[] = { MVT::f32,   MVT::f64,  MVT::v2f32,
343                                  MVT::v4f32, MVT::v2f64 };
344   for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
345     MVT Ty = RoundingTypes[I];
346     setOperationAction(ISD::FFLOOR, Ty, Legal);
347     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
348     setOperationAction(ISD::FCEIL, Ty, Legal);
349     setOperationAction(ISD::FRINT, Ty, Legal);
350     setOperationAction(ISD::FTRUNC, Ty, Legal);
351     setOperationAction(ISD::FROUND, Ty, Legal);
352   }
353
354   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
355
356   if (Subtarget->isTargetMachO()) {
357     // For iOS, we don't want to the normal expansion of a libcall to
358     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
359     // traffic.
360     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
361     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
362   } else {
363     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
364     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
365   }
366
367   // ARM64 does not have floating-point extending loads, i1 sign-extending load,
368   // floating-point truncating stores, or v2i32->v2i16 truncating store.
369   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
370   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
371   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
372   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
373   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
374   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
375   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
376   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
377   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
378   // Indexed loads and stores are supported.
379   for (unsigned im = (unsigned)ISD::PRE_INC;
380        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
381     setIndexedLoadAction(im, MVT::i8, Legal);
382     setIndexedLoadAction(im, MVT::i16, Legal);
383     setIndexedLoadAction(im, MVT::i32, Legal);
384     setIndexedLoadAction(im, MVT::i64, Legal);
385     setIndexedLoadAction(im, MVT::f64, Legal);
386     setIndexedLoadAction(im, MVT::f32, Legal);
387     setIndexedStoreAction(im, MVT::i8, Legal);
388     setIndexedStoreAction(im, MVT::i16, Legal);
389     setIndexedStoreAction(im, MVT::i32, Legal);
390     setIndexedStoreAction(im, MVT::i64, Legal);
391     setIndexedStoreAction(im, MVT::f64, Legal);
392     setIndexedStoreAction(im, MVT::f32, Legal);
393   }
394
395   // Likewise, narrowing and extending vector loads/stores aren't handled
396   // directly.
397   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
398        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
399
400     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
401                        Expand);
402
403     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
405       setTruncStoreAction((MVT::SimpleValueType)VT,
406                           (MVT::SimpleValueType)InnerVT, Expand);
407     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
408     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
410   }
411
412   // Trap.
413   setOperationAction(ISD::TRAP, MVT::Other, Legal);
414   setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
415
416   // We combine OR nodes for bitfield operations.
417   setTargetDAGCombine(ISD::OR);
418
419   // Vector add and sub nodes may conceal a high-half opportunity.
420   // Also, try to fold ADD into CSINC/CSINV..
421   setTargetDAGCombine(ISD::ADD);
422   setTargetDAGCombine(ISD::SUB);
423
424   setTargetDAGCombine(ISD::XOR);
425   setTargetDAGCombine(ISD::SINT_TO_FP);
426   setTargetDAGCombine(ISD::UINT_TO_FP);
427
428   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
429
430   setTargetDAGCombine(ISD::ANY_EXTEND);
431   setTargetDAGCombine(ISD::ZERO_EXTEND);
432   setTargetDAGCombine(ISD::SIGN_EXTEND);
433   setTargetDAGCombine(ISD::BITCAST);
434   setTargetDAGCombine(ISD::CONCAT_VECTORS);
435   setTargetDAGCombine(ISD::STORE);
436
437   setTargetDAGCombine(ISD::MUL);
438
439   setTargetDAGCombine(ISD::VSELECT);
440
441   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
442   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
443   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
444
445   setStackPointerRegisterToSaveRestore(ARM64::SP);
446
447   setSchedulingPreference(Sched::Hybrid);
448
449   // Enable TBZ/TBNZ
450   MaskAndBranchFoldingIsLegal = true;
451
452   setMinFunctionAlignment(2);
453
454   RequireStrictAlign = StrictAlign;
455 }
456
457 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
458   if (VT == MVT::v2f32) {
459     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
460     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
461
462     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
463     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
464   } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
465     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
466     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
467
468     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
469     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
470   }
471
472   // Mark vector float intrinsics as expand.
473   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
474     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
475     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
476     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
477     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
478     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
479     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
480     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
481     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
482     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
483   }
484
485   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
486   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
487   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
488   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
489   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
490   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
491   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
492   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
493   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
494   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
495   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
496   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
497
498   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
499   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
500   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
501   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
502
503   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
504   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
505   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
506   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
507   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
508
509   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
510   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
511 }
512
513 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
514   addRegisterClass(VT, &ARM64::FPR64RegClass);
515   addTypeForNEON(VT, MVT::v2i32);
516 }
517
518 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
519   addRegisterClass(VT, &ARM64::FPR128RegClass);
520   addTypeForNEON(VT, MVT::v4i32);
521 }
522
523 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
524   if (!VT.isVector())
525     return MVT::i32;
526   return VT.changeVectorElementTypeToInteger();
527 }
528
529 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
530 /// Mask are known to be either zero or one and return them in the
531 /// KnownZero/KnownOne bitsets.
532 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
533     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
534     const SelectionDAG &DAG, unsigned Depth) const {
535   switch (Op.getOpcode()) {
536   default:
537     break;
538   case ARM64ISD::CSEL: {
539     APInt KnownZero2, KnownOne2;
540     DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
541     DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
542     KnownZero &= KnownZero2;
543     KnownOne &= KnownOne2;
544     break;
545   }
546   case ISD::INTRINSIC_W_CHAIN:
547     break;
548   case ISD::INTRINSIC_WO_CHAIN:
549   case ISD::INTRINSIC_VOID: {
550     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
551     switch (IntNo) {
552     default:
553       break;
554     case Intrinsic::arm64_neon_umaxv:
555     case Intrinsic::arm64_neon_uminv: {
556       // Figure out the datatype of the vector operand. The UMINV instruction
557       // will zero extend the result, so we can mark as known zero all the
558       // bits larger than the element datatype. 32-bit or larget doesn't need
559       // this as those are legal types and will be handled by isel directly.
560       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
561       unsigned BitWidth = KnownZero.getBitWidth();
562       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
563         assert(BitWidth >= 8 && "Unexpected width!");
564         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
565         KnownZero |= Mask;
566       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
567         assert(BitWidth >= 16 && "Unexpected width!");
568         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
569         KnownZero |= Mask;
570       }
571       break;
572     } break;
573     }
574   }
575   }
576 }
577
578 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
579   return MVT::i64;
580 }
581
582 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
583   // FIXME: On ARM64, this depends on the type.
584   // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
585   // and the offset has to be a multiple of the related size in bytes.
586   return 4095;
587 }
588
589 FastISel *
590 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
591                                     const TargetLibraryInfo *libInfo) const {
592   return ARM64::createFastISel(funcInfo, libInfo);
593 }
594
595 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
596   switch (Opcode) {
597   default:
598     return 0;
599   case ARM64ISD::CALL:              return "ARM64ISD::CALL";
600   case ARM64ISD::ADRP:              return "ARM64ISD::ADRP";
601   case ARM64ISD::ADDlow:            return "ARM64ISD::ADDlow";
602   case ARM64ISD::LOADgot:           return "ARM64ISD::LOADgot";
603   case ARM64ISD::RET_FLAG:          return "ARM64ISD::RET_FLAG";
604   case ARM64ISD::BRCOND:            return "ARM64ISD::BRCOND";
605   case ARM64ISD::CSEL:              return "ARM64ISD::CSEL";
606   case ARM64ISD::FCSEL:             return "ARM64ISD::FCSEL";
607   case ARM64ISD::CSINV:             return "ARM64ISD::CSINV";
608   case ARM64ISD::CSNEG:             return "ARM64ISD::CSNEG";
609   case ARM64ISD::CSINC:             return "ARM64ISD::CSINC";
610   case ARM64ISD::THREAD_POINTER:    return "ARM64ISD::THREAD_POINTER";
611   case ARM64ISD::TLSDESC_CALL:      return "ARM64ISD::TLSDESC_CALL";
612   case ARM64ISD::ADC:               return "ARM64ISD::ADC";
613   case ARM64ISD::SBC:               return "ARM64ISD::SBC";
614   case ARM64ISD::ADDS:              return "ARM64ISD::ADDS";
615   case ARM64ISD::SUBS:              return "ARM64ISD::SUBS";
616   case ARM64ISD::ADCS:              return "ARM64ISD::ADCS";
617   case ARM64ISD::SBCS:              return "ARM64ISD::SBCS";
618   case ARM64ISD::ANDS:              return "ARM64ISD::ANDS";
619   case ARM64ISD::FCMP:              return "ARM64ISD::FCMP";
620   case ARM64ISD::FMIN:              return "ARM64ISD::FMIN";
621   case ARM64ISD::FMAX:              return "ARM64ISD::FMAX";
622   case ARM64ISD::DUP:               return "ARM64ISD::DUP";
623   case ARM64ISD::DUPLANE8:          return "ARM64ISD::DUPLANE8";
624   case ARM64ISD::DUPLANE16:         return "ARM64ISD::DUPLANE16";
625   case ARM64ISD::DUPLANE32:         return "ARM64ISD::DUPLANE32";
626   case ARM64ISD::DUPLANE64:         return "ARM64ISD::DUPLANE64";
627   case ARM64ISD::MOVI:              return "ARM64ISD::MOVI";
628   case ARM64ISD::MOVIshift:         return "ARM64ISD::MOVIshift";
629   case ARM64ISD::MOVIedit:          return "ARM64ISD::MOVIedit";
630   case ARM64ISD::MOVImsl:           return "ARM64ISD::MOVImsl";
631   case ARM64ISD::FMOV:              return "ARM64ISD::FMOV";
632   case ARM64ISD::MVNIshift:         return "ARM64ISD::MVNIshift";
633   case ARM64ISD::MVNImsl:           return "ARM64ISD::MVNImsl";
634   case ARM64ISD::BICi:              return "ARM64ISD::BICi";
635   case ARM64ISD::ORRi:              return "ARM64ISD::ORRi";
636   case ARM64ISD::NEG:               return "ARM64ISD::NEG";
637   case ARM64ISD::EXTR:              return "ARM64ISD::EXTR";
638   case ARM64ISD::ZIP1:              return "ARM64ISD::ZIP1";
639   case ARM64ISD::ZIP2:              return "ARM64ISD::ZIP2";
640   case ARM64ISD::UZP1:              return "ARM64ISD::UZP1";
641   case ARM64ISD::UZP2:              return "ARM64ISD::UZP2";
642   case ARM64ISD::TRN1:              return "ARM64ISD::TRN1";
643   case ARM64ISD::TRN2:              return "ARM64ISD::TRN2";
644   case ARM64ISD::REV16:             return "ARM64ISD::REV16";
645   case ARM64ISD::REV32:             return "ARM64ISD::REV32";
646   case ARM64ISD::REV64:             return "ARM64ISD::REV64";
647   case ARM64ISD::EXT:               return "ARM64ISD::EXT";
648   case ARM64ISD::VSHL:              return "ARM64ISD::VSHL";
649   case ARM64ISD::VLSHR:             return "ARM64ISD::VLSHR";
650   case ARM64ISD::VASHR:             return "ARM64ISD::VASHR";
651   case ARM64ISD::CMEQ:              return "ARM64ISD::CMEQ";
652   case ARM64ISD::CMGE:              return "ARM64ISD::CMGE";
653   case ARM64ISD::CMGT:              return "ARM64ISD::CMGT";
654   case ARM64ISD::CMHI:              return "ARM64ISD::CMHI";
655   case ARM64ISD::CMHS:              return "ARM64ISD::CMHS";
656   case ARM64ISD::FCMEQ:             return "ARM64ISD::FCMEQ";
657   case ARM64ISD::FCMGE:             return "ARM64ISD::FCMGE";
658   case ARM64ISD::FCMGT:             return "ARM64ISD::FCMGT";
659   case ARM64ISD::CMEQz:             return "ARM64ISD::CMEQz";
660   case ARM64ISD::CMGEz:             return "ARM64ISD::CMGEz";
661   case ARM64ISD::CMGTz:             return "ARM64ISD::CMGTz";
662   case ARM64ISD::CMLEz:             return "ARM64ISD::CMLEz";
663   case ARM64ISD::CMLTz:             return "ARM64ISD::CMLTz";
664   case ARM64ISD::FCMEQz:            return "ARM64ISD::FCMEQz";
665   case ARM64ISD::FCMGEz:            return "ARM64ISD::FCMGEz";
666   case ARM64ISD::FCMGTz:            return "ARM64ISD::FCMGTz";
667   case ARM64ISD::FCMLEz:            return "ARM64ISD::FCMLEz";
668   case ARM64ISD::FCMLTz:            return "ARM64ISD::FCMLTz";
669   case ARM64ISD::NOT:               return "ARM64ISD::NOT";
670   case ARM64ISD::BIT:               return "ARM64ISD::BIT";
671   case ARM64ISD::CBZ:               return "ARM64ISD::CBZ";
672   case ARM64ISD::CBNZ:              return "ARM64ISD::CBNZ";
673   case ARM64ISD::TBZ:               return "ARM64ISD::TBZ";
674   case ARM64ISD::TBNZ:              return "ARM64ISD::TBNZ";
675   case ARM64ISD::TC_RETURN:         return "ARM64ISD::TC_RETURN";
676   case ARM64ISD::SITOF:             return "ARM64ISD::SITOF";
677   case ARM64ISD::UITOF:             return "ARM64ISD::UITOF";
678   case ARM64ISD::SQSHL_I:           return "ARM64ISD::SQSHL_I";
679   case ARM64ISD::UQSHL_I:           return "ARM64ISD::UQSHL_I";
680   case ARM64ISD::SRSHR_I:           return "ARM64ISD::SRSHR_I";
681   case ARM64ISD::URSHR_I:           return "ARM64ISD::URSHR_I";
682   case ARM64ISD::SQSHLU_I:          return "ARM64ISD::SQSHLU_I";
683   case ARM64ISD::WrapperLarge:      return "ARM64ISD::WrapperLarge";
684   }
685 }
686
687 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
688                                   unsigned &LdrOpc, unsigned &StrOpc) {
689   static unsigned LoadBares[] = { ARM64::LDXRB, ARM64::LDXRH, ARM64::LDXRW,
690                                   ARM64::LDXRX, ARM64::LDXPX };
691   static unsigned LoadAcqs[] = { ARM64::LDAXRB, ARM64::LDAXRH, ARM64::LDAXRW,
692                                  ARM64::LDAXRX, ARM64::LDAXPX };
693   static unsigned StoreBares[] = { ARM64::STXRB, ARM64::STXRH, ARM64::STXRW,
694                                    ARM64::STXRX, ARM64::STXPX };
695   static unsigned StoreRels[] = { ARM64::STLXRB, ARM64::STLXRH, ARM64::STLXRW,
696                                   ARM64::STLXRX, ARM64::STLXPX };
697
698   unsigned *LoadOps, *StoreOps;
699   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
700     LoadOps = LoadAcqs;
701   else
702     LoadOps = LoadBares;
703
704   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
705     StoreOps = StoreRels;
706   else
707     StoreOps = StoreBares;
708
709   assert(isPowerOf2_32(Size) && Size <= 16 &&
710          "unsupported size for atomic binary op!");
711
712   LdrOpc = LoadOps[Log2_32(Size)];
713   StrOpc = StoreOps[Log2_32(Size)];
714 }
715
716 MachineBasicBlock *ARM64TargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
717                                                           MachineBasicBlock *BB,
718                                                           unsigned Size) const {
719   unsigned dest = MI->getOperand(0).getReg();
720   unsigned ptr = MI->getOperand(1).getReg();
721   unsigned oldval = MI->getOperand(2).getReg();
722   unsigned newval = MI->getOperand(3).getReg();
723   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
724   unsigned scratch = BB->getParent()->getRegInfo().createVirtualRegister(
725       &ARM64::GPR32RegClass);
726   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
727   DebugLoc dl = MI->getDebugLoc();
728
729   // FIXME: We currently always generate a seq_cst operation; we should
730   // be able to relax this in some cases.
731   unsigned ldrOpc, strOpc;
732   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
733
734   MachineFunction *MF = BB->getParent();
735   const BasicBlock *LLVM_BB = BB->getBasicBlock();
736   MachineFunction::iterator It = BB;
737   ++It; // insert the new blocks after the current block
738
739   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
740   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
741   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
742   MF->insert(It, loop1MBB);
743   MF->insert(It, loop2MBB);
744   MF->insert(It, exitMBB);
745
746   // Transfer the remainder of BB and its successor edges to exitMBB.
747   exitMBB->splice(exitMBB->begin(), BB,
748                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
749   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
750
751   //  thisMBB:
752   //   ...
753   //   fallthrough --> loop1MBB
754   BB->addSuccessor(loop1MBB);
755
756   // loop1MBB:
757   //   ldrex dest, [ptr]
758   //   cmp dest, oldval
759   //   bne exitMBB
760   BB = loop1MBB;
761   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
762   BuildMI(BB, dl, TII->get(Size == 8 ? ARM64::SUBSXrr : ARM64::SUBSWrr))
763       .addReg(Size == 8 ? ARM64::XZR : ARM64::WZR, RegState::Define)
764       .addReg(dest)
765       .addReg(oldval);
766   BuildMI(BB, dl, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(exitMBB);
767   BB->addSuccessor(loop2MBB);
768   BB->addSuccessor(exitMBB);
769
770   // loop2MBB:
771   //   strex scratch, newval, [ptr]
772   //   cmp scratch, #0
773   //   bne loop1MBB
774   BB = loop2MBB;
775   BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
776   BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loop1MBB);
777   BB->addSuccessor(loop1MBB);
778   BB->addSuccessor(exitMBB);
779
780   //  exitMBB:
781   //   ...
782   BB = exitMBB;
783
784   MI->eraseFromParent(); // The instruction is gone now.
785
786   return BB;
787 }
788
789 MachineBasicBlock *
790 ARM64TargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
791                                       unsigned Size, unsigned BinOpcode) const {
792   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
793   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
794
795   const BasicBlock *LLVM_BB = BB->getBasicBlock();
796   MachineFunction *MF = BB->getParent();
797   MachineFunction::iterator It = BB;
798   ++It;
799
800   unsigned dest = MI->getOperand(0).getReg();
801   unsigned ptr = MI->getOperand(1).getReg();
802   unsigned incr = MI->getOperand(2).getReg();
803   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
804   DebugLoc dl = MI->getDebugLoc();
805
806   unsigned ldrOpc, strOpc;
807   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
808
809   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
810   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
811   MF->insert(It, loopMBB);
812   MF->insert(It, exitMBB);
813
814   // Transfer the remainder of BB and its successor edges to exitMBB.
815   exitMBB->splice(exitMBB->begin(), BB,
816                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
817   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
818
819   MachineRegisterInfo &RegInfo = MF->getRegInfo();
820   unsigned scratch = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
821   unsigned scratch2 =
822       (!BinOpcode)
823           ? incr
824           : RegInfo.createVirtualRegister(Size == 8 ? &ARM64::GPR64RegClass
825                                                     : &ARM64::GPR32RegClass);
826
827   //  thisMBB:
828   //   ...
829   //   fallthrough --> loopMBB
830   BB->addSuccessor(loopMBB);
831
832   //  loopMBB:
833   //   ldxr dest, ptr
834   //   <binop> scratch2, dest, incr
835   //   stxr scratch, scratch2, ptr
836   //   cbnz scratch, loopMBB
837   //   fallthrough --> exitMBB
838   BB = loopMBB;
839   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
840   if (BinOpcode) {
841     // operand order needs to go the other way for NAND
842     if (BinOpcode == ARM64::BICWrr || BinOpcode == ARM64::BICXrr)
843       BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(incr).addReg(dest);
844     else
845       BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(dest).addReg(incr);
846   }
847
848   BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
849   BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loopMBB);
850
851   BB->addSuccessor(loopMBB);
852   BB->addSuccessor(exitMBB);
853
854   //  exitMBB:
855   //   ...
856   BB = exitMBB;
857
858   MI->eraseFromParent(); // The instruction is gone now.
859
860   return BB;
861 }
862
863 MachineBasicBlock *ARM64TargetLowering::EmitAtomicBinary128(
864     MachineInstr *MI, MachineBasicBlock *BB, unsigned BinOpcodeLo,
865     unsigned BinOpcodeHi) const {
866   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
867   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
868
869   const BasicBlock *LLVM_BB = BB->getBasicBlock();
870   MachineFunction *MF = BB->getParent();
871   MachineFunction::iterator It = BB;
872   ++It;
873
874   unsigned DestLo = MI->getOperand(0).getReg();
875   unsigned DestHi = MI->getOperand(1).getReg();
876   unsigned Ptr = MI->getOperand(2).getReg();
877   unsigned IncrLo = MI->getOperand(3).getReg();
878   unsigned IncrHi = MI->getOperand(4).getReg();
879   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
880   DebugLoc DL = MI->getDebugLoc();
881
882   unsigned LdrOpc, StrOpc;
883   getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
884
885   MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
886   MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
887   MF->insert(It, LoopMBB);
888   MF->insert(It, ExitMBB);
889
890   // Transfer the remainder of BB and its successor edges to exitMBB.
891   ExitMBB->splice(ExitMBB->begin(), BB,
892                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
893   ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
894
895   MachineRegisterInfo &RegInfo = MF->getRegInfo();
896   unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
897   unsigned ScratchLo = IncrLo, ScratchHi = IncrHi;
898   if (BinOpcodeLo) {
899     assert(BinOpcodeHi && "Expect neither or both opcodes to be defined");
900     ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
901     ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
902   }
903
904   //  ThisMBB:
905   //   ...
906   //   fallthrough --> LoopMBB
907   BB->addSuccessor(LoopMBB);
908
909   //  LoopMBB:
910   //   ldxp DestLo, DestHi, Ptr
911   //   <binoplo> ScratchLo, DestLo, IncrLo
912   //   <binophi> ScratchHi, DestHi, IncrHi
913   //   stxp ScratchRes, ScratchLo, ScratchHi, ptr
914   //   cbnz ScratchRes, LoopMBB
915   //   fallthrough --> ExitMBB
916   BB = LoopMBB;
917   BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
918       .addReg(DestHi, RegState::Define)
919       .addReg(Ptr);
920   if (BinOpcodeLo) {
921     // operand order needs to go the other way for NAND
922     if (BinOpcodeLo == ARM64::BICXrr) {
923       std::swap(IncrLo, DestLo);
924       std::swap(IncrHi, DestHi);
925     }
926
927     BuildMI(BB, DL, TII->get(BinOpcodeLo), ScratchLo).addReg(DestLo).addReg(
928         IncrLo);
929     BuildMI(BB, DL, TII->get(BinOpcodeHi), ScratchHi).addReg(DestHi).addReg(
930         IncrHi);
931   }
932
933   BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
934       .addReg(ScratchLo)
935       .addReg(ScratchHi)
936       .addReg(Ptr);
937   BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
938
939   BB->addSuccessor(LoopMBB);
940   BB->addSuccessor(ExitMBB);
941
942   //  ExitMBB:
943   //   ...
944   BB = ExitMBB;
945
946   MI->eraseFromParent(); // The instruction is gone now.
947
948   return BB;
949 }
950
951 MachineBasicBlock *
952 ARM64TargetLowering::EmitAtomicCmpSwap128(MachineInstr *MI,
953                                           MachineBasicBlock *BB) const {
954   unsigned DestLo = MI->getOperand(0).getReg();
955   unsigned DestHi = MI->getOperand(1).getReg();
956   unsigned Ptr = MI->getOperand(2).getReg();
957   unsigned OldValLo = MI->getOperand(3).getReg();
958   unsigned OldValHi = MI->getOperand(4).getReg();
959   unsigned NewValLo = MI->getOperand(5).getReg();
960   unsigned NewValHi = MI->getOperand(6).getReg();
961   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(7).getImm());
962   unsigned ScratchRes = BB->getParent()->getRegInfo().createVirtualRegister(
963       &ARM64::GPR32RegClass);
964   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
965   DebugLoc DL = MI->getDebugLoc();
966
967   unsigned LdrOpc, StrOpc;
968   getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
969
970   MachineFunction *MF = BB->getParent();
971   const BasicBlock *LLVM_BB = BB->getBasicBlock();
972   MachineFunction::iterator It = BB;
973   ++It; // insert the new blocks after the current block
974
975   MachineBasicBlock *Loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
976   MachineBasicBlock *Loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
977   MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
978   MF->insert(It, Loop1MBB);
979   MF->insert(It, Loop2MBB);
980   MF->insert(It, ExitMBB);
981
982   // Transfer the remainder of BB and its successor edges to exitMBB.
983   ExitMBB->splice(ExitMBB->begin(), BB,
984                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
985   ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
986
987   //  ThisMBB:
988   //   ...
989   //   fallthrough --> Loop1MBB
990   BB->addSuccessor(Loop1MBB);
991
992   // Loop1MBB:
993   //   ldxp DestLo, DestHi, [Ptr]
994   //   cmp DestLo, OldValLo
995   //   sbc xzr, DestHi, OldValHi
996   //   bne ExitMBB
997   BB = Loop1MBB;
998   BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
999       .addReg(DestHi, RegState::Define)
1000       .addReg(Ptr);
1001   BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1002       OldValLo);
1003   BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1004       OldValHi);
1005
1006   BuildMI(BB, DL, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(ExitMBB);
1007   BB->addSuccessor(Loop2MBB);
1008   BB->addSuccessor(ExitMBB);
1009
1010   // Loop2MBB:
1011   //   stxp ScratchRes, NewValLo, NewValHi, [Ptr]
1012   //   cbnz ScratchRes, Loop1MBB
1013   BB = Loop2MBB;
1014   BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1015       .addReg(NewValLo)
1016       .addReg(NewValHi)
1017       .addReg(Ptr);
1018   BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(Loop1MBB);
1019   BB->addSuccessor(Loop1MBB);
1020   BB->addSuccessor(ExitMBB);
1021
1022   //  ExitMBB:
1023   //   ...
1024   BB = ExitMBB;
1025
1026   MI->eraseFromParent(); // The instruction is gone now.
1027
1028   return BB;
1029 }
1030
1031 MachineBasicBlock *ARM64TargetLowering::EmitAtomicMinMax128(
1032     MachineInstr *MI, MachineBasicBlock *BB, unsigned CondCode) const {
1033   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
1034   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1035
1036   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1037   MachineFunction *MF = BB->getParent();
1038   MachineFunction::iterator It = BB;
1039   ++It;
1040
1041   unsigned DestLo = MI->getOperand(0).getReg();
1042   unsigned DestHi = MI->getOperand(1).getReg();
1043   unsigned Ptr = MI->getOperand(2).getReg();
1044   unsigned IncrLo = MI->getOperand(3).getReg();
1045   unsigned IncrHi = MI->getOperand(4).getReg();
1046   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
1047   DebugLoc DL = MI->getDebugLoc();
1048
1049   unsigned LdrOpc, StrOpc;
1050   getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
1051
1052   MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1053   MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054   MF->insert(It, LoopMBB);
1055   MF->insert(It, ExitMBB);
1056
1057   // Transfer the remainder of BB and its successor edges to exitMBB.
1058   ExitMBB->splice(ExitMBB->begin(), BB,
1059                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1060   ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
1061
1062   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1063   unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
1064   unsigned ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1065   unsigned ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1066
1067   //  ThisMBB:
1068   //   ...
1069   //   fallthrough --> LoopMBB
1070   BB->addSuccessor(LoopMBB);
1071
1072   //  LoopMBB:
1073   //   ldxp DestLo, DestHi, Ptr
1074   //   cmp ScratchLo, DestLo, IncrLo
1075   //   sbc xzr, ScratchHi, DestHi, IncrHi
1076   //   csel ScratchLo, DestLo, IncrLo, <cmp-op>
1077   //   csel ScratchHi, DestHi, IncrHi, <cmp-op>
1078   //   stxp ScratchRes, ScratchLo, ScratchHi, ptr
1079   //   cbnz ScratchRes, LoopMBB
1080   //   fallthrough --> ExitMBB
1081   BB = LoopMBB;
1082   BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
1083       .addReg(DestHi, RegState::Define)
1084       .addReg(Ptr);
1085
1086   BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1087       IncrLo);
1088   BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1089       IncrHi);
1090
1091   BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchLo)
1092       .addReg(DestLo)
1093       .addReg(IncrLo)
1094       .addImm(CondCode);
1095   BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchHi)
1096       .addReg(DestHi)
1097       .addReg(IncrHi)
1098       .addImm(CondCode);
1099
1100   BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1101       .addReg(ScratchLo)
1102       .addReg(ScratchHi)
1103       .addReg(Ptr);
1104   BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
1105
1106   BB->addSuccessor(LoopMBB);
1107   BB->addSuccessor(ExitMBB);
1108
1109   //  ExitMBB:
1110   //   ...
1111   BB = ExitMBB;
1112
1113   MI->eraseFromParent(); // The instruction is gone now.
1114
1115   return BB;
1116 }
1117
1118 MachineBasicBlock *
1119 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
1120                                   MachineBasicBlock *MBB) const {
1121   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1122   // phi node:
1123
1124   // OrigBB:
1125   //     [... previous instrs leading to comparison ...]
1126   //     b.ne TrueBB
1127   //     b EndBB
1128   // TrueBB:
1129   //     ; Fallthrough
1130   // EndBB:
1131   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1132
1133   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1134   MachineFunction *MF = MBB->getParent();
1135   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1136   DebugLoc DL = MI->getDebugLoc();
1137   MachineFunction::iterator It = MBB;
1138   ++It;
1139
1140   unsigned DestReg = MI->getOperand(0).getReg();
1141   unsigned IfTrueReg = MI->getOperand(1).getReg();
1142   unsigned IfFalseReg = MI->getOperand(2).getReg();
1143   unsigned CondCode = MI->getOperand(3).getImm();
1144   bool CPSRKilled = MI->getOperand(4).isKill();
1145
1146   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1147   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1148   MF->insert(It, TrueBB);
1149   MF->insert(It, EndBB);
1150
1151   // Transfer rest of current basic-block to EndBB
1152   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1153                 MBB->end());
1154   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1155
1156   BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1157   BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
1158   MBB->addSuccessor(TrueBB);
1159   MBB->addSuccessor(EndBB);
1160
1161   // TrueBB falls through to the end.
1162   TrueBB->addSuccessor(EndBB);
1163
1164   if (!CPSRKilled) {
1165     TrueBB->addLiveIn(ARM64::CPSR);
1166     EndBB->addLiveIn(ARM64::CPSR);
1167   }
1168
1169   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
1170       .addReg(IfTrueReg)
1171       .addMBB(TrueBB)
1172       .addReg(IfFalseReg)
1173       .addMBB(MBB);
1174
1175   MI->eraseFromParent();
1176   return EndBB;
1177 }
1178
1179 MachineBasicBlock *
1180 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1181                                                  MachineBasicBlock *BB) const {
1182   switch (MI->getOpcode()) {
1183   default:
1184 #ifndef NDEBUG
1185     MI->dump();
1186 #endif
1187     assert(0 && "Unexpected instruction for custom inserter!");
1188     break;
1189
1190   case ARM64::ATOMIC_LOAD_ADD_I8:
1191     return EmitAtomicBinary(MI, BB, 1, ARM64::ADDWrr);
1192   case ARM64::ATOMIC_LOAD_ADD_I16:
1193     return EmitAtomicBinary(MI, BB, 2, ARM64::ADDWrr);
1194   case ARM64::ATOMIC_LOAD_ADD_I32:
1195     return EmitAtomicBinary(MI, BB, 4, ARM64::ADDWrr);
1196   case ARM64::ATOMIC_LOAD_ADD_I64:
1197     return EmitAtomicBinary(MI, BB, 8, ARM64::ADDXrr);
1198   case ARM64::ATOMIC_LOAD_ADD_I128:
1199     return EmitAtomicBinary128(MI, BB, ARM64::ADDSXrr, ARM64::ADCXr);
1200
1201   case ARM64::ATOMIC_LOAD_AND_I8:
1202     return EmitAtomicBinary(MI, BB, 1, ARM64::ANDWrr);
1203   case ARM64::ATOMIC_LOAD_AND_I16:
1204     return EmitAtomicBinary(MI, BB, 2, ARM64::ANDWrr);
1205   case ARM64::ATOMIC_LOAD_AND_I32:
1206     return EmitAtomicBinary(MI, BB, 4, ARM64::ANDWrr);
1207   case ARM64::ATOMIC_LOAD_AND_I64:
1208     return EmitAtomicBinary(MI, BB, 8, ARM64::ANDXrr);
1209   case ARM64::ATOMIC_LOAD_AND_I128:
1210     return EmitAtomicBinary128(MI, BB, ARM64::ANDXrr, ARM64::ANDXrr);
1211
1212   case ARM64::ATOMIC_LOAD_OR_I8:
1213     return EmitAtomicBinary(MI, BB, 1, ARM64::ORRWrr);
1214   case ARM64::ATOMIC_LOAD_OR_I16:
1215     return EmitAtomicBinary(MI, BB, 2, ARM64::ORRWrr);
1216   case ARM64::ATOMIC_LOAD_OR_I32:
1217     return EmitAtomicBinary(MI, BB, 4, ARM64::ORRWrr);
1218   case ARM64::ATOMIC_LOAD_OR_I64:
1219     return EmitAtomicBinary(MI, BB, 8, ARM64::ORRXrr);
1220   case ARM64::ATOMIC_LOAD_OR_I128:
1221     return EmitAtomicBinary128(MI, BB, ARM64::ORRXrr, ARM64::ORRXrr);
1222
1223   case ARM64::ATOMIC_LOAD_XOR_I8:
1224     return EmitAtomicBinary(MI, BB, 1, ARM64::EORWrr);
1225   case ARM64::ATOMIC_LOAD_XOR_I16:
1226     return EmitAtomicBinary(MI, BB, 2, ARM64::EORWrr);
1227   case ARM64::ATOMIC_LOAD_XOR_I32:
1228     return EmitAtomicBinary(MI, BB, 4, ARM64::EORWrr);
1229   case ARM64::ATOMIC_LOAD_XOR_I64:
1230     return EmitAtomicBinary(MI, BB, 8, ARM64::EORXrr);
1231   case ARM64::ATOMIC_LOAD_XOR_I128:
1232     return EmitAtomicBinary128(MI, BB, ARM64::EORXrr, ARM64::EORXrr);
1233
1234   case ARM64::ATOMIC_LOAD_NAND_I8:
1235     return EmitAtomicBinary(MI, BB, 1, ARM64::BICWrr);
1236   case ARM64::ATOMIC_LOAD_NAND_I16:
1237     return EmitAtomicBinary(MI, BB, 2, ARM64::BICWrr);
1238   case ARM64::ATOMIC_LOAD_NAND_I32:
1239     return EmitAtomicBinary(MI, BB, 4, ARM64::BICWrr);
1240   case ARM64::ATOMIC_LOAD_NAND_I64:
1241     return EmitAtomicBinary(MI, BB, 8, ARM64::BICXrr);
1242   case ARM64::ATOMIC_LOAD_NAND_I128:
1243     return EmitAtomicBinary128(MI, BB, ARM64::BICXrr, ARM64::BICXrr);
1244
1245   case ARM64::ATOMIC_LOAD_SUB_I8:
1246     return EmitAtomicBinary(MI, BB, 1, ARM64::SUBWrr);
1247   case ARM64::ATOMIC_LOAD_SUB_I16:
1248     return EmitAtomicBinary(MI, BB, 2, ARM64::SUBWrr);
1249   case ARM64::ATOMIC_LOAD_SUB_I32:
1250     return EmitAtomicBinary(MI, BB, 4, ARM64::SUBWrr);
1251   case ARM64::ATOMIC_LOAD_SUB_I64:
1252     return EmitAtomicBinary(MI, BB, 8, ARM64::SUBXrr);
1253   case ARM64::ATOMIC_LOAD_SUB_I128:
1254     return EmitAtomicBinary128(MI, BB, ARM64::SUBSXrr, ARM64::SBCXr);
1255
1256   case ARM64::ATOMIC_LOAD_MIN_I128:
1257     return EmitAtomicMinMax128(MI, BB, ARM64CC::LT);
1258
1259   case ARM64::ATOMIC_LOAD_MAX_I128:
1260     return EmitAtomicMinMax128(MI, BB, ARM64CC::GT);
1261
1262   case ARM64::ATOMIC_LOAD_UMIN_I128:
1263     return EmitAtomicMinMax128(MI, BB, ARM64CC::CC);
1264
1265   case ARM64::ATOMIC_LOAD_UMAX_I128:
1266     return EmitAtomicMinMax128(MI, BB, ARM64CC::HI);
1267
1268   case ARM64::ATOMIC_SWAP_I8:
1269     return EmitAtomicBinary(MI, BB, 1, 0);
1270   case ARM64::ATOMIC_SWAP_I16:
1271     return EmitAtomicBinary(MI, BB, 2, 0);
1272   case ARM64::ATOMIC_SWAP_I32:
1273     return EmitAtomicBinary(MI, BB, 4, 0);
1274   case ARM64::ATOMIC_SWAP_I64:
1275     return EmitAtomicBinary(MI, BB, 8, 0);
1276   case ARM64::ATOMIC_SWAP_I128:
1277     return EmitAtomicBinary128(MI, BB, 0, 0);
1278
1279   case ARM64::ATOMIC_CMP_SWAP_I8:
1280     return EmitAtomicCmpSwap(MI, BB, 1);
1281   case ARM64::ATOMIC_CMP_SWAP_I16:
1282     return EmitAtomicCmpSwap(MI, BB, 2);
1283   case ARM64::ATOMIC_CMP_SWAP_I32:
1284     return EmitAtomicCmpSwap(MI, BB, 4);
1285   case ARM64::ATOMIC_CMP_SWAP_I64:
1286     return EmitAtomicCmpSwap(MI, BB, 8);
1287   case ARM64::ATOMIC_CMP_SWAP_I128:
1288     return EmitAtomicCmpSwap128(MI, BB);
1289
1290   case ARM64::F128CSEL:
1291     return EmitF128CSEL(MI, BB);
1292
1293   case TargetOpcode::STACKMAP:
1294   case TargetOpcode::PATCHPOINT:
1295     return emitPatchPoint(MI, BB);
1296   }
1297   llvm_unreachable("Unexpected instruction for custom inserter!");
1298 }
1299
1300 //===----------------------------------------------------------------------===//
1301 // ARM64 Lowering private implementation.
1302 //===----------------------------------------------------------------------===//
1303
1304 //===----------------------------------------------------------------------===//
1305 // Lowering Code
1306 //===----------------------------------------------------------------------===//
1307
1308 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
1309 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
1310   switch (CC) {
1311   default:
1312     llvm_unreachable("Unknown condition code!");
1313   case ISD::SETNE:
1314     return ARM64CC::NE;
1315   case ISD::SETEQ:
1316     return ARM64CC::EQ;
1317   case ISD::SETGT:
1318     return ARM64CC::GT;
1319   case ISD::SETGE:
1320     return ARM64CC::GE;
1321   case ISD::SETLT:
1322     return ARM64CC::LT;
1323   case ISD::SETLE:
1324     return ARM64CC::LE;
1325   case ISD::SETUGT:
1326     return ARM64CC::HI;
1327   case ISD::SETUGE:
1328     return ARM64CC::CS;
1329   case ISD::SETULT:
1330     return ARM64CC::CC;
1331   case ISD::SETULE:
1332     return ARM64CC::LS;
1333   }
1334 }
1335
1336 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
1337 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
1338                                 ARM64CC::CondCode &CondCode2) {
1339   CondCode2 = ARM64CC::AL;
1340   switch (CC) {
1341   default:
1342     llvm_unreachable("Unknown FP condition!");
1343   case ISD::SETEQ:
1344   case ISD::SETOEQ:
1345     CondCode = ARM64CC::EQ;
1346     break;
1347   case ISD::SETGT:
1348   case ISD::SETOGT:
1349     CondCode = ARM64CC::GT;
1350     break;
1351   case ISD::SETGE:
1352   case ISD::SETOGE:
1353     CondCode = ARM64CC::GE;
1354     break;
1355   case ISD::SETOLT:
1356     CondCode = ARM64CC::MI;
1357     break;
1358   case ISD::SETOLE:
1359     CondCode = ARM64CC::LS;
1360     break;
1361   case ISD::SETONE:
1362     CondCode = ARM64CC::MI;
1363     CondCode2 = ARM64CC::GT;
1364     break;
1365   case ISD::SETO:
1366     CondCode = ARM64CC::VC;
1367     break;
1368   case ISD::SETUO:
1369     CondCode = ARM64CC::VS;
1370     break;
1371   case ISD::SETUEQ:
1372     CondCode = ARM64CC::EQ;
1373     CondCode2 = ARM64CC::VS;
1374     break;
1375   case ISD::SETUGT:
1376     CondCode = ARM64CC::HI;
1377     break;
1378   case ISD::SETUGE:
1379     CondCode = ARM64CC::PL;
1380     break;
1381   case ISD::SETLT:
1382   case ISD::SETULT:
1383     CondCode = ARM64CC::LT;
1384     break;
1385   case ISD::SETLE:
1386   case ISD::SETULE:
1387     CondCode = ARM64CC::LE;
1388     break;
1389   case ISD::SETNE:
1390   case ISD::SETUNE:
1391     CondCode = ARM64CC::NE;
1392     break;
1393   }
1394 }
1395
1396 static bool isLegalArithImmed(uint64_t C) {
1397   // Matches ARM64DAGToDAGISel::SelectArithImmed().
1398   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1399 }
1400
1401 static SDValue emitComparison(SDValue LHS, SDValue RHS, SDLoc dl,
1402                               SelectionDAG &DAG) {
1403   EVT VT = LHS.getValueType();
1404
1405   if (VT.isFloatingPoint())
1406     return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
1407
1408   // The CMP instruction is just an alias for SUBS, and representing it as
1409   // SUBS means that it's possible to get CSE with subtract operations.
1410   // A later phase can perform the optimization of setting the destination
1411   // register to WZR/XZR if it ends up being unused.
1412   return DAG.getNode(ARM64ISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1413       .getValue(1);
1414 }
1415
1416 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1417                            SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
1418   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1419     EVT VT = RHS.getValueType();
1420     uint64_t C = RHSC->getZExtValue();
1421     if (!isLegalArithImmed(C)) {
1422       // Constant does not fit, try adjusting it by one?
1423       switch (CC) {
1424       default:
1425         break;
1426       case ISD::SETLT:
1427       case ISD::SETGE:
1428         if ((VT == MVT::i32 && C != 0x80000000 &&
1429              isLegalArithImmed((uint32_t)(C - 1))) ||
1430             (VT == MVT::i64 && C != 0x80000000ULL &&
1431              isLegalArithImmed(C - 1ULL))) {
1432           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1433           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1434           RHS = DAG.getConstant(C, VT);
1435         }
1436         break;
1437       case ISD::SETULT:
1438       case ISD::SETUGE:
1439         if ((VT == MVT::i32 && C != 0 &&
1440              isLegalArithImmed((uint32_t)(C - 1))) ||
1441             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1442           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1443           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1444           RHS = DAG.getConstant(C, VT);
1445         }
1446         break;
1447       case ISD::SETLE:
1448       case ISD::SETGT:
1449         if ((VT == MVT::i32 && C != 0x7fffffff &&
1450              isLegalArithImmed((uint32_t)(C + 1))) ||
1451             (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1452              isLegalArithImmed(C + 1ULL))) {
1453           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1454           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1455           RHS = DAG.getConstant(C, VT);
1456         }
1457         break;
1458       case ISD::SETULE:
1459       case ISD::SETUGT:
1460         if ((VT == MVT::i32 && C != 0xffffffff &&
1461              isLegalArithImmed((uint32_t)(C + 1))) ||
1462             (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1463              isLegalArithImmed(C + 1ULL))) {
1464           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1465           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1466           RHS = DAG.getConstant(C, VT);
1467         }
1468         break;
1469       }
1470     }
1471   }
1472
1473   SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
1474   ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1475   ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1476   return Cmp;
1477 }
1478
1479 static std::pair<SDValue, SDValue>
1480 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1481   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1482          "Unsupported value type");
1483   SDValue Value, Overflow;
1484   SDLoc DL(Op);
1485   SDValue LHS = Op.getOperand(0);
1486   SDValue RHS = Op.getOperand(1);
1487   unsigned Opc = 0;
1488   switch (Op.getOpcode()) {
1489   default:
1490     llvm_unreachable("Unknown overflow instruction!");
1491   case ISD::SADDO:
1492     Opc = ARM64ISD::ADDS;
1493     CC = ARM64CC::VS;
1494     break;
1495   case ISD::UADDO:
1496     Opc = ARM64ISD::ADDS;
1497     CC = ARM64CC::CS;
1498     break;
1499   case ISD::SSUBO:
1500     Opc = ARM64ISD::SUBS;
1501     CC = ARM64CC::VS;
1502     break;
1503   case ISD::USUBO:
1504     Opc = ARM64ISD::SUBS;
1505     CC = ARM64CC::CC;
1506     break;
1507   // Multiply needs a little bit extra work.
1508   case ISD::SMULO:
1509   case ISD::UMULO: {
1510     CC = ARM64CC::NE;
1511     bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1512     if (Op.getValueType() == MVT::i32) {
1513       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1514       // For a 32 bit multiply with overflow check we want the instruction
1515       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1516       // need to generate the following pattern:
1517       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1518       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1519       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1520       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1521       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1522                                 DAG.getConstant(0, MVT::i64));
1523       // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1524       // operation. We need to clear out the upper 32 bits, because we used a
1525       // widening multiply that wrote all 64 bits. In the end this should be a
1526       // noop.
1527       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1528       if (IsSigned) {
1529         // The signed overflow check requires more than just a simple check for
1530         // any bit set in the upper 32 bits of the result. These bits could be
1531         // just the sign bits of a negative number. To perform the overflow
1532         // check we have to arithmetic shift right the 32nd bit of the result by
1533         // 31 bits. Then we compare the result to the upper 32 bits.
1534         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1535                                         DAG.getConstant(32, MVT::i64));
1536         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1537         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1538                                         DAG.getConstant(31, MVT::i64));
1539         // It is important that LowerBits is last, otherwise the arithmetic
1540         // shift will not be folded into the compare (SUBS).
1541         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1542         Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1543                        .getValue(1);
1544       } else {
1545         // The overflow check for unsigned multiply is easy. We only need to
1546         // check if any of the upper 32 bits are set. This can be done with a
1547         // CMP (shifted register). For that we need to generate the following
1548         // pattern:
1549         // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1550         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1551                                         DAG.getConstant(32, MVT::i64));
1552         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1553         Overflow =
1554             DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1555                         UpperBits).getValue(1);
1556       }
1557       break;
1558     }
1559     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1560     // For the 64 bit multiply
1561     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1562     if (IsSigned) {
1563       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1564       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1565                                       DAG.getConstant(63, MVT::i64));
1566       // It is important that LowerBits is last, otherwise the arithmetic
1567       // shift will not be folded into the compare (SUBS).
1568       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1569       Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1570                      .getValue(1);
1571     } else {
1572       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1573       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1574       Overflow =
1575           DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1576                       UpperBits).getValue(1);
1577     }
1578     break;
1579   }
1580   } // switch (...)
1581
1582   if (Opc) {
1583     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1584
1585     // Emit the ARM64 operation with overflow check.
1586     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1587     Overflow = Value.getValue(1);
1588   }
1589   return std::make_pair(Value, Overflow);
1590 }
1591
1592 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1593                                            RTLIB::Libcall Call) const {
1594   SmallVector<SDValue, 2> Ops;
1595   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1596     Ops.push_back(Op.getOperand(i));
1597
1598   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1599                      SDLoc(Op)).first;
1600 }
1601
1602 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1603   SDValue Sel = Op.getOperand(0);
1604   SDValue Other = Op.getOperand(1);
1605
1606   // If neither operand is a SELECT_CC, give up.
1607   if (Sel.getOpcode() != ISD::SELECT_CC)
1608     std::swap(Sel, Other);
1609   if (Sel.getOpcode() != ISD::SELECT_CC)
1610     return Op;
1611
1612   // The folding we want to perform is:
1613   // (xor x, (select_cc a, b, cc, 0, -1) )
1614   //   -->
1615   // (csel x, (xor x, -1), cc ...)
1616   //
1617   // The latter will get matched to a CSINV instruction.
1618
1619   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1620   SDValue LHS = Sel.getOperand(0);
1621   SDValue RHS = Sel.getOperand(1);
1622   SDValue TVal = Sel.getOperand(2);
1623   SDValue FVal = Sel.getOperand(3);
1624   SDLoc dl(Sel);
1625
1626   // FIXME: This could be generalized to non-integer comparisons.
1627   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1628     return Op;
1629
1630   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1631   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1632
1633   // The the values aren't constants, this isn't the pattern we're looking for.
1634   if (!CFVal || !CTVal)
1635     return Op;
1636
1637   // We can commute the SELECT_CC by inverting the condition.  This
1638   // might be needed to make this fit into a CSINV pattern.
1639   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1640     std::swap(TVal, FVal);
1641     std::swap(CTVal, CFVal);
1642     CC = ISD::getSetCCInverse(CC, true);
1643   }
1644
1645   // If the constants line up, perform the transform!
1646   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1647     SDValue CCVal;
1648     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1649
1650     FVal = Other;
1651     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1652                        DAG.getConstant(-1ULL, Other.getValueType()));
1653
1654     return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1655                        CCVal, Cmp);
1656   }
1657
1658   return Op;
1659 }
1660
1661 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1662   EVT VT = Op.getValueType();
1663
1664   // Let legalize expand this if it isn't a legal type yet.
1665   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1666     return SDValue();
1667
1668   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1669
1670   unsigned Opc;
1671   bool ExtraOp = false;
1672   switch (Op.getOpcode()) {
1673   default:
1674     assert(0 && "Invalid code");
1675   case ISD::ADDC:
1676     Opc = ARM64ISD::ADDS;
1677     break;
1678   case ISD::SUBC:
1679     Opc = ARM64ISD::SUBS;
1680     break;
1681   case ISD::ADDE:
1682     Opc = ARM64ISD::ADCS;
1683     ExtraOp = true;
1684     break;
1685   case ISD::SUBE:
1686     Opc = ARM64ISD::SBCS;
1687     ExtraOp = true;
1688     break;
1689   }
1690
1691   if (!ExtraOp)
1692     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1693   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1694                      Op.getOperand(2));
1695 }
1696
1697 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1698   // Let legalize expand this if it isn't a legal type yet.
1699   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1700     return SDValue();
1701
1702   ARM64CC::CondCode CC;
1703   // The actual operation that sets the overflow or carry flag.
1704   SDValue Value, Overflow;
1705   std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1706
1707   // We use 0 and 1 as false and true values.
1708   SDValue TVal = DAG.getConstant(1, MVT::i32);
1709   SDValue FVal = DAG.getConstant(0, MVT::i32);
1710
1711   // We use an inverted condition, because the conditional select is inverted
1712   // too. This will allow it to be selected to a single instruction:
1713   // CSINC Wd, WZR, WZR, invert(cond).
1714   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1715   Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1716                          Overflow);
1717
1718   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1719   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1720 }
1721
1722 // Prefetch operands are:
1723 // 1: Address to prefetch
1724 // 2: bool isWrite
1725 // 3: int locality (0 = no locality ... 3 = extreme locality)
1726 // 4: bool isDataCache
1727 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1728   SDLoc DL(Op);
1729   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1730   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1731   // The data thing is not used.
1732   // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1733
1734   bool IsStream = !Locality;
1735   // When the locality number is set
1736   if (Locality) {
1737     // The front-end should have filtered out the out-of-range values
1738     assert(Locality <= 3 && "Prefetch locality out-of-range");
1739     // The locality degree is the opposite of the cache speed.
1740     // Put the number the other way around.
1741     // The encoding starts at 0 for level 1
1742     Locality = 3 - Locality;
1743   }
1744
1745   // built the mask value encoding the expected behavior.
1746   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1747                    (Locality << 1) |    // Cache level bits
1748                    (unsigned)IsStream;  // Stream bit
1749   return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1750                      DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1751 }
1752
1753 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1754                                             SelectionDAG &DAG) const {
1755   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1756
1757   RTLIB::Libcall LC;
1758   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1759
1760   return LowerF128Call(Op, DAG, LC);
1761 }
1762
1763 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1764                                            SelectionDAG &DAG) const {
1765   if (Op.getOperand(0).getValueType() != MVT::f128) {
1766     // It's legal except when f128 is involved
1767     return Op;
1768   }
1769
1770   RTLIB::Libcall LC;
1771   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1772
1773   // FP_ROUND node has a second operand indicating whether it is known to be
1774   // precise. That doesn't take part in the LibCall so we can't directly use
1775   // LowerF128Call.
1776   SDValue SrcVal = Op.getOperand(0);
1777   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1778                      /*isSigned*/ false, SDLoc(Op)).first;
1779 }
1780
1781 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1782   // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1783   // Any additional optimization in this function should be recorded
1784   // in the cost tables.
1785   EVT InVT = Op.getOperand(0).getValueType();
1786   EVT VT = Op.getValueType();
1787
1788   // FP_TO_XINT conversion from the same type are legal.
1789   if (VT.getSizeInBits() == InVT.getSizeInBits())
1790     return Op;
1791
1792   if (InVT == MVT::v2f64) {
1793     SDLoc dl(Op);
1794     SDValue Cv = DAG.getNode(Op.getOpcode(), dl, MVT::v2i64, Op.getOperand(0));
1795     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1796   }
1797
1798   // Type changing conversions are illegal.
1799   return SDValue();
1800 }
1801
1802 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1803                                             SelectionDAG &DAG) const {
1804   if (Op.getOperand(0).getValueType().isVector())
1805     return LowerVectorFP_TO_INT(Op, DAG);
1806
1807   if (Op.getOperand(0).getValueType() != MVT::f128) {
1808     // It's legal except when f128 is involved
1809     return Op;
1810   }
1811
1812   RTLIB::Libcall LC;
1813   if (Op.getOpcode() == ISD::FP_TO_SINT)
1814     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1815   else
1816     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1817
1818   SmallVector<SDValue, 2> Ops;
1819   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1820     Ops.push_back(Op.getOperand(i));
1821
1822   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1823                      SDLoc(Op)).first;
1824 }
1825
1826 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1827   // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1828   // Any additional optimization in this function should be recorded
1829   // in the cost tables.
1830   EVT VT = Op.getValueType();
1831   SDLoc dl(Op);
1832   SDValue In = Op.getOperand(0);
1833   EVT InVT = In.getValueType();
1834
1835   // v2i32 to v2f32 is legal.
1836   if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1837     return Op;
1838
1839   // This function only handles v2f64 outputs.
1840   if (VT == MVT::v2f64) {
1841     // Extend the input argument to a v2i64 that we can feed into the
1842     // floating point conversion. Zero or sign extend based on whether
1843     // we're doing a signed or unsigned float conversion.
1844     unsigned Opc =
1845         Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1846     assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1847     SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1848     return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1849   }
1850
1851   // Scalarize v2i64 to v2f32 conversions.
1852   std::vector<SDValue> BuildVectorOps;
1853   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1854     SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1855                                DAG.getConstant(i, MVT::i64));
1856     Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1857     BuildVectorOps.push_back(Sclr);
1858   }
1859
1860   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1861                      BuildVectorOps.size());
1862 }
1863
1864 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1865                                             SelectionDAG &DAG) const {
1866   if (Op.getValueType().isVector())
1867     return LowerVectorINT_TO_FP(Op, DAG);
1868
1869   // i128 conversions are libcalls.
1870   if (Op.getOperand(0).getValueType() == MVT::i128)
1871     return SDValue();
1872
1873   // Other conversions are legal, unless it's to the completely software-based
1874   // fp128.
1875   if (Op.getValueType() != MVT::f128)
1876     return Op;
1877
1878   RTLIB::Libcall LC;
1879   if (Op.getOpcode() == ISD::SINT_TO_FP)
1880     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1881   else
1882     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1883
1884   return LowerF128Call(Op, DAG, LC);
1885 }
1886
1887 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1888   // For iOS, we want to call an alternative entry point: __sincos_stret,
1889   // which returns the values in two S / D registers.
1890   SDLoc dl(Op);
1891   SDValue Arg = Op.getOperand(0);
1892   EVT ArgVT = Arg.getValueType();
1893   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1894
1895   ArgListTy Args;
1896   ArgListEntry Entry;
1897
1898   Entry.Node = Arg;
1899   Entry.Ty = ArgTy;
1900   Entry.isSExt = false;
1901   Entry.isZExt = false;
1902   Args.push_back(Entry);
1903
1904   const char *LibcallName =
1905       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1906   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1907
1908   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1909   TargetLowering::CallLoweringInfo CLI(
1910       DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1911       CallingConv::Fast, /*isTaillCall=*/false,
1912       /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1913   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1914   return CallResult.first;
1915 }
1916
1917 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1918                                             SelectionDAG &DAG) const {
1919   switch (Op.getOpcode()) {
1920   default:
1921     llvm_unreachable("unimplemented operand");
1922     return SDValue();
1923   case ISD::GlobalAddress:
1924     return LowerGlobalAddress(Op, DAG);
1925   case ISD::GlobalTLSAddress:
1926     return LowerGlobalTLSAddress(Op, DAG);
1927   case ISD::SETCC:
1928     return LowerSETCC(Op, DAG);
1929   case ISD::BR_CC:
1930     return LowerBR_CC(Op, DAG);
1931   case ISD::SELECT:
1932     return LowerSELECT(Op, DAG);
1933   case ISD::SELECT_CC:
1934     return LowerSELECT_CC(Op, DAG);
1935   case ISD::JumpTable:
1936     return LowerJumpTable(Op, DAG);
1937   case ISD::ConstantPool:
1938     return LowerConstantPool(Op, DAG);
1939   case ISD::BlockAddress:
1940     return LowerBlockAddress(Op, DAG);
1941   case ISD::VASTART:
1942     return LowerVASTART(Op, DAG);
1943   case ISD::VACOPY:
1944     return LowerVACOPY(Op, DAG);
1945   case ISD::VAARG:
1946     return LowerVAARG(Op, DAG);
1947   case ISD::ADDC:
1948   case ISD::ADDE:
1949   case ISD::SUBC:
1950   case ISD::SUBE:
1951     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1952   case ISD::SADDO:
1953   case ISD::UADDO:
1954   case ISD::SSUBO:
1955   case ISD::USUBO:
1956   case ISD::SMULO:
1957   case ISD::UMULO:
1958     return LowerXALUO(Op, DAG);
1959   case ISD::FADD:
1960     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1961   case ISD::FSUB:
1962     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1963   case ISD::FMUL:
1964     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1965   case ISD::FDIV:
1966     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1967   case ISD::FP_ROUND:
1968     return LowerFP_ROUND(Op, DAG);
1969   case ISD::FP_EXTEND:
1970     return LowerFP_EXTEND(Op, DAG);
1971   case ISD::FRAMEADDR:
1972     return LowerFRAMEADDR(Op, DAG);
1973   case ISD::RETURNADDR:
1974     return LowerRETURNADDR(Op, DAG);
1975   case ISD::INSERT_VECTOR_ELT:
1976     return LowerINSERT_VECTOR_ELT(Op, DAG);
1977   case ISD::EXTRACT_VECTOR_ELT:
1978     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1979   case ISD::BUILD_VECTOR:
1980     return LowerBUILD_VECTOR(Op, DAG);
1981   case ISD::VECTOR_SHUFFLE:
1982     return LowerVECTOR_SHUFFLE(Op, DAG);
1983   case ISD::EXTRACT_SUBVECTOR:
1984     return LowerEXTRACT_SUBVECTOR(Op, DAG);
1985   case ISD::SRA:
1986   case ISD::SRL:
1987   case ISD::SHL:
1988     return LowerVectorSRA_SRL_SHL(Op, DAG);
1989   case ISD::SHL_PARTS:
1990     return LowerShiftLeftParts(Op, DAG);
1991   case ISD::SRL_PARTS:
1992   case ISD::SRA_PARTS:
1993     return LowerShiftRightParts(Op, DAG);
1994   case ISD::CTPOP:
1995     return LowerCTPOP(Op, DAG);
1996   case ISD::FCOPYSIGN:
1997     return LowerFCOPYSIGN(Op, DAG);
1998   case ISD::AND:
1999     return LowerVectorAND(Op, DAG);
2000   case ISD::OR:
2001     return LowerVectorOR(Op, DAG);
2002   case ISD::XOR:
2003     return LowerXOR(Op, DAG);
2004   case ISD::PREFETCH:
2005     return LowerPREFETCH(Op, DAG);
2006   case ISD::SINT_TO_FP:
2007   case ISD::UINT_TO_FP:
2008     return LowerINT_TO_FP(Op, DAG);
2009   case ISD::FP_TO_SINT:
2010   case ISD::FP_TO_UINT:
2011     return LowerFP_TO_INT(Op, DAG);
2012   case ISD::FSINCOS:
2013     return LowerFSINCOS(Op, DAG);
2014   }
2015 }
2016
2017 /// getFunctionAlignment - Return the Log2 alignment of this function.
2018 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
2019   return 2;
2020 }
2021
2022 //===----------------------------------------------------------------------===//
2023 //                      Calling Convention Implementation
2024 //===----------------------------------------------------------------------===//
2025
2026 #include "ARM64GenCallingConv.inc"
2027
2028 /// Selects the correct CCAssignFn for a the given CallingConvention
2029 /// value.
2030 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2031                                                    bool IsVarArg) const {
2032   switch (CC) {
2033   default:
2034     llvm_unreachable("Unsupported calling convention.");
2035   case CallingConv::WebKit_JS:
2036     return CC_ARM64_WebKit_JS;
2037   case CallingConv::C:
2038   case CallingConv::Fast:
2039     if (!Subtarget->isTargetDarwin())
2040       return CC_ARM64_AAPCS;
2041     return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
2042   }
2043 }
2044
2045 SDValue ARM64TargetLowering::LowerFormalArguments(
2046     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2047     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2048     SmallVectorImpl<SDValue> &InVals) const {
2049   MachineFunction &MF = DAG.getMachineFunction();
2050   MachineFrameInfo *MFI = MF.getFrameInfo();
2051
2052   // Assign locations to all of the incoming arguments.
2053   SmallVector<CCValAssign, 16> ArgLocs;
2054   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2055                  getTargetMachine(), ArgLocs, *DAG.getContext());
2056
2057   // At this point, Ins[].VT may already be promoted to i32. To correctly
2058   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2059   // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2060   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2061   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2062   // LocVT.
2063   unsigned NumArgs = Ins.size();
2064   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2065   unsigned CurArgIdx = 0;
2066   for (unsigned i = 0; i != NumArgs; ++i) {
2067     MVT ValVT = Ins[i].VT;
2068     std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
2069     CurArgIdx = Ins[i].OrigArgIndex;
2070
2071     // Get type of the original argument.
2072     EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2073     MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2074     // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2075     MVT LocVT = ValVT;
2076     if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2077       LocVT = MVT::i8;
2078     else if (ActualMVT == MVT::i16)
2079       LocVT = MVT::i16;
2080
2081     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2082     bool Res =
2083         AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2084     assert(!Res && "Call operand has unhandled type");
2085     (void)Res;
2086   }
2087
2088   SmallVector<SDValue, 16> ArgValues;
2089   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2090     CCValAssign &VA = ArgLocs[i];
2091
2092     // Arguments stored in registers.
2093     if (VA.isRegLoc()) {
2094       EVT RegVT = VA.getLocVT();
2095
2096       SDValue ArgValue;
2097       const TargetRegisterClass *RC;
2098
2099       if (RegVT == MVT::i32)
2100         RC = &ARM64::GPR32RegClass;
2101       else if (RegVT == MVT::i64)
2102         RC = &ARM64::GPR64RegClass;
2103       else if (RegVT == MVT::f32)
2104         RC = &ARM64::FPR32RegClass;
2105       else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
2106                RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
2107                RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
2108         RC = &ARM64::FPR64RegClass;
2109       else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
2110                RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
2111         RC = &ARM64::FPR128RegClass;
2112       else
2113         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2114
2115       // Transform the arguments in physical registers into virtual ones.
2116       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2117       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2118
2119       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2120       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2121       // truncate to the right size.
2122       switch (VA.getLocInfo()) {
2123       default:
2124         llvm_unreachable("Unknown loc info!");
2125       case CCValAssign::Full:
2126         break;
2127       case CCValAssign::BCvt:
2128         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2129         break;
2130       case CCValAssign::SExt:
2131         ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2132                                DAG.getValueType(VA.getValVT()));
2133         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2134         break;
2135       case CCValAssign::ZExt:
2136         ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2137                                DAG.getValueType(VA.getValVT()));
2138         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2139         break;
2140       }
2141
2142       InVals.push_back(ArgValue);
2143
2144     } else { // VA.isRegLoc()
2145       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2146       unsigned ArgOffset = VA.getLocMemOffset();
2147       unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2148       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2149
2150       // Create load nodes to retrieve arguments from the stack.
2151       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2152       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
2153                                    MachinePointerInfo::getFixedStack(FI), false,
2154                                    false, false, 0));
2155     }
2156   }
2157
2158   // varargs
2159   if (isVarArg) {
2160     if (!Subtarget->isTargetDarwin()) {
2161       // The AAPCS variadic function ABI is identical to the non-variadic
2162       // one. As a result there may be more arguments in registers and we should
2163       // save them for future reference.
2164       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2165     }
2166
2167     ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
2168     // This will point to the next argument passed via stack.
2169     unsigned StackOffset = CCInfo.getNextStackOffset();
2170     // We currently pass all varargs at 8-byte alignment.
2171     StackOffset = ((StackOffset + 7) & ~7);
2172     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2173   }
2174
2175   return Chain;
2176 }
2177
2178 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2179                                               SelectionDAG &DAG, SDLoc DL,
2180                                               SDValue &Chain) const {
2181   MachineFunction &MF = DAG.getMachineFunction();
2182   MachineFrameInfo *MFI = MF.getFrameInfo();
2183   ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
2184
2185   SmallVector<SDValue, 8> MemOps;
2186
2187   static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
2188                                           ARM64::X3, ARM64::X4, ARM64::X5,
2189                                           ARM64::X6, ARM64::X7 };
2190   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2191   unsigned FirstVariadicGPR =
2192       CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
2193
2194   static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
2195                                           ARM64::Q3, ARM64::Q4, ARM64::Q5,
2196                                           ARM64::Q6, ARM64::Q7 };
2197   static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2198   unsigned FirstVariadicFPR =
2199       CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
2200
2201   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2202   int GPRIdx = 0;
2203   if (GPRSaveSize != 0) {
2204     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2205
2206     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2207
2208     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2209       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
2210       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2211       SDValue Store =
2212           DAG.getStore(Val.getValue(1), DL, Val, FIN,
2213                        MachinePointerInfo::getStack(i * 8), false, false, 0);
2214       MemOps.push_back(Store);
2215       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2216                         DAG.getConstant(8, getPointerTy()));
2217     }
2218   }
2219
2220   unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2221   int FPRIdx = 0;
2222   if (FPRSaveSize != 0) {
2223     FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2224
2225     SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2226
2227     for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2228       unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
2229       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
2230       SDValue Store =
2231           DAG.getStore(Val.getValue(1), DL, Val, FIN,
2232                        MachinePointerInfo::getStack(i * 16), false, false, 0);
2233       MemOps.push_back(Store);
2234       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2235                         DAG.getConstant(16, getPointerTy()));
2236     }
2237   }
2238
2239   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2240   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2241   FuncInfo->setVarArgsFPRIndex(FPRIdx);
2242   FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2243
2244   if (!MemOps.empty()) {
2245     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2246                         MemOps.size());
2247   }
2248 }
2249
2250 /// LowerCallResult - Lower the result values of a call into the
2251 /// appropriate copies out of appropriate physical registers.
2252 SDValue ARM64TargetLowering::LowerCallResult(
2253     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2254     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2255     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2256     SDValue ThisVal) const {
2257   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2258                                                          : RetCC_ARM64_AAPCS;
2259   // Assign locations to each value returned by this call.
2260   SmallVector<CCValAssign, 16> RVLocs;
2261   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2262                  getTargetMachine(), RVLocs, *DAG.getContext());
2263   CCInfo.AnalyzeCallResult(Ins, RetCC);
2264
2265   // Copy all of the result registers out of their specified physreg.
2266   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2267     CCValAssign VA = RVLocs[i];
2268
2269     // Pass 'this' value directly from the argument to return value, to avoid
2270     // reg unit interference
2271     if (i == 0 && isThisReturn) {
2272       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2273              "unexpected return calling convention register assignment");
2274       InVals.push_back(ThisVal);
2275       continue;
2276     }
2277
2278     SDValue Val =
2279         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2280     Chain = Val.getValue(1);
2281     InFlag = Val.getValue(2);
2282
2283     switch (VA.getLocInfo()) {
2284     default:
2285       llvm_unreachable("Unknown loc info!");
2286     case CCValAssign::Full:
2287       break;
2288     case CCValAssign::BCvt:
2289       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2290       break;
2291     }
2292
2293     InVals.push_back(Val);
2294   }
2295
2296   return Chain;
2297 }
2298
2299 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
2300     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2301     bool isCalleeStructRet, bool isCallerStructRet,
2302     const SmallVectorImpl<ISD::OutputArg> &Outs,
2303     const SmallVectorImpl<SDValue> &OutVals,
2304     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2305   // Look for obvious safe cases to perform tail call optimization that do not
2306   // require ABI changes. This is what gcc calls sibcall.
2307
2308   // Do not sibcall optimize vararg calls unless the call site is not passing
2309   // any arguments.
2310   if (isVarArg && !Outs.empty())
2311     return false;
2312
2313   // Also avoid sibcall optimization if either caller or callee uses struct
2314   // return semantics.
2315   if (isCalleeStructRet || isCallerStructRet)
2316     return false;
2317
2318   // Note that currently ARM64 "C" calling convention and "Fast" calling
2319   // convention are compatible. If/when that ever changes, we'll need to
2320   // add checks here to make sure any interactions are OK.
2321
2322   // If the callee takes no arguments then go on to check the results of the
2323   // call.
2324   if (!Outs.empty()) {
2325     // Check if stack adjustment is needed. For now, do not do this if any
2326     // argument is passed on the stack.
2327     SmallVector<CCValAssign, 16> ArgLocs;
2328     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2329                    getTargetMachine(), ArgLocs, *DAG.getContext());
2330     CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
2331     CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2332     if (CCInfo.getNextStackOffset()) {
2333       // Check if the arguments are already laid out in the right way as
2334       // the caller's fixed stack objects.
2335       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2336            ++i, ++realArgIdx) {
2337         CCValAssign &VA = ArgLocs[i];
2338         if (VA.getLocInfo() == CCValAssign::Indirect)
2339           return false;
2340         if (VA.needsCustom()) {
2341           // Just don't handle anything that needs custom adjustments for now.
2342           // If need be, we can revisit later, but we shouldn't ever end up
2343           // here.
2344           return false;
2345         } else if (!VA.isRegLoc()) {
2346           // Likewise, don't try to handle stack based arguments for the
2347           // time being.
2348           return false;
2349         }
2350       }
2351     }
2352   }
2353
2354   return true;
2355 }
2356 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2357 /// and add input and output parameter nodes.
2358 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2359                                        SmallVectorImpl<SDValue> &InVals) const {
2360   SelectionDAG &DAG = CLI.DAG;
2361   SDLoc &DL = CLI.DL;
2362   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2363   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2364   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2365   SDValue Chain = CLI.Chain;
2366   SDValue Callee = CLI.Callee;
2367   bool &IsTailCall = CLI.IsTailCall;
2368   CallingConv::ID CallConv = CLI.CallConv;
2369   bool IsVarArg = CLI.IsVarArg;
2370
2371   MachineFunction &MF = DAG.getMachineFunction();
2372   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2373   bool IsThisReturn = false;
2374
2375   // If tail calls are explicitly disabled, make sure not to use them.
2376   if (!EnableARM64TailCalls)
2377     IsTailCall = false;
2378
2379   if (IsTailCall) {
2380     // Check if it's really possible to do a tail call.
2381     IsTailCall = isEligibleForTailCallOptimization(
2382         Callee, CallConv, IsVarArg, IsStructRet,
2383         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2384     // We don't support GuaranteedTailCallOpt, only automatically
2385     // detected sibcalls.
2386     // FIXME: Re-evaluate. Is this true? Should it be true?
2387     if (IsTailCall)
2388       ++NumTailCalls;
2389   }
2390
2391   // Analyze operands of the call, assigning locations to each operand.
2392   SmallVector<CCValAssign, 16> ArgLocs;
2393   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2394                  getTargetMachine(), ArgLocs, *DAG.getContext());
2395
2396   if (IsVarArg) {
2397     // Handle fixed and variable vector arguments differently.
2398     // Variable vector arguments always go into memory.
2399     unsigned NumArgs = Outs.size();
2400
2401     for (unsigned i = 0; i != NumArgs; ++i) {
2402       MVT ArgVT = Outs[i].VT;
2403       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2404       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2405                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2406       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2407       assert(!Res && "Call operand has unhandled type");
2408       (void)Res;
2409     }
2410   } else {
2411     // At this point, Outs[].VT may already be promoted to i32. To correctly
2412     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2413     // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2414     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2415     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2416     // LocVT.
2417     unsigned NumArgs = Outs.size();
2418     for (unsigned i = 0; i != NumArgs; ++i) {
2419       MVT ValVT = Outs[i].VT;
2420       // Get type of the original argument.
2421       EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2422                                   /*AllowUnknown*/ true);
2423       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2424       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2425       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2426       MVT LocVT = ValVT;
2427       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2428         LocVT = MVT::i8;
2429       else if (ActualMVT == MVT::i16)
2430         LocVT = MVT::i16;
2431
2432       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2433       bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2434       assert(!Res && "Call operand has unhandled type");
2435       (void)Res;
2436     }
2437   }
2438
2439   // Get a count of how many bytes are to be pushed on the stack.
2440   unsigned NumBytes = CCInfo.getNextStackOffset();
2441
2442   // Adjust the stack pointer for the new arguments...
2443   // These operations are automatically eliminated by the prolog/epilog pass
2444   if (!IsTailCall)
2445     Chain =
2446         DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2447
2448   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2449
2450   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2451   SmallVector<SDValue, 8> MemOpChains;
2452
2453   // Walk the register/memloc assignments, inserting copies/loads.
2454   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2455        ++i, ++realArgIdx) {
2456     CCValAssign &VA = ArgLocs[i];
2457     SDValue Arg = OutVals[realArgIdx];
2458     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2459
2460     // Promote the value if needed.
2461     switch (VA.getLocInfo()) {
2462     default:
2463       llvm_unreachable("Unknown loc info!");
2464     case CCValAssign::Full:
2465       break;
2466     case CCValAssign::SExt:
2467       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2468       break;
2469     case CCValAssign::ZExt:
2470       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2471       break;
2472     case CCValAssign::AExt:
2473       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2474       break;
2475     case CCValAssign::BCvt:
2476       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2477       break;
2478     case CCValAssign::FPExt:
2479       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2480       break;
2481     }
2482
2483     if (VA.isRegLoc()) {
2484       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2485         assert(VA.getLocVT() == MVT::i64 &&
2486                "unexpected calling convention register assignment");
2487         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2488                "unexpected use of 'returned'");
2489         IsThisReturn = true;
2490       }
2491       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2492     } else {
2493       assert(VA.isMemLoc());
2494       // There's no reason we can't support stack args w/ tailcall, but
2495       // we currently don't, so assert if we see one.
2496       assert(!IsTailCall && "stack argument with tail call!?");
2497       unsigned LocMemOffset = VA.getLocMemOffset();
2498       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2499       PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2500
2501       // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2502       // promoted to a legal register type i32, we should truncate Arg back to
2503       // i1/i8/i16.
2504       if (Arg.getValueType().isSimple() &&
2505           Arg.getValueType().getSimpleVT() == MVT::i32 &&
2506           (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2507            VA.getLocVT() == MVT::i16))
2508         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2509
2510       SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2511                                    MachinePointerInfo::getStack(LocMemOffset),
2512                                    false, false, 0);
2513       MemOpChains.push_back(Store);
2514     }
2515   }
2516
2517   if (!MemOpChains.empty())
2518     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2519                         MemOpChains.size());
2520
2521   // Build a sequence of copy-to-reg nodes chained together with token chain
2522   // and flag operands which copy the outgoing args into the appropriate regs.
2523   SDValue InFlag;
2524   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2525     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2526                              RegsToPass[i].second, InFlag);
2527     InFlag = Chain.getValue(1);
2528   }
2529
2530   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2531   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2532   // node so that legalize doesn't hack it.
2533   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2534       Subtarget->isTargetMachO()) {
2535     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2536       const GlobalValue *GV = G->getGlobal();
2537       bool InternalLinkage = GV->hasInternalLinkage();
2538       if (InternalLinkage)
2539         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2540       else {
2541         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2542                                             ARM64II::MO_GOT);
2543         Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2544       }
2545     } else if (ExternalSymbolSDNode *S =
2546                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
2547       const char *Sym = S->getSymbol();
2548       Callee =
2549           DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2550       Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2551     }
2552   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2553     const GlobalValue *GV = G->getGlobal();
2554     Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2555   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2556     const char *Sym = S->getSymbol();
2557     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2558   }
2559
2560   std::vector<SDValue> Ops;
2561   Ops.push_back(Chain);
2562   Ops.push_back(Callee);
2563
2564   // Add argument registers to the end of the list so that they are known live
2565   // into the call.
2566   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2567     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2568                                   RegsToPass[i].second.getValueType()));
2569
2570   // Add a register mask operand representing the call-preserved registers.
2571   const uint32_t *Mask;
2572   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2573   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2574   if (IsThisReturn) {
2575     // For 'this' returns, use the X0-preserving mask if applicable
2576     Mask = ARI->getThisReturnPreservedMask(CallConv);
2577     if (!Mask) {
2578       IsThisReturn = false;
2579       Mask = ARI->getCallPreservedMask(CallConv);
2580     }
2581   } else
2582     Mask = ARI->getCallPreservedMask(CallConv);
2583
2584   assert(Mask && "Missing call preserved mask for calling convention");
2585   Ops.push_back(DAG.getRegisterMask(Mask));
2586
2587   if (InFlag.getNode())
2588     Ops.push_back(InFlag);
2589
2590   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2591
2592   // If we're doing a tall call, use a TC_RETURN here rather than an
2593   // actual call instruction.
2594   if (IsTailCall)
2595     return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2596
2597   // Returns a chain and a flag for retval copy to use.
2598   Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2599   InFlag = Chain.getValue(1);
2600
2601   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2602                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2603   if (!Ins.empty())
2604     InFlag = Chain.getValue(1);
2605
2606   // Handle result values, copying them out of physregs into vregs that we
2607   // return.
2608   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2609                          InVals, IsThisReturn,
2610                          IsThisReturn ? OutVals[0] : SDValue());
2611 }
2612
2613 bool ARM64TargetLowering::CanLowerReturn(
2614     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2615     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2616   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2617                                                          : RetCC_ARM64_AAPCS;
2618   SmallVector<CCValAssign, 16> RVLocs;
2619   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2620   return CCInfo.CheckReturn(Outs, RetCC);
2621 }
2622
2623 SDValue
2624 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2625                                  bool isVarArg,
2626                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2627                                  const SmallVectorImpl<SDValue> &OutVals,
2628                                  SDLoc DL, SelectionDAG &DAG) const {
2629   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2630                                                          : RetCC_ARM64_AAPCS;
2631   SmallVector<CCValAssign, 16> RVLocs;
2632   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2633                  getTargetMachine(), RVLocs, *DAG.getContext());
2634   CCInfo.AnalyzeReturn(Outs, RetCC);
2635
2636   // Copy the result values into the output registers.
2637   SDValue Flag;
2638   SmallVector<SDValue, 4> RetOps(1, Chain);
2639   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2640        ++i, ++realRVLocIdx) {
2641     CCValAssign &VA = RVLocs[i];
2642     assert(VA.isRegLoc() && "Can only return in registers!");
2643     SDValue Arg = OutVals[realRVLocIdx];
2644
2645     switch (VA.getLocInfo()) {
2646     default:
2647       llvm_unreachable("Unknown loc info!");
2648     case CCValAssign::Full:
2649       break;
2650     case CCValAssign::BCvt:
2651       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2652       break;
2653     }
2654
2655     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2656     Flag = Chain.getValue(1);
2657     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2658   }
2659
2660   RetOps[0] = Chain; // Update chain.
2661
2662   // Add the flag if we have it.
2663   if (Flag.getNode())
2664     RetOps.push_back(Flag);
2665
2666   return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2667                      RetOps.size());
2668 }
2669
2670 //===----------------------------------------------------------------------===//
2671 //  Other Lowering Code
2672 //===----------------------------------------------------------------------===//
2673
2674 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2675                                                 SelectionDAG &DAG) const {
2676   EVT PtrVT = getPointerTy();
2677   SDLoc DL(Op);
2678   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2679   unsigned char OpFlags =
2680       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2681
2682   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2683          "unexpected offset in global node");
2684
2685   // This also catched the large code model case for Darwin.
2686   if ((OpFlags & ARM64II::MO_GOT) != 0) {
2687     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2688     // FIXME: Once remat is capable of dealing with instructions with register
2689     // operands, expand this into two nodes instead of using a wrapper node.
2690     return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2691   }
2692
2693   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2694     const unsigned char MO_NC = ARM64II::MO_NC;
2695     return DAG.getNode(
2696         ARM64ISD::WrapperLarge, DL, PtrVT,
2697         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2698         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2699         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2700         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2701   } else {
2702     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2703     // the only correct model on Darwin.
2704     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2705                                             OpFlags | ARM64II::MO_PAGE);
2706     unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2707     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2708
2709     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2710     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2711   }
2712 }
2713
2714 /// \brief Convert a TLS address reference into the correct sequence of loads
2715 /// and calls to compute the variable's address (for Darwin, currently) and
2716 /// return an SDValue containing the final node.
2717
2718 /// Darwin only has one TLS scheme which must be capable of dealing with the
2719 /// fully general situation, in the worst case. This means:
2720 ///     + "extern __thread" declaration.
2721 ///     + Defined in a possibly unknown dynamic library.
2722 ///
2723 /// The general system is that each __thread variable has a [3 x i64] descriptor
2724 /// which contains information used by the runtime to calculate the address. The
2725 /// only part of this the compiler needs to know about is the first xword, which
2726 /// contains a function pointer that must be called with the address of the
2727 /// entire descriptor in "x0".
2728 ///
2729 /// Since this descriptor may be in a different unit, in general even the
2730 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2731 /// is:
2732 ///     adrp x0, _var@TLVPPAGE
2733 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
2734 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
2735 ///                                      ; the function pointer
2736 ///     blr x1                           ; Uses descriptor address in x0
2737 ///     ; Address of _var is now in x0.
2738 ///
2739 /// If the address of _var's descriptor *is* known to the linker, then it can
2740 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2741 /// a slight efficiency gain.
2742 SDValue
2743 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2744                                                  SelectionDAG &DAG) const {
2745   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2746
2747   SDLoc DL(Op);
2748   MVT PtrVT = getPointerTy();
2749   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2750
2751   SDValue TLVPAddr =
2752       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2753   SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2754
2755   // The first entry in the descriptor is a function pointer that we must call
2756   // to obtain the address of the variable.
2757   SDValue Chain = DAG.getEntryNode();
2758   SDValue FuncTLVGet =
2759       DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2760                   false, true, true, 8);
2761   Chain = FuncTLVGet.getValue(1);
2762
2763   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2764   MFI->setAdjustsStack(true);
2765
2766   // TLS calls preserve all registers except those that absolutely must be
2767   // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2768   // silly).
2769   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2770   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2771   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2772
2773   // Finally, we can make the call. This is just a degenerate version of a
2774   // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2775   // the address of the variable in this thread.
2776   Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2777   Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2778                       Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2779                       DAG.getRegisterMask(Mask), Chain.getValue(1));
2780   return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2781 }
2782
2783 /// When accessing thread-local variables under either the general-dynamic or
2784 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2785 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2786 /// is a function pointer to carry out the resolution. This function takes the
2787 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2788 /// other registers (except LR, CPSR) are preserved.
2789 ///
2790 /// Thus, the ideal call sequence on AArch64 is:
2791 ///
2792 ///     adrp x0, :tlsdesc:thread_var
2793 ///     ldr x8, [x0, :tlsdesc_lo12:thread_var]
2794 ///     add x0, x0, :tlsdesc_lo12:thread_var
2795 ///     .tlsdesccall thread_var
2796 ///     blr x8
2797 ///     (TPIDR_EL0 offset now in x0).
2798 ///
2799 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2800 /// relocation to help the linker relax this sequence if it turns out to be too
2801 /// conservative.
2802 ///
2803 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2804 /// is harmless.
2805 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2806                                                  SDValue DescAddr, SDLoc DL,
2807                                                  SelectionDAG &DAG) const {
2808   EVT PtrVT = getPointerTy();
2809
2810   // The function we need to call is simply the first entry in the GOT for this
2811   // descriptor, load it in preparation.
2812   SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2813
2814   // TLS calls preserve all registers except those that absolutely must be
2815   // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2816   // silly).
2817   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2818   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2819   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2820
2821   // The function takes only one argument: the address of the descriptor itself
2822   // in X0.
2823   SDValue Glue, Chain;
2824   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2825   Glue = Chain.getValue(1);
2826
2827   // We're now ready to populate the argument list, as with a normal call:
2828   SmallVector<SDValue, 6> Ops;
2829   Ops.push_back(Chain);
2830   Ops.push_back(Func);
2831   Ops.push_back(SymAddr);
2832   Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2833   Ops.push_back(DAG.getRegisterMask(Mask));
2834   Ops.push_back(Glue);
2835
2836   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2837   Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2838   Glue = Chain.getValue(1);
2839
2840   return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2841 }
2842
2843 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2844                                                       SelectionDAG &DAG) const {
2845   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2846   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2847          "ELF TLS only supported in small memory model");
2848   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2849
2850   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2851
2852   SDValue TPOff;
2853   EVT PtrVT = getPointerTy();
2854   SDLoc DL(Op);
2855   const GlobalValue *GV = GA->getGlobal();
2856
2857   SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2858
2859   if (Model == TLSModel::LocalExec) {
2860     SDValue HiVar = DAG.getTargetGlobalAddress(
2861         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2862     SDValue LoVar = DAG.getTargetGlobalAddress(
2863         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2864
2865     TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2866                                        DAG.getTargetConstant(16, MVT::i32)),
2867                     0);
2868     TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2869                                        DAG.getTargetConstant(0, MVT::i32)),
2870                     0);
2871   } else if (Model == TLSModel::InitialExec) {
2872     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2873     TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2874   } else if (Model == TLSModel::LocalDynamic) {
2875     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2876     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2877     // the beginning of the module's TLS region, followed by a DTPREL offset
2878     // calculation.
2879
2880     // These accesses will need deduplicating if there's more than one.
2881     ARM64FunctionInfo *MFI =
2882         DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2883     MFI->incNumLocalDynamicTLSAccesses();
2884
2885     // Accesses used in this sequence go via the TLS descriptor which lives in
2886     // the GOT. Prepare an address we can use to handle this.
2887     SDValue HiDesc = DAG.getTargetExternalSymbol(
2888         "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2889     SDValue LoDesc = DAG.getTargetExternalSymbol(
2890         "_TLS_MODULE_BASE_", PtrVT,
2891         ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2892
2893     // First argument to the descriptor call is the address of the descriptor
2894     // itself.
2895     SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2896     DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2897
2898     // The call needs a relocation too for linker relaxation. It doesn't make
2899     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2900     // the address.
2901     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2902                                                   ARM64II::MO_TLS);
2903
2904     // Now we can calculate the offset from TPIDR_EL0 to this module's
2905     // thread-local area.
2906     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2907
2908     // Now use :dtprel_whatever: operations to calculate this variable's offset
2909     // in its thread-storage area.
2910     SDValue HiVar = DAG.getTargetGlobalAddress(
2911         GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2912     SDValue LoVar = DAG.getTargetGlobalAddress(
2913         GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2914
2915     SDValue DTPOff =
2916         SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2917                                    DAG.getTargetConstant(16, MVT::i32)),
2918                 0);
2919     DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2920                                         DAG.getTargetConstant(0, MVT::i32)),
2921                      0);
2922
2923     TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2924   } else if (Model == TLSModel::GeneralDynamic) {
2925     // Accesses used in this sequence go via the TLS descriptor which lives in
2926     // the GOT. Prepare an address we can use to handle this.
2927     SDValue HiDesc = DAG.getTargetGlobalAddress(
2928         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2929     SDValue LoDesc = DAG.getTargetGlobalAddress(
2930         GV, DL, PtrVT, 0,
2931         ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2932
2933     // First argument to the descriptor call is the address of the descriptor
2934     // itself.
2935     SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2936     DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2937
2938     // The call needs a relocation too for linker relaxation. It doesn't make
2939     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2940     // the address.
2941     SDValue SymAddr =
2942         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2943
2944     // Finally we can make a call to calculate the offset from tpidr_el0.
2945     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2946   } else
2947     llvm_unreachable("Unsupported ELF TLS access model");
2948
2949   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2950 }
2951
2952 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2953                                                    SelectionDAG &DAG) const {
2954   if (Subtarget->isTargetDarwin())
2955     return LowerDarwinGlobalTLSAddress(Op, DAG);
2956   else if (Subtarget->isTargetELF())
2957     return LowerELFGlobalTLSAddress(Op, DAG);
2958
2959   llvm_unreachable("Unexpected platform trying to use TLS");
2960 }
2961 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2962   SDValue Chain = Op.getOperand(0);
2963   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2964   SDValue LHS = Op.getOperand(2);
2965   SDValue RHS = Op.getOperand(3);
2966   SDValue Dest = Op.getOperand(4);
2967   SDLoc dl(Op);
2968
2969   // Handle f128 first, since lowering it will result in comparing the return
2970   // value of a libcall against zero, which is just what the rest of LowerBR_CC
2971   // is expecting to deal with.
2972   if (LHS.getValueType() == MVT::f128) {
2973     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2974
2975     // If softenSetCCOperands returned a scalar, we need to compare the result
2976     // against zero to select between true and false values.
2977     if (RHS.getNode() == 0) {
2978       RHS = DAG.getConstant(0, LHS.getValueType());
2979       CC = ISD::SETNE;
2980     }
2981   }
2982
2983   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2984   // instruction.
2985   unsigned Opc = LHS.getOpcode();
2986   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2987       cast<ConstantSDNode>(RHS)->isOne() &&
2988       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2989        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2990     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2991            "Unexpected condition code.");
2992     // Only lower legal XALUO ops.
2993     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2994       return SDValue();
2995
2996     // The actual operation with overflow check.
2997     ARM64CC::CondCode OFCC;
2998     SDValue Value, Overflow;
2999     std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
3000
3001     if (CC == ISD::SETNE)
3002       OFCC = getInvertedCondCode(OFCC);
3003     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3004
3005     return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
3006                        CCVal, Overflow);
3007   }
3008
3009   if (LHS.getValueType().isInteger()) {
3010     assert((LHS.getValueType() == RHS.getValueType()) &&
3011            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3012
3013     // If the RHS of the comparison is zero, we can potentially fold this
3014     // to a specialized branch.
3015     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3016     if (RHSC && RHSC->getZExtValue() == 0) {
3017       if (CC == ISD::SETEQ) {
3018         // See if we can use a TBZ to fold in an AND as well.
3019         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3020         // out of bounds, a late MI-layer pass rewrites branches.
3021         // 403.gcc is an example that hits this case.
3022         if (LHS.getOpcode() == ISD::AND &&
3023             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3024             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3025           SDValue Test = LHS.getOperand(0);
3026           uint64_t Mask = LHS.getConstantOperandVal(1);
3027
3028           // TBZ only operates on i64's, but the ext should be free.
3029           if (Test.getValueType() == MVT::i32)
3030             Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3031
3032           return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
3033                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3034         }
3035
3036         return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3037       } else if (CC == ISD::SETNE) {
3038         // See if we can use a TBZ to fold in an AND as well.
3039         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3040         // out of bounds, a late MI-layer pass rewrites branches.
3041         // 403.gcc is an example that hits this case.
3042         if (LHS.getOpcode() == ISD::AND &&
3043             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3044             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3045           SDValue Test = LHS.getOperand(0);
3046           uint64_t Mask = LHS.getConstantOperandVal(1);
3047
3048           // TBNZ only operates on i64's, but the ext should be free.
3049           if (Test.getValueType() == MVT::i32)
3050             Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3051
3052           return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3053                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3054         }
3055
3056         return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3057       }
3058     }
3059
3060     SDValue CCVal;
3061     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3062     return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3063                        Cmp);
3064   }
3065
3066   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3067
3068   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3069   // clean.  Some of them require two branches to implement.
3070   SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3071   ARM64CC::CondCode CC1, CC2;
3072   changeFPCCToARM64CC(CC, CC1, CC2);
3073   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3074   SDValue BR1 =
3075       DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3076   if (CC2 != ARM64CC::AL) {
3077     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3078     return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3079                        Cmp);
3080   }
3081
3082   return BR1;
3083 }
3084
3085 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3086                                             SelectionDAG &DAG) const {
3087   EVT VT = Op.getValueType();
3088   SDLoc DL(Op);
3089
3090   SDValue In1 = Op.getOperand(0);
3091   SDValue In2 = Op.getOperand(1);
3092   EVT SrcVT = In2.getValueType();
3093   if (SrcVT != VT) {
3094     if (SrcVT == MVT::f32 && VT == MVT::f64)
3095       In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3096     else if (SrcVT == MVT::f64 && VT == MVT::f32)
3097       In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3098     else
3099       // FIXME: Src type is different, bail out for now. Can VT really be a
3100       // vector type?
3101       return SDValue();
3102   }
3103
3104   EVT VecVT;
3105   EVT EltVT;
3106   SDValue EltMask, VecVal1, VecVal2;
3107   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3108     EltVT = MVT::i32;
3109     VecVT = MVT::v4i32;
3110     EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3111
3112     if (!VT.isVector()) {
3113       VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3114                                           DAG.getUNDEF(VecVT), In1);
3115       VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3116                                           DAG.getUNDEF(VecVT), In2);
3117     } else {
3118       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3119       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3120     }
3121   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3122     EltVT = MVT::i64;
3123     VecVT = MVT::v2i64;
3124
3125     // We want to materialize a mask with the the high bit set, but the AdvSIMD
3126     // immediate moves cannot materialize that in a single instruction for
3127     // 64-bit elements. Instead, materialize zero and then negate it.
3128     EltMask = DAG.getConstant(0, EltVT);
3129
3130     if (!VT.isVector()) {
3131       VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3132                                           DAG.getUNDEF(VecVT), In1);
3133       VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3134                                           DAG.getUNDEF(VecVT), In2);
3135     } else {
3136       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3137       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3138     }
3139   } else {
3140     llvm_unreachable("Invalid type for copysign!");
3141   }
3142
3143   std::vector<SDValue> BuildVectorOps;
3144   for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3145     BuildVectorOps.push_back(EltMask);
3146
3147   SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
3148                                  &BuildVectorOps[0], BuildVectorOps.size());
3149
3150   // If we couldn't materialize the mask above, then the mask vector will be
3151   // the zero vector, and we need to negate it here.
3152   if (VT == MVT::f64 || VT == MVT::v2f64) {
3153     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3154     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3155     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3156   }
3157
3158   SDValue Sel =
3159       DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3160
3161   if (VT == MVT::f32)
3162     return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
3163   else if (VT == MVT::f64)
3164     return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
3165   else
3166     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3167 }
3168
3169 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3170   if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3171           AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3172     return SDValue();
3173
3174   // While there is no integer popcount instruction, it can
3175   // be more efficiently lowered to the following sequence that uses
3176   // AdvSIMD registers/instructions as long as the copies to/from
3177   // the AdvSIMD registers are cheap.
3178   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
3179   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
3180   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
3181   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
3182   SDValue Val = Op.getOperand(0);
3183   SDLoc DL(Op);
3184   EVT VT = Op.getValueType();
3185   SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3186
3187   SDValue VecVal;
3188   if (VT == MVT::i32) {
3189     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3190     VecVal =
3191         DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
3192   } else {
3193     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3194   }
3195
3196   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3197   SDValue UaddLV = DAG.getNode(
3198       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3199       DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
3200
3201   if (VT == MVT::i64)
3202     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3203   return UaddLV;
3204 }
3205
3206 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3207
3208   if (Op.getValueType().isVector())
3209     return LowerVSETCC(Op, DAG);
3210
3211   SDValue LHS = Op.getOperand(0);
3212   SDValue RHS = Op.getOperand(1);
3213   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3214   SDLoc dl(Op);
3215
3216   // We chose ZeroOrOneBooleanContents, so use zero and one.
3217   EVT VT = Op.getValueType();
3218   SDValue TVal = DAG.getConstant(1, VT);
3219   SDValue FVal = DAG.getConstant(0, VT);
3220
3221   // Handle f128 first, since one possible outcome is a normal integer
3222   // comparison which gets picked up by the next if statement.
3223   if (LHS.getValueType() == MVT::f128) {
3224     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3225
3226     // If softenSetCCOperands returned a scalar, use it.
3227     if (RHS.getNode() == 0) {
3228       assert(LHS.getValueType() == Op.getValueType() &&
3229              "Unexpected setcc expansion!");
3230       return LHS;
3231     }
3232   }
3233
3234   if (LHS.getValueType().isInteger()) {
3235     SDValue CCVal;
3236     SDValue Cmp =
3237         getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3238
3239     // Note that we inverted the condition above, so we reverse the order of
3240     // the true and false operands here.  This will allow the setcc to be
3241     // matched to a single CSINC instruction.
3242     return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3243   }
3244
3245   // Now we know we're dealing with FP values.
3246   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3247
3248   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3249   // and do the comparison.
3250   SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3251
3252   ARM64CC::CondCode CC1, CC2;
3253   changeFPCCToARM64CC(CC, CC1, CC2);
3254   if (CC2 == ARM64CC::AL) {
3255     changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3256     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3257
3258     // Note that we inverted the condition above, so we reverse the order of
3259     // the true and false operands here.  This will allow the setcc to be
3260     // matched to a single CSINC instruction.
3261     return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3262   } else {
3263     // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3264     // clean.  Some of them require two CSELs to implement.  As is in this case,
3265     // we emit the first CSEL and then emit a second using the output of the
3266     // first as the RHS.  We're effectively OR'ing the two CC's together.
3267
3268     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3269     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3270     SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3271
3272     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3273     return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3274   }
3275 }
3276
3277 /// A SELECT_CC operation is really some kind of max or min if both values being
3278 /// compared are, in some sense, equal to the results in either case. However,
3279 /// it is permissible to compare f32 values and produce directly extended f64
3280 /// values.
3281 ///
3282 /// Extending the comparison operands would also be allowed, but is less likely
3283 /// to happen in practice since their use is right here. Note that truncate
3284 /// operations would *not* be semantically equivalent.
3285 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3286   if (Cmp == Result)
3287     return true;
3288
3289   ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3290   ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3291   if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3292       Result.getValueType() == MVT::f64) {
3293     bool Lossy;
3294     APFloat CmpVal = CCmp->getValueAPF();
3295     CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3296     return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3297   }
3298
3299   return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3300 }
3301
3302 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3303   SDValue CC = Op->getOperand(0);
3304   SDValue TVal = Op->getOperand(1);
3305   SDValue FVal = Op->getOperand(2);
3306   SDLoc DL(Op);
3307
3308   unsigned Opc = CC.getOpcode();
3309   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3310   // instruction.
3311   if (CC.getResNo() == 1 &&
3312       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3313        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3314     // Only lower legal XALUO ops.
3315     if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3316       return SDValue();
3317
3318     ARM64CC::CondCode OFCC;
3319     SDValue Value, Overflow;
3320     std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
3321     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3322
3323     return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
3324                        Overflow);
3325   }
3326
3327   if (CC.getOpcode() == ISD::SETCC)
3328     return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3329                            cast<CondCodeSDNode>(CC.getOperand(2))->get());
3330   else
3331     return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3332                            FVal, ISD::SETNE);
3333 }
3334
3335 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
3336                                             SelectionDAG &DAG) const {
3337   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3338   SDValue LHS = Op.getOperand(0);
3339   SDValue RHS = Op.getOperand(1);
3340   SDValue TVal = Op.getOperand(2);
3341   SDValue FVal = Op.getOperand(3);
3342   SDLoc dl(Op);
3343
3344   // Handle f128 first, because it will result in a comparison of some RTLIB
3345   // call result against zero.
3346   if (LHS.getValueType() == MVT::f128) {
3347     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3348
3349     // If softenSetCCOperands returned a scalar, we need to compare the result
3350     // against zero to select between true and false values.
3351     if (RHS.getNode() == 0) {
3352       RHS = DAG.getConstant(0, LHS.getValueType());
3353       CC = ISD::SETNE;
3354     }
3355   }
3356
3357   // Handle integers first.
3358   if (LHS.getValueType().isInteger()) {
3359     assert((LHS.getValueType() == RHS.getValueType()) &&
3360            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3361
3362     unsigned Opcode = ARM64ISD::CSEL;
3363
3364     // If both the TVal and the FVal are constants, see if we can swap them in
3365     // order to for a CSINV or CSINC out of them.
3366     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3367     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3368
3369     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3370       std::swap(TVal, FVal);
3371       std::swap(CTVal, CFVal);
3372       CC = ISD::getSetCCInverse(CC, true);
3373     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3374       std::swap(TVal, FVal);
3375       std::swap(CTVal, CFVal);
3376       CC = ISD::getSetCCInverse(CC, true);
3377     } else if (TVal.getOpcode() == ISD::XOR) {
3378       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3379       // with a CSINV rather than a CSEL.
3380       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3381
3382       if (CVal && CVal->isAllOnesValue()) {
3383         std::swap(TVal, FVal);
3384         std::swap(CTVal, CFVal);
3385         CC = ISD::getSetCCInverse(CC, true);
3386       }
3387     } else if (TVal.getOpcode() == ISD::SUB) {
3388       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3389       // that we can match with a CSNEG rather than a CSEL.
3390       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3391
3392       if (CVal && CVal->isNullValue()) {
3393         std::swap(TVal, FVal);
3394         std::swap(CTVal, CFVal);
3395         CC = ISD::getSetCCInverse(CC, true);
3396       }
3397     } else if (CTVal && CFVal) {
3398       const int64_t TrueVal = CTVal->getSExtValue();
3399       const int64_t FalseVal = CFVal->getSExtValue();
3400       bool Swap = false;
3401
3402       // If both TVal and FVal are constants, see if FVal is the
3403       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3404       // instead of a CSEL in that case.
3405       if (TrueVal == ~FalseVal) {
3406         Opcode = ARM64ISD::CSINV;
3407       } else if (TrueVal == -FalseVal) {
3408         Opcode = ARM64ISD::CSNEG;
3409       } else if (TVal.getValueType() == MVT::i32) {
3410         // If our operands are only 32-bit wide, make sure we use 32-bit
3411         // arithmetic for the check whether we can use CSINC. This ensures that
3412         // the addition in the check will wrap around properly in case there is
3413         // an overflow (which would not be the case if we do the check with
3414         // 64-bit arithmetic).
3415         const uint32_t TrueVal32 = CTVal->getZExtValue();
3416         const uint32_t FalseVal32 = CFVal->getZExtValue();
3417
3418         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3419           Opcode = ARM64ISD::CSINC;
3420
3421           if (TrueVal32 > FalseVal32) {
3422             Swap = true;
3423           }
3424         }
3425         // 64-bit check whether we can use CSINC.
3426       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3427         Opcode = ARM64ISD::CSINC;
3428
3429         if (TrueVal > FalseVal) {
3430           Swap = true;
3431         }
3432       }
3433
3434       // Swap TVal and FVal if necessary.
3435       if (Swap) {
3436         std::swap(TVal, FVal);
3437         std::swap(CTVal, CFVal);
3438         CC = ISD::getSetCCInverse(CC, true);
3439       }
3440
3441       if (Opcode != ARM64ISD::CSEL) {
3442         // Drop FVal since we can get its value by simply inverting/negating
3443         // TVal.
3444         FVal = TVal;
3445       }
3446     }
3447
3448     SDValue CCVal;
3449     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3450
3451     EVT VT = Op.getValueType();
3452     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3453   }
3454
3455   // Now we know we're dealing with FP values.
3456   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3457   assert(LHS.getValueType() == RHS.getValueType());
3458   EVT VT = Op.getValueType();
3459
3460   // Try to match this select into a max/min operation, which have dedicated
3461   // opcode in the instruction set.
3462   // NOTE: This is not correct in the presence of NaNs, so we only enable this
3463   // in no-NaNs mode.
3464   if (getTargetMachine().Options.NoNaNsFPMath) {
3465     if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3466         selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3467       CC = ISD::getSetCCSwappedOperands(CC);
3468       std::swap(TVal, FVal);
3469     }
3470
3471     if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3472         selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3473       switch (CC) {
3474       default:
3475         break;
3476       case ISD::SETGT:
3477       case ISD::SETGE:
3478       case ISD::SETUGT:
3479       case ISD::SETUGE:
3480       case ISD::SETOGT:
3481       case ISD::SETOGE:
3482         return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3483         break;
3484       case ISD::SETLT:
3485       case ISD::SETLE:
3486       case ISD::SETULT:
3487       case ISD::SETULE:
3488       case ISD::SETOLT:
3489       case ISD::SETOLE:
3490         return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3491         break;
3492       }
3493     }
3494   }
3495
3496   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3497   // and do the comparison.
3498   SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3499
3500   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3501   // clean.  Some of them require two CSELs to implement.
3502   ARM64CC::CondCode CC1, CC2;
3503   changeFPCCToARM64CC(CC, CC1, CC2);
3504   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3505   SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3506
3507   // If we need a second CSEL, emit it, using the output of the first as the
3508   // RHS.  We're effectively OR'ing the two CC's together.
3509   if (CC2 != ARM64CC::AL) {
3510     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3511     return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3512   }
3513
3514   // Otherwise, return the output of the first CSEL.
3515   return CS1;
3516 }
3517
3518 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3519                                             SelectionDAG &DAG) const {
3520   // Jump table entries as PC relative offsets. No additional tweaking
3521   // is necessary here. Just get the address of the jump table.
3522   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3523   EVT PtrVT = getPointerTy();
3524   SDLoc DL(Op);
3525
3526   SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3527   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3528                                       ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3529   SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3530   return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3531 }
3532
3533 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3534                                                SelectionDAG &DAG) const {
3535   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3536   EVT PtrVT = getPointerTy();
3537   SDLoc DL(Op);
3538
3539   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3540     // Use the GOT for the large code model on iOS.
3541     if (Subtarget->isTargetMachO()) {
3542       SDValue GotAddr = DAG.getTargetConstantPool(
3543           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3544           ARM64II::MO_GOT);
3545       return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3546     }
3547
3548     const unsigned char MO_NC = ARM64II::MO_NC;
3549     return DAG.getNode(
3550         ARM64ISD::WrapperLarge, DL, PtrVT,
3551         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3552                                   CP->getOffset(), ARM64II::MO_G3),
3553         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3554                                   CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3555         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3556                                   CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3557         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3558                                   CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3559   } else {
3560     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3561     // ELF, the only valid one on Darwin.
3562     SDValue Hi =
3563         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3564                                   CP->getOffset(), ARM64II::MO_PAGE);
3565     SDValue Lo = DAG.getTargetConstantPool(
3566         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3567         ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3568
3569     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3570     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3571   }
3572 }
3573
3574 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3575                                                SelectionDAG &DAG) const {
3576   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3577   EVT PtrVT = getPointerTy();
3578   SDLoc DL(Op);
3579   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3580       !Subtarget->isTargetMachO()) {
3581     const unsigned char MO_NC = ARM64II::MO_NC;
3582     return DAG.getNode(
3583         ARM64ISD::WrapperLarge, DL, PtrVT,
3584         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3585         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3586         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3587         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3588   } else {
3589     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3590     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3591                                                              ARM64II::MO_NC);
3592     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3593     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3594   }
3595 }
3596
3597 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3598                                                  SelectionDAG &DAG) const {
3599   ARM64FunctionInfo *FuncInfo =
3600       DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3601
3602   SDLoc DL(Op);
3603   SDValue FR =
3604       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3605   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3606   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3607                       MachinePointerInfo(SV), false, false, 0);
3608 }
3609
3610 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3611                                                 SelectionDAG &DAG) const {
3612   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3613   // Standard, section B.3.
3614   MachineFunction &MF = DAG.getMachineFunction();
3615   ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3616   SDLoc DL(Op);
3617
3618   SDValue Chain = Op.getOperand(0);
3619   SDValue VAList = Op.getOperand(1);
3620   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3621   SmallVector<SDValue, 4> MemOps;
3622
3623   // void *__stack at offset 0
3624   SDValue Stack =
3625       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3626   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3627                                 MachinePointerInfo(SV), false, false, 8));
3628
3629   // void *__gr_top at offset 8
3630   int GPRSize = FuncInfo->getVarArgsGPRSize();
3631   if (GPRSize > 0) {
3632     SDValue GRTop, GRTopAddr;
3633
3634     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3635                             DAG.getConstant(8, getPointerTy()));
3636
3637     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3638     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3639                         DAG.getConstant(GPRSize, getPointerTy()));
3640
3641     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3642                                   MachinePointerInfo(SV, 8), false, false, 8));
3643   }
3644
3645   // void *__vr_top at offset 16
3646   int FPRSize = FuncInfo->getVarArgsFPRSize();
3647   if (FPRSize > 0) {
3648     SDValue VRTop, VRTopAddr;
3649     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3650                             DAG.getConstant(16, getPointerTy()));
3651
3652     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3653     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3654                         DAG.getConstant(FPRSize, getPointerTy()));
3655
3656     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3657                                   MachinePointerInfo(SV, 16), false, false, 8));
3658   }
3659
3660   // int __gr_offs at offset 24
3661   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3662                                    DAG.getConstant(24, getPointerTy()));
3663   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3664                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
3665                                 false, 4));
3666
3667   // int __vr_offs at offset 28
3668   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3669                                    DAG.getConstant(28, getPointerTy()));
3670   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3671                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
3672                                 false, 4));
3673
3674   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3675                      MemOps.size());
3676 }
3677
3678 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3679   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3680                                      : LowerAAPCS_VASTART(Op, DAG);
3681 }
3682
3683 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3684   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3685   // pointer.
3686   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3687   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3688   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3689
3690   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3691                        Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3692                        8, false, false, MachinePointerInfo(DestSV),
3693                        MachinePointerInfo(SrcSV));
3694 }
3695
3696 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3697   assert(Subtarget->isTargetDarwin() &&
3698          "automatic va_arg instruction only works on Darwin");
3699
3700   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3701   EVT VT = Op.getValueType();
3702   SDLoc DL(Op);
3703   SDValue Chain = Op.getOperand(0);
3704   SDValue Addr = Op.getOperand(1);
3705   unsigned Align = Op.getConstantOperandVal(3);
3706
3707   SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3708                                MachinePointerInfo(V), false, false, false, 0);
3709   Chain = VAList.getValue(1);
3710
3711   if (Align > 8) {
3712     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3713     VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3714                          DAG.getConstant(Align - 1, getPointerTy()));
3715     VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3716                          DAG.getConstant(-(int64_t)Align, getPointerTy()));
3717   }
3718
3719   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3720   uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3721
3722   // Scalar integer and FP values smaller than 64 bits are implicitly extended
3723   // up to 64 bits.  At the very least, we have to increase the striding of the
3724   // vaargs list to match this, and for FP values we need to introduce
3725   // FP_ROUND nodes as well.
3726   if (VT.isInteger() && !VT.isVector())
3727     ArgSize = 8;
3728   bool NeedFPTrunc = false;
3729   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3730     ArgSize = 8;
3731     NeedFPTrunc = true;
3732   }
3733
3734   // Increment the pointer, VAList, to the next vaarg
3735   SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3736                                DAG.getConstant(ArgSize, getPointerTy()));
3737   // Store the incremented VAList to the legalized pointer
3738   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3739                                  false, false, 0);
3740
3741   // Load the actual argument out of the pointer VAList
3742   if (NeedFPTrunc) {
3743     // Load the value as an f64.
3744     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3745                                  MachinePointerInfo(), false, false, false, 0);
3746     // Round the value down to an f32.
3747     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3748                                    DAG.getIntPtrConstant(1));
3749     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3750     // Merge the rounded value with the chain output of the load.
3751     return DAG.getMergeValues(Ops, 2, DL);
3752   }
3753
3754   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3755                      false, false, 0);
3756 }
3757
3758 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3759                                             SelectionDAG &DAG) const {
3760   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3761   MFI->setFrameAddressIsTaken(true);
3762
3763   EVT VT = Op.getValueType();
3764   SDLoc DL(Op);
3765   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3766   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3767   while (Depth--)
3768     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3769                             MachinePointerInfo(), false, false, false, 0);
3770   return FrameAddr;
3771 }
3772
3773 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3774                                              SelectionDAG &DAG) const {
3775   MachineFunction &MF = DAG.getMachineFunction();
3776   MachineFrameInfo *MFI = MF.getFrameInfo();
3777   MFI->setReturnAddressIsTaken(true);
3778
3779   EVT VT = Op.getValueType();
3780   SDLoc DL(Op);
3781   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3782   if (Depth) {
3783     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3784     SDValue Offset = DAG.getConstant(8, getPointerTy());
3785     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3786                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3787                        MachinePointerInfo(), false, false, false, 0);
3788   }
3789
3790   // Return LR, which contains the return address. Mark it an implicit live-in.
3791   unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3792   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3793 }
3794
3795 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3796 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3797 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3798                                                   SelectionDAG &DAG) const {
3799   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3800   EVT VT = Op.getValueType();
3801   unsigned VTBits = VT.getSizeInBits();
3802   SDLoc dl(Op);
3803   SDValue ShOpLo = Op.getOperand(0);
3804   SDValue ShOpHi = Op.getOperand(1);
3805   SDValue ShAmt = Op.getOperand(2);
3806   SDValue ARMcc;
3807   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3808
3809   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3810
3811   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3812                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3813   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3814   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3815                                    DAG.getConstant(VTBits, MVT::i64));
3816   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3817
3818   SDValue Cmp =
3819       emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3820   SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3821
3822   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3823   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3824   SDValue Lo =
3825       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3826
3827   // ARM64 shifts larger than the register width are wrapped rather than
3828   // clamped, so we can't just emit "hi >> x".
3829   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3830   SDValue TrueValHi = Opc == ISD::SRA
3831                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
3832                                         DAG.getConstant(VTBits - 1, MVT::i64))
3833                           : DAG.getConstant(0, VT);
3834   SDValue Hi =
3835       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3836
3837   SDValue Ops[2] = { Lo, Hi };
3838   return DAG.getMergeValues(Ops, 2, dl);
3839 }
3840
3841 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3842 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3843 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3844                                                  SelectionDAG &DAG) const {
3845   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3846   EVT VT = Op.getValueType();
3847   unsigned VTBits = VT.getSizeInBits();
3848   SDLoc dl(Op);
3849   SDValue ShOpLo = Op.getOperand(0);
3850   SDValue ShOpHi = Op.getOperand(1);
3851   SDValue ShAmt = Op.getOperand(2);
3852   SDValue ARMcc;
3853
3854   assert(Op.getOpcode() == ISD::SHL_PARTS);
3855   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3856                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3857   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3858   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3859                                    DAG.getConstant(VTBits, MVT::i64));
3860   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3861   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3862
3863   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3864
3865   SDValue Cmp =
3866       emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3867   SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3868   SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3869
3870   // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3871   // so we can't just emit "lo << a" if a is too big.
3872   SDValue TrueValLo = DAG.getConstant(0, VT);
3873   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3874   SDValue Lo =
3875       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3876
3877   SDValue Ops[2] = { Lo, Hi };
3878   return DAG.getMergeValues(Ops, 2, dl);
3879 }
3880
3881 bool
3882 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3883   // The ARM64 target doesn't support folding offsets into global addresses.
3884   return false;
3885 }
3886
3887 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3888   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3889   // FIXME: We should be able to handle f128 as well with a clever lowering.
3890   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3891     return true;
3892
3893   if (VT == MVT::f64)
3894     return ARM64_AM::getFP64Imm(Imm) != -1;
3895   else if (VT == MVT::f32)
3896     return ARM64_AM::getFP32Imm(Imm) != -1;
3897   return false;
3898 }
3899
3900 //===----------------------------------------------------------------------===//
3901 //                          ARM64 Optimization Hooks
3902 //===----------------------------------------------------------------------===//
3903
3904 //===----------------------------------------------------------------------===//
3905 //                          ARM64 Inline Assembly Support
3906 //===----------------------------------------------------------------------===//
3907
3908 // Table of Constraints
3909 // TODO: This is the current set of constraints supported by ARM for the
3910 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3911 //
3912 // r - A general register
3913 // w - An FP/SIMD register of some size in the range v0-v31
3914 // x - An FP/SIMD register of some size in the range v0-v15
3915 // I - Constant that can be used with an ADD instruction
3916 // J - Constant that can be used with a SUB instruction
3917 // K - Constant that can be used with a 32-bit logical instruction
3918 // L - Constant that can be used with a 64-bit logical instruction
3919 // M - Constant that can be used as a 32-bit MOV immediate
3920 // N - Constant that can be used as a 64-bit MOV immediate
3921 // Q - A memory reference with base register and no offset
3922 // S - A symbolic address
3923 // Y - Floating point constant zero
3924 // Z - Integer constant zero
3925 //
3926 //   Note that general register operands will be output using their 64-bit x
3927 // register name, whatever the size of the variable, unless the asm operand
3928 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3929 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3930 // %q modifier.
3931
3932 /// getConstraintType - Given a constraint letter, return the type of
3933 /// constraint it is for this target.
3934 ARM64TargetLowering::ConstraintType
3935 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3936   if (Constraint.size() == 1) {
3937     switch (Constraint[0]) {
3938     default:
3939       break;
3940     case 'z':
3941       return C_Other;
3942     case 'x':
3943     case 'w':
3944       return C_RegisterClass;
3945     // An address with a single base register. Due to the way we
3946     // currently handle addresses it is the same as 'r'.
3947     case 'Q':
3948       return C_Memory;
3949     }
3950   }
3951   return TargetLowering::getConstraintType(Constraint);
3952 }
3953
3954 /// Examine constraint type and operand type and determine a weight value.
3955 /// This object must already have been set up with the operand type
3956 /// and the current alternative constraint selected.
3957 TargetLowering::ConstraintWeight
3958 ARM64TargetLowering::getSingleConstraintMatchWeight(
3959     AsmOperandInfo &info, const char *constraint) const {
3960   ConstraintWeight weight = CW_Invalid;
3961   Value *CallOperandVal = info.CallOperandVal;
3962   // If we don't have a value, we can't do a match,
3963   // but allow it at the lowest weight.
3964   if (CallOperandVal == NULL)
3965     return CW_Default;
3966   Type *type = CallOperandVal->getType();
3967   // Look at the constraint type.
3968   switch (*constraint) {
3969   default:
3970     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3971     break;
3972   case 'x':
3973   case 'w':
3974     if (type->isFloatingPointTy() || type->isVectorTy())
3975       weight = CW_Register;
3976     break;
3977   case 'z':
3978     weight = CW_Constant;
3979     break;
3980   }
3981   return weight;
3982 }
3983
3984 std::pair<unsigned, const TargetRegisterClass *>
3985 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3986                                                   MVT VT) const {
3987   if (Constraint.size() == 1) {
3988     switch (Constraint[0]) {
3989     case 'r':
3990       if (VT.getSizeInBits() == 64)
3991         return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3992       return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3993     case 'w':
3994       if (VT == MVT::f32)
3995         return std::make_pair(0U, &ARM64::FPR32RegClass);
3996       if (VT.getSizeInBits() == 64)
3997         return std::make_pair(0U, &ARM64::FPR64RegClass);
3998       if (VT.getSizeInBits() == 128)
3999         return std::make_pair(0U, &ARM64::FPR128RegClass);
4000       break;
4001     // The instructions that this constraint is designed for can
4002     // only take 128-bit registers so just use that regclass.
4003     case 'x':
4004       if (VT.getSizeInBits() == 128)
4005         return std::make_pair(0U, &ARM64::FPR128_loRegClass);
4006       break;
4007     }
4008   }
4009   if (StringRef("{cc}").equals_lower(Constraint))
4010     return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
4011
4012   // Use the default implementation in TargetLowering to convert the register
4013   // constraint into a member of a register class.
4014   std::pair<unsigned, const TargetRegisterClass *> Res;
4015   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4016
4017   // Not found as a standard register?
4018   if (Res.second == 0) {
4019     unsigned Size = Constraint.size();
4020     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4021         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4022       const std::string Reg =
4023           std::string(&Constraint[2], &Constraint[Size - 1]);
4024       int RegNo = atoi(Reg.c_str());
4025       if (RegNo >= 0 && RegNo <= 31) {
4026         // v0 - v31 are aliases of q0 - q31.
4027         // By default we'll emit v0-v31 for this unless there's a modifier where
4028         // we'll emit the correct register as well.
4029         Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
4030         Res.second = &ARM64::FPR128RegClass;
4031       }
4032     }
4033   }
4034
4035   return Res;
4036 }
4037
4038 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4039 /// vector.  If it is invalid, don't add anything to Ops.
4040 void ARM64TargetLowering::LowerAsmOperandForConstraint(
4041     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4042     SelectionDAG &DAG) const {
4043   SDValue Result(0, 0);
4044
4045   // Currently only support length 1 constraints.
4046   if (Constraint.length() != 1)
4047     return;
4048
4049   char ConstraintLetter = Constraint[0];
4050   switch (ConstraintLetter) {
4051   default:
4052     break;
4053
4054   // This set of constraints deal with valid constants for various instructions.
4055   // Validate and return a target constant for them if we can.
4056   case 'z': {
4057     // 'z' maps to xzr or wzr so it needs an input of 0.
4058     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4059     if (!C || C->getZExtValue() != 0)
4060       return;
4061
4062     if (Op.getValueType() == MVT::i64)
4063       Result = DAG.getRegister(ARM64::XZR, MVT::i64);
4064     else
4065       Result = DAG.getRegister(ARM64::WZR, MVT::i32);
4066     break;
4067   }
4068
4069   case 'I':
4070   case 'J':
4071   case 'K':
4072   case 'L':
4073   case 'M':
4074   case 'N':
4075     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4076     if (!C)
4077       return;
4078
4079     // Grab the value and do some validation.
4080     uint64_t CVal = C->getZExtValue();
4081     switch (ConstraintLetter) {
4082     // The I constraint applies only to simple ADD or SUB immediate operands:
4083     // i.e. 0 to 4095 with optional shift by 12
4084     // The J constraint applies only to ADD or SUB immediates that would be
4085     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4086     // instruction [or vice versa], in other words -1 to -4095 with optional
4087     // left shift by 12.
4088     case 'I':
4089       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4090         break;
4091       return;
4092     case 'J': {
4093       uint64_t NVal = -C->getSExtValue();
4094       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
4095         break;
4096       return;
4097     }
4098     // The K and L constraints apply *only* to logical immediates, including
4099     // what used to be the MOVI alias for ORR (though the MOVI alias has now
4100     // been removed and MOV should be used). So these constraints have to
4101     // distinguish between bit patterns that are valid 32-bit or 64-bit
4102     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4103     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4104     // versa.
4105     case 'K':
4106       if (ARM64_AM::isLogicalImmediate(CVal, 32))
4107         break;
4108       return;
4109     case 'L':
4110       if (ARM64_AM::isLogicalImmediate(CVal, 64))
4111         break;
4112       return;
4113     // The M and N constraints are a superset of K and L respectively, for use
4114     // with the MOV (immediate) alias. As well as the logical immediates they
4115     // also match 32 or 64-bit immediates that can be loaded either using a
4116     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4117     // (M) or 64-bit 0x1234000000000000 (N) etc.
4118     // As a note some of this code is liberally stolen from the asm parser.
4119     case 'M': {
4120       if (!isUInt<32>(CVal))
4121         return;
4122       if (ARM64_AM::isLogicalImmediate(CVal, 32))
4123         break;
4124       if ((CVal & 0xFFFF) == CVal)
4125         break;
4126       if ((CVal & 0xFFFF0000ULL) == CVal)
4127         break;
4128       uint64_t NCVal = ~(uint32_t)CVal;
4129       if ((NCVal & 0xFFFFULL) == NCVal)
4130         break;
4131       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4132         break;
4133       return;
4134     }
4135     case 'N': {
4136       if (ARM64_AM::isLogicalImmediate(CVal, 64))
4137         break;
4138       if ((CVal & 0xFFFFULL) == CVal)
4139         break;
4140       if ((CVal & 0xFFFF0000ULL) == CVal)
4141         break;
4142       if ((CVal & 0xFFFF00000000ULL) == CVal)
4143         break;
4144       if ((CVal & 0xFFFF000000000000ULL) == CVal)
4145         break;
4146       uint64_t NCVal = ~CVal;
4147       if ((NCVal & 0xFFFFULL) == NCVal)
4148         break;
4149       if ((NCVal & 0xFFFF0000ULL) == NCVal)
4150         break;
4151       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4152         break;
4153       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4154         break;
4155       return;
4156     }
4157     default:
4158       return;
4159     }
4160
4161     // All assembler immediates are 64-bit integers.
4162     Result = DAG.getTargetConstant(CVal, MVT::i64);
4163     break;
4164   }
4165
4166   if (Result.getNode()) {
4167     Ops.push_back(Result);
4168     return;
4169   }
4170
4171   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4172 }
4173
4174 //===----------------------------------------------------------------------===//
4175 //                     ARM64 Advanced SIMD Support
4176 //===----------------------------------------------------------------------===//
4177
4178 /// WidenVector - Given a value in the V64 register class, produce the
4179 /// equivalent value in the V128 register class.
4180 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4181   EVT VT = V64Reg.getValueType();
4182   unsigned NarrowSize = VT.getVectorNumElements();
4183   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4184   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4185   SDLoc DL(V64Reg);
4186
4187   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4188                      V64Reg, DAG.getConstant(0, MVT::i32));
4189 }
4190
4191 /// getExtFactor - Determine the adjustment factor for the position when
4192 /// generating an "extract from vector registers" instruction.
4193 static unsigned getExtFactor(SDValue &V) {
4194   EVT EltType = V.getValueType().getVectorElementType();
4195   return EltType.getSizeInBits() / 8;
4196 }
4197
4198 /// NarrowVector - Given a value in the V128 register class, produce the
4199 /// equivalent value in the V64 register class.
4200 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4201   EVT VT = V128Reg.getValueType();
4202   unsigned WideSize = VT.getVectorNumElements();
4203   MVT EltTy = VT.getVectorElementType().getSimpleVT();
4204   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4205   SDLoc DL(V128Reg);
4206
4207   return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
4208 }
4209
4210 // Gather data to see if the operation can be modelled as a
4211 // shuffle in combination with VEXTs.
4212 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
4213                                                 SelectionDAG &DAG) const {
4214   SDLoc dl(Op);
4215   EVT VT = Op.getValueType();
4216   unsigned NumElts = VT.getVectorNumElements();
4217
4218   SmallVector<SDValue, 2> SourceVecs;
4219   SmallVector<unsigned, 2> MinElts;
4220   SmallVector<unsigned, 2> MaxElts;
4221
4222   for (unsigned i = 0; i < NumElts; ++i) {
4223     SDValue V = Op.getOperand(i);
4224     if (V.getOpcode() == ISD::UNDEF)
4225       continue;
4226     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4227       // A shuffle can only come from building a vector from various
4228       // elements of other vectors.
4229       return SDValue();
4230     }
4231
4232     // Record this extraction against the appropriate vector if possible...
4233     SDValue SourceVec = V.getOperand(0);
4234     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4235     bool FoundSource = false;
4236     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4237       if (SourceVecs[j] == SourceVec) {
4238         if (MinElts[j] > EltNo)
4239           MinElts[j] = EltNo;
4240         if (MaxElts[j] < EltNo)
4241           MaxElts[j] = EltNo;
4242         FoundSource = true;
4243         break;
4244       }
4245     }
4246
4247     // Or record a new source if not...
4248     if (!FoundSource) {
4249       SourceVecs.push_back(SourceVec);
4250       MinElts.push_back(EltNo);
4251       MaxElts.push_back(EltNo);
4252     }
4253   }
4254
4255   // Currently only do something sane when at most two source vectors
4256   // involved.
4257   if (SourceVecs.size() > 2)
4258     return SDValue();
4259
4260   SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4261   int VEXTOffsets[2] = { 0, 0 };
4262
4263   // This loop extracts the usage patterns of the source vectors
4264   // and prepares appropriate SDValues for a shuffle if possible.
4265   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4266     if (SourceVecs[i].getValueType() == VT) {
4267       // No VEXT necessary
4268       ShuffleSrcs[i] = SourceVecs[i];
4269       VEXTOffsets[i] = 0;
4270       continue;
4271     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4272       // It probably isn't worth padding out a smaller vector just to
4273       // break it down again in a shuffle.
4274       return SDValue();
4275     }
4276
4277     // Don't attempt to extract subvectors from BUILD_VECTOR sources
4278     // that expand or trunc the original value.
4279     // TODO: We can try to bitcast and ANY_EXTEND the result but
4280     // we need to consider the cost of vector ANY_EXTEND, and the
4281     // legality of all the types.
4282     if (SourceVecs[i].getValueType().getVectorElementType() !=
4283         VT.getVectorElementType())
4284       return SDValue();
4285
4286     // Since only 64-bit and 128-bit vectors are legal on ARM and
4287     // we've eliminated the other cases...
4288     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
4289            "unexpected vector sizes in ReconstructShuffle");
4290
4291     if (MaxElts[i] - MinElts[i] >= NumElts) {
4292       // Span too large for a VEXT to cope
4293       return SDValue();
4294     }
4295
4296     if (MinElts[i] >= NumElts) {
4297       // The extraction can just take the second half
4298       VEXTOffsets[i] = NumElts;
4299       ShuffleSrcs[i] =
4300           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4301                       DAG.getIntPtrConstant(NumElts));
4302     } else if (MaxElts[i] < NumElts) {
4303       // The extraction can just take the first half
4304       VEXTOffsets[i] = 0;
4305       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4306                                    SourceVecs[i], DAG.getIntPtrConstant(0));
4307     } else {
4308       // An actual VEXT is needed
4309       VEXTOffsets[i] = MinElts[i];
4310       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4311                                      SourceVecs[i], DAG.getIntPtrConstant(0));
4312       SDValue VEXTSrc2 =
4313           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4314                       DAG.getIntPtrConstant(NumElts));
4315       unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
4316       ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
4317                                    DAG.getConstant(Imm, MVT::i32));
4318     }
4319   }
4320
4321   SmallVector<int, 8> Mask;
4322
4323   for (unsigned i = 0; i < NumElts; ++i) {
4324     SDValue Entry = Op.getOperand(i);
4325     if (Entry.getOpcode() == ISD::UNDEF) {
4326       Mask.push_back(-1);
4327       continue;
4328     }
4329
4330     SDValue ExtractVec = Entry.getOperand(0);
4331     int ExtractElt =
4332         cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
4333     if (ExtractVec == SourceVecs[0]) {
4334       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4335     } else {
4336       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4337     }
4338   }
4339
4340   // Final check before we try to produce nonsense...
4341   if (isShuffleMaskLegal(Mask, VT))
4342     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4343                                 &Mask[0]);
4344
4345   return SDValue();
4346 }
4347
4348 // check if an EXT instruction can handle the shuffle mask when the
4349 // vector sources of the shuffle are the same.
4350 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4351   unsigned NumElts = VT.getVectorNumElements();
4352
4353   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4354   if (M[0] < 0)
4355     return false;
4356
4357   Imm = M[0];
4358
4359   // If this is a VEXT shuffle, the immediate value is the index of the first
4360   // element.  The other shuffle indices must be the successive elements after
4361   // the first one.
4362   unsigned ExpectedElt = Imm;
4363   for (unsigned i = 1; i < NumElts; ++i) {
4364     // Increment the expected index.  If it wraps around, just follow it
4365     // back to index zero and keep going.
4366     ++ExpectedElt;
4367     if (ExpectedElt == NumElts)
4368       ExpectedElt = 0;
4369
4370     if (M[i] < 0)
4371       continue; // ignore UNDEF indices
4372     if (ExpectedElt != static_cast<unsigned>(M[i]))
4373       return false;
4374   }
4375
4376   return true;
4377 }
4378
4379 // check if an EXT instruction can handle the shuffle mask when the
4380 // vector sources of the shuffle are different.
4381 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4382                       unsigned &Imm) {
4383   unsigned NumElts = VT.getVectorNumElements();
4384   ReverseEXT = false;
4385
4386   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4387   if (M[0] < 0)
4388     return false;
4389
4390   Imm = M[0];
4391
4392   // If this is a VEXT shuffle, the immediate value is the index of the first
4393   // element.  The other shuffle indices must be the successive elements after
4394   // the first one.
4395   unsigned ExpectedElt = Imm;
4396   for (unsigned i = 1; i < NumElts; ++i) {
4397     // Increment the expected index.  If it wraps around, it may still be
4398     // a VEXT but the source vectors must be swapped.
4399     ExpectedElt += 1;
4400     if (ExpectedElt == NumElts * 2) {
4401       ExpectedElt = 0;
4402       ReverseEXT = true;
4403     }
4404
4405     if (M[i] < 0)
4406       continue; // ignore UNDEF indices
4407     if (ExpectedElt != static_cast<unsigned>(M[i]))
4408       return false;
4409   }
4410
4411   // Adjust the index value if the source operands will be swapped.
4412   if (ReverseEXT)
4413     Imm -= NumElts;
4414
4415   return true;
4416 }
4417
4418 /// isREVMask - Check if a vector shuffle corresponds to a REV
4419 /// instruction with the specified blocksize.  (The order of the elements
4420 /// within each block of the vector is reversed.)
4421 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4422   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4423          "Only possible block sizes for REV are: 16, 32, 64");
4424
4425   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4426   if (EltSz == 64)
4427     return false;
4428
4429   unsigned NumElts = VT.getVectorNumElements();
4430   unsigned BlockElts = M[0] + 1;
4431   // If the first shuffle index is UNDEF, be optimistic.
4432   if (M[0] < 0)
4433     BlockElts = BlockSize / EltSz;
4434
4435   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4436     return false;
4437
4438   for (unsigned i = 0; i < NumElts; ++i) {
4439     if (M[i] < 0)
4440       continue; // ignore UNDEF indices
4441     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4442       return false;
4443   }
4444
4445   return true;
4446 }
4447
4448 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4449   unsigned NumElts = VT.getVectorNumElements();
4450   WhichResult = (M[0] == 0 ? 0 : 1);
4451   unsigned Idx = WhichResult * NumElts / 2;
4452   for (unsigned i = 0; i != NumElts; i += 2) {
4453     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4454         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4455       return false;
4456     Idx += 1;
4457   }
4458
4459   return true;
4460 }
4461
4462 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4463   unsigned NumElts = VT.getVectorNumElements();
4464   WhichResult = (M[0] == 0 ? 0 : 1);
4465   for (unsigned i = 0; i != NumElts; ++i) {
4466     if (M[i] < 0)
4467       continue; // ignore UNDEF indices
4468     if ((unsigned)M[i] != 2 * i + WhichResult)
4469       return false;
4470   }
4471
4472   return true;
4473 }
4474
4475 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4476   unsigned NumElts = VT.getVectorNumElements();
4477   WhichResult = (M[0] == 0 ? 0 : 1);
4478   for (unsigned i = 0; i < NumElts; i += 2) {
4479     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4480         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4481       return false;
4482   }
4483   return true;
4484 }
4485
4486 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4487 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4488 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4489 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4490   unsigned NumElts = VT.getVectorNumElements();
4491   WhichResult = (M[0] == 0 ? 0 : 1);
4492   unsigned Idx = WhichResult * NumElts / 2;
4493   for (unsigned i = 0; i != NumElts; i += 2) {
4494     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4495         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4496       return false;
4497     Idx += 1;
4498   }
4499
4500   return true;
4501 }
4502
4503 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4504 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4505 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4506 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4507   unsigned Half = VT.getVectorNumElements() / 2;
4508   WhichResult = (M[0] == 0 ? 0 : 1);
4509   for (unsigned j = 0; j != 2; ++j) {
4510     unsigned Idx = WhichResult;
4511     for (unsigned i = 0; i != Half; ++i) {
4512       int MIdx = M[i + j * Half];
4513       if (MIdx >= 0 && (unsigned)MIdx != Idx)
4514         return false;
4515       Idx += 2;
4516     }
4517   }
4518
4519   return true;
4520 }
4521
4522 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4523 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4524 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4525 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4526   unsigned NumElts = VT.getVectorNumElements();
4527   WhichResult = (M[0] == 0 ? 0 : 1);
4528   for (unsigned i = 0; i < NumElts; i += 2) {
4529     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4530         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4531       return false;
4532   }
4533   return true;
4534 }
4535
4536 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4537 /// the specified operations to build the shuffle.
4538 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4539                                       SDValue RHS, SelectionDAG &DAG,
4540                                       SDLoc dl) {
4541   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4542   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4543   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4544
4545   enum {
4546     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4547     OP_VREV,
4548     OP_VDUP0,
4549     OP_VDUP1,
4550     OP_VDUP2,
4551     OP_VDUP3,
4552     OP_VEXT1,
4553     OP_VEXT2,
4554     OP_VEXT3,
4555     OP_VUZPL, // VUZP, left result
4556     OP_VUZPR, // VUZP, right result
4557     OP_VZIPL, // VZIP, left result
4558     OP_VZIPR, // VZIP, right result
4559     OP_VTRNL, // VTRN, left result
4560     OP_VTRNR  // VTRN, right result
4561   };
4562
4563   if (OpNum == OP_COPY) {
4564     if (LHSID == (1 * 9 + 2) * 9 + 3)
4565       return LHS;
4566     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4567     return RHS;
4568   }
4569
4570   SDValue OpLHS, OpRHS;
4571   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4572   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4573   EVT VT = OpLHS.getValueType();
4574
4575   switch (OpNum) {
4576   default:
4577     llvm_unreachable("Unknown shuffle opcode!");
4578   case OP_VREV:
4579     // VREV divides the vector in half and swaps within the half.
4580     if (VT.getVectorElementType() == MVT::i32 ||
4581         VT.getVectorElementType() == MVT::f32)
4582       return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4583     // vrev <4 x i16> -> REV32
4584     if (VT.getVectorElementType() == MVT::i16)
4585       return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4586     // vrev <4 x i8> -> REV16
4587     assert(VT.getVectorElementType() == MVT::i8);
4588     return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4589   case OP_VDUP0:
4590   case OP_VDUP1:
4591   case OP_VDUP2:
4592   case OP_VDUP3: {
4593     EVT EltTy = VT.getVectorElementType();
4594     unsigned Opcode;
4595     if (EltTy == MVT::i8)
4596       Opcode = ARM64ISD::DUPLANE8;
4597     else if (EltTy == MVT::i16)
4598       Opcode = ARM64ISD::DUPLANE16;
4599     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4600       Opcode = ARM64ISD::DUPLANE32;
4601     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4602       Opcode = ARM64ISD::DUPLANE64;
4603     else
4604       llvm_unreachable("Invalid vector element type?");
4605
4606     if (VT.getSizeInBits() == 64)
4607       OpLHS = WidenVector(OpLHS, DAG);
4608     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4609     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4610   }
4611   case OP_VEXT1:
4612   case OP_VEXT2:
4613   case OP_VEXT3: {
4614     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4615     return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4616                        DAG.getConstant(Imm, MVT::i32));
4617   }
4618   case OP_VUZPL:
4619     return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4620   case OP_VUZPR:
4621     return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4622   case OP_VZIPL:
4623     return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4624   case OP_VZIPR:
4625     return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4626   case OP_VTRNL:
4627     return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4628   case OP_VTRNR:
4629     return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4630   }
4631 }
4632
4633 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4634                            SelectionDAG &DAG) {
4635   // Check to see if we can use the TBL instruction.
4636   SDValue V1 = Op.getOperand(0);
4637   SDValue V2 = Op.getOperand(1);
4638   SDLoc DL(Op);
4639
4640   EVT EltVT = Op.getValueType().getVectorElementType();
4641   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4642
4643   SmallVector<SDValue, 8> TBLMask;
4644   for (int Val : ShuffleMask) {
4645     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4646       unsigned Offset = Byte + Val * BytesPerElt;
4647       TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4648     }
4649   }
4650
4651   MVT IndexVT = MVT::v8i8;
4652   unsigned IndexLen = 8;
4653   if (Op.getValueType().getSizeInBits() == 128) {
4654     IndexVT = MVT::v16i8;
4655     IndexLen = 16;
4656   }
4657
4658   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4659   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4660
4661   SDValue Shuffle;
4662   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4663     if (IndexLen == 8)
4664       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4665     Shuffle = DAG.getNode(
4666         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4667         DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4668         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4669   } else {
4670     if (IndexLen == 8) {
4671       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4672       Shuffle = DAG.getNode(
4673           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4674           DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4675           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4676     } else {
4677       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4678       // cannot currently represent the register constraints on the input
4679       // table registers.
4680       //  Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4681       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4682       //                               &TBLMask[0], IndexLen));
4683       Shuffle = DAG.getNode(
4684           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4685           DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4686           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4687     }
4688   }
4689   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4690 }
4691
4692 static unsigned getDUPLANEOp(EVT EltType) {
4693   if (EltType == MVT::i8)
4694     return ARM64ISD::DUPLANE8;
4695   if (EltType == MVT::i16)
4696     return ARM64ISD::DUPLANE16;
4697   if (EltType == MVT::i32 || EltType == MVT::f32)
4698     return ARM64ISD::DUPLANE32;
4699   if (EltType == MVT::i64 || EltType == MVT::f64)
4700     return ARM64ISD::DUPLANE64;
4701
4702   llvm_unreachable("Invalid vector element type?");
4703 }
4704
4705 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4706                                                  SelectionDAG &DAG) const {
4707   SDLoc dl(Op);
4708   EVT VT = Op.getValueType();
4709
4710   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4711
4712   // Convert shuffles that are directly supported on NEON to target-specific
4713   // DAG nodes, instead of keeping them as shuffles and matching them again
4714   // during code selection.  This is more efficient and avoids the possibility
4715   // of inconsistencies between legalization and selection.
4716   ArrayRef<int> ShuffleMask = SVN->getMask();
4717
4718   SDValue V1 = Op.getOperand(0);
4719   SDValue V2 = Op.getOperand(1);
4720
4721   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4722                                        V1.getValueType().getSimpleVT())) {
4723     int Lane = SVN->getSplatIndex();
4724     // If this is undef splat, generate it via "just" vdup, if possible.
4725     if (Lane == -1)
4726       Lane = 0;
4727
4728     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4729       return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4730                          V1.getOperand(0));
4731     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4732     // constant. If so, we can just reference the lane's definition directly.
4733     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4734         !isa<ConstantSDNode>(V1.getOperand(Lane)))
4735       return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4736
4737     // Otherwise, duplicate from the lane of the input vector.
4738     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4739
4740     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4741     // to make a vector of the same size as this SHUFFLE. We can ignore the
4742     // extract entirely, and canonicalise the concat using WidenVector.
4743     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4744       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4745       V1 = V1.getOperand(0);
4746     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4747       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4748       Lane -= Idx * VT.getVectorNumElements() / 2;
4749       V1 = WidenVector(V1.getOperand(Idx), DAG);
4750     } else if (VT.getSizeInBits() == 64)
4751       V1 = WidenVector(V1, DAG);
4752
4753     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4754   }
4755
4756   if (isREVMask(ShuffleMask, VT, 64))
4757     return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4758   if (isREVMask(ShuffleMask, VT, 32))
4759     return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4760   if (isREVMask(ShuffleMask, VT, 16))
4761     return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4762
4763   bool ReverseEXT = false;
4764   unsigned Imm;
4765   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4766     if (ReverseEXT)
4767       std::swap(V1, V2);
4768     Imm *= getExtFactor(V1);
4769     return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4770                        DAG.getConstant(Imm, MVT::i32));
4771   } else if (V2->getOpcode() == ISD::UNDEF &&
4772              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4773     Imm *= getExtFactor(V1);
4774     return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4775                        DAG.getConstant(Imm, MVT::i32));
4776   }
4777
4778   unsigned WhichResult;
4779   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4780     unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4781     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4782   }
4783   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4784     unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4785     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4786   }
4787   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4788     unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4789     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4790   }
4791
4792   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4793     unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4794     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4795   }
4796   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4797     unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4798     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4799   }
4800   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4801     unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4802     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4803   }
4804
4805   // If the shuffle is not directly supported and it has 4 elements, use
4806   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4807   unsigned NumElts = VT.getVectorNumElements();
4808   if (NumElts == 4) {
4809     unsigned PFIndexes[4];
4810     for (unsigned i = 0; i != 4; ++i) {
4811       if (ShuffleMask[i] < 0)
4812         PFIndexes[i] = 8;
4813       else
4814         PFIndexes[i] = ShuffleMask[i];
4815     }
4816
4817     // Compute the index in the perfect shuffle table.
4818     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4819                             PFIndexes[2] * 9 + PFIndexes[3];
4820     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4821     unsigned Cost = (PFEntry >> 30);
4822
4823     if (Cost <= 4)
4824       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4825   }
4826
4827   return GenerateTBL(Op, ShuffleMask, DAG);
4828 }
4829
4830 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4831                                APInt &UndefBits) {
4832   EVT VT = BVN->getValueType(0);
4833   APInt SplatBits, SplatUndef;
4834   unsigned SplatBitSize;
4835   bool HasAnyUndefs;
4836   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4837     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4838
4839     for (unsigned i = 0; i < NumSplats; ++i) {
4840       CnstBits <<= SplatBitSize;
4841       UndefBits <<= SplatBitSize;
4842       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4843       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4844     }
4845
4846     return true;
4847   }
4848
4849   return false;
4850 }
4851
4852 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4853                                             SelectionDAG &DAG) const {
4854   BuildVectorSDNode *BVN =
4855       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4856   SDValue LHS = Op.getOperand(0);
4857   SDLoc dl(Op);
4858   EVT VT = Op.getValueType();
4859
4860   if (!BVN)
4861     return Op;
4862
4863   APInt CnstBits(VT.getSizeInBits(), 0);
4864   APInt UndefBits(VT.getSizeInBits(), 0);
4865   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4866     // We only have BIC vector immediate instruction, which is and-not.
4867     CnstBits = ~CnstBits;
4868
4869     // We make use of a little bit of goto ickiness in order to avoid having to
4870     // duplicate the immediate matching logic for the undef toggled case.
4871     bool SecondTry = false;
4872   AttemptModImm:
4873
4874     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4875       CnstBits = CnstBits.zextOrTrunc(64);
4876       uint64_t CnstVal = CnstBits.getZExtValue();
4877
4878       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4879         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4880         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4881         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4882                                   DAG.getConstant(CnstVal, MVT::i32),
4883                                   DAG.getConstant(0, MVT::i32));
4884         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4885       }
4886
4887       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4888         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4889         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4890         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4891                                   DAG.getConstant(CnstVal, MVT::i32),
4892                                   DAG.getConstant(8, MVT::i32));
4893         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4894       }
4895
4896       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4897         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4898         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4899         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4900                                   DAG.getConstant(CnstVal, MVT::i32),
4901                                   DAG.getConstant(16, MVT::i32));
4902         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4903       }
4904
4905       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4906         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4907         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4908         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4909                                   DAG.getConstant(CnstVal, MVT::i32),
4910                                   DAG.getConstant(24, MVT::i32));
4911         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4912       }
4913
4914       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4915         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4916         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4917         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4918                                   DAG.getConstant(CnstVal, MVT::i32),
4919                                   DAG.getConstant(0, MVT::i32));
4920         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4921       }
4922
4923       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4924         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4925         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4926         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4927                                   DAG.getConstant(CnstVal, MVT::i32),
4928                                   DAG.getConstant(8, MVT::i32));
4929         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4930       }
4931     }
4932
4933     if (SecondTry)
4934       goto FailedModImm;
4935     SecondTry = true;
4936     CnstBits = ~UndefBits;
4937     goto AttemptModImm;
4938   }
4939
4940 // We can always fall back to a non-immediate AND.
4941 FailedModImm:
4942   return Op;
4943 }
4944
4945 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4946 // consists of only the same constant int value, returned in reference arg
4947 // ConstVal
4948 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4949                                      uint64_t &ConstVal) {
4950   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4951   if (!Bvec)
4952     return false;
4953   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4954   if (!FirstElt)
4955     return false;
4956   EVT VT = Bvec->getValueType(0);
4957   unsigned NumElts = VT.getVectorNumElements();
4958   for (unsigned i = 1; i < NumElts; ++i)
4959     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4960       return false;
4961   ConstVal = FirstElt->getZExtValue();
4962   return true;
4963 }
4964
4965 static unsigned getIntrinsicID(const SDNode *N) {
4966   unsigned Opcode = N->getOpcode();
4967   switch (Opcode) {
4968   default:
4969     return Intrinsic::not_intrinsic;
4970   case ISD::INTRINSIC_WO_CHAIN: {
4971     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4972     if (IID < Intrinsic::num_intrinsics)
4973       return IID;
4974     return Intrinsic::not_intrinsic;
4975   }
4976   }
4977 }
4978
4979 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4980 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4981 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4982 // Also, logical shift right -> sri, with the same structure.
4983 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4984   EVT VT = N->getValueType(0);
4985
4986   if (!VT.isVector())
4987     return SDValue();
4988
4989   SDLoc DL(N);
4990
4991   // Is the first op an AND?
4992   const SDValue And = N->getOperand(0);
4993   if (And.getOpcode() != ISD::AND)
4994     return SDValue();
4995
4996   // Is the second op an shl or lshr?
4997   SDValue Shift = N->getOperand(1);
4998   // This will have been turned into: ARM64ISD::VSHL vector, #shift
4999   // or ARM64ISD::VLSHR vector, #shift
5000   unsigned ShiftOpc = Shift.getOpcode();
5001   if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
5002     return SDValue();
5003   bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
5004
5005   // Is the shift amount constant?
5006   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5007   if (!C2node)
5008     return SDValue();
5009
5010   // Is the and mask vector all constant?
5011   uint64_t C1;
5012   if (!isAllConstantBuildVector(And.getOperand(1), C1))
5013     return SDValue();
5014
5015   // Is C1 == ~C2, taking into account how much one can shift elements of a
5016   // particular size?
5017   uint64_t C2 = C2node->getZExtValue();
5018   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5019   if (C2 > ElemSizeInBits)
5020     return SDValue();
5021   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5022   if ((C1 & ElemMask) != (~C2 & ElemMask))
5023     return SDValue();
5024
5025   SDValue X = And.getOperand(0);
5026   SDValue Y = Shift.getOperand(0);
5027
5028   unsigned Intrin =
5029       IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
5030   SDValue ResultSLI =
5031       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5032                   DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5033
5034   DEBUG(dbgs() << "arm64-lower: transformed: \n");
5035   DEBUG(N->dump(&DAG));
5036   DEBUG(dbgs() << "into: \n");
5037   DEBUG(ResultSLI->dump(&DAG));
5038
5039   ++NumShiftInserts;
5040   return ResultSLI;
5041 }
5042
5043 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
5044                                            SelectionDAG &DAG) const {
5045   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5046   if (EnableARM64SlrGeneration) {
5047     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5048     if (Res.getNode())
5049       return Res;
5050   }
5051
5052   BuildVectorSDNode *BVN =
5053       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5054   SDValue LHS = Op.getOperand(1);
5055   SDLoc dl(Op);
5056   EVT VT = Op.getValueType();
5057
5058   // OR commutes, so try swapping the operands.
5059   if (!BVN) {
5060     LHS = Op.getOperand(0);
5061     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5062   }
5063   if (!BVN)
5064     return Op;
5065
5066   APInt CnstBits(VT.getSizeInBits(), 0);
5067   APInt UndefBits(VT.getSizeInBits(), 0);
5068   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5069     // We make use of a little bit of goto ickiness in order to avoid having to
5070     // duplicate the immediate matching logic for the undef toggled case.
5071     bool SecondTry = false;
5072   AttemptModImm:
5073
5074     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5075       CnstBits = CnstBits.zextOrTrunc(64);
5076       uint64_t CnstVal = CnstBits.getZExtValue();
5077
5078       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5079         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5080         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5081         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5082                                   DAG.getConstant(CnstVal, MVT::i32),
5083                                   DAG.getConstant(0, MVT::i32));
5084         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5085       }
5086
5087       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5088         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5089         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5090         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5091                                   DAG.getConstant(CnstVal, MVT::i32),
5092                                   DAG.getConstant(8, MVT::i32));
5093         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5094       }
5095
5096       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5097         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5098         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5099         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5100                                   DAG.getConstant(CnstVal, MVT::i32),
5101                                   DAG.getConstant(16, MVT::i32));
5102         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5103       }
5104
5105       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5106         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5107         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5108         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5109                                   DAG.getConstant(CnstVal, MVT::i32),
5110                                   DAG.getConstant(24, MVT::i32));
5111         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5112       }
5113
5114       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5115         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5116         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5117         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5118                                   DAG.getConstant(CnstVal, MVT::i32),
5119                                   DAG.getConstant(0, MVT::i32));
5120         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5121       }
5122
5123       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5124         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5125         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5126         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5127                                   DAG.getConstant(CnstVal, MVT::i32),
5128                                   DAG.getConstant(8, MVT::i32));
5129         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5130       }
5131     }
5132
5133     if (SecondTry)
5134       goto FailedModImm;
5135     SecondTry = true;
5136     CnstBits = UndefBits;
5137     goto AttemptModImm;
5138   }
5139
5140 // We can always fall back to a non-immediate OR.
5141 FailedModImm:
5142   return Op;
5143 }
5144
5145 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5146                                                SelectionDAG &DAG) const {
5147   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5148   SDLoc dl(Op);
5149   EVT VT = Op.getValueType();
5150
5151   APInt CnstBits(VT.getSizeInBits(), 0);
5152   APInt UndefBits(VT.getSizeInBits(), 0);
5153   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5154     // We make use of a little bit of goto ickiness in order to avoid having to
5155     // duplicate the immediate matching logic for the undef toggled case.
5156     bool SecondTry = false;
5157   AttemptModImm:
5158
5159     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5160       CnstBits = CnstBits.zextOrTrunc(64);
5161       uint64_t CnstVal = CnstBits.getZExtValue();
5162
5163       // Certain magic vector constants (used to express things like NOT
5164       // and NEG) are passed through unmodified.  This allows codegen patterns
5165       // for these operations to match.  Special-purpose patterns will lower
5166       // these immediates to MOVIs if it proves necessary.
5167       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5168         return Op;
5169
5170       // The many faces of MOVI...
5171       if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
5172         CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
5173         if (VT.getSizeInBits() == 128) {
5174           SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
5175                                     DAG.getConstant(CnstVal, MVT::i32));
5176           return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5177         }
5178
5179         // Support the V64 version via subregister insertion.
5180         SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
5181                                   DAG.getConstant(CnstVal, MVT::i32));
5182         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5183       }
5184
5185       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5186         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5187         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5188         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5189                                   DAG.getConstant(CnstVal, MVT::i32),
5190                                   DAG.getConstant(0, MVT::i32));
5191         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5192       }
5193
5194       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5195         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5196         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5197         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5198                                   DAG.getConstant(CnstVal, MVT::i32),
5199                                   DAG.getConstant(8, MVT::i32));
5200         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5201       }
5202
5203       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5204         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5205         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5206         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5207                                   DAG.getConstant(CnstVal, MVT::i32),
5208                                   DAG.getConstant(16, MVT::i32));
5209         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5210       }
5211
5212       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5213         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5214         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5215         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5216                                   DAG.getConstant(CnstVal, MVT::i32),
5217                                   DAG.getConstant(24, MVT::i32));
5218         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5219       }
5220
5221       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5222         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5223         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5224         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5225                                   DAG.getConstant(CnstVal, MVT::i32),
5226                                   DAG.getConstant(0, MVT::i32));
5227         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5228       }
5229
5230       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5231         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5232         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5233         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5234                                   DAG.getConstant(CnstVal, MVT::i32),
5235                                   DAG.getConstant(8, MVT::i32));
5236         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5237       }
5238
5239       if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5240         CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5241         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5242         SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5243                                   DAG.getConstant(CnstVal, MVT::i32),
5244                                   DAG.getConstant(264, MVT::i32));
5245         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5246       }
5247
5248       if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5249         CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5250         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5251         SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5252                                   DAG.getConstant(CnstVal, MVT::i32),
5253                                   DAG.getConstant(272, MVT::i32));
5254         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5255       }
5256
5257       if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5258         CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5259         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5260         SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5261                                   DAG.getConstant(CnstVal, MVT::i32));
5262         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5263       }
5264
5265       // The few faces of FMOV...
5266       if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5267         CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5268         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5269         SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5270                                   DAG.getConstant(CnstVal, MVT::i32));
5271         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5272       }
5273
5274       if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5275           VT.getSizeInBits() == 128) {
5276         CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5277         SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5278                                   DAG.getConstant(CnstVal, MVT::i32));
5279         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5280       }
5281
5282       // The many faces of MVNI...
5283       CnstVal = ~CnstVal;
5284       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5285         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5286         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5287         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5288                                   DAG.getConstant(CnstVal, MVT::i32),
5289                                   DAG.getConstant(0, MVT::i32));
5290         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5291       }
5292
5293       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5294         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5295         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5296         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5297                                   DAG.getConstant(CnstVal, MVT::i32),
5298                                   DAG.getConstant(8, MVT::i32));
5299         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5300       }
5301
5302       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5303         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5304         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5305         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5306                                   DAG.getConstant(CnstVal, MVT::i32),
5307                                   DAG.getConstant(16, MVT::i32));
5308         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5309       }
5310
5311       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5312         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5313         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5314         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5315                                   DAG.getConstant(CnstVal, MVT::i32),
5316                                   DAG.getConstant(24, MVT::i32));
5317         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5318       }
5319
5320       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5321         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5322         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5323         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5324                                   DAG.getConstant(CnstVal, MVT::i32),
5325                                   DAG.getConstant(0, MVT::i32));
5326         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5327       }
5328
5329       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5330         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5331         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5332         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5333                                   DAG.getConstant(CnstVal, MVT::i32),
5334                                   DAG.getConstant(8, MVT::i32));
5335         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5336       }
5337
5338       if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5339         CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5340         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5341         SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5342                                   DAG.getConstant(CnstVal, MVT::i32),
5343                                   DAG.getConstant(264, MVT::i32));
5344         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5345       }
5346
5347       if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5348         CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5349         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5350         SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5351                                   DAG.getConstant(CnstVal, MVT::i32),
5352                                   DAG.getConstant(272, MVT::i32));
5353         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5354       }
5355     }
5356
5357     if (SecondTry)
5358       goto FailedModImm;
5359     SecondTry = true;
5360     CnstBits = UndefBits;
5361     goto AttemptModImm;
5362   }
5363 FailedModImm:
5364
5365   // Scan through the operands to find some interesting properties we can
5366   // exploit:
5367   //   1) If only one value is used, we can use a DUP, or
5368   //   2) if only the low element is not undef, we can just insert that, or
5369   //   3) if only one constant value is used (w/ some non-constant lanes),
5370   //      we can splat the constant value into the whole vector then fill
5371   //      in the non-constant lanes.
5372   //   4) FIXME: If different constant values are used, but we can intelligently
5373   //             select the values we'll be overwriting for the non-constant
5374   //             lanes such that we can directly materialize the vector
5375   //             some other way (MOVI, e.g.), we can be sneaky.
5376   unsigned NumElts = VT.getVectorNumElements();
5377   bool isOnlyLowElement = true;
5378   bool usesOnlyOneValue = true;
5379   bool usesOnlyOneConstantValue = true;
5380   bool isConstant = true;
5381   unsigned NumConstantLanes = 0;
5382   SDValue Value;
5383   SDValue ConstantValue;
5384   for (unsigned i = 0; i < NumElts; ++i) {
5385     SDValue V = Op.getOperand(i);
5386     if (V.getOpcode() == ISD::UNDEF)
5387       continue;
5388     if (i > 0)
5389       isOnlyLowElement = false;
5390     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5391       isConstant = false;
5392
5393     if (isa<ConstantSDNode>(V)) {
5394       ++NumConstantLanes;
5395       if (!ConstantValue.getNode())
5396         ConstantValue = V;
5397       else if (ConstantValue != V)
5398         usesOnlyOneConstantValue = false;
5399     }
5400
5401     if (!Value.getNode())
5402       Value = V;
5403     else if (V != Value)
5404       usesOnlyOneValue = false;
5405   }
5406
5407   if (!Value.getNode())
5408     return DAG.getUNDEF(VT);
5409
5410   if (isOnlyLowElement)
5411     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5412
5413   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
5414   // i32 and try again.
5415   if (usesOnlyOneValue) {
5416     if (!isConstant) {
5417       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5418           Value.getValueType() != VT)
5419         return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5420
5421       // This is actually a DUPLANExx operation, which keeps everything vectory.
5422
5423       // DUPLANE works on 128-bit vectors, widen it if necessary.
5424       SDValue Lane = Value.getOperand(1);
5425       Value = Value.getOperand(0);
5426       if (Value.getValueType().getSizeInBits() == 64)
5427         Value = WidenVector(Value, DAG);
5428
5429       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5430       return DAG.getNode(Opcode, dl, VT, Value, Lane);
5431     }
5432
5433     if (VT.getVectorElementType().isFloatingPoint()) {
5434       SmallVector<SDValue, 8> Ops;
5435       MVT NewType =
5436           (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5437       for (unsigned i = 0; i < NumElts; ++i)
5438         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5439       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5440       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5441       Val = LowerBUILD_VECTOR(Val, DAG);
5442       if (Val.getNode())
5443         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5444     }
5445   }
5446
5447   // If there was only one constant value used and for more than one lane,
5448   // start by splatting that value, then replace the non-constant lanes. This
5449   // is better than the default, which will perform a separate initialization
5450   // for each lane.
5451   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5452     SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5453     // Now insert the non-constant lanes.
5454     for (unsigned i = 0; i < NumElts; ++i) {
5455       SDValue V = Op.getOperand(i);
5456       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5457       if (!isa<ConstantSDNode>(V)) {
5458         // Note that type legalization likely mucked about with the VT of the
5459         // source operand, so we may have to convert it here before inserting.
5460         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5461       }
5462     }
5463     return Val;
5464   }
5465
5466   // If all elements are constants and the case above didn't get hit, fall back
5467   // to the default expansion, which will generate a load from the constant
5468   // pool.
5469   if (isConstant)
5470     return SDValue();
5471
5472   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5473   if (NumElts >= 4) {
5474     SDValue shuffle = ReconstructShuffle(Op, DAG);
5475     if (shuffle != SDValue())
5476       return shuffle;
5477   }
5478
5479   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5480   // know the default expansion would otherwise fall back on something even
5481   // worse. For a vector with one or two non-undef values, that's
5482   // scalar_to_vector for the elements followed by a shuffle (provided the
5483   // shuffle is valid for the target) and materialization element by element
5484   // on the stack followed by a load for everything else.
5485   if (!isConstant && !usesOnlyOneValue) {
5486     SDValue Vec = DAG.getUNDEF(VT);
5487     SDValue Op0 = Op.getOperand(0);
5488     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5489     unsigned i = 0;
5490     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5491     // a) Avoid a RMW dependency on the full vector register, and
5492     // b) Allow the register coalescer to fold away the copy if the
5493     //    value is already in an S or D register.
5494     if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5495       unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5496       MachineSDNode *N =
5497           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5498                              DAG.getTargetConstant(SubIdx, MVT::i32));
5499       Vec = SDValue(N, 0);
5500       ++i;
5501     }
5502     for (; i < NumElts; ++i) {
5503       SDValue V = Op.getOperand(i);
5504       if (V.getOpcode() == ISD::UNDEF)
5505         continue;
5506       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5507       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5508     }
5509     return Vec;
5510   }
5511
5512   // Just use the default expansion. We failed to find a better alternative.
5513   return SDValue();
5514 }
5515
5516 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5517                                                     SelectionDAG &DAG) const {
5518   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5519
5520   // Check for non-constant lane.
5521   if (!isa<ConstantSDNode>(Op.getOperand(2)))
5522     return SDValue();
5523
5524   EVT VT = Op.getOperand(0).getValueType();
5525
5526   // Insertion/extraction are legal for V128 types.
5527   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5528       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5529     return Op;
5530
5531   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5532       VT != MVT::v1i64 && VT != MVT::v2f32)
5533     return SDValue();
5534
5535   // For V64 types, we perform insertion by expanding the value
5536   // to a V128 type and perform the insertion on that.
5537   SDLoc DL(Op);
5538   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5539   EVT WideTy = WideVec.getValueType();
5540
5541   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5542                              Op.getOperand(1), Op.getOperand(2));
5543   // Re-narrow the resultant vector.
5544   return NarrowVector(Node, DAG);
5545 }
5546
5547 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5548                                                      SelectionDAG &DAG) const {
5549   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5550
5551   // Check for non-constant lane.
5552   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5553     return SDValue();
5554
5555   EVT VT = Op.getOperand(0).getValueType();
5556
5557   // Insertion/extraction are legal for V128 types.
5558   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5559       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5560     return Op;
5561
5562   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5563       VT != MVT::v1i64 && VT != MVT::v2f32)
5564     return SDValue();
5565
5566   // For V64 types, we perform extraction by expanding the value
5567   // to a V128 type and perform the extraction on that.
5568   SDLoc DL(Op);
5569   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5570   EVT WideTy = WideVec.getValueType();
5571
5572   EVT ExtrTy = WideTy.getVectorElementType();
5573   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5574     ExtrTy = MVT::i32;
5575
5576   // For extractions, we just return the result directly.
5577   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5578                      Op.getOperand(1));
5579 }
5580
5581 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5582                                                     SelectionDAG &DAG) const {
5583   EVT VT = Op.getOperand(0).getValueType();
5584   SDLoc dl(Op);
5585   // Just in case...
5586   if (!VT.isVector())
5587     return SDValue();
5588
5589   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5590   if (!Cst)
5591     return SDValue();
5592   unsigned Val = Cst->getZExtValue();
5593
5594   unsigned Size = Op.getValueType().getSizeInBits();
5595   if (Val == 0) {
5596     switch (Size) {
5597     case 8:
5598       return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5599                                         Op.getOperand(0));
5600     case 16:
5601       return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5602                                         Op.getOperand(0));
5603     case 32:
5604       return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5605                                         Op.getOperand(0));
5606     case 64:
5607       return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5608                                         Op.getOperand(0));
5609     default:
5610       llvm_unreachable("Unexpected vector type in extract_subvector!");
5611     }
5612   }
5613   // If this is extracting the upper 64-bits of a 128-bit vector, we match
5614   // that directly.
5615   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5616     return Op;
5617
5618   return SDValue();
5619 }
5620
5621 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5622                                              EVT VT) const {
5623   if (VT.getVectorNumElements() == 4 &&
5624       (VT.is128BitVector() || VT.is64BitVector())) {
5625     unsigned PFIndexes[4];
5626     for (unsigned i = 0; i != 4; ++i) {
5627       if (M[i] < 0)
5628         PFIndexes[i] = 8;
5629       else
5630         PFIndexes[i] = M[i];
5631     }
5632
5633     // Compute the index in the perfect shuffle table.
5634     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5635                             PFIndexes[2] * 9 + PFIndexes[3];
5636     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5637     unsigned Cost = (PFEntry >> 30);
5638
5639     if (Cost <= 4)
5640       return true;
5641   }
5642
5643   bool ReverseVEXT;
5644   unsigned Imm, WhichResult;
5645
5646   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5647           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5648           isEXTMask(M, VT, ReverseVEXT, Imm) ||
5649           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5650           isTRNMask(M, VT, WhichResult) || isUZPMask(M, VT, WhichResult) ||
5651           isZIPMask(M, VT, WhichResult) ||
5652           isTRN_v_undef_Mask(M, VT, WhichResult) ||
5653           isUZP_v_undef_Mask(M, VT, WhichResult) ||
5654           isZIP_v_undef_Mask(M, VT, WhichResult));
5655 }
5656
5657 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5658 /// operand of a vector shift operation, where all the elements of the
5659 /// build_vector must have the same constant integer value.
5660 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5661   // Ignore bit_converts.
5662   while (Op.getOpcode() == ISD::BITCAST)
5663     Op = Op.getOperand(0);
5664   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5665   APInt SplatBits, SplatUndef;
5666   unsigned SplatBitSize;
5667   bool HasAnyUndefs;
5668   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5669                                     HasAnyUndefs, ElementBits) ||
5670       SplatBitSize > ElementBits)
5671     return false;
5672   Cnt = SplatBits.getSExtValue();
5673   return true;
5674 }
5675
5676 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5677 /// operand of a vector shift left operation.  That value must be in the range:
5678 ///   0 <= Value < ElementBits for a left shift; or
5679 ///   0 <= Value <= ElementBits for a long left shift.
5680 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5681   assert(VT.isVector() && "vector shift count is not a vector type");
5682   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5683   if (!getVShiftImm(Op, ElementBits, Cnt))
5684     return false;
5685   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5686 }
5687
5688 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5689 /// operand of a vector shift right operation.  For a shift opcode, the value
5690 /// is positive, but for an intrinsic the value count must be negative. The
5691 /// absolute value must be in the range:
5692 ///   1 <= |Value| <= ElementBits for a right shift; or
5693 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
5694 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5695                          int64_t &Cnt) {
5696   assert(VT.isVector() && "vector shift count is not a vector type");
5697   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5698   if (!getVShiftImm(Op, ElementBits, Cnt))
5699     return false;
5700   if (isIntrinsic)
5701     Cnt = -Cnt;
5702   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5703 }
5704
5705 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5706                                                     SelectionDAG &DAG) const {
5707   EVT VT = Op.getValueType();
5708   SDLoc DL(Op);
5709   int64_t Cnt;
5710
5711   if (!Op.getOperand(1).getValueType().isVector())
5712     return Op;
5713   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5714
5715   switch (Op.getOpcode()) {
5716   default:
5717     llvm_unreachable("unexpected shift opcode");
5718
5719   case ISD::SHL:
5720     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5721       return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5722                          DAG.getConstant(Cnt, MVT::i32));
5723     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5724                        DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5725                        Op.getOperand(0), Op.getOperand(1));
5726   case ISD::SRA:
5727   case ISD::SRL:
5728     // Right shift immediate
5729     if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5730         Cnt < EltSize) {
5731       unsigned Opc =
5732           (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5733       return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5734                          DAG.getConstant(Cnt, MVT::i32));
5735     }
5736
5737     // Right shift register.  Note, there is not a shift right register
5738     // instruction, but the shift left register instruction takes a signed
5739     // value, where negative numbers specify a right shift.
5740     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5741                                                 : Intrinsic::arm64_neon_ushl;
5742     // negate the shift amount
5743     SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5744     SDValue NegShiftLeft =
5745         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5746                     DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5747     return NegShiftLeft;
5748   }
5749
5750   return SDValue();
5751 }
5752
5753 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5754                                     ARM64CC::CondCode CC, bool NoNans, EVT VT,
5755                                     SDLoc dl, SelectionDAG &DAG) {
5756   EVT SrcVT = LHS.getValueType();
5757
5758   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5759   APInt CnstBits(VT.getSizeInBits(), 0);
5760   APInt UndefBits(VT.getSizeInBits(), 0);
5761   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5762   bool IsZero = IsCnst && (CnstBits == 0);
5763
5764   if (SrcVT.getVectorElementType().isFloatingPoint()) {
5765     switch (CC) {
5766     default:
5767       return SDValue();
5768     case ARM64CC::NE: {
5769       SDValue Fcmeq;
5770       if (IsZero)
5771         Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5772       else
5773         Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5774       return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5775     }
5776     case ARM64CC::EQ:
5777       if (IsZero)
5778         return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5779       return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5780     case ARM64CC::GE:
5781       if (IsZero)
5782         return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5783       return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5784     case ARM64CC::GT:
5785       if (IsZero)
5786         return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5787       return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5788     case ARM64CC::LS:
5789       if (IsZero)
5790         return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5791       return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5792     case ARM64CC::LT:
5793       if (!NoNans)
5794         return SDValue();
5795     // If we ignore NaNs then we can use to the MI implementation.
5796     // Fallthrough.
5797     case ARM64CC::MI:
5798       if (IsZero)
5799         return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5800       return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5801     }
5802   }
5803
5804   switch (CC) {
5805   default:
5806     return SDValue();
5807   case ARM64CC::NE: {
5808     SDValue Cmeq;
5809     if (IsZero)
5810       Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5811     else
5812       Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5813     return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5814   }
5815   case ARM64CC::EQ:
5816     if (IsZero)
5817       return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5818     return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5819   case ARM64CC::GE:
5820     if (IsZero)
5821       return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5822     return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5823   case ARM64CC::GT:
5824     if (IsZero)
5825       return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5826     return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5827   case ARM64CC::LE:
5828     if (IsZero)
5829       return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5830     return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5831   case ARM64CC::LS:
5832     return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5833   case ARM64CC::CC:
5834     return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5835   case ARM64CC::LT:
5836     if (IsZero)
5837       return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5838     return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5839   case ARM64CC::HI:
5840     return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5841   case ARM64CC::CS:
5842     return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5843   }
5844 }
5845
5846 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5847   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5848   SDValue LHS = Op.getOperand(0);
5849   SDValue RHS = Op.getOperand(1);
5850   SDLoc dl(Op);
5851
5852   if (LHS.getValueType().getVectorElementType().isInteger()) {
5853     assert(LHS.getValueType() == RHS.getValueType());
5854     ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5855     return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5856                                 DAG);
5857   }
5858
5859   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5860          LHS.getValueType().getVectorElementType() == MVT::f64);
5861
5862   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5863   // clean.  Some of them require two branches to implement.
5864   ARM64CC::CondCode CC1, CC2;
5865   changeFPCCToARM64CC(CC, CC1, CC2);
5866
5867   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5868   SDValue Cmp1 =
5869       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5870   if (!Cmp1.getNode())
5871     return SDValue();
5872
5873   if (CC2 != ARM64CC::AL) {
5874     SDValue Cmp2 =
5875         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5876     if (!Cmp2.getNode())
5877       return SDValue();
5878
5879     return DAG.getNode(ISD::OR, dl, Cmp1.getValueType(), Cmp1, Cmp2);
5880   }
5881
5882   return Cmp1;
5883 }
5884
5885 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5886 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
5887 /// specified in the intrinsic calls.
5888 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5889                                              const CallInst &I,
5890                                              unsigned Intrinsic) const {
5891   switch (Intrinsic) {
5892   case Intrinsic::arm64_neon_ld2:
5893   case Intrinsic::arm64_neon_ld3:
5894   case Intrinsic::arm64_neon_ld4:
5895   case Intrinsic::arm64_neon_ld2lane:
5896   case Intrinsic::arm64_neon_ld3lane:
5897   case Intrinsic::arm64_neon_ld4lane:
5898   case Intrinsic::arm64_neon_ld2r:
5899   case Intrinsic::arm64_neon_ld3r:
5900   case Intrinsic::arm64_neon_ld4r: {
5901     Info.opc = ISD::INTRINSIC_W_CHAIN;
5902     // Conservatively set memVT to the entire set of vectors loaded.
5903     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5904     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5905     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5906     Info.offset = 0;
5907     Info.align = 0;
5908     Info.vol = false; // volatile loads with NEON intrinsics not supported
5909     Info.readMem = true;
5910     Info.writeMem = false;
5911     return true;
5912   }
5913   case Intrinsic::arm64_neon_st2:
5914   case Intrinsic::arm64_neon_st3:
5915   case Intrinsic::arm64_neon_st4:
5916   case Intrinsic::arm64_neon_st2lane:
5917   case Intrinsic::arm64_neon_st3lane:
5918   case Intrinsic::arm64_neon_st4lane: {
5919     Info.opc = ISD::INTRINSIC_VOID;
5920     // Conservatively set memVT to the entire set of vectors stored.
5921     unsigned NumElts = 0;
5922     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5923       Type *ArgTy = I.getArgOperand(ArgI)->getType();
5924       if (!ArgTy->isVectorTy())
5925         break;
5926       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5927     }
5928     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5929     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5930     Info.offset = 0;
5931     Info.align = 0;
5932     Info.vol = false; // volatile stores with NEON intrinsics not supported
5933     Info.readMem = false;
5934     Info.writeMem = true;
5935     return true;
5936   }
5937   case Intrinsic::arm64_ldxr: {
5938     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5939     Info.opc = ISD::INTRINSIC_W_CHAIN;
5940     Info.memVT = MVT::getVT(PtrTy->getElementType());
5941     Info.ptrVal = I.getArgOperand(0);
5942     Info.offset = 0;
5943     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5944     Info.vol = true;
5945     Info.readMem = true;
5946     Info.writeMem = false;
5947     return true;
5948   }
5949   case Intrinsic::arm64_stxr: {
5950     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5951     Info.opc = ISD::INTRINSIC_W_CHAIN;
5952     Info.memVT = MVT::getVT(PtrTy->getElementType());
5953     Info.ptrVal = I.getArgOperand(1);
5954     Info.offset = 0;
5955     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5956     Info.vol = true;
5957     Info.readMem = false;
5958     Info.writeMem = true;
5959     return true;
5960   }
5961   case Intrinsic::arm64_ldxp: {
5962     Info.opc = ISD::INTRINSIC_W_CHAIN;
5963     Info.memVT = MVT::i128;
5964     Info.ptrVal = I.getArgOperand(0);
5965     Info.offset = 0;
5966     Info.align = 16;
5967     Info.vol = true;
5968     Info.readMem = true;
5969     Info.writeMem = false;
5970     return true;
5971   }
5972   case Intrinsic::arm64_stxp: {
5973     Info.opc = ISD::INTRINSIC_W_CHAIN;
5974     Info.memVT = MVT::i128;
5975     Info.ptrVal = I.getArgOperand(2);
5976     Info.offset = 0;
5977     Info.align = 16;
5978     Info.vol = true;
5979     Info.readMem = false;
5980     Info.writeMem = true;
5981     return true;
5982   }
5983   default:
5984     break;
5985   }
5986
5987   return false;
5988 }
5989
5990 // Truncations from 64-bit GPR to 32-bit GPR is free.
5991 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5992   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5993     return false;
5994   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5995   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5996   if (NumBits1 <= NumBits2)
5997     return false;
5998   return true;
5999 }
6000 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6001   if (!VT1.isInteger() || !VT2.isInteger())
6002     return false;
6003   unsigned NumBits1 = VT1.getSizeInBits();
6004   unsigned NumBits2 = VT2.getSizeInBits();
6005   if (NumBits1 <= NumBits2)
6006     return false;
6007   return true;
6008 }
6009
6010 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6011 // 64-bit GPR.
6012 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6013   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6014     return false;
6015   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6016   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6017   if (NumBits1 == 32 && NumBits2 == 64)
6018     return true;
6019   return false;
6020 }
6021 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6022   if (!VT1.isInteger() || !VT2.isInteger())
6023     return false;
6024   unsigned NumBits1 = VT1.getSizeInBits();
6025   unsigned NumBits2 = VT2.getSizeInBits();
6026   if (NumBits1 == 32 && NumBits2 == 64)
6027     return true;
6028   return false;
6029 }
6030
6031 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6032   EVT VT1 = Val.getValueType();
6033   if (isZExtFree(VT1, VT2)) {
6034     return true;
6035   }
6036
6037   if (Val.getOpcode() != ISD::LOAD)
6038     return false;
6039
6040   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6041   return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
6042           VT2.isInteger() && VT1.getSizeInBits() <= 32);
6043 }
6044
6045 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
6046                                         unsigned &RequiredAligment) const {
6047   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6048     return false;
6049   // Cyclone supports unaligned accesses.
6050   RequiredAligment = 0;
6051   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6052   return NumBits == 32 || NumBits == 64;
6053 }
6054
6055 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
6056                                         unsigned &RequiredAligment) const {
6057   if (!LoadedType.isSimple() ||
6058       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6059     return false;
6060   // Cyclone supports unaligned accesses.
6061   RequiredAligment = 0;
6062   unsigned NumBits = LoadedType.getSizeInBits();
6063   return NumBits == 32 || NumBits == 64;
6064 }
6065
6066 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6067                        unsigned AlignCheck) {
6068   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6069           (DstAlign == 0 || DstAlign % AlignCheck == 0));
6070 }
6071
6072 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6073                                              unsigned SrcAlign, bool IsMemset,
6074                                              bool ZeroMemset, bool MemcpyStrSrc,
6075                                              MachineFunction &MF) const {
6076   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6077   // instruction to materialize the v2i64 zero and one store (with restrictive
6078   // addressing mode). Just do two i64 store of zero-registers.
6079   bool Fast;
6080   const Function *F = MF.getFunction();
6081   if (!IsMemset && Size >= 16 &&
6082       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6083                                        Attribute::NoImplicitFloat) &&
6084       (memOpAlign(SrcAlign, DstAlign, 16) ||
6085        (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
6086     return MVT::v2i64;
6087
6088   return Size >= 8 ? MVT::i64 : MVT::i32;
6089 }
6090
6091 // 12-bit optionally shifted immediates are legal for adds.
6092 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6093   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6094     return true;
6095   return false;
6096 }
6097
6098 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6099 // immediates is the same as for an add or a sub.
6100 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6101   if (Immed < 0)
6102     Immed *= -1;
6103   return isLegalAddImmediate(Immed);
6104 }
6105
6106 /// isLegalAddressingMode - Return true if the addressing mode represented
6107 /// by AM is legal for this target, for a load/store of the specified type.
6108 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6109                                                 Type *Ty) const {
6110   // ARM64 has five basic addressing modes:
6111   //  reg
6112   //  reg + 9-bit signed offset
6113   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
6114   //  reg1 + reg2
6115   //  reg + SIZE_IN_BYTES * reg
6116
6117   // No global is ever allowed as a base.
6118   if (AM.BaseGV)
6119     return false;
6120
6121   // No reg+reg+imm addressing.
6122   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6123     return false;
6124
6125   // check reg + imm case:
6126   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6127   uint64_t NumBytes = 0;
6128   if (Ty->isSized()) {
6129     uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6130     NumBytes = NumBits / 8;
6131     if (!isPowerOf2_64(NumBits))
6132       NumBytes = 0;
6133   }
6134
6135   if (!AM.Scale) {
6136     int64_t Offset = AM.BaseOffs;
6137
6138     // 9-bit signed offset
6139     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6140       return true;
6141
6142     // 12-bit unsigned offset
6143     unsigned shift = Log2_64(NumBytes);
6144     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6145         // Must be a multiple of NumBytes (NumBytes is a power of 2)
6146         (Offset >> shift) << shift == Offset)
6147       return true;
6148     return false;
6149   }
6150
6151   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6152
6153   if (!AM.Scale || AM.Scale == 1 ||
6154       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6155     return true;
6156   return false;
6157 }
6158
6159 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6160                                               Type *Ty) const {
6161   // Scaling factors are not free at all.
6162   // Operands                     | Rt Latency
6163   // -------------------------------------------
6164   // Rt, [Xn, Xm]                 | 4
6165   // -------------------------------------------
6166   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
6167   // Rt, [Xn, Wm, <extend> #imm]  |
6168   if (isLegalAddressingMode(AM, Ty))
6169     // Scale represents reg2 * scale, thus account for 1 if
6170     // it is not equal to 0 or 1.
6171     return AM.Scale != 0 && AM.Scale != 1;
6172   return -1;
6173 }
6174
6175 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6176   VT = VT.getScalarType();
6177
6178   if (!VT.isSimple())
6179     return false;
6180
6181   switch (VT.getSimpleVT().SimpleTy) {
6182   case MVT::f32:
6183   case MVT::f64:
6184     return true;
6185   default:
6186     break;
6187   }
6188
6189   return false;
6190 }
6191
6192 const MCPhysReg *
6193 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6194   // LR is a callee-save register, but we must treat it as clobbered by any call
6195   // site. Hence we include LR in the scratch registers, which are in turn added
6196   // as implicit-defs for stackmaps and patchpoints.
6197   static const MCPhysReg ScratchRegs[] = {
6198     ARM64::X16, ARM64::X17, ARM64::LR, 0
6199   };
6200   return ScratchRegs;
6201 }
6202
6203 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6204                                                             Type *Ty) const {
6205   assert(Ty->isIntegerTy());
6206
6207   unsigned BitSize = Ty->getPrimitiveSizeInBits();
6208   if (BitSize == 0)
6209     return false;
6210
6211   int64_t Val = Imm.getSExtValue();
6212   if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
6213     return true;
6214
6215   if ((int64_t)Val < 0)
6216     Val = ~Val;
6217   if (BitSize == 32)
6218     Val &= (1LL << 32) - 1;
6219
6220   unsigned LZ = countLeadingZeros((uint64_t)Val);
6221   unsigned Shift = (63 - LZ) / 16;
6222   // MOVZ is free so return true for one or fewer MOVK.
6223   return (Shift < 3) ? true : false;
6224 }
6225
6226 // Generate SUBS and CSEL for integer abs.
6227 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6228   EVT VT = N->getValueType(0);
6229
6230   SDValue N0 = N->getOperand(0);
6231   SDValue N1 = N->getOperand(1);
6232   SDLoc DL(N);
6233
6234   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6235   // and change it to SUB and CSEL.
6236   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6237       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6238       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6239     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6240       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6241         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6242                                   N0.getOperand(0));
6243         // Generate SUBS & CSEL.
6244         SDValue Cmp =
6245             DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6246                         N0.getOperand(0), DAG.getConstant(0, VT));
6247         return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6248                            DAG.getConstant(ARM64CC::PL, MVT::i32),
6249                            SDValue(Cmp.getNode(), 1));
6250       }
6251   return SDValue();
6252 }
6253
6254 // performXorCombine - Attempts to handle integer ABS.
6255 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6256                                  TargetLowering::DAGCombinerInfo &DCI,
6257                                  const ARM64Subtarget *Subtarget) {
6258   if (DCI.isBeforeLegalizeOps())
6259     return SDValue();
6260
6261   return performIntegerAbsCombine(N, DAG);
6262 }
6263
6264 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6265                                  TargetLowering::DAGCombinerInfo &DCI,
6266                                  const ARM64Subtarget *Subtarget) {
6267   if (DCI.isBeforeLegalizeOps())
6268     return SDValue();
6269
6270   // Multiplication of a power of two plus/minus one can be done more
6271   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6272   // future CPUs have a cheaper MADD instruction, this may need to be
6273   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6274   // 64-bit is 5 cycles, so this is always a win.
6275   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6276     APInt Value = C->getAPIntValue();
6277     EVT VT = N->getValueType(0);
6278     APInt VP1 = Value + 1;
6279     if (VP1.isPowerOf2()) {
6280       // Multiplying by one less than a power of two, replace with a shift
6281       // and a subtract.
6282       SDValue ShiftedVal =
6283           DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6284                       DAG.getConstant(VP1.logBase2(), MVT::i64));
6285       return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6286     }
6287     APInt VM1 = Value - 1;
6288     if (VM1.isPowerOf2()) {
6289       // Multiplying by one more than a power of two, replace with a shift
6290       // and an add.
6291       SDValue ShiftedVal =
6292           DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6293                       DAG.getConstant(VM1.logBase2(), MVT::i64));
6294       return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6295     }
6296   }
6297   return SDValue();
6298 }
6299
6300 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6301   EVT VT = N->getValueType(0);
6302   if (VT != MVT::f32 && VT != MVT::f64)
6303     return SDValue();
6304   // Only optimize when the source and destination types have the same width.
6305   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6306     return SDValue();
6307
6308   // If the result of an integer load is only used by an integer-to-float
6309   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6310   // This eliminates an "integer-to-vector-move UOP and improve throughput.
6311   SDValue N0 = N->getOperand(0);
6312   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6313       // Do not change the width of a volatile load.
6314       !cast<LoadSDNode>(N0)->isVolatile()) {
6315     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6316     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6317                                LN0->getPointerInfo(), LN0->isVolatile(),
6318                                LN0->isNonTemporal(), LN0->isInvariant(),
6319                                LN0->getAlignment());
6320
6321     // Make sure successors of the original load stay after it by updating them
6322     // to use the new Chain.
6323     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6324
6325     unsigned Opcode =
6326         (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6327     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6328   }
6329
6330   return SDValue();
6331 }
6332
6333 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6334 /// searches for and classifies those shifts.
6335 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6336                          bool &FromHi) {
6337   if (N.getOpcode() == ISD::SHL)
6338     FromHi = false;
6339   else if (N.getOpcode() == ISD::SRL)
6340     FromHi = true;
6341   else
6342     return false;
6343
6344   if (!isa<ConstantSDNode>(N.getOperand(1)))
6345     return false;
6346
6347   ShiftAmount = N->getConstantOperandVal(1);
6348   Src = N->getOperand(0);
6349   return true;
6350 }
6351
6352 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6353 /// registers viewed as a high/low pair. This function looks for the pattern:
6354 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6355 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6356 /// independent.
6357 static SDValue tryCombineToEXTR(SDNode *N,
6358                                 TargetLowering::DAGCombinerInfo &DCI) {
6359   SelectionDAG &DAG = DCI.DAG;
6360   SDLoc DL(N);
6361   EVT VT = N->getValueType(0);
6362
6363   assert(N->getOpcode() == ISD::OR && "Unexpected root");
6364
6365   if (VT != MVT::i32 && VT != MVT::i64)
6366     return SDValue();
6367
6368   SDValue LHS;
6369   uint32_t ShiftLHS = 0;
6370   bool LHSFromHi = 0;
6371   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6372     return SDValue();
6373
6374   SDValue RHS;
6375   uint32_t ShiftRHS = 0;
6376   bool RHSFromHi = 0;
6377   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6378     return SDValue();
6379
6380   // If they're both trying to come from the high part of the register, they're
6381   // not really an EXTR.
6382   if (LHSFromHi == RHSFromHi)
6383     return SDValue();
6384
6385   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6386     return SDValue();
6387
6388   if (LHSFromHi) {
6389     std::swap(LHS, RHS);
6390     std::swap(ShiftLHS, ShiftRHS);
6391   }
6392
6393   return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6394                      DAG.getConstant(ShiftRHS, MVT::i64));
6395 }
6396
6397 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6398                                 const ARM64Subtarget *Subtarget) {
6399   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6400   if (!EnableARM64ExtrGeneration)
6401     return SDValue();
6402   SelectionDAG &DAG = DCI.DAG;
6403   EVT VT = N->getValueType(0);
6404
6405   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6406     return SDValue();
6407
6408   SDValue Res = tryCombineToEXTR(N, DCI);
6409   if (Res.getNode())
6410     return Res;
6411
6412   return SDValue();
6413 }
6414
6415 static SDValue performBitcastCombine(SDNode *N,
6416                                      TargetLowering::DAGCombinerInfo &DCI,
6417                                      SelectionDAG &DAG) {
6418   // Wait 'til after everything is legalized to try this. That way we have
6419   // legal vector types and such.
6420   if (DCI.isBeforeLegalizeOps())
6421     return SDValue();
6422
6423   // Remove extraneous bitcasts around an extract_subvector.
6424   // For example,
6425   //    (v4i16 (bitconvert
6426   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6427   //  becomes
6428   //    (extract_subvector ((v8i16 ...), (i64 4)))
6429
6430   // Only interested in 64-bit vectors as the ultimate result.
6431   EVT VT = N->getValueType(0);
6432   if (!VT.isVector())
6433     return SDValue();
6434   if (VT.getSimpleVT().getSizeInBits() != 64)
6435     return SDValue();
6436   // Is the operand an extract_subvector starting at the beginning or halfway
6437   // point of the vector? A low half may also come through as an
6438   // EXTRACT_SUBREG, so look for that, too.
6439   SDValue Op0 = N->getOperand(0);
6440   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6441       !(Op0->isMachineOpcode() &&
6442         Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6443     return SDValue();
6444   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6445   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6446     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6447       return SDValue();
6448   } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6449     if (idx != ARM64::dsub)
6450       return SDValue();
6451     // The dsub reference is equivalent to a lane zero subvector reference.
6452     idx = 0;
6453   }
6454   // Look through the bitcast of the input to the extract.
6455   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6456     return SDValue();
6457   SDValue Source = Op0->getOperand(0)->getOperand(0);
6458   // If the source type has twice the number of elements as our destination
6459   // type, we know this is an extract of the high or low half of the vector.
6460   EVT SVT = Source->getValueType(0);
6461   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6462     return SDValue();
6463
6464   DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6465
6466   // Create the simplified form to just extract the low or high half of the
6467   // vector directly rather than bothering with the bitcasts.
6468   SDLoc dl(N);
6469   unsigned NumElements = VT.getVectorNumElements();
6470   if (idx) {
6471     SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6472     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6473   } else {
6474     SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6475     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6476                                       Source, SubReg),
6477                    0);
6478   }
6479 }
6480
6481 static SDValue performConcatVectorsCombine(SDNode *N,
6482                                            TargetLowering::DAGCombinerInfo &DCI,
6483                                            SelectionDAG &DAG) {
6484   // Wait 'til after everything is legalized to try this. That way we have
6485   // legal vector types and such.
6486   if (DCI.isBeforeLegalizeOps())
6487     return SDValue();
6488
6489   SDLoc dl(N);
6490   EVT VT = N->getValueType(0);
6491
6492   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6493   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6494   // canonicalise to that.
6495   if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6496     assert(VT.getVectorElementType().getSizeInBits() == 64);
6497     return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6498                        WidenVector(N->getOperand(0), DAG),
6499                        DAG.getConstant(0, MVT::i64));
6500   }
6501
6502   // Canonicalise concat_vectors so that the right-hand vector has as few
6503   // bit-casts as possible before its real operation. The primary matching
6504   // destination for these operations will be the narrowing "2" instructions,
6505   // which depend on the operation being performed on this right-hand vector.
6506   // For example,
6507   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
6508   // becomes
6509   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6510
6511   SDValue Op1 = N->getOperand(1);
6512   if (Op1->getOpcode() != ISD::BITCAST)
6513     return SDValue();
6514   SDValue RHS = Op1->getOperand(0);
6515   MVT RHSTy = RHS.getValueType().getSimpleVT();
6516   // If the RHS is not a vector, this is not the pattern we're looking for.
6517   if (!RHSTy.isVector())
6518     return SDValue();
6519
6520   DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6521
6522   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6523                                   RHSTy.getVectorNumElements() * 2);
6524   return DAG.getNode(
6525       ISD::BITCAST, dl, VT,
6526       DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6527                   DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6528 }
6529
6530 static SDValue tryCombineFixedPointConvert(SDNode *N,
6531                                            TargetLowering::DAGCombinerInfo &DCI,
6532                                            SelectionDAG &DAG) {
6533   // Wait 'til after everything is legalized to try this. That way we have
6534   // legal vector types and such.
6535   if (DCI.isBeforeLegalizeOps())
6536     return SDValue();
6537   // Transform a scalar conversion of a value from a lane extract into a
6538   // lane extract of a vector conversion. E.g., from foo1 to foo2:
6539   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6540   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6541   //
6542   // The second form interacts better with instruction selection and the
6543   // register allocator to avoid cross-class register copies that aren't
6544   // coalescable due to a lane reference.
6545
6546   // Check the operand and see if it originates from a lane extract.
6547   SDValue Op1 = N->getOperand(1);
6548   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6549     // Yep, no additional predication needed. Perform the transform.
6550     SDValue IID = N->getOperand(0);
6551     SDValue Shift = N->getOperand(2);
6552     SDValue Vec = Op1.getOperand(0);
6553     SDValue Lane = Op1.getOperand(1);
6554     EVT ResTy = N->getValueType(0);
6555     EVT VecResTy;
6556     SDLoc DL(N);
6557
6558     // The vector width should be 128 bits by the time we get here, even
6559     // if it started as 64 bits (the extract_vector handling will have
6560     // done so).
6561     assert(Vec.getValueType().getSizeInBits() == 128 &&
6562            "unexpected vector size on extract_vector_elt!");
6563     if (Vec.getValueType() == MVT::v4i32)
6564       VecResTy = MVT::v4f32;
6565     else if (Vec.getValueType() == MVT::v2i64)
6566       VecResTy = MVT::v2f64;
6567     else
6568       assert(0 && "unexpected vector type!");
6569
6570     SDValue Convert =
6571         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6572     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6573   }
6574   return SDValue();
6575 }
6576
6577 // AArch64 high-vector "long" operations are formed by performing the non-high
6578 // version on an extract_subvector of each operand which gets the high half:
6579 //
6580 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6581 //
6582 // However, there are cases which don't have an extract_high explicitly, but
6583 // have another operation that can be made compatible with one for free. For
6584 // example:
6585 //
6586 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
6587 //
6588 // This routine does the actual conversion of such DUPs, once outer routines
6589 // have determined that everything else is in order.
6590 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6591   // We can handle most types of duplicate, but the lane ones have an extra
6592   // operand saying *which* lane, so we need to know.
6593   bool IsDUPLANE;
6594   switch (N.getOpcode()) {
6595   case ARM64ISD::DUP:
6596     IsDUPLANE = false;
6597     break;
6598   case ARM64ISD::DUPLANE8:
6599   case ARM64ISD::DUPLANE16:
6600   case ARM64ISD::DUPLANE32:
6601   case ARM64ISD::DUPLANE64:
6602     IsDUPLANE = true;
6603     break;
6604   default:
6605     return SDValue();
6606   }
6607
6608   MVT NarrowTy = N.getSimpleValueType();
6609   if (!NarrowTy.is64BitVector())
6610     return SDValue();
6611
6612   MVT ElementTy = NarrowTy.getVectorElementType();
6613   unsigned NumElems = NarrowTy.getVectorNumElements();
6614   MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6615
6616   SDValue NewDUP;
6617   if (IsDUPLANE)
6618     NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6619                          N.getOperand(1));
6620   else
6621     NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6622
6623   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6624                      NewDUP, DAG.getConstant(NumElems, MVT::i64));
6625 }
6626
6627 static bool isEssentiallyExtractSubvector(SDValue N) {
6628   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6629     return true;
6630
6631   return N.getOpcode() == ISD::BITCAST &&
6632          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6633 }
6634
6635 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6636 struct GenericSetCCInfo {
6637   const SDValue *Opnd0;
6638   const SDValue *Opnd1;
6639   ISD::CondCode CC;
6640 };
6641
6642 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6643 struct ARM64SetCCInfo {
6644   const SDValue *Cmp;
6645   ARM64CC::CondCode CC;
6646 };
6647
6648 /// \brief Helper structure to keep track of SetCC information.
6649 union SetCCInfo {
6650   GenericSetCCInfo Generic;
6651   ARM64SetCCInfo ARM64;
6652 };
6653
6654 /// \brief Helper structure to be able to read SetCC information.
6655 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6656 /// a GenericSetCCInfo.
6657 struct SetCCInfoAndKind {
6658   SetCCInfo Info;
6659   bool IsARM64;
6660 };
6661
6662 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6663 /// an
6664 /// ARM64 lowered one.
6665 /// \p SetCCInfo is filled accordingly.
6666 /// \post SetCCInfo is meanginfull only when this function returns true.
6667 /// \return True when Op is a kind of SET_CC operation.
6668 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6669   // If this is a setcc, this is straight forward.
6670   if (Op.getOpcode() == ISD::SETCC) {
6671     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6672     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6673     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6674     SetCCInfo.IsARM64 = false;
6675     return true;
6676   }
6677   // Otherwise, check if this is a matching csel instruction.
6678   // In other words:
6679   // - csel 1, 0, cc
6680   // - csel 0, 1, !cc
6681   if (Op.getOpcode() != ARM64ISD::CSEL)
6682     return false;
6683   // Set the information about the operands.
6684   // TODO: we want the operands of the Cmp not the csel
6685   SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6686   SetCCInfo.IsARM64 = true;
6687   SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6688       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6689
6690   // Check that the operands matches the constraints:
6691   // (1) Both operands must be constants.
6692   // (2) One must be 1 and the other must be 0.
6693   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6694   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6695
6696   // Check (1).
6697   if (!TValue || !FValue)
6698     return false;
6699
6700   // Check (2).
6701   if (!TValue->isOne()) {
6702     // Update the comparison when we are interested in !cc.
6703     std::swap(TValue, FValue);
6704     SetCCInfo.Info.ARM64.CC =
6705         ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6706   }
6707   return TValue->isOne() && FValue->isNullValue();
6708 }
6709
6710 // The folding we want to perform is:
6711 // (add x, (setcc cc ...) )
6712 //   -->
6713 // (csel x, (add x, 1), !cc ...)
6714 //
6715 // The latter will get matched to a CSINC instruction.
6716 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6717   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6718   SDValue LHS = Op->getOperand(0);
6719   SDValue RHS = Op->getOperand(1);
6720   SetCCInfoAndKind InfoAndKind;
6721
6722   // If neither operand is a SET_CC, give up.
6723   if (!isSetCC(LHS, InfoAndKind)) {
6724     std::swap(LHS, RHS);
6725     if (!isSetCC(LHS, InfoAndKind))
6726       return SDValue();
6727   }
6728
6729   // FIXME: This could be generatized to work for FP comparisons.
6730   EVT CmpVT = InfoAndKind.IsARM64
6731                   ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6732                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
6733   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6734     return SDValue();
6735
6736   SDValue CCVal;
6737   SDValue Cmp;
6738   SDLoc dl(Op);
6739   if (InfoAndKind.IsARM64) {
6740     CCVal = DAG.getConstant(
6741         ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6742     Cmp = *InfoAndKind.Info.ARM64.Cmp;
6743   } else
6744     Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6745                       *InfoAndKind.Info.Generic.Opnd1,
6746                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6747                       CCVal, DAG, dl);
6748
6749   EVT VT = Op->getValueType(0);
6750   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6751   return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6752 }
6753
6754 // The basic add/sub long vector instructions have variants with "2" on the end
6755 // which act on the high-half of their inputs. They are normally matched by
6756 // patterns like:
6757 //
6758 // (add (zeroext (extract_high LHS)),
6759 //      (zeroext (extract_high RHS)))
6760 // -> uaddl2 vD, vN, vM
6761 //
6762 // However, if one of the extracts is something like a duplicate, this
6763 // instruction can still be used profitably. This function puts the DAG into a
6764 // more appropriate form for those patterns to trigger.
6765 static SDValue performAddSubLongCombine(SDNode *N,
6766                                         TargetLowering::DAGCombinerInfo &DCI,
6767                                         SelectionDAG &DAG) {
6768   if (DCI.isBeforeLegalizeOps())
6769     return SDValue();
6770
6771   MVT VT = N->getSimpleValueType(0);
6772   if (!VT.is128BitVector()) {
6773     if (N->getOpcode() == ISD::ADD)
6774       return performSetccAddFolding(N, DAG);
6775     return SDValue();
6776   }
6777
6778   // Make sure both branches are extended in the same way.
6779   SDValue LHS = N->getOperand(0);
6780   SDValue RHS = N->getOperand(1);
6781   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6782        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6783       LHS.getOpcode() != RHS.getOpcode())
6784     return SDValue();
6785
6786   unsigned ExtType = LHS.getOpcode();
6787
6788   // It's not worth doing if at least one of the inputs isn't already an
6789   // extract, but we don't know which it'll be so we have to try both.
6790   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6791     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6792     if (!RHS.getNode())
6793       return SDValue();
6794
6795     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6796   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6797     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6798     if (!LHS.getNode())
6799       return SDValue();
6800
6801     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6802   }
6803
6804   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6805 }
6806
6807 // Massage DAGs which we can use the high-half "long" operations on into
6808 // something isel will recognize better. E.g.
6809 //
6810 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6811 //   (arm64_neon_umull (extract_high (v2i64 vec)))
6812 //                     (extract_high (v2i64 (dup128 scalar)))))
6813 //
6814 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6815                                        TargetLowering::DAGCombinerInfo &DCI,
6816                                        SelectionDAG &DAG) {
6817   if (DCI.isBeforeLegalizeOps())
6818     return SDValue();
6819
6820   SDValue LHS = N->getOperand(1);
6821   SDValue RHS = N->getOperand(2);
6822   assert(LHS.getValueType().is64BitVector() &&
6823          RHS.getValueType().is64BitVector() &&
6824          "unexpected shape for long operation");
6825
6826   // Either node could be a DUP, but it's not worth doing both of them (you'd
6827   // just as well use the non-high version) so look for a corresponding extract
6828   // operation on the other "wing".
6829   if (isEssentiallyExtractSubvector(LHS)) {
6830     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6831     if (!RHS.getNode())
6832       return SDValue();
6833   } else if (isEssentiallyExtractSubvector(RHS)) {
6834     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6835     if (!LHS.getNode())
6836       return SDValue();
6837   }
6838
6839   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6840                      N->getOperand(0), LHS, RHS);
6841 }
6842
6843 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6844   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6845   unsigned ElemBits = ElemTy.getSizeInBits();
6846
6847   int64_t ShiftAmount;
6848   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6849     APInt SplatValue, SplatUndef;
6850     unsigned SplatBitSize;
6851     bool HasAnyUndefs;
6852     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6853                               HasAnyUndefs, ElemBits) ||
6854         SplatBitSize != ElemBits)
6855       return SDValue();
6856
6857     ShiftAmount = SplatValue.getSExtValue();
6858   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6859     ShiftAmount = CVN->getSExtValue();
6860   } else
6861     return SDValue();
6862
6863   unsigned Opcode;
6864   bool IsRightShift;
6865   switch (IID) {
6866   default:
6867     llvm_unreachable("Unknown shift intrinsic");
6868   case Intrinsic::arm64_neon_sqshl:
6869     Opcode = ARM64ISD::SQSHL_I;
6870     IsRightShift = false;
6871     break;
6872   case Intrinsic::arm64_neon_uqshl:
6873     Opcode = ARM64ISD::UQSHL_I;
6874     IsRightShift = false;
6875     break;
6876   case Intrinsic::arm64_neon_srshl:
6877     Opcode = ARM64ISD::SRSHR_I;
6878     IsRightShift = true;
6879     break;
6880   case Intrinsic::arm64_neon_urshl:
6881     Opcode = ARM64ISD::URSHR_I;
6882     IsRightShift = true;
6883     break;
6884   case Intrinsic::arm64_neon_sqshlu:
6885     Opcode = ARM64ISD::SQSHLU_I;
6886     IsRightShift = false;
6887     break;
6888   }
6889
6890   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6891     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6892                        DAG.getConstant(-ShiftAmount, MVT::i32));
6893   else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6894     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6895                        DAG.getConstant(ShiftAmount, MVT::i32));
6896
6897   return SDValue();
6898 }
6899
6900 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6901 // the intrinsics must be legal and take an i32, this means there's almost
6902 // certainly going to be a zext in the DAG which we can eliminate.
6903 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6904   SDValue AndN = N->getOperand(2);
6905   if (AndN.getOpcode() != ISD::AND)
6906     return SDValue();
6907
6908   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6909   if (!CMask || CMask->getZExtValue() != Mask)
6910     return SDValue();
6911
6912   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6913                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6914 }
6915
6916 static SDValue performIntrinsicCombine(SDNode *N,
6917                                        TargetLowering::DAGCombinerInfo &DCI,
6918                                        const ARM64Subtarget *Subtarget) {
6919   SelectionDAG &DAG = DCI.DAG;
6920   unsigned IID = getIntrinsicID(N);
6921   switch (IID) {
6922   default:
6923     break;
6924   case Intrinsic::arm64_neon_vcvtfxs2fp:
6925   case Intrinsic::arm64_neon_vcvtfxu2fp:
6926     return tryCombineFixedPointConvert(N, DCI, DAG);
6927     break;
6928   case Intrinsic::arm64_neon_fmax:
6929     return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6930                        N->getOperand(1), N->getOperand(2));
6931   case Intrinsic::arm64_neon_fmin:
6932     return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6933                        N->getOperand(1), N->getOperand(2));
6934   case Intrinsic::arm64_neon_smull:
6935   case Intrinsic::arm64_neon_umull:
6936   case Intrinsic::arm64_neon_pmull:
6937   case Intrinsic::arm64_neon_sqdmull:
6938     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6939   case Intrinsic::arm64_neon_sqshl:
6940   case Intrinsic::arm64_neon_uqshl:
6941   case Intrinsic::arm64_neon_sqshlu:
6942   case Intrinsic::arm64_neon_srshl:
6943   case Intrinsic::arm64_neon_urshl:
6944     return tryCombineShiftImm(IID, N, DAG);
6945   case Intrinsic::arm64_crc32b:
6946   case Intrinsic::arm64_crc32cb:
6947     return tryCombineCRC32(0xff, N, DAG);
6948   case Intrinsic::arm64_crc32h:
6949   case Intrinsic::arm64_crc32ch:
6950     return tryCombineCRC32(0xffff, N, DAG);
6951   }
6952   return SDValue();
6953 }
6954
6955 static SDValue performExtendCombine(SDNode *N,
6956                                     TargetLowering::DAGCombinerInfo &DCI,
6957                                     SelectionDAG &DAG) {
6958   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6959   // we can convert that DUP into another extract_high (of a bigger DUP), which
6960   // helps the backend to decide that an sabdl2 would be useful, saving a real
6961   // extract_high operation.
6962   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6963       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6964     SDNode *ABDNode = N->getOperand(0).getNode();
6965     unsigned IID = getIntrinsicID(ABDNode);
6966     if (IID == Intrinsic::arm64_neon_sabd ||
6967         IID == Intrinsic::arm64_neon_uabd) {
6968       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6969       if (!NewABD.getNode())
6970         return SDValue();
6971
6972       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6973                          NewABD);
6974     }
6975   }
6976
6977   // This is effectively a custom type legalization for ARM64.
6978   //
6979   // Type legalization will split an extend of a small, legal, type to a larger
6980   // illegal type by first splitting the destination type, often creating
6981   // illegal source types, which then get legalized in isel-confusing ways,
6982   // leading to really terrible codegen. E.g.,
6983   //   %result = v8i32 sext v8i8 %value
6984   // becomes
6985   //   %losrc = extract_subreg %value, ...
6986   //   %hisrc = extract_subreg %value, ...
6987   //   %lo = v4i32 sext v4i8 %losrc
6988   //   %hi = v4i32 sext v4i8 %hisrc
6989   // Things go rapidly downhill from there.
6990   //
6991   // For ARM64, the [sz]ext vector instructions can only go up one element
6992   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6993   // take two instructions.
6994   //
6995   // This implies that the most efficient way to do the extend from v8i8
6996   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6997   // the normal splitting to happen for the v8i16->v8i32.
6998
6999   // This is pre-legalization to catch some cases where the default
7000   // type legalization will create ill-tempered code.
7001   if (!DCI.isBeforeLegalizeOps())
7002     return SDValue();
7003
7004   // We're only interested in cleaning things up for non-legal vector types
7005   // here. If both the source and destination are legal, things will just
7006   // work naturally without any fiddling.
7007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7008   EVT ResVT = N->getValueType(0);
7009   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7010     return SDValue();
7011   // If the vector type isn't a simple VT, it's beyond the scope of what
7012   // we're  worried about here. Let legalization do its thing and hope for
7013   // the best.
7014   if (!ResVT.isSimple())
7015     return SDValue();
7016
7017   SDValue Src = N->getOperand(0);
7018   MVT SrcVT = Src->getValueType(0).getSimpleVT();
7019   // If the source VT is a 64-bit vector, we can play games and get the
7020   // better results we want.
7021   if (SrcVT.getSizeInBits() != 64)
7022     return SDValue();
7023
7024   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7025   unsigned ElementCount = SrcVT.getVectorNumElements();
7026   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7027   SDLoc DL(N);
7028   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7029
7030   // Now split the rest of the operation into two halves, each with a 64
7031   // bit source.
7032   EVT LoVT, HiVT;
7033   SDValue Lo, Hi;
7034   unsigned NumElements = ResVT.getVectorNumElements();
7035   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7036   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7037                                  ResVT.getVectorElementType(), NumElements / 2);
7038
7039   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7040                                LoVT.getVectorNumElements());
7041   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7042                    DAG.getIntPtrConstant(0));
7043   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7044                    DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7045   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7046   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7047
7048   // Now combine the parts back together so we still have a single result
7049   // like the combiner expects.
7050   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7051 }
7052
7053 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7054 /// value. The load store optimizer pass will merge them to store pair stores.
7055 /// This has better performance than a splat of the scalar followed by a split
7056 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7057 /// followed by an ext.b and two stores.
7058 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7059   SDValue StVal = St->getValue();
7060   EVT VT = StVal.getValueType();
7061
7062   // Don't replace floating point stores, they possibly won't be transformed to
7063   // stp because of the store pair suppress pass.
7064   if (VT.isFloatingPoint())
7065     return SDValue();
7066
7067   // Check for insert vector elements.
7068   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7069     return SDValue();
7070
7071   // We can express a splat as store pair(s) for 2 or 4 elements.
7072   unsigned NumVecElts = VT.getVectorNumElements();
7073   if (NumVecElts != 4 && NumVecElts != 2)
7074     return SDValue();
7075   SDValue SplatVal = StVal.getOperand(1);
7076   unsigned RemainInsertElts = NumVecElts - 1;
7077
7078   // Check that this is a splat.
7079   while (--RemainInsertElts) {
7080     SDValue NextInsertElt = StVal.getOperand(0);
7081     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7082       return SDValue();
7083     if (NextInsertElt.getOperand(1) != SplatVal)
7084       return SDValue();
7085     StVal = NextInsertElt;
7086   }
7087   unsigned OrigAlignment = St->getAlignment();
7088   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7089   unsigned Alignment = std::min(OrigAlignment, EltOffset);
7090
7091   // Create scalar stores. This is at least as good as the code sequence for a
7092   // split unaligned store wich is a dup.s, ext.b, and two stores.
7093   // Most of the time the three stores should be replaced by store pair
7094   // instructions (stp).
7095   SDLoc DL(St);
7096   SDValue BasePtr = St->getBasePtr();
7097   SDValue NewST1 =
7098       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7099                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7100
7101   unsigned Offset = EltOffset;
7102   while (--NumVecElts) {
7103     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7104                                     DAG.getConstant(Offset, MVT::i64));
7105     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7106                           St->getPointerInfo(), St->isVolatile(),
7107                           St->isNonTemporal(), Alignment);
7108     Offset += EltOffset;
7109   }
7110   return NewST1;
7111 }
7112
7113 static SDValue performSTORECombine(SDNode *N,
7114                                    TargetLowering::DAGCombinerInfo &DCI,
7115                                    SelectionDAG &DAG,
7116                                    const ARM64Subtarget *Subtarget) {
7117   if (!DCI.isBeforeLegalize())
7118     return SDValue();
7119
7120   StoreSDNode *S = cast<StoreSDNode>(N);
7121   if (S->isVolatile())
7122     return SDValue();
7123
7124   // Cyclone has bad performance on unaligned 16B stores when crossing line and
7125   // page boundries. We want to split such stores.
7126   if (!Subtarget->isCyclone())
7127     return SDValue();
7128
7129   // Don't split at Oz.
7130   MachineFunction &MF = DAG.getMachineFunction();
7131   bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7132       AttributeSet::FunctionIndex, Attribute::MinSize);
7133   if (IsMinSize)
7134     return SDValue();
7135
7136   SDValue StVal = S->getValue();
7137   EVT VT = StVal.getValueType();
7138
7139   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7140   // those up regresses performance on micro-benchmarks and olden/bh.
7141   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7142     return SDValue();
7143
7144   // Split unaligned 16B stores. They are terrible for performance.
7145   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7146   // extensions can use this to mark that it does not want splitting to happen
7147   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7148   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7149   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7150       S->getAlignment() <= 2)
7151     return SDValue();
7152
7153   // If we get a splat of a scalar convert this vector store to a store of
7154   // scalars. They will be merged into store pairs thereby removing two
7155   // instructions.
7156   SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7157   if (ReplacedSplat != SDValue())
7158     return ReplacedSplat;
7159
7160   SDLoc DL(S);
7161   unsigned NumElts = VT.getVectorNumElements() / 2;
7162   // Split VT into two.
7163   EVT HalfVT =
7164       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7165   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7166                                    DAG.getIntPtrConstant(0));
7167   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7168                                    DAG.getIntPtrConstant(NumElts));
7169   SDValue BasePtr = S->getBasePtr();
7170   SDValue NewST1 =
7171       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7172                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7173   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7174                                   DAG.getConstant(8, MVT::i64));
7175   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7176                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7177                       S->getAlignment());
7178 }
7179
7180 // Optimize compare with zero and branch.
7181 static SDValue performBRCONDCombine(SDNode *N,
7182                                     TargetLowering::DAGCombinerInfo &DCI,
7183                                     SelectionDAG &DAG) {
7184   SDValue Chain = N->getOperand(0);
7185   SDValue Dest = N->getOperand(1);
7186   SDValue CCVal = N->getOperand(2);
7187   SDValue Cmp = N->getOperand(3);
7188
7189   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7190   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7191   if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7192     return SDValue();
7193
7194   unsigned CmpOpc = Cmp.getOpcode();
7195   if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7196     return SDValue();
7197
7198   // Only attempt folding if there is only one use of the flag and no use of the
7199   // value.
7200   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7201     return SDValue();
7202
7203   SDValue LHS = Cmp.getOperand(0);
7204   SDValue RHS = Cmp.getOperand(1);
7205
7206   assert(LHS.getValueType() == RHS.getValueType() &&
7207          "Expected the value type to be the same for both operands!");
7208   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7209     return SDValue();
7210
7211   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7212     std::swap(LHS, RHS);
7213
7214   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7215     return SDValue();
7216
7217   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7218       LHS.getOpcode() == ISD::SRL)
7219     return SDValue();
7220
7221   // Fold the compare into the branch instruction.
7222   SDValue BR;
7223   if (CC == ARM64CC::EQ)
7224     BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7225   else
7226     BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7227
7228   // Do not add new nodes to DAG combiner worklist.
7229   DCI.CombineTo(N, BR, false);
7230
7231   return SDValue();
7232 }
7233
7234 // vselect (v1i1 setcc) ->
7235 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
7236 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7237 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7238 // such VSELECT.
7239 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7240   SDValue N0 = N->getOperand(0);
7241   EVT CCVT = N0.getValueType();
7242
7243   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7244       CCVT.getVectorElementType() != MVT::i1)
7245     return SDValue();
7246
7247   EVT ResVT = N->getValueType(0);
7248   EVT CmpVT = N0.getOperand(0).getValueType();
7249   // Only combine when the result type is of the same size as the compared
7250   // operands.
7251   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7252     return SDValue();
7253
7254   SDValue IfTrue = N->getOperand(1);
7255   SDValue IfFalse = N->getOperand(2);
7256   SDValue SetCC =
7257       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7258                    N0.getOperand(0), N0.getOperand(1),
7259                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
7260   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7261                      IfTrue, IfFalse);
7262 }
7263
7264 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7265                                                DAGCombinerInfo &DCI) const {
7266   SelectionDAG &DAG = DCI.DAG;
7267   switch (N->getOpcode()) {
7268   default:
7269     break;
7270   case ISD::ADD:
7271   case ISD::SUB:
7272     return performAddSubLongCombine(N, DCI, DAG);
7273   case ISD::XOR:
7274     return performXorCombine(N, DAG, DCI, Subtarget);
7275   case ISD::MUL:
7276     return performMulCombine(N, DAG, DCI, Subtarget);
7277   case ISD::SINT_TO_FP:
7278   case ISD::UINT_TO_FP:
7279     return performIntToFpCombine(N, DAG);
7280   case ISD::OR:
7281     return performORCombine(N, DCI, Subtarget);
7282   case ISD::INTRINSIC_WO_CHAIN:
7283     return performIntrinsicCombine(N, DCI, Subtarget);
7284   case ISD::ANY_EXTEND:
7285   case ISD::ZERO_EXTEND:
7286   case ISD::SIGN_EXTEND:
7287     return performExtendCombine(N, DCI, DAG);
7288   case ISD::BITCAST:
7289     return performBitcastCombine(N, DCI, DAG);
7290   case ISD::CONCAT_VECTORS:
7291     return performConcatVectorsCombine(N, DCI, DAG);
7292   case ISD::VSELECT:
7293     return performVSelectCombine(N, DCI.DAG);
7294   case ISD::STORE:
7295     return performSTORECombine(N, DCI, DAG, Subtarget);
7296   case ARM64ISD::BRCOND:
7297     return performBRCONDCombine(N, DCI, DAG);
7298   }
7299   return SDValue();
7300 }
7301
7302 // Check if the return value is used as only a return value, as otherwise
7303 // we can't perform a tail-call. In particular, we need to check for
7304 // target ISD nodes that are returns and any other "odd" constructs
7305 // that the generic analysis code won't necessarily catch.
7306 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7307   if (N->getNumValues() != 1)
7308     return false;
7309   if (!N->hasNUsesOfValue(1, 0))
7310     return false;
7311
7312   SDValue TCChain = Chain;
7313   SDNode *Copy = *N->use_begin();
7314   if (Copy->getOpcode() == ISD::CopyToReg) {
7315     // If the copy has a glue operand, we conservatively assume it isn't safe to
7316     // perform a tail call.
7317     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7318         MVT::Glue)
7319       return false;
7320     TCChain = Copy->getOperand(0);
7321   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7322     return false;
7323
7324   bool HasRet = false;
7325   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
7326        UI != UE; ++UI) {
7327     if (UI->getOpcode() != ARM64ISD::RET_FLAG)
7328       return false;
7329     HasRet = true;
7330   }
7331
7332   if (!HasRet)
7333     return false;
7334
7335   Chain = TCChain;
7336   return true;
7337 }
7338
7339 // Return whether the an instruction can potentially be optimized to a tail
7340 // call. This will cause the optimizers to attempt to move, or duplicate,
7341 // return instructions to help enable tail call optimizations for this
7342 // instruction.
7343 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7344   if (!EnableARM64TailCalls)
7345     return false;
7346
7347   if (!CI->isTailCall())
7348     return false;
7349
7350   return true;
7351 }
7352
7353 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7354                                                  SDValue &Offset,
7355                                                  ISD::MemIndexedMode &AM,
7356                                                  bool &IsInc,
7357                                                  SelectionDAG &DAG) const {
7358   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7359     return false;
7360
7361   Base = Op->getOperand(0);
7362   // All of the indexed addressing mode instructions take a signed
7363   // 9 bit immediate offset.
7364   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7365     int64_t RHSC = (int64_t)RHS->getZExtValue();
7366     if (RHSC >= 256 || RHSC <= -256)
7367       return false;
7368     IsInc = (Op->getOpcode() == ISD::ADD);
7369     Offset = Op->getOperand(1);
7370     return true;
7371   }
7372   return false;
7373 }
7374
7375 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7376                                                     SDValue &Offset,
7377                                                     ISD::MemIndexedMode &AM,
7378                                                     SelectionDAG &DAG) const {
7379   EVT VT;
7380   SDValue Ptr;
7381   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7382     VT = LD->getMemoryVT();
7383     Ptr = LD->getBasePtr();
7384   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7385     VT = ST->getMemoryVT();
7386     Ptr = ST->getBasePtr();
7387   } else
7388     return false;
7389
7390   bool IsInc;
7391   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7392     return false;
7393   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7394   return true;
7395 }
7396
7397 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7398                                                      SDValue &Base,
7399                                                      SDValue &Offset,
7400                                                      ISD::MemIndexedMode &AM,
7401                                                      SelectionDAG &DAG) const {
7402   EVT VT;
7403   SDValue Ptr;
7404   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7405     VT = LD->getMemoryVT();
7406     Ptr = LD->getBasePtr();
7407   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7408     VT = ST->getMemoryVT();
7409     Ptr = ST->getBasePtr();
7410   } else
7411     return false;
7412
7413   bool IsInc;
7414   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7415     return false;
7416   // Post-indexing updates the base, so it's not a valid transform
7417   // if that's not the same as the load's pointer.
7418   if (Ptr != Base)
7419     return false;
7420   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7421   return true;
7422 }
7423
7424 /// The only 128-bit atomic operation is an stxp that succeeds. In particular
7425 /// neither ldp nor ldxp are atomic. So the canonical sequence for an atomic
7426 /// load is:
7427 ///     loop:
7428 ///         ldxp x0, x1, [x8]
7429 ///         stxp w2, x0, x1, [x8]
7430 ///         cbnz w2, loop
7431 /// If the stxp succeeds then the ldxp managed to get both halves without an
7432 /// intervening stxp from a different thread and the read was atomic.
7433 static void ReplaceATOMIC_LOAD_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7434                                    SelectionDAG &DAG) {
7435   SDLoc DL(N);
7436   AtomicSDNode *AN = cast<AtomicSDNode>(N);
7437   EVT VT = AN->getMemoryVT();
7438   SDValue Zero = DAG.getConstant(0, VT);
7439
7440   // FIXME: Really want ATOMIC_LOAD_NOP but that doesn't fit into the existing
7441   // scheme very well. Given the complexity of what we're already generating, an
7442   // extra couple of ORRs probably won't make much difference.
7443   SDValue Result = DAG.getAtomic(ISD::ATOMIC_LOAD_OR, DL, AN->getMemoryVT(),
7444                                  N->getOperand(0), N->getOperand(1), Zero,
7445                                  AN->getMemOperand(), AN->getOrdering(),
7446                                  AN->getSynchScope());
7447
7448   Results.push_back(Result.getValue(0)); // Value
7449   Results.push_back(Result.getValue(1)); // Chain
7450 }
7451
7452 static void ReplaceATOMIC_OP_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7453                                  SelectionDAG &DAG, unsigned NewOp) {
7454   SDLoc DL(N);
7455   AtomicOrdering Ordering = cast<AtomicSDNode>(N)->getOrdering();
7456   assert(N->getValueType(0) == MVT::i128 &&
7457          "Only know how to expand i128 atomics");
7458
7459   SmallVector<SDValue, 6> Ops;
7460   Ops.push_back(N->getOperand(1)); // Ptr
7461   // Low part of Val1
7462   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7463                             N->getOperand(2), DAG.getIntPtrConstant(0)));
7464   // High part of Val1
7465   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7466                             N->getOperand(2), DAG.getIntPtrConstant(1)));
7467   if (NewOp == ARM64::ATOMIC_CMP_SWAP_I128) {
7468     // Low part of Val2
7469     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7470                               N->getOperand(3), DAG.getIntPtrConstant(0)));
7471     // High part of Val2
7472     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7473                               N->getOperand(3), DAG.getIntPtrConstant(1)));
7474   }
7475
7476   Ops.push_back(DAG.getTargetConstant(Ordering, MVT::i32));
7477   Ops.push_back(N->getOperand(0)); // Chain
7478
7479   SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
7480   SDNode *Result = DAG.getMachineNode(NewOp, DL, Tys, Ops);
7481   SDValue OpsF[] = { SDValue(Result, 0), SDValue(Result, 1) };
7482   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, OpsF, 2));
7483   Results.push_back(SDValue(Result, 2));
7484 }
7485
7486 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7487                                              SmallVectorImpl<SDValue> &Results,
7488                                              SelectionDAG &DAG) const {
7489   switch (N->getOpcode()) {
7490   default:
7491     llvm_unreachable("Don't know how to custom expand this");
7492   case ISD::ATOMIC_LOAD:
7493     ReplaceATOMIC_LOAD_128(N, Results, DAG);
7494     return;
7495   case ISD::ATOMIC_LOAD_ADD:
7496     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_ADD_I128);
7497     return;
7498   case ISD::ATOMIC_LOAD_SUB:
7499     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_SUB_I128);
7500     return;
7501   case ISD::ATOMIC_LOAD_AND:
7502     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_AND_I128);
7503     return;
7504   case ISD::ATOMIC_LOAD_OR:
7505     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_OR_I128);
7506     return;
7507   case ISD::ATOMIC_LOAD_XOR:
7508     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_XOR_I128);
7509     return;
7510   case ISD::ATOMIC_LOAD_NAND:
7511     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_NAND_I128);
7512     return;
7513   case ISD::ATOMIC_SWAP:
7514     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_SWAP_I128);
7515     return;
7516   case ISD::ATOMIC_LOAD_MIN:
7517     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MIN_I128);
7518     return;
7519   case ISD::ATOMIC_LOAD_MAX:
7520     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MAX_I128);
7521     return;
7522   case ISD::ATOMIC_LOAD_UMIN:
7523     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMIN_I128);
7524     return;
7525   case ISD::ATOMIC_LOAD_UMAX:
7526     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMAX_I128);
7527     return;
7528   case ISD::ATOMIC_CMP_SWAP:
7529     ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_CMP_SWAP_I128);
7530     return;
7531   case ISD::FP_TO_UINT:
7532   case ISD::FP_TO_SINT:
7533     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7534     // Let normal code take care of it by not adding anything to Results.
7535     return;
7536   }
7537 }