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