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