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