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