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