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