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