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