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